userver: Statistics and Metrics
Loading...
Searching...
No Matches
Statistics and Metrics

What are Metrics?

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.

What to Measure?

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:

  1. Successfully processed requests/messages/tasks. Basic metrics showing the volume of work the service performs.
  2. Errors. Critical metrics indicating the presence or absence of explicit problems in the service. It's usually valuable to track both the total number of errors and errors by type (e.g., client errors, server errors, timeouts, socket errors, task cancellations, etc.).
  3. Performance speed/Latency. For handlers, measure request/message processing times (timings). Since processing time varies per message/request, timing aggregates are typically tracked as percentiles. For message/task queues, queue length is also measured (in the number of messages or the time a message waits to be processed).
  4. Resource utilization. This applies to both physical and virtual resources. A service can monitor the usage of existing resources (e.g., OS resources like CPU, RAM, network) or create its own (e.g., connection pool or worker pool utilization). These metrics are essential for determining resource efficiency and predicting when current resources will become insufficient.

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.

Existing Metrics and Statistics of userver

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.

How to write metrics and statistics

How NOT to Write Metrics

  1. Callback Function Should Not Modify Service State. The statistics handler might be triggered not only for sending metrics to metrics storage but also for other purposes; a cron task might unexpectedly poll the service more frequently or a manual request for metrics can be performed. Therefore, the approach "read the current counter value, emit it as a metric, then reset the counter" is invalid. Instead, use a monotonic counter. Resets are permitted only in tests. Only optimizations that do not affect the final result (e.g., caching or memoization) are allowed.
  2. Callback Function Should Not Access External Services. All data required for metric generation must reside in the process's memory. For metrics requiring DB access, standard practice involves caching database responses in a background variable and computing metrics from this cached value.
  3. Avoid Blocking Synchronization Primitives. The callback should ideally avoid synchronization primitives that may cause blocking (mutexes, semaphores, etc.). Your service should be able to report metrics even if critical components are deadlocked.
  4. Minimize Observation Overhead. When adding metric collection, ensure it does not slow down the observed code. Event tracking must be maximally efficient.
  5. Optimize for Event Accounting Over Metric Reporting. While the speed of the statistics endpoint is less critical, prefer faster event accounting even if it slows down final metric aggregation. Favor this tradeoff.

How to Register Your Metric Set

Method 1: Via utils::statistics::MetricTag

Register a metric type via utils::statistics::MetricTag and provide a DumpMetric function for exporting it:

const utils::statistics::MetricTag<Stats> kTcpEchoTag{"tcp-echo"};
void DumpMetric(utils::statistics::Writer& writer, const Stats& stats) {
writer["sockets"]["opened"] = stats.opened_sockets;
writer["sockets"]["closed"] = stats.closed_sockets;
writer["bytes"]["read"] = stats.bytes_read;
}
void ResetMetric(Stats& stats) {
ResetMetric(stats.opened_sockets);
ResetMetric(stats.closed_sockets);
ResetMetric(stats.bytes_read);
}

Now the tag could be used in component constructor to get a reference to the struct Stats:

Echo::Echo(const components::ComponentConfig& config, const components::ComponentContext& context)
: TcpAcceptorBase(config, context),
stats_(context.FindComponent<components::StatisticsStorage>().GetMetricsStorage()->GetMetric(kTcpEchoTag))
{}

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.

Component::Component(const components::ComponentConfig& config, const components::ComponentContext& context)
: ComponentBase{config, context},
resolver_{GetFsTaskProcessor(config, context), config.As<::userver::static_config::DnsClient>()}
{
utils::statistics::RegisterWriterScope(context, fmt::format("{}.replies", config.Name()), [this](auto& writer) {
resolver_.WriteMetrics(writer);
});
}

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:

// `storage` is utils::statistics::Storage; `scopes` is utils::ResourceScopeStorage that owns the writer
// lifetime.
storage.RegisterWriter(
scopes,
"path-begin",
[&](utils::statistics::Writer& writer) {
writer["metric1"] = 1;
writer["metric2"].ValueWithLabels(2, {"label_name1", "value1"});
writer["metric3"].ValueWithLabels(3, {{"label_name2", "value2"}, {"label_name3", "value3"}});
if (auto subpath = writer["a"]["b"]) {
subpath["mc4"] = HeavyComputation();
subpath["mc5"] = HeavyComputation2();
}
},
{{"label_for_all", "value_all"}}
);

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.

Metric Types

Built-in metric types and user-defined types with DumpMetric can be written directly to a utils::statistics::Writer.

Basic Primitives for Metrics

Additional Primitives

Custom User Metric Types

Instead of writing one giant DumpMetric or WriteStatistics somewhere, it is recommended to break these functions into pieces:

struct ComponentMetricsNested {
std::atomic<int> nested1{17};
std::atomic<int> nested2{18};
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const ComponentMetricsNested& m) {
writer["nested1"] = m.nested1;
writer["nested2"].ValueWithLabels(m.nested2, {"label_name", "label_value"});
}

DumpMetric functions nest well, labels are propagated to the nested DumpMetric:

struct ComponentMetrics {
std::atomic<int> total{42};
ComponentMetricsNested summary;
std::unordered_map<std::string, std::shared_ptr<ComponentMetricsNested>> metrics;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const ComponentMetrics& m) {
writer["total"] = m.total;
writer["summary"] = m.summary;
for (const auto& [key, value] : m.metrics) {
if (!value) {
continue;
}
writer.ValueWithLabels(*value, {{"a_label", key}, {"b_label", "b"}});
}
}

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.

Using a writer

Writing values

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.

Paths

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.

Labels

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.

Database Metrics

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:

  1. Object count in a table:
    • For a database-backed message queue, this, reflects queue size.
    • For rough estimates (to reduce DB load), use reltuples instead of COUNT.
  2. Objects matching specific queries:
    • Helps evaluate "lost," "unprocessed," or otherwise problematic records.

⚠️ Critical before production:

  • Always analyze query performance and index usage via EXPLAIN ANALYZE.
  • Metric collection must not significantly strain the database.

How to test metrics in testsuite and gtest

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.

gtest

For metrics declared through utils::statistics::MetricTag, create a utils::statistics::MetricsStorage in the test:

UTEST(MetricsStorage, SampleTesting) {
// Changing metric in test
metrics_storage.GetMetric(kMetricV1) = utils::statistics::Rate{42};
// Retrieving metric value
EXPECT_EQ(metrics_storage.GetMetric(kMetricV1).Load(), utils::statistics::Rate{42});
}

To unit test a metric type with DumpMetric, pass an object directly to utils::statistics::Snapshot:

namespace {
struct SampleMetrics {
utils::statistics::RateCounter foo;
utils::statistics::RateCounter bar;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const SampleMetrics& metrics) {
writer["foo"] = metrics.foo;
writer["bar"].ValueWithLabels(metrics.bar, {"kind", "x"});
}
} // namespace
TEST(Snapshot, FromMetric) {
SampleMetrics metrics;
metrics.foo = utils::statistics::Rate{1};
metrics.bar = utils::statistics::Rate{2};
const utils::statistics::Snapshot snapshot{metrics};
EXPECT_EQ(snapshot.SingleMetric("foo"), utils::statistics::Rate{1});
EXPECT_EQ(snapshot.SingleMetric("bar", {{"kind", "x"}}), utils::statistics::Rate{2});
EXPECT_EQ(snapshot.SingleMetricOptional("missing"), std::nullopt);
}

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:

namespace {
class ToyMetrics {
public:
ToyMetrics(utils::ResourceScopeStorage& scopes, utils::statistics::Storage& storage) {
storage.RegisterWriter(scopes, "toy", [this](utils::statistics::Writer& writer) {
writer["foo"] = foo;
writer["bar"] = bar;
});
}
utils::statistics::RateCounter foo;
utils::statistics::RateCounter bar;
};
} // namespace
UTEST(Snapshot, FromStorage) {
utils::WithResourceScopes<ToyMetrics> toy(std::in_place, storage);
toy->foo = utils::statistics::Rate{1};
toy->bar = utils::statistics::Rate{2};
const utils::statistics::Snapshot snapshot{storage};
EXPECT_EQ(snapshot.SingleMetric("toy.foo"), utils::statistics::Rate{1});
EXPECT_EQ(snapshot.SingleMetric("toy.bar"), utils::statistics::Rate{2});
}

When the same logical metric is split across paths or label sets, dump once and compare subgroups:

namespace {
struct PathOnlySubgroup {
utils::statistics::RateCounter queued;
utils::statistics::RateCounter dropped;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const PathOnlySubgroup& subgroup) {
writer["queued"] = subgroup.queued;
writer["dropped"] = subgroup.dropped;
}
struct PathAndLabelSubgroup {
utils::statistics::RateCounter processed;
utils::statistics::RateCounter failed;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const PathAndLabelSubgroup& subgroup) {
writer["processed"] = subgroup.processed;
writer["failed"] = subgroup.failed;
}
struct SubgroupSampleMetrics {
PathOnlySubgroup ingress;
PathAndLabelSubgroup handler;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const SubgroupSampleMetrics& metrics) {
writer["ingress"] = metrics.ingress;
writer["handler"].ValueWithLabels(metrics.handler, {"handler", "/create"});
}
} // namespace
TEST(Snapshot, SubgroupSlicesFromMetricSnapshot) {
SubgroupSampleMetrics metrics;
metrics.ingress.queued = utils::statistics::Rate{2};
metrics.ingress.dropped = utils::statistics::Rate{1};
metrics.handler.processed = utils::statistics::Rate{7};
metrics.handler.failed = utils::statistics::Rate{3};
const utils::statistics::Snapshot all{metrics};
all,
{.require_prefix = "ingress"},
};
EXPECT_EQ(ingress.SingleMetric("queued"), utils::statistics::Rate{2});
EXPECT_EQ(ingress.SingleMetric("dropped"), utils::statistics::Rate{1});
all,
{.require_prefix = "handler", .require_labels = {{"handler", "/create"}}},
};
EXPECT_EQ(handler.SingleMetric("processed"), utils::statistics::Rate{7});
EXPECT_EQ(handler.SingleMetric("failed"), utils::statistics::Rate{3});
}

testsuite

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().