Skip to content

Custom actuator metric with request counter#836

Draft
dennisvang wants to merge 29 commits intosupport/1.18.xfrom
feature/661-metrics
Draft

Custom actuator metric with request counter#836
dennisvang wants to merge 29 commits intosupport/1.18.xfrom
feature/661-metrics

Conversation

@dennisvang
Copy link
Copy Markdown
Contributor

@dennisvang dennisvang commented Jan 27, 2026

For #661 we are interested in counting the requests to individual resources.

However, the default Spring MVC actuator metric http.server.requests does not count requests for individual resources. Instead, it only shows counts for the path patterns defined for the controllers, such as

path = {"", "{oUrlPrefix:[^.]+}/{oRecordId:[^.]+}"},

To count requests to individual resource URIs, I added a custom micrometer ObservationFilter implementation that replaces the default uri path pattern by the full path. Also see spring observability docs.

Note

Although it is relatively quick and easy to use Spring actuator metrics for this, I'm not convinced this is the best approach. I think it would make more sense to do this at the deployment level, e.g. based on proxy logs, instead of the app level.

fixes #661

todo

  • Exclude default metrics, only expose the custom one.
    So, figure out why the following lines are ignored by the fdp, whereas they do work in a fresh spring project, and they also work without issue if we apply them to the develop branch...
    metrics:
    enable:
    all: false
    http:
    server: true

usage example

To see totals and list available endpoints (they only appear in the list after they have been visited at least once):

curl http://localhost:8080/actuator/metrics/http.server.requests | jq
{
  "name": "http.server.requests",
  "baseUnit": "seconds",
  "measurements": [
    {
      "statistic": "COUNT",
      "value": 67.0
    },
    {
      "statistic": "TOTAL_TIME",
      "value": 1.3833911090000002
    },
    {
      "statistic": "MAX",
      "value": 0.089165968
    }
  ],
  "availableTags": [
    {
      "tag": "exception",
      "values": [
        "none"
      ]
    },
    {
      "tag": "method",
      "values": [
        "POST",
        "PUT",
        "GET"
      ]
    },
    {
      "tag": "http.url",
      "values": [
        "/index/admin/trigger",
        "/configs/bootstrap",
        "/index/entries",
        "/index/entries/info",
        "/index/entries/654b5878-fc8a-44db-bb47-81754617f5a5",
        "/spec",
        "/actuator/info",
        "/actuator/metrics/",
        "/actuator/metrics/http.server.requests",
        "/meta",
        "/"
      ]
    },
    {
      "tag": "error",
      "values": [
        "none"
      ]
    },
    {
      "tag": "outcome",
      "values": [
        "CLIENT_ERROR",
        "SUCCESS"
      ]
    },
    {
      "tag": "status",
      "values": [
        "404",
        "200",
        "204"
      ]
    }
  ]
}

To see details for a specific endpoint:

http://localhost:8080/actuator/metrics/http.server.requests?tag=http.url:/index/entries/654b5878-fc8a-44db-bb47-81754617f5a5 | jq
{
  "name": "http.server.requests",
  "baseUnit": "seconds",
  "measurements": [
    {
      "statistic": "COUNT",
      "value": 3.0
    },
    {
      "statistic": "TOTAL_TIME",
      "value": 0.138951876
    },
    {
      "statistic": "MAX",
      "value": 0.05697992
    }
  ],
  "availableTags": [
    {
      "tag": "exception",
      "values": [
        "none"
      ]
    },
    {
      "tag": "method",
      "values": [
        "PUT",
        "GET"
      ]
    },
    {
      "tag": "error",
      "values": [
        "none"
      ]
    },
    {
      "tag": "outcome",
      "values": [
        "SUCCESS"
      ]
    },
    {
      "tag": "status",
      "values": [
        "200"
      ]
    }
  ]
}

@dennisvang
Copy link
Copy Markdown
Contributor Author

dennisvang commented Jan 28, 2026

Initially I implemented this by extending OncePerRequestFilter and creating a custom metric.

However, a micrometer dev suggested another approach in this comment from 2018.
Do note that the classes mentioned in that comment have been deprecated in favor of the micrometer observation APIs, as mentioned in spring boot 3 release notes.

The latest and greatest approach is probably to override either DefaultServerRequestObservationConvention, or micrometer ObservationFilter, as mentioned in the observability docs.

@dennisvang dennisvang force-pushed the feature/661-metrics branch 2 times, most recently from eca3a0e to 401221b Compare January 28, 2026 19:25
@dennisvang
Copy link
Copy Markdown
Contributor Author

dennisvang commented Jan 29, 2026

ran into #839

Squashed result of the following commits:

* bump fdp minor version in pom

* add new rdf4j-spring-boot-sparql-web dependency from org.eclipse.rdf4j

* exclude logback from rdf4j-spring-boot-sparql-web

* provide custom name for ProfileController bean (to disambiguate from the profileController defined in org/springframework/data/rest/webmvc/RestControllerConfiguration.class, which is used by the rdf4j sparql endpoint package)

* scan for components only in the sparql package (this prevents autowiring of the QueryResponder controller class)

* add SearchSparqlController, based on rdf4j's spring-boot-sparql-web (https://github.com/eclipse-rdf4j/rdf4j/blob/main/spring-components/spring-boot-sparql-web)

* license and style for SearchSparqlController

* add openapi tag for sparql controller

* exclude all transitive dependencies from rdf4j-spring-boot-sparql-web (because we don't need them, and dependencies like spring-data-rest cause unwanted side-effects, such as exposing all repository methods as rest endpoints)

* make enum classes explicit and rearrange input args

* handle empty graph uri values in sparql controller

* fall back on application/json if Accept header is */*

* provide sparql post example values for openapi docs and swagger-ui

* add rudimentary integration tests for basic SPARQL queries

* add naive tests to verify that sparql update operations are not allowed

* add license to sparql test file

* mention whitelist in test

* Revert "provide custom name for ProfileController bean" (because this is no longer necessary now that we've excluded all transitive dependencies from rdf4j-spring-boot-sparql-web, This reverts commit 3d531e0.)

* switch from multipart form to json data fro sparql post requests (this is consistent with the other api endpoints)

* adapt sparql endpoint tests to use JSON request body

* mention accept header values in javadoc

* rename TestSparqlPost to TestSearchSparqlController and rename test methods for clarity (for clarity, we're not following the project test naming convention)

* limit supported sparql output types to application/json, application/ld+json
spring-boot-starter-parent 3.5.10 -> 3.5.12
springdoc-openapi-starter-webmvc-ui 2.8.15 -> 2.8.16
checkstyle 13.0.0 -> 13.3.0
spotbugs-maven-plugin 4.9.3.0 -> 4.9.8.2
This basically modifies every source file in the repo.

* move all files from nl/dtls to org/fairdatateam

* replace all references to nl.dtls by org.fairdatateam

* replace groupId nl.dtls by org.fairdatateam in pom.xml (note that the develop branch uses org.fairdatapoint, but that is inconsistent with the rest of our packages, so we need to fix the groupId for develop as well...)

* bump version to 1.19.1, because the change is only internal and there is no change in functionality (fdp is not a library, and it is not published in any package repo, so there should not be any dependent projects)
* change license owner from DTL to FAIR Data Team in pom.xml

* replace DTL by FAIR Data Team in license text for *all* files

* replace dtls in path in mongo migration readme
this is much more convenient for the user, not having to scroll through the many options
* hide user details in mapping from SearchSavedQuery to SearchSavedQueryDTO (for backward compatibility, the structure of the returned json object remains unchanged, but the values are now anonymized)

* adapt SearchSavedQueryService methods to new signature for SearchSavedQueryMapper.toDTO()

* update security.md

todo: for the next major release, we should simply replace the user object by the user's uuid string
Internal changes only:

* replace CurrentUserService.isAdmin by HttpServletRequest.isUserInRole

* modify SearchSavedQueryMapper.fromChangeDto to accept userUuid string instead of UserDTO

* remove current user methods from UserService and clean up CurrentUserService

* rename CurrentUserService to CurrentUserProvider, to prevent confusion with UserService

* move CurrentUserProvider to service.security package, because it is mainly concerned with spring security authentication stuff
* handle null fileUrl in loadSparqlQueryTemplate

* move queryTemplate.sparql into new resources/sparql folder

* move predifined sparql query files into resources/sparql/ (now we have all *.sparql files in one place)

* add tests for predefined sparql queries in AbstractMetadataRepository (apparently these were not covered yet)
Main changes:

* let AbstractMetadataRepository implement MetaDataRepository explicitly
* remove GenericMetadataRepository interface and rename implementation
* remove CatalogMetadataRepository interface and rename implementation
* flatten database/rdf/repository file structure (in main and test)

Additional cleanup

* use constructor autowiring for AbstractMetadataRepository, CatalogMetadataRepository, and GenericMetadataRepository
* remove redundant qualifiers and imports
* fix Class generic type for MetadataRepository.runSparqlQuery
* mock GenericMetadataRepository, instead of spy, in HarvesterServiceTest
* remove unused findResources and getRepository methods from MetadataRepository

* move search-related methods from (Abstract)MetadataRepository into SearchService and SearchMapper, because that's where they belong (the repository interface should be independent of search)

* move search-related test methods from MetadataRepositoryTest into new SearchServiceTest class

* replace overloaded runSparqlQuery by runSparqlQueryFromFile and simplify the corresponding method signatures

* remove loadSparqlQuery in favor of  re-using ResourceReader.loadResource
* constructor autowiring for SearchService

* move SearchMapper.toSubstitutions into SearchService.composeQuery

* remove overloaded SearchService.search for SearchSavedQueryDTO, because this is overcomplicated: we can simply pass in the variables in the caller

* rename SearchService.search input args for clarity

* replace SearchService.loadSparqlQueryTemplate by existing ResourceLoader.loadResource

* load the query template in the constructor and rename QUERY_TEMPLATE to queryTemplate accordingly
@dennisvang
Copy link
Copy Markdown
Contributor Author

The current implementation still shows all metrics, so the filter in application.yml is ignored for some reason.

This can be checked as follows:

curl http://localhost:8080/actuator/metrics | jq

which still returns a long list, instead of just http.server.requests:

Details

{
  "names": [
    "application.ready.time",
    "application.started.time",
    "executor.active",
    "executor.completed",
    "executor.pool.core",
    "executor.pool.max",
    "executor.pool.size",
    "executor.queue.remaining",
    "executor.queued",
    "http.client.requests",
    "http.client.requests.active",
    "http.server.requests",
    "http.server.requests.active",
    "mongodb.driver.commands",
    "mongodb.driver.pool.checkedout",
    "mongodb.driver.pool.checkoutfailed",
    "mongodb.driver.pool.size",
    "mongodb.driver.pool.waitqueuesize",
    "spring.data.repository.invocations",
    "spring.security.authorizations",
    "spring.security.authorizations.active",
    "spring.security.filterchains",
    "spring.security.filterchains.CORSFilter.after",
    "spring.security.filterchains.CORSFilter.before",
    "spring.security.filterchains.JwtTokenFilter.after",
    "spring.security.filterchains.JwtTokenFilter.before",
    "spring.security.filterchains.LoggingFilter.after",
    "spring.security.filterchains.LoggingFilter.before",
    "spring.security.filterchains.access.exceptions.after",
    "spring.security.filterchains.access.exceptions.before",
    "spring.security.filterchains.active",
    "spring.security.filterchains.authentication.anonymous.after",
    "spring.security.filterchains.authentication.anonymous.before",
    "spring.security.filterchains.authorization.after",
    "spring.security.filterchains.authorization.before",
    "spring.security.filterchains.context.async.after",
    "spring.security.filterchains.context.async.before",
    "spring.security.filterchains.context.holder.after",
    "spring.security.filterchains.context.holder.before",
    "spring.security.filterchains.context.servlet.after",
    "spring.security.filterchains.context.servlet.before",
    "spring.security.filterchains.header.after",
    "spring.security.filterchains.header.before",
    "spring.security.filterchains.logout.after",
    "spring.security.filterchains.logout.before",
    "spring.security.filterchains.requestcache.after",
    "spring.security.filterchains.requestcache.before",
    "spring.security.filterchains.session.management.after",
    "spring.security.filterchains.session.management.before",
    "spring.security.filterchains.session.urlencoding.after",
    "spring.security.filterchains.session.urlencoding.before",
    "spring.security.http.secured.requests",
    "spring.security.http.secured.requests.active",
    "tomcat.sessions.active.current",
    "tomcat.sessions.active.max",
    "tomcat.sessions.alive.max",
    "tomcat.sessions.created",
    "tomcat.sessions.expired",
    "tomcat.sessions.rejected"
  ]
}

@dennisvang dennisvang force-pushed the feature/661-metrics branch from 9c7fc37 to cd2e98c Compare May 1, 2026 15:51
dennisvang added 2 commits May 1, 2026 17:54
metrics are a new feature
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant