Metrics are numerical values representing specific indicators that change over time (time series). They can be collected from service via special agents and sent to a metrics storage system (Prometheus/Graphite/VictoriaMetrics/...). As numerical values, metrics typically capture fundamental service indicators that signal the overall health of a service or subsystem (e.g., the background error rate in a message queue handler). Services log additional detailed textual information for troubleshooting in logs. Logs help identify the root causes of errors, correlate them with client issues, trace causality, etc. Attempting to encode textual event information into metric names usually results in metrics bloat and makes them difficult to navigate.
There guarantees regarding the delivery of metrics mostly depend on metrics delivery agent and metrics storage system. Some metrics may fail to reach the server, and already saved metrics may become temporarily unavailable due to server downtime (e.g., for several hours), metrics storage downtime or special agent malfunction.
If higher guarantees of availability and reliability for delivery and access are required, it's recommended to use another storage system or agent that provide such guarantees. Specifically, if metrics are involved in computations critical to service functionality (e.g., triggering fallbacks), you should use a database with stronger guarantees than metrics.
The metrics collection interval depend on the agent, userver may report metrics at any rate.
Services, daemons, cron tasks, and other programs perform useful work. Characteristics of this work should be reflected in metrics. There are four main categories of informative metrics:
In specific cases, more exotic metrics might also be appropriate.
When introducing new metrics, keep in mind that storing metrics is not free and consumes space in metrics storage. Only implement metrics that genuinely reflect the service's state and can help developers or operations understand the health of the service or feature.
Components from userver provide metrics by default. No additional setup beyond including the component is required.
See Retrieving Service Statistics and Metrics (Prometheus/Graphite/...) and Default Metrics Description for information on how to retrieve metrics and for a list of metrics.
Method 1: Via utils::statistics::MetricTag
Register a metric type via utils::statistics::MetricTag and provide a DumpMetric function for exporting it:
Now the tag could be used in component constructor to get a reference to the struct Stats:
See also TCP full-duplex server with metrics and Spans for a complete example.
Method 2: Register a writer callback
In a component constructor, use utils::statistics::RegisterWriterScope with the component context. The helper retrieves the default components::StatisticsStorage component and registers the callback with its utils::statistics::Storage.
For a component exporting its own state, a WriteStatistics member called by the callback is sufficient. The component does not need its own DumpMetric just to export its state. Structures that group its metrics can provide DumpMetric, so they can be written from WriteStatistics and tested independently of the component.
If the metrics callback calls a method of the component itself, use context.Scopes(). utils::statistics::RegisterWriterScope uses these scopes automatically. For callbacks on other objects, see where to obtain scopes.
To register directly with utils::statistics::Storage, pass the chosen scopes as the first argument to utils::statistics::Storage::RegisterWriter:
The callback can run concurrently with other code, so access to shared data must be thread-safe. See also utils::statistics::Writer for more details.
Built-in metric types and user-defined types with DumpMetric can be written directly to a utils::statistics::Writer.
Instead of writing one giant DumpMetric or WriteStatistics somewhere, it is recommended to break these functions into pieces:
DumpMetric functions nest well, labels are propagated to the nested DumpMetric:
Recommendations for organizing custom metric types:
Declare DumpMetric alongside the type, in the same namespace, so argument-dependent lookup (ADL) can find it. Define it in the corresponding .cpp; template and header-only types may define it in the header. A declaration that only mentions utils::statistics::Writer can include <userver/utils/statistics/fwd.hpp>; code using the writer's operations needs <userver/utils/statistics/writer.hpp>.
Keep the representation with the type: write a nested object as writer["child"] = stats.child rather than repeating its field-by-field export at every call site.
Put loops over containers inside DumpMetric for your own enclosing type. Do not add overloads for third-party containers or aliases of those containers.
If the same data needs distinct representations, use wrapper types with their own DumpMetric functions.
Provide ResetMetric if the type supports resetting. It is not required for exporting metrics. For tests, prefer pytest_userver.client.ClientMonitor.metrics_diff to resetting shared service state.
Generic helpers can constrain metric arguments with utils::statistics::HasWriterSupport.
Write supported metric objects directly. Calling .load() or .Load() just to export a counter is unnecessary. Explicit reads are appropriate when computing a value, such as an error ratio.
| Metric type | Writing its value |
|---|---|
| utils::statistics::RateCounter | writer["requests"] = requests |
| std::atomic<std::uint64_t> | writer["active"] = active |
| utils::statistics::RelaxedCounter | writer["active"] = active |
Plain integers, double, and utils::statistics::Rate can also be written directly. Integers and double are exported as GAUGE; Rate is exported as RATE. This is useful for computed values and for data protected by a mutex. Read protected data under the same mutex when exporting it. See Database metrics for background collection.
Other metric types from utils::statistics and user-defined types with DumpMetric are supported too. Define void DumpMetric(utils::statistics::Writer&, const T&) in the namespace of the user-defined type T.
Writing writer["timings"] = timings, where timings is a utils::statistics::RecentPeriod, aggregates the configured window without the current incomplete epoch. There is no need to call timings.GetStatsForPeriod() just for this assignment. To select another interval or include the current epoch, call utils::statistics::RecentPeriod::GetStatsForPeriod with the desired arguments and write its result.
Write each metric, identified by its path and labels, once per collection. Repeated writes do not replace the previous value. Compute the final value before exporting it; see utils::statistics::Writer for the contract.
Use a local child utils::statistics::Writer when several metrics share a path prefix, and write only the suffixes through it. A single metric usually needs no local child. The registration example above groups mc4 and mc5 under the same a.b prefix.
See utils::statistics::Writer for child lifetime restrictions and utils::statistics::Writer::operator[] for path semantics. In particular, writer["a.b"] and writer["a"]["b"] produce the same path; output formats handle escaping.
Avoid creating temporary std::string copies solely to pass a path. Path forwarding helpers can take std::string_view.
Attach labels shared by all fields once with utils::statistics::Writer::ValueWithLabels on the whole object. The object's DumpMetric propagates them to nested metrics. Labels that vary between metrics belong on those individual metrics. See the nested DumpMetric example in the custom metric types section above.
Label forwarding helpers can take std::string_view too. Keep owning strings when storing data. See utils::statistics::Writer::ValueWithLabels for label propagation and string lifetime requirements.
It's common to need to expose database data in metrics. Querying the database directly from the metrics handler is discouraged, as metrics must be returned quickly and should not depend on external resource states (e.g., DB availability). Instead, use a utils::PeriodicTask or DistLock to query the database and cache results in process memory. See also Periodics and DistLocks.
For current state computed by a periodic task, use GAUGE metrics stored in atomics or a concurrent::Variable. With concurrent::Variable, the task updates the data and the metrics callback reads it under the same lock. Perform expensive work before acquiring the lock, then publish the result in a short critical section. Count events, such as successful task runs, separately with utils::statistics::RateCounter.
Key scenarios where such metrics are useful:
⚠️ Critical before production:
Prefer gtest when the metric logic is local to a component; use testsuite when the assertion needs a running service and the monitor HTTP endpoint.
For metrics declared through utils::statistics::MetricTag, create a utils::statistics::MetricsStorage in the test:
To unit test a metric type with DumpMetric, pass an object directly to utils::statistics::Snapshot:
Test the production DumpMetric directly; do not reproduce its export logic in a test-only function. There is no need to create a utils::statistics::Storage and register a writer solely to inspect an object that already supports DumpMetric.
If the class registers writers in utils::statistics::Storage, pass Storage:
When the same logical metric is split across paths or label sets, dump once and compare subgroups:
Use monitor_client to check metrics from a running service. See Metrics testing in testsuite for the API, examples, snapshot comparisons, and before/after assertions with metrics_diff().