Production-grade guide to metrics collection strategies covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Metrics collection is the process of gathering time-series data from systems, services, and infrastructure to understand performance, health, and behavior over time. It matters when you need to detect anomalies, diagnose issues, validate changes, and guide capacity planning—especially in distributed, dynamic environments where latency, throughput, and error rates evolve continuously.
Metrics must serve a clear purpose: monitoring a service’s availability, tracking API latency, or observing resource utilization across a fleet of nodes. Each metric should answer a specific question. For example, http_request_duration_seconds answers “How long do requests take on average?” but http_request_duration_seconds{method="POST",service="user-service"} answers “How long do POST requests to the user service take?”
To define a metric, specify:
disk_io_utilization, cache_hit_ratio)counter, gauge, histogram, or summaryservice="auth-service", region="us-west-1")seconds, bytes, percent, requests_per_secondA metric definition in Prometheus format:
- name: http_request_duration_seconds
help: "Duration of HTTP requests in seconds."
type: histogram
label_names:
- method
- service
- status_code
unit: seconds
buckets:
- 0.1
- 0.5
- 1.0
- 2.0
Aggregation determines how raw data is reduced into meaningful values. The wrong strategy silently distorts understanding.
requests_total{method="GET",service="api-gateway"} increases monotonically.rate(requests_total[5m]) to get requests per minute over the last five minutes.memory_usage_bytes{instance="web-01"} updates periodically via push or pull.http_request_duration_seconds_bucket{le="1.0",method="POST"} with buckets at 0.1, 0.5, 1.0, 2.0.histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) to compute 95th percentile latency over five minutes.request_size_bytes_summary{service="payment-service"} with quantile="0.95", value="1024".user_sessions_total{user_id="12345",region="asia-east1",device="mobile",browser="chrome"} where user_id is highly variable.rate() calculations.rate(requests_total[1h]) underestimates request rate when a service restarts mid-interval.irate(requests_total[5m]) for near-real-time metrics or rate(requests_total[1h]) with count_over_time(requests_total[1h]) to detect resets.[1,2,5,10]) across multiple services with varying latency profiles leads to poor percentile estimates.[0.1,0.5,1.0,2.0] buckets well, but a 1s backend with 95% of requests under 5s underutilizes buckets.Metrics must be sampled at a frequency that captures the underlying behavior without excessive overhead.
cpu_load{instance="db-01"} collected every 5 seconds.disk_usage_bytes{mount="/var/log"} updated every 10 minutes.Use the Nyquist–Shannon sampling theorem: sample at least twice the highest expected frequency. For a service with 90% of requests under 100ms, sample metrics at least every 50ms.
Two primary patterns exist for transporting metrics from source to storage.
http://auth-service:9090/metrics every 30 seconds. # prometheus.yml
scrape_configs:
- job_name: 'auth-service'
static_configs:
- targets: ['auth-service:9090']
scrape_interval: 30s
metrics_path: '/metrics'
scheme: 'http'
http://metrics-collector:8080/metrics every 10 seconds using net/http and encoding/json. package main
import (
"context"
"encoding/json"
"net/http"
"time"
)
func pushMetrics() {
payload := map[string]interface{}{
"name": "http_request_duration_seconds",
"type": "histogram",
"labels": map[string]string{
"method": "POST",
"service": "user-service",
"status": "200",
},
"values": []float64{0.1, 0.2, 0.5, 1.0, 2.0},
"count": 1500,
"sum": 420.3,
}
body, _ := json.Marshal(payload)
req, _ := http.NewRequestWithContext(context.Background(), "POST", "http://metrics-collector:8080/metrics", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 5 * time.Second}
client.Do(req)
}
Failure modes are often silent and hard to diagnose.
Error scraping target "auth-service:9090": context deadline exceededscrape_timeout and add relabel_configs to detect and alert on failed scrapes.http://metrics-collector:8080/metrics returns 503 Service Unavailable but no error is logged.2024-04-05T10:00:00Z but the collector’s clock is 200ms fast.timestamp field in metric payloads and align timestamps in the collector.Metrics should be collected at multiple levels: infrastructure, service, application, and business.
node_exporter or collectd.node_cpu_seconds_total{mode="idle",instance="web-01"}.http_requests_total{method="GET",service="order-service",status_code="500"}. # Python application
from prometheus_client import Counter, Histogram
signup_requests = Counter('user_signup_requests_total', 'Total number of user signups')
signup_duration = Histogram('user_signup_duration_seconds', 'Time to complete user signup')
with signup_duration.time():
try:
user = create_user(email, password)
signup_requests.inc()
except Exception as e:
signup_requests.labels(result='failed').inc()
raise
end_to_end_latency_seconds{service="checkout-flow",step="payment-confirmation"}.Labels are the primary mechanism for slicing and dicing metrics.
service, environment, region, instance, versionuser_id, session_id, correlation_id, trace_idcluster=region+az)Avoid over-labeling. A metric with 1000 unique combinations of user_id, service, and region will have high cardinality, increasing memory and query cost.
Metrics must be retained for different durations based on their use.
http_request_duration_seconds stored with 1s resolution for 7 days.user_sessions_total aggregated into daily summaries.Use tiered storage: hot (fast access), warm (medium access), cold (infrequent access).
Metrics should not be static. They evolve as systems change.
http_request_duration_seconds{version="v1.2.0",service="api-gateway"}.kafka_consumer_lag_bytes was added on 2024-03-01; use kafka-consumer-groups.sh to compute lag for the previous month.api_request_count was replaced by http_requests_total; keep the old metric for 6 months, then archive it.Use streaming aggregation to compute derived metrics on the fly.
avg(rate(http_requests_total[5m])) gives 5-minute moving average of requests per minute.sum_over_time(http_request_duration_seconds[1h]) computes total duration over the last hour.avg(rate(http_request_duration_seconds{status_code="500"}[15m])) computes average 500 error latency.Derive new metrics from existing ones using queries.
rate(http_requests_total{status_code=~"5.."}[1h]) / rate(http_requests_total[1h])rate(http_requests_total[5m])histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))count_over_time(http_request_duration_seconds{status_code="200"}[1h]) / count_over_time(http_request_duration_seconds[1h])Alerts must capture the right signal with minimal false positives.
http_request_duration_seconds > 1.0s for 5 minutesanomalies(http_request_duration_seconds, window="1h", threshold="3σ")rate(http_requests_total[10m]) < 0.8 * avg(rate(http_requests_total[1h])) to detect traffic drops.Alerts should be evaluated at consistent intervals and include a window of time to reduce jitter.
Metrics are not just for monitoring—they are the foundation of diagnosing issues.
http_request_duration_seconds in auth-service with database_query_duration_seconds in user-db.memory_usage_bytes over time to detect memory leaks.When a service fails, the first question is: “What metrics changed just before the failure?” The answer often reveals the root cause.
This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy