Comprehensive guide to metrics pipeline design for production observability and monitoring systems.
Metrics Pipeline Design is the practice of structuring the flow of metric data from collection at source to storage, processing, and delivery to consumers—whether dashboards, alerting systems, or analytics tools. It matters when systems grow beyond a single host or service, and when you need to correlate, aggregate, or react to time-series data at scale. The pipeline must handle high cardinality, ensure timely delivery, and adapt to changing needs without breaking existing queries or alerts.
Metrics are collected at source—application code, infrastructure, or custom exporters. The choice of collector affects latency, cardinality, and reliability.
For application-level metrics, use a standard instrumentation library. In Go, github.com/go-kit/kit/metrics provides a Gauge, Counter, and Histogram interface with Set() and Add() methods:
var (
requests = kitmetrics.NewCounter("http_requests_total")
latency = kitmetrics.NewHistogram("http_request_duration_seconds", 0.01, 10.0, 100)
)
func HandleRequest(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
latency.Observe(time.Since(start).Seconds())
}()
requests.Inc()
w.Write([]byte("Hello"))
}
Each metric emits a JSON or Protobuf payload. For high-frequency metrics, use the OpenTelemetry Metrics SDK with the Push API, which batches metrics and sends them over HTTP:
{
"resource": {
"attributes": [
{ "key": "service.name", "value": { "stringValue": "auth-service" } }
]
},
"instrumentationLibrary": {
"name": "myapp",
"version": "1.0.0"
},
"metrics": [
{
"name": "http.request.duration",
"description": "Duration of HTTP requests",
"unit": "s",
"sum": {
"dataPoints": [
{
"startTime": "2024-03-14T12:00:00Z",
"time": "2024-03-14T12:00:05Z",
"value": 1.72,
"attributes": [
{ "key": "http.method", "value": { "stringValue": "POST" } }
]
}
]
}
}
]
}
The collector runs as a sidecar or in-process daemon. It must handle network outages, buffer metrics, and retry failed batches. When the collector fails to send, it writes to a local file in the metrics-<timestamp>.json format, which the pipeline reads at startup.
The pipeline must decide whether to process metrics in batch or stream mode.
Batch processing uses periodic jobs that pull data from storage, transform it, and write to a downstream system. A typical job is a cron-scheduled bash script:
#!/bin/bash
export PGHOST=metrics-db.prod
export PGDATABASE=observability
export PGUSER=observer
# Pull raw metrics from the storage backend
curl -s "http://storage:8080/v1/metrics?since=2024-03-14T12:00:00Z&until=2024-03-14T12:10:00Z" \
| jq -c '.[] | {timestamp: .timestamp, service: .labels.service, value: .value}' \
> /data/processed/2024-03-14T12-00-00.json
# Aggregate per-minute metrics using a Python script
python3 /opt/pipeline/aggregator.py \
--input /data/processed/2024-03-14T12-00-00.json \
--output /data/aggregated/2024-03-14T12-00-00.parquet
# Upload to the analytics warehouse
aws s3 cp /data/aggregated/2024-03-14T12-00-00.parquet \
s3://metrics-analytics/parquet/2024/03/14/12/
# Update metadata
psql -c "INSERT INTO metrics_metadata (timestamp, source, processed) VALUES ('2024-03-14T12:00:00Z', 'batch', true);"
This approach is predictable, idempotent, and fault-tolerant. But it introduces latency: a 10-minute batch job means metrics appear 10 minutes after ingestion.
Stream processing uses a message queue as the backbone. The collector sends metrics to a Kafka topic metrics.raw with key=service.name and value=metric.json. A consumer group processes each record:
{
"topic": "metrics.raw",
"partition": 3,
"offset": 45829,
"key": "auth-service",
"value": {
"timestamp": "2024-03-14T12:00:05Z",
"labels": {
"http.method": "POST",
"region": "us-west-1"
},
"value": 1.72
}
}
A stream processor in Python uses confluent-kafka to consume and transform:
from confluent_kafka import Consumer, Producer
import json
conf = {
'bootstrap.servers': 'kafka-1:9092,kafka-2:9092',
'group.id': 'metrics-processor',
'auto.offset.reset': 'earliest'
}
c = Consumer(conf)
c.subscribe(['metrics.raw'])
p = Producer({'bootstrap.servers': 'kafka-1:9092'})
while True:
msg = c.poll(timeout=1.0)
if msg is None:
continue
if msg.error():
print(f"Consumer error: {msg.error()}")
continue
data = json.loads(msg.value())
service = data['labels']['service']
window = data['timestamp'][:16] # HH:MM
# Emit to aggregated topic
p.produce(
topic='metrics.aggregated',
key=service,
value=json.dumps({
"service": service,
"window": window,
"count": 1,
"sum": data['value'],
"min": data['value'],
"max": data['value']
}),
timestamp=int(data['timestamp'].replace('T', ' ').replace('Z', '') + '000')
)
p.flush()
c.close()
Stream processing offers sub-minute latency and handles irregular traffic well. But it requires careful handling of out-of-order events, idempotent processing, and exactly-once semantics.
The pipeline chooses a storage backend based on access patterns and cost.
For high-cardinality, time-series data, use a columnar store like Apache Parquet or Delta Lake. The pipeline writes data in daily or hourly partitions:
s3://metrics/parquet/
├── year=2024/
│ ├── month=03/
│ │ ├── day=14/
│ │ │ ├── hour=12/
│ │ │ │ ├── data-00001.parquet
│ │ │ │ └── data-00002.parquet
│ │ │ └── hour=13/
│ │ │ └── data-00001.parquet
│ │ └── month=04/
└── year=2025/
└── ...
Each file contains a set of metrics with common time windows and labels. Queries use predicate pushdown to read only relevant data.
For real-time access, use a purpose-built time-series database like InfluxDB, TimescaleDB, or OpenTSDB. The pipeline writes to the database via HTTP:
POST /api/v1/write?db=metrics&precision=s HTTP/1.1
Host: influxdb.prod
Content-Type: text/plain
http_request_duration,service=auth-service,method=POST value=1.72 1709795205
http_request_duration,service=auth-service,method=GET value=0.42 1709795210
http_request_duration,service=api-gateway,method=POST value=2.11 1709795208
InfluxDB supports tags, fields, and timestamps. The pipeline must handle write failures: a 500 response with {"error": "write failed"} triggers retries with exponential backoff.
When storage is shared across multiple services, use a metric table with a composite primary key:
CREATE TABLE metrics (
service TEXT NOT NULL,
metric_name TEXT NOT NULL,
timestamp TIMESTAMPTZ NOT NULL,
value DOUBLE PRECISION NOT NULL,
tags JSONB,
PRIMARY KEY (service, metric_name, timestamp)
);
The tags column stores a JSON object with key-value pairs. Queries use WHERE tags ? 'region' and tags->>'region' = 'us-west-1' to filter.
The pipeline must enrich raw metrics with context and compute derived values.
Enrichment uses a lookup service. A metrics.enrich Kafka topic receives raw events and emits enriched ones:
{
"raw": {
"service": "auth-service",
"metric": "http.request.duration",
"timestamp": "2024-03-14T12:00:05Z",
"value": 1.72
},
"enrichment": {
"cluster": "prod-west",
"environment": "production",
"version": "v1.2.3",
"region": "us-west-1"
}
}
The enrichment service queries a metadata database to resolve service metadata:
SELECT cluster, environment, version
FROM service_metadata
WHERE service = $1 AND environment = 'production';
It uses key=service in the metadata table and returns the latest metadata for the service. If the service is not found, it logs a warning and uses default values.
Derived metrics are computed using a materialized view or a batch job. The pipeline computes p95, p99, and error_rate per service and per HTTP method:
CREATE MATERIALIZED VIEW metrics_summary AS
SELECT
service,
method,
COUNT(*) AS request_count,
AVG(value) AS avg_latency,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY value) AS p95,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY value) AS p99,
COUNT(*) FILTER (WHERE value > 1.0) AS slow_requests,
(COUNT(*) FILTER (WHERE value > 1.0) * 100.0) / COUNT(*) AS error_rate
FROM metrics
WHERE timestamp >= NOW() - INTERVAL '1 hour'
GROUP BY service, method;
The pipeline refreshes this view every 5 minutes using pg_cron:
SELECT cron.schedule(
'update-metrics-summary',
'*/5 * * * *',
'REFRESH MATERIALIZED VIEW metrics_summary'
);
The pipeline delivers metrics to consumers: dashboards, alerting systems, and analytics tools.
Dashboards use a REST API that serves aggregated data. A client fetches metrics with a GET /api/v1/metrics request:
GET /api/v1/metrics?service=auth-service&metric=latency&start=2024-03-14T12:00:00Z&end=2024-03-14T13:00:00Z&interval=1m HTTP/1.1
Host: metrics-api.prod
Accept: application/json
Authorization: Bearer <token>
The API returns a JSON array:
{
"series": [
{
"metric": "http_request_duration_seconds",
"labels": { "service": "auth-service", "method": "POST" },
"data": [
[ "2024-03-14T12:00:00Z", 1.72 ],
[ "2024-03-14T12:01:00Z", 1.81 ],
[ "2024-03-14T12:02:00Z", 1.65 ]
]
}
]
}
Alerting systems consume metrics via a similar API. An alert rule triggers when p95 > 1.5 for 10 minutes:
{
"name": "High Latency in Auth Service",
"query": "SELECT p95 FROM metrics_summary WHERE service = 'auth-service' AND method = 'POST'",
"threshold": 1.5,
"window": "10m",
"interval": "1m",
"action": "send-email",
"contact": "[email protected]"
}
The pipeline evaluates the rule every minute and emits alerts to a alerts topic. The alerting system uses key=alert_name and value=alert_json for deduplication and replay.
The pipeline silently fails in many ways.
When the Kafka broker is down, the collector buffers metrics locally. If the buffer fills, it drops the oldest entries. If the buffer is full and the pipeline restarts, it reads from the last committed offset, but may miss events.
Stream processors must handle message reordering. A message with timestamp=2024-03-14T12:00:05Z may arrive after a message with timestamp=2024-03-14T12:00:03Z. The processor must use a watermark to track processed time and emit results based on event time, not processing time.
Batch jobs fail silently when the input directory is missing. The pipeline expects /data/processed/2024-03-14T12-00-00.json, but the previous job missed a batch. It logs No input file for 2024-03-14T12-00-00.json and skips the job.
Storage becomes a bottleneck when the metrics table grows beyond 100 million rows. Queries take seconds. The pipeline adds a partition on timestamp and service, and creates a GIST index on tags:
CREATE INDEX ON metrics (timestamp) WHERE timestamp >= '2024-03-14';
CREATE INDEX ON metrics USING GIST (tags);
When the metadata service is slow or unreachable, the enrichment step takes longer. The pipeline must track latency and emit a enrichment.latency metric to detect slow enrichments.
Finally, the pipeline must handle schema evolution. The collector may send a new value field as float instead of double. The pipeline must validate the schema and log schema mismatch errors. It uses a schema.json file to define expected fields, and a validate-metrics.sh script checks incoming data against it.
The pipeline design is complete when every failure is observable, every step is idempotent, and every component can be replaced without breaking the flow.
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