Metrics Aggregation Pattern: Collect, Tag & Query
How to collect, tag, and aggregate metrics for observability. Covers Prometheus, OpenTelemetry, custom metrics, histograms, and dashboarding.
Overview
Metrics aggregation is the practice of recording numeric measurements from your application, tagging them with contextual labels, and letting a time-series system aggregate them for querying and alerting. Unlike logs, which record individual events, metrics are pre-aggregated numbers: request count, error rate, a latency percentile, active connections. That makes them cheap to store and fast to query, even at high traffic.
The pattern covers four metric types: counters (monotonically increasing), gauges (values that go up or down), histograms (distribution of values), and summaries (pre-computed quantiles). Together with structured logging and distributed tracing, metrics are one of the three pillars of observability, and usually the cheapest one to run at scale.
Aggregation actually happens twice. Instrumentation keeps running totals and bucket counts in memory, so recording a metric costs almost nothing per request. Then the storage backend aggregates further, summing counters across instances or computing percentiles from buckets at query time. Splitting the work this way is what lets a handful of series describe the behavior of an entire fleet.
When to Use
- Any production application that needs observability beyond logs.
- Alerting on SLOs: error rate, latency percentiles, throughput.
- Capacity planning, following resource usage trends over weeks.
- Business dashboards: orders per minute, active users, revenue.
- Performance monitoring: request latency, queue depth, cache hit rate.
When NOT to Use
- Individual event tracking. When you need every single event on record, logs or event streams are the right tool.
- Debugging one specific request. Logs and traces answer “what happened here”; metrics answer “how often does it happen”.
- Very low-traffic applications where rates and percentiles aren’t statistically meaningful.
- When the overhead of running a metrics backend isn’t justified yet. A simple health check endpoint may be enough.
Solution
Prometheus client (Python)
# Python — prometheus_client for metrics
from prometheus_client import Counter, Gauge, Histogram, Summary, start_http_server
import time
import random
# Counter — monotonically increasing (request count, error count)
REQUEST_COUNT = Counter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status'],
)
# Gauge — can go up or down (active connections, queue depth)
ACTIVE_CONNECTIONS = Gauge(
'active_connections',
'Currently active connections',
)
QUEUE_DEPTH = Gauge(
'message_queue_depth',
'Messages waiting in queue',
['queue_name'],
)
# Histogram — distribution of values (request latency)
REQUEST_LATENCY = Histogram(
'http_request_duration_seconds',
'HTTP request duration in seconds',
['method', 'endpoint'],
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
)
# Summary — quantiles of values
RESPONSE_SIZE = Summary(
'http_response_size_bytes',
'HTTP response size in bytes',
['endpoint'],
)
# Usage
def handle_request(method, endpoint):
start_time = time.time()
# Simulate processing
time.sleep(random.uniform(0.01, 0.2))
status = random.choice([200, 200, 200, 200, 404, 500])
# Record metrics
REQUEST_COUNT.labels(method=method, endpoint=endpoint, status=str(status)).inc()
REQUEST_LATENCY.labels(method=method, endpoint=endpoint).observe(time.time() - start_time)
RESPONSE_SIZE.labels(endpoint=endpoint).observe(random.randint(100, 5000))
return status
# Start metrics server on port 9090
start_http_server(9090)
# Update gauges
ACTIVE_CONNECTIONS.set(42)
QUEUE_DEPTH.labels(queue_name='orders').set(150)
FastAPI middleware with metrics
# Python — FastAPI middleware for automatic request metrics
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, start_http_server
import time
app = FastAPI()
REQUEST_COUNT = Counter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status'],
)
REQUEST_LATENCY = Histogram(
'http_request_duration_seconds',
'HTTP request duration',
['method', 'endpoint'],
)
@app.middleware("http")
async def metrics_middleware(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
duration = time.time() - start_time
endpoint = request.url.path
method = request.method
status = str(response.status_code)
REQUEST_COUNT.labels(method=method, endpoint=endpoint, status=status).inc()
REQUEST_LATENCY.labels(method=method, endpoint=endpoint).observe(duration)
return response
# Start metrics server
start_http_server(9090)
OpenTelemetry metrics (Python)
# Python — OpenTelemetry metrics API
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from opentelemetry.sdk.resources import Resource
# Setup
resource = Resource.create({"service.name": "order-service"})
reader = PrometheusMetricReader()
provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(provider)
meter = metrics.get_meter("order-service")
# Create instruments
request_counter = meter.create_counter(
"http_requests_total",
description="Total HTTP requests",
unit="1",
)
request_duration = meter.create_histogram(
"http_request_duration_seconds",
description="HTTP request duration",
unit="s",
)
active_connections = meter.create_up_down_counter(
"active_connections",
description="Active connections",
unit="1",
)
# Usage
def handle_order(order_id):
attrs = {"endpoint": "/api/orders", "method": "POST"}
request_counter.add(1, attrs)
active_connections.add(1, attrs)
start = time.time()
# Process order
duration = time.time() - start
request_duration.record(duration, attrs)
active_connections.add(-1, attrs)
Node.js with prom-client
// JavaScript — prom-client for Prometheus metrics
const promClient = require('prom-client');
// Create a Registry
const register = new promClient.Registry();
// Default metrics (CPU, memory, GC)
promClient.collectDefaultMetrics({ register });
// Custom metrics
const httpRequestTotal = new promClient.Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'endpoint', 'status'],
registers: [register],
});
const httpRequestDuration = new promClient.Histogram({
name: 'http_request_duration_seconds',
help: 'HTTP request duration in seconds',
labelNames: ['method', 'endpoint'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
registers: [register],
});
const activeConnections = new promClient.Gauge({
name: 'active_connections',
help: 'Currently active connections',
registers: [register],
});
const queueDepth = new promClient.Gauge({
name: 'message_queue_depth',
help: 'Messages waiting in queue',
labelNames: ['queue_name'],
registers: [register],
});
// Express middleware
const express = require('express');
const app = express();
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000;
httpRequestTotal.labels(req.method, req.path, String(res.statusCode)).inc();
httpRequestDuration.labels(req.method, req.path).observe(duration);
});
next();
});
// Metrics endpoint
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});
// Update gauges
activeConnections.set(42);
queueDepth.labels({ queue_name: 'orders' }).set(150);
Business metrics with tagging
# Python — business metrics with dimensional tags
from prometheus_client import Counter, Gauge, Histogram
# Order metrics with rich tags
ORDERS_PROCESSED = Counter(
'orders_processed_total',
'Total orders processed',
['product_category', 'payment_method', 'region', 'status'],
)
ORDER_VALUE = Histogram(
'order_value_usd',
'Order value in USD',
['product_category', 'region'],
buckets=[1, 5, 10, 25, 50, 100, 250, 500, 1000, 5000],
)
ACTIVE_SUBSCRIPTIONS = Gauge(
'active_subscriptions',
'Currently active subscriptions',
['plan', 'region'],
)
# Usage
def process_order(order):
ORDER_VALUE.labels(
product_category=order.category,
region=order.region,
).observe(order.total)
ORDERS_PROCESSED.labels(
product_category=order.category,
payment_method=order.payment_method,
region=order.region,
status='success' if order.success else 'failed',
).inc()
Java with Micrometer
// Java — Micrometer metrics
import io.micrometer.core.instrument.*;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
// Counter
Counter orderCounter = Counter.builder("orders_processed")
.description("Total orders processed")
.tag("product_category", "electronics")
.tag("region", "us-east")
.register(registry);
orderCounter.increment();
// Timer (equivalent to histogram for duration)
Timer orderTimer = Timer.builder("order_processing_duration")
.description("Order processing duration")
.tag("endpoint", "/api/orders")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
orderTimer.record(() -> processOrder(order));
// Gauge
Gauge activeConnections = Gauge.builder("active_connections",
() -> getActiveConnectionCount())
.description("Currently active connections")
.register(registry);
// Distribution summary (histogram for arbitrary values)
DistributionSummary orderValue = DistributionSummary.builder("order_value_usd")
.description("Order value in USD")
.tag("region", "us-east")
.register(registry);
orderValue.record(order.getTotal());
// Expose metrics endpoint
// Spring Boot auto-configures /actuator/prometheus
Prometheus scrape configuration
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'order-service'
metrics_path: /metrics
static_configs:
- targets: ['order-service:9090']
labels:
service: 'order-service'
env: 'production'
- job_name: 'payment-service'
metrics_path: /metrics
static_configs:
- targets: ['payment-service:9090']
labels:
service: 'payment-service'
env: 'production'
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
Grafana dashboard queries
# PromQL queries for common dashboards
# Request rate (requests per second)
rate(http_requests_total[5m])
# Error rate (percentage of 5xx responses)
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m])) * 100
# 95th percentile latency
histogram_quantile(0.95,
rate(http_request_duration_seconds_bucket[5m]))
# Average latency by endpoint
rate(http_request_duration_seconds_sum[5m])
/ rate(http_request_duration_seconds_count[5m])
# Active connections over time
active_connections
# Orders per minute by category
sum(rate(orders_processed_total[1m])) by (product_category)
# Top 5 slowest endpoints
topk(5,
histogram_quantile(0.95,
rate(http_request_duration_seconds_bucket[5m])) by (endpoint))
Alerting rules
# Prometheus alerting rules
groups:
- name: order-service
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m])) > 0.05
for: 10m
labels:
severity: critical
annotations:
summary: "Error rate above 5% for 10 minutes"
description: "Current error rate: {{ $value }}"
- alert: HighLatency
expr: |
histogram_quantile(0.95,
rate(http_request_duration_seconds_bucket[5m])) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "95th percentile latency above 2 seconds"
- alert: ServiceDown
expr: up{job="order-service"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Order service is down"
How It Works
Your application records values in memory as events happen. Every inc(), observe(), or set() just updates a few numbers; no disk writes, no network calls. On each scrape interval, Prometheus reads the /metrics endpoint, which dumps every series as text: metric name, label set, and current value. Storing the scrape timestamp with each sample turns those counters and gauges into time series you can query later.
Cardinality is the real cost
Each distinct set of label values turns into its own time series. Tag requests by method, endpoint, and status and you get maybe 4 × 30 × 6 = 720 series per service, which is fine. Tag by user_id and every new user creates a series that lives for the retention window; a few million users will exhaust the memory of a Prometheus server. Keep labels to bounded dimensions: endpoint, method, status code class, region, plan tier. Anything unbounded (IDs, emails, URLs with path parameters) belongs in logs or traces, not metrics.
Two practical consequences follow. First, decide your label set before shipping, because adding or removing a label later creates new series and orphans the old history. Second, watch out for accidental unboundedness: endpoint looks safe until a route like /orders/{id} gets recorded as /orders/8421, at which point every order mints a new series.
Histograms vs summaries
Both track distributions, but they differ in where the math happens. A summary computes quantiles inside your process and exposes finished numbers, so p95 across five instances can’t be combined afterwards. A histogram only counts how many observations fell into each bucket; the server-side histogram_quantile() then approximates any percentile, and you can sum buckets across all your instances first. That’s why the usual advice is: use histograms for anything you’ll ever want to aggregate, and pick bucket boundaries that bracket your SLO so the percentile you care about doesn’t land in an enormous bucket.
Pull vs push
Pull is the Prometheus model: your app exposes /metrics and the server decides when to scrape. Push systems like StatsD or the Prometheus Pushgateway invert it, and the app sends data out. Pull gives you health for free (a failed scrape is itself the up metric) and keeps the app simpler. Push still fits short-lived batch jobs that won’t be alive when the next scrape comes around.
Naming deserves more attention than it usually gets. Prometheus conventions use a _total suffix on counters, a unit suffix like _seconds or _bytes on durations and sizes, and a stable namespace prefix per application. Following those conventions makes rate() results self-explanatory and keeps dashboards portable across services.
Retention is worth deciding early too. Local Prometheus storage typically keeps a few weeks; teams that need months of history ship samples to long-term stores like Thanos, Mimir, or a managed service via remote write. The instrumentation side stays identical either way, so you can start with a single Prometheus and add remote write when retention or HA becomes a requirement.
Variants
Push-based metrics with StatsD
# Python — StatsD push-based metrics
import statsd
client = statsd.StatsClient('localhost', 8125, prefix='order-service')
# Counter
client.incr('orders.created')
client.incr('orders.failed', count=1)
# Timing
with client.timer('order_processing_duration'):
process_order(order)
# Gauge
client.gauge('active_connections', 42)
# Sets (unique count)
client.set('unique_users', user_id)
Custom business metrics dashboard
// JavaScript — custom business metrics
const businessMetrics = {
// Revenue tracking
revenueToday: new promClient.Gauge({
name: 'revenue_today_usd',
help: 'Total revenue today in USD',
registers: [register],
}),
// Conversion funnel
funnelStage: new promClient.Counter({
name: 'funnel_stage_total',
help: 'Users reaching each funnel stage',
labelNames: ['stage'],
registers: [register],
}),
// Feature usage
featureUsage: new promClient.Counter({
name: 'feature_usage_total',
help: 'Feature usage count',
labelNames: ['feature', 'user_tier'],
registers: [register],
}),
};
// Track funnel stages
function trackFunnel(userId, stage) {
businessMetrics.funnelStage.labels({ stage }).inc();
}
trackFunnel(userId, 'page_view');
trackFunnel(userId, 'add_to_cart');
trackFunnel(userId, 'checkout');
trackFunnel(userId, 'purchase');
Best Practices
- Choose the metric type that fits. Counters for totals, gauges for current state, histograms for distributions. A gauge where a counter belongs silently breaks
rate(). - Tag with bounded dimensions: endpoint, method, status class, region. Tags are what let you slice one metric into per-endpoint or per-region views.
- Keep cardinality bounded. Never tag with user IDs, request IDs, or raw URLs.
- Expose a
/metricsendpoint and let Prometheus scrape it. Reserve push for batch jobs that die before the next scrape. - Track business metrics alongside technical ones. Orders, revenue, and conversions belong next to CPU and latency, and they’re often the first thing stakeholders look at.
- Alert on SLOs rather than on “is it up”. Error rate and latency percentiles catch real user pain; an
up == 0alert is a backup, not the plan.
Common Mistakes
- Unbounded cardinality: tagging with user IDs or request IDs creates a new time series per value, and Prometheus memory grows until it falls over. Once a dimension runs into hundreds of possible values, keep it out of your metric labels.
- Using gauges for counters: gauges can go down, so
rate()returns nonsense. A value that only goes up is a counter. - Not tagging at all: a bare
http_requests_totalcan’t be sliced by endpoint or status. Decide your dimensions upfront, because adding a label later changes the series identity and orphans your historical data. - Too many histogram buckets: 50 buckets multiplies every label combination by 50. Ten to fifteen well-chosen buckets cover most latency ranges.
- Ignoring counter resets: counters reset to zero when the process restarts. Never alert or graph a raw counter; always wrap it in
rate()orincrease(), which handle resets.
Further Reading
- Prometheus metric types — official reference for counters, gauges, histograms, and summaries.
- OpenTelemetry metrics specification — the vendor-neutral metrics API and data model.
- PromQL querying basics — including
rate(),increase(), andhistogram_quantile(). - For a deeper guide to the full observability stack, see Observability — Metrics, Logs, and Traces Complete Guide, and for storage internals see the time-series database guide.
Frequently Asked Questions
What are the four metric types?
Counters (monotonically increasing values like request count), gauges (values that go up or down like active connections), histograms (distributions like request latency), and summaries (pre-computed quantiles like p95 response size).
Should I use histograms or summaries?
Use histograms. They can be aggregated across instances and let you calculate any percentile at query time with histogram_quantile(). Summaries compute quantiles in the client, so their values can't be combined afterwards. Reserve them for cases where you need a cheap per-instance quantile.
How do I reduce metric cardinality?
Audit your labels and drop any dimension with unbounded values: user IDs, request IDs, full URLs. Replace a raw path label with a route template (/orders/{id} instead of /orders/8421). If you still need high-cardinality data, keep it in logs or traces instead of metrics.
What is cardinality and why does it matter?
Cardinality is the number of unique label combinations on a metric, and each combination is a separate time series stored in memory. High cardinality exhausts the server and slows queries, so keeping it bounded is the single most important design decision in a metrics setup.
How often should I update metrics?
Counters and histograms update in place as events happen; there's no batching step. Gauges update whenever the underlying value changes. Prometheus scrapes every 15 seconds by default, so don't push: let the server pull.
Can I use metrics for billing or audits?
Not reliably. Metrics systems sample and aggregate, so individual values can drift or be lost between scrapes. For anything that must be exact, like billing, record events in your database and treat metrics as a monitoring tool, not a ledger.
What is the difference between push and pull metrics?
With pull (Prometheus), the server scrapes your /metrics endpoint on a schedule, and a failed scrape doubles as a health signal. With push (StatsD, Pushgateway), the application sends data to a collector. Pull is simpler for long-running services; push fits short-lived batch jobs.
Related Resources
Structured Logging: Emit JSON Logs with Consistent Fields
How to emit structured JSON logs with consistent fields for searchability. Covers Python structlog, Winston, pino, Serilog, log levels, and log aggregation.
PatternDistributed Tracing: Propagate Trace Context Across Services
How to propagate trace context across service boundaries with OpenTelemetry. Covers span creation, context propagation, sampling, and trace analysis.
PatternHealth Check Pattern: Expose Liveness and Readiness Probes
Implement liveness and readiness probes for container orchestrators. Covers Kubernetes probe config, dependency checks, and graceful degradation.
PatternCircuit Breaker with Monitoring
How to expose circuit breaker state as metrics for observability. Covers Prometheus integration, alerting rules, dashboards, and state transitions.
GuideTime-Series Databases — InfluxDB, TimescaleDB, ClickHouse
Practical guide to time-series databases: when to use a TSDB, data model, retention policies, and choosing between InfluxDB, TimescaleDB, and ClickHouse.
RecipeMetrics Collection: Prometheus, StatsD & OpenTelemetry
Collect, aggregate, and expose application and infrastructure metrics with Prometheus, StatsD, and OpenTelemetry for monitoring and alerting.