I would like to measure database latency for my Spring Boot microservice, which is using MongoDB as a database. I’m using Micrometer, metrics are scraped by Prometheus and visualized by Grafana. Do I need to create an aspect for my repository methods or Micrometer provides those metrics out of the box?
Micrometer provides the following metrics out of the box:
# HELP mongodb_driver_commands_seconds_max Timer of mongodb commands
# TYPE mongodb_driver_commands_seconds_max gauge
--
# HELP mongodb_driver_commands_seconds Timer of mongodb commands
# TYPE mongodb_driver_commands_seconds summary
--
# HELP mongodb_driver_pool_waitqueuesize the current size of the wait queue for a connection from the pool
# TYPE mongodb_driver_pool_waitqueuesize gauge
--
# HELP mongodb_driver_pool_checkedout the count of connections that are currently in use
# TYPE mongodb_driver_pool_checkedout gauge
--
# HELP mongodb_driver_pool_size the current size of the connection pool, including idle and and in-use members
# TYPE mongodb_driver_pool_size gauge
Important: when you start your service locally and call your metrics endpoint, those metrics won’t be visible, unless your application made a request to MongoDB. To see them, you will need to call some endpoint with business logic, which uses a database. After that, you can call your metrics endpoint and see MongoDB driver metrics.
For example, you can calculate average database latency per shard using the following PromQL:
sum by (server_address) ((rate(mongodb_driver_commands_seconds_sum{app="${Application}",pod=~"${PodName}"}[$__rate_interval])))
/
sum by (server_address) ((rate(mongodb_driver_commands_seconds_count{app="${Application}",pod=~"${PodName}"}[$__rate_interval])))
Or to get average latency by collection:
sum by (collection) (rate(mongodb_driver_commands_seconds_sum{app="${Application}",pod=~"${PodName}"}[$__rate_interval]))
/
sum by (collection) (rate(mongodb_driver_commands_seconds_count{app="${Application}",pod=~"${PodName}"}[$__rate_interval]))