Summary#
Observability is how well you can understand what a running system is doing, and why, from the data it emits, without shipping new code to find out. It rests on three kinds of telemetry, often called the three pillars:
- Metrics are numbers aggregated over time: request rate, error rate, latency percentiles, CPU. They are cheap, fast to query, and ideal for dashboards and alerts. Prometheus and Grafana are the classic open-source pair.
- Logs are timestamped records of individual events. They are rich in detail, and best when structured (JSON with consistent fields), then shipped to a search store such as the ELK stack (Elasticsearch, Logstash, Kibana) or Grafana Loki.
- Traces follow one request across many services, as a tree of timed spans. OpenTelemetry is the standard way to produce them.
You turn telemetry into reliability goals with SLIs (what you measure), SLOs (the target, for example "99.9% of requests succeed within 300 ms over 30 days"), SLAs (the contract with penalties), and error budgets: 99.9% leaves about 43 minutes of failure per month. You alert on symptoms users feel, such as SLO burn rate, not on every cause. The four golden signals, the RED method (for services) and the USE method (for resources) tell you what to measure.
Why It Exists#
A single program on one machine can be debugged with a debugger and print statements. A modern system is dozens to thousands of services, containers that live for minutes, managed cloud components, queues, caches and third-party APIs. Failures in such systems are rarely "the server is down". They are partial and emergent:
- p99 latency doubles for users in one region;
- one tenant's queries time out;
- a retry storm starts after a deploy;
- a cache's hit rate falls slowly.
You can't attach a debugger to that. You need the system to tell you what's happening, all the time, in a form you can slice in ways you didn't predict.
The distinction between monitoring and observability is useful.
- Monitoring answers questions you knew to ask in advance: "Is CPU above 90%? Is the error rate above 1%?" It suits known unknowns.
- Observability lets you ask new questions during an incident, for unknown unknowns: "Which customers, on which app version, hitting which shard, see slow checkouts since 14:02?" That needs telemetry with rich context (high-cardinality attributes such as user ID, build version and shard), and tools that can slice it freely.
Both matter. Monitoring wakes you up, and observability helps you find the cause.
Observability also pays off outside incidents:
- in capacity planning, from trends in saturation;
- in performance work, where traces show where the time goes;
- in deploy safety, where canary analysis compares metrics between the old and new versions;
- in business insight, such as orders per minute or conversion;
- in security, through audit logs and anomaly detection.
How It Works#
Logs, metrics and traces#
Each pillar answers a different question, costs differently, and fails differently.
| Signal | What it is | Best for | Cost driver | Typical tools |
|---|---|---|---|---|
| Metrics | Numeric time series: name + labels + (timestamp, value) | Dashboards, alerting, trends, SLOs | Number of unique series (cardinality) | Prometheus, Mimir, Thanos, VictoriaMetrics, Datadog, CloudWatch |
| Logs | Timestamped event records (ideally structured) | Debugging specific events, audit, forensics | Volume: bytes per day ingested and stored | Elasticsearch/OpenSearch (ELK), Loki, Splunk, ClickHouse, CloudWatch Logs |
| Traces | Trees of spans for one request across services | Latency breakdown, dependency maps, cross-service debugging | Number of spans kept (sampling) | OpenTelemetry + Jaeger, Tempo, Zipkin, Honeycomb, X-Ray |
- Metrics compress many events into a few numbers. A service handling 50,000 requests per second exports
http_requests_totalas one counter per label combination, scraped every 15 seconds. Storage is constant per series, however many requests there are, so metrics are the cheapest signal per event, and the right thing to alert on. The price is lost detail. A metric tells you the error rate rose, not which request failed or why. - Logs keep the detail, at a cost per event. At 50,000 requests per second, one 500-byte log line per request is 25 MB/s, or about 2.2 TB per day before replication and indexing. That's why high-volume services log selectively (errors, slow requests, a sample), and keep only debug logs that can be switched on dynamically.
- Traces connect the dots across services. A trace shows that a 2-second checkout spent 1.7 seconds waiting on the inventory service's database call. Logs and metrics, separately, couldn't show that causal chain. Traces are usually sampled, because keeping every span from every request is expensive.
The pillars work best correlated:
- An alert fires on a metric.
- You click through from a latency spike on a dashboard to exemplars: sample trace IDs attached to histogram buckets.
- You open a slow trace.
- You jump from a span to the logs carrying the same
trace_id.
Making that path work, with shared resource attributes (service.name, deployment.environment, k8s.pod.name) and the trace ID in every log line, is most of the practical value of an observability platform.
Newer signals are sometimes added as further pillars:
- continuous profiling: CPU and memory flame graphs sampled across the whole fleet, with tools such as Pyroscope, Parca, or Google Cloud Profiler;
- events: deploys, configuration changes, feature-flag flips, drawn as annotations on graphs, because "what changed?" is the first question in most incidents;
- real-user monitoring (RUM): browser and mobile telemetry, including Core Web Vitals.
A different school, popularised by Honeycomb, argues for wide structured events: one rich event per request per service, with dozens of attributes, from which metrics and traces can be derived. Both views agree that context-rich, correlated telemetry beats three disconnected silos.
Logs, metrics and traces, in depth: cost, cardinality and what to emit where#
Cardinality is the number of unique time series. A metric http_requests_total{service, method, route, status} with 20 services, 5 methods, 50 routes and 10 status codes could produce up to 50,000 series. Add a user_id label with a million users, and it explodes to 50 billion. No metrics backend can hold that. Prometheus keeps each active series in memory, at roughly a few KB per series including indexes, so a few million active series per server is a practical ceiling. The rules:
- Bounded labels only on metrics: status class, route template (
/orders/{id}, not/orders/123), region, version. - Unbounded values (user ID, order ID, request ID, full URL, error message text) go in logs and traces, where they're stored per event rather than per series.
- Watch for accidental cardinality: labels taken from user input, pod names in clusters with heavy churn, and histogram buckets multiplied across many label combinations.
Which signal for which question:
| Question | Signal |
|---|---|
| Is the service healthy right now? Should I page someone? | Metrics (SLIs, burn rate) |
| Which dependency made this request slow? | Trace |
| What exactly happened to order 8812? | Logs (filtered by order ID), plus its trace |
| Which customers are affected? | High-cardinality events or traces grouped by tenant; logs |
| Is CPU or memory near limits? Do we need more capacity? | Metrics (USE) |
| Which function burns CPU in production? | Continuous profiling |
| Did the 14:02 deploy cause this? | Deploy events overlaid on metrics; canary comparison |
Cost control. Observability bills often grow faster than infrastructure, and it's common to hear of observability spend reaching a sizeable fraction of the infrastructure bill. The levers:
- drop or aggregate noisy metrics at the collector;
- set log levels per environment;
- sample traces, using tail-based sampling to keep errors and slow requests;
- tier storage: hot for 7–15 days, then cheaper object storage;
- set retention by value, for example metrics 13 months downsampled, debug logs 3 days, audit logs 1 year or more.
The goal is the useful telemetry, not all of it.
Structured logging and ELK#
A log is a record of something that happened. Unstructured logs look like this:
2026-12-02 14:03:11 ERROR Payment failed for order 8812 user 551 after 3 retries: timeoutThey're easy to write, and painful at scale. Searching means fragile regular expressions, fields aren't typed, and every team formats differently. Structured logging emits machine-readable records, usually JSON, with consistent field names:
{"ts":"2026-12-02T14:03:11.482Z","level":"error","service":"checkout",
"version":"2026.12.02-3","env":"prod","region":"eu-west-1",
"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7",
"event":"payment_failed","order_id":"8812","user_id":"551",
"attempts":3,"error_type":"timeout","dependency":"psp-adyen","duration_ms":3012}Now you can query event:payment_failed AND dependency:psp-adyen and group by error_type, or join to the trace. Good practice:
- Consistent schema across services, for example the OpenTelemetry semantic conventions or Elastic Common Schema (ECS):
service.name,trace_id,http.response.status_code. - Levels used with discipline. ERROR means someone may need to act. WARN means unexpected but handled. INFO marks business-significant events. DEBUG is off in production by default, but can be switched on per service or per request.
- Context propagated automatically: request ID, trace ID, tenant and user, added by middleware rather than by hand.
- Event names, not prose.
event: "payment_failed"is queryable; "Oops, something broke" isn't. - Never log secrets or raw PII: passwords, tokens, full card numbers, and often emails. Redact in the logging library, by field name and pattern (Security Fundamentals).
- Log to stdout in containers, and let the platform collect. Don't manage log files inside the app (a 12-factor principle).
Canonical log lines. Stripe popularised a simple addition to structured logging: besides normal log lines, every request emits one wide line at the end that summarises it. That line holds the method, path and status, the authenticated user and how they authenticated, rate limiter results, total time and time spent in the database, query counts, and team or permission data. Questions that would otherwise need a join across many lines become one filter, for example "which users are rate limited most" or "p99 latency of one customer's successful charges". The cost is one larger line per request, which is small next to the debug lines it often replaces. Because each line is a complete record of a request, canonical lines can also be loaded into a warehouse for long-term analysis. This is the same idea behind "wide events" in modern observability tools. See Stripe's engineering lessons for the full story.
The ELK stack is the classic centralised logging pipeline:
- Elasticsearch stores and indexes logs. It is a distributed search engine built on Lucene inverted indexes, so full-text and field queries take seconds across billions of documents.
- Logstash (or the lighter Beats/Fluent Bit/Fluentd/Vector agents) collects, parses and enriches logs: it parses unstructured lines with grok patterns, adds Kubernetes metadata, drops noise, and masks PII.
- Kibana is the UI for search, dashboards and alerts.
OpenSearch is the Apache-licensed fork of Elasticsearch and Kibana, maintained by AWS since 2021. A common production layout:
- Agents on each node (Fluent Bit as a DaemonSet) tail container stdout.
- They ship to Kafka, as a durable buffer that absorbs spikes and decouples producers from the store.
- Logstash or Vector consumers parse and enrich.
- Elasticsearch indexes into time-based indexes, managed by index lifecycle policies: hot, warm and cold tiers, then delete.
Structured logging and ELK, in depth: indexing cost, Loki's alternative and log pipelines at scale#
Why Elasticsearch gets expensive. Elasticsearch builds an inverted index over (by default) every field. That makes arbitrary search fast, but it multiplies storage: indexed logs often take 1–1.5× the raw size, plus replicas. Ingest also costs CPU. At 2 TB per day with one replica and 30 days' retention, you store about 120–180 TB on SSD-backed nodes. Mitigations:
- explicit mappings, which disable indexing on fields you never search;
keywordrather thantextfor identifiers;- index lifecycle management: roll over by size (say 50 GB shards), shrink and force-merge warm indices, move to cold or frozen tiers backed by object storage, and delete on schedule;
- keeping shard counts sane, because too many small shards overload the cluster's state.
Grafana Loki takes the opposite approach. It indexes only a small set of labels (service, namespace, level), stores log lines compressed in chunks on object storage, and brute-force scans the matching chunks at query time. That's much cheaper to ingest and store. The cost is that queries over large time ranges without selective labels are slower. It's a good fit for "show me checkout's errors in the last hour", and weaker for "search all logs for this string over 30 days". The same label-cardinality rules apply as for Prometheus.
Columnar log stores. ClickHouse-based systems treat logs as wide tables, compress them heavily with columnar encoding, and run fast SQL aggregations. Several companies have published moves of their logging to ClickHouse for cost. Columnar stores shine when you aggregate over logs ("count errors by error_type per minute") rather than doing needle-in-haystack text search.
Pipeline reliability. Logging must never take the application down. So:
- Write logs asynchronously, with bounded buffers. Drop, and count the drops, rather than blocking request threads when the pipeline is slow.
- Buffer in Kafka, so an Elasticsearch outage delays logs rather than losing them.
- Watch the pipeline itself: ingest lag, dropped events, parse failures. Lost logs are discovered at the worst time, during an incident.
Audit logs are different. Security and compliance logs need completeness and tamper resistance: append-only storage, separate access controls, and longer retention. Don't run them through the same lossy, sampled path as debug logs.
Log-based metrics. Counting log lines ("errors per minute") works, but it is a costly way to make metrics. Prefer emitting a counter in code, and use logs for detail. Keep log-derived metrics for systems you can't instrument, such as third-party appliances.
Metric types and Prometheus/Grafana#
A metric is a named time series, identified by its name plus a set of key-value labels, holding (timestamp, value) samples. In Prometheus notation: http_requests_total{service="checkout", route="/orders", status="500"} 1027. There are four core types, and each answers a different question.
- Counter: a value that only goes up, resetting to zero on restart. Examples are requests served, errors, bytes sent and jobs completed. You never graph the raw value. You graph its rate:
rate(http_requests_total[5m])gives requests per second, averaged over 5 minutes. The rate function handles resets automatically. - Gauge: a value that goes up and down. Examples are memory in use, queue depth, active connections, temperature and replica lag. You graph it directly, or with
max_over_timeandavg_over_time. - Histogram: counts observations into configurable buckets. For example, request durations go into ≤5 ms, ≤10 ms, ≤25 ms … ≤10 s, along with a total count and a sum. From the buckets you estimate percentiles at query time, aggregated across instances:
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))). Histograms are the right way to measure latency. - Summary: computes quantiles (such as p50 and p99) inside each client. It is accurate for that one instance, but summaries can't be aggregated. Averaging the p99 of 20 pods doesn't give the fleet's p99. Prefer histograms, unless you need exact per-instance quantiles.
Why percentiles, not averages. Latency distributions are skewed. Suppose 98 requests take 20 ms, and 2 take 2 seconds. The average is about 60 ms, which describes nobody's experience. The p99 is 2 seconds, which is what the slowest 1% of users actually feel. Users often make many requests per page, so tail latency compounds. If one page load fans out to 50 backend calls, each with a 1% chance of being slow, then 1 − 0.99⁵⁰ ≈ 39% of page loads hit at least one slow call. Dean and Barroso's "The Tail at Scale" (Communications of the ACM, 2013) made this argument famous. Track p50, p90, p99 and sometimes p99.9, alongside the rate and error rate.
Prometheus (started at SoundCloud in 2012, and the second CNCF project to graduate, after Kubernetes) is the de facto open-source metrics system.
- It scrapes (pulls) the
/metricsHTTP endpoints of targets every 15–60 seconds. It finds the targets through service discovery: Kubernetes, Consul, EC2 or static lists. - It stores samples in a local time-series database (TSDB).
- It evaluates recording rules, which precompute expensive queries, and alerting rules, which send to Alertmanager for grouping, deduplication, silencing and routing.
- It is queried in PromQL.
Grafana is the visualisation layer: dashboards over Prometheus, Loki, Tempo, Elasticsearch, cloud monitoring and SQL sources. It has variables (pick service or region), annotations (deploys) and alerting. A single Prometheus server is deliberately simple, with no clustering and no long-term storage. Thanos, Cortex/Mimir and VictoriaMetrics add global querying, high availability, multi-tenancy, and years of retention on object storage.
A minimal instrumentation and alert sketch: a histogram in TypeScript with prom-client, and an SLO burn-rate rule.
import client from "prom-client";
const httpDuration = new client.Histogram({
name: "http_request_duration_seconds",
help: "HTTP request latency",
labelNames: ["route", "method", "status_class"], // bounded labels only
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
});
export function instrument(route: string) { // route template, not raw URL
return (req: any, res: any, next: () => void) => {
const end = httpDuration.startTimer({ route, method: req.method });
res.on("finish", () => end({ status_class: `${Math.floor(res.statusCode / 100)}xx` }));
next();
};
}
// GET /metrics -> res.end(await client.register.metrics())Metric types and Prometheus, in depth: TSDB internals, histogram accuracy and scaling ingestion#
How a TSDB stores samples cheaply. Facebook's Gorilla paper (Pelkonen et al., "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015) introduced two compression tricks that Prometheus and others adopted:
- delta-of-delta encoding for timestamps: scrapes are regular, so most deltas-of-deltas are 0, which fits in 1 bit;
- XOR encoding for float values: consecutive values are similar, so the XOR has many leading and trailing zeros.
Together they bring a 16-byte (timestamp, value) pair down to about 1.37 bytes on average. Prometheus's TSDB has four parts:
- incoming samples go into an in-memory head block, protected by a write-ahead log;
- every 2 hours, immutable blocks are cut, holding compressed chunks plus an inverted index from label pairs to series IDs. That index is what makes
{service="checkout", status="500"}fast; - older blocks are compacted into larger ones;
- a full sample costs about 1–2 bytes on disk.
Sizing example (the monitoring-platform interview). 500,000 servers each emit 100 metrics every 10 seconds. That's 5 million samples per second, and 50 million active series. Sent over the wire as text or protobuf with labels, at 100–200 bytes per sample, ingest is roughly 0.5–1 GB/s. After TSDB compression, around 1.5 bytes per sample, storage is 5 × 10⁶ × 1.5 ≈ 7.5 MB/s, about 650 GB per day, or about 240 TB per year at full resolution. That's why downsampling is mandatory. Keep raw 10-second data for 15 days, 1-minute rollups for 90 days, and 1-hour rollups for 13 months. A query over "the last 30 days" then reads 720 hourly points per series, not 259,200 raw ones, and dashboards spanning weeks return in seconds. This is the same pre-aggregation idea as an ad-click aggregator's minute and daily tables. You trade storage for fast common queries, much like a cache. Store min, max, sum and count in each rollup, so averages and extremes stay correct, and percentiles are only approximate unless you keep histogram buckets.
Scaling ingestion.
- Shard series across ingesters by hashing the series labels, using consistent hashing (Mimir and Cortex use a hash ring).
- Replicate each series to 3 ingesters, for availability.
- Put a queue (Kafka) in front, for spikes and backend outages.
- Batch writes.
- Flush completed blocks to object storage, and query through store gateways.
- Separate the write path from the read path, so a heavy dashboard query can't slow ingestion. Use query frontends that split long ranges into day-sized sub-queries, run them in parallel, and cache the results.
Late and out-of-order data. Network delays and agent buffering mean samples arrive late. Classic Prometheus rejects samples older than the head block. Newer versions add a configurable out-of-order window. Streaming aggregators (Flink) use event time with watermarks, so a late sample still lands in the right minute bucket, and windows close only once the watermark passes. Pick a lateness bound, such as 2–5 minutes. Beyond it, drop and count, or route to a correction path.
Cardinality explosion protection. One bad deploy that adds a request_id label can create millions of series in minutes, and knock over the metrics backend for everyone. Defences:
- per-tenant and per-metric series limits at ingestion, rejecting new series beyond the limit;
- cardinality dashboards, showing the top metrics by series count;
- relabelling rules at the scraper or collector, to drop offending labels;
- CI linting of metric definitions.
Histogram accuracy. Bucketed histograms estimate a quantile by linear interpolation within its bucket. If p99 falls in the 250 ms–500 ms bucket, the reported value could be off by up to the bucket width. Choose buckets around your SLO threshold, so "is it below 300 ms?" is exact if 300 ms is a bucket boundary. Native, or exponential, histograms solve this differently. Prometheus native histograms, OpenTelemetry exponential histograms, and DDSketch (Masson, Rim and Lee, VLDB 2019) use exponentially spaced buckets with bounded relative error, for example ±1% accuracy across nanoseconds to hours, at low memory cost. They are mergeable across instances, unlike summaries. t-digest (Dunning) is another mergeable quantile sketch.
Push vs pull metrics collection#
There are two models for getting metrics from applications to the backend.
- Pull (scrape): the monitoring server periodically fetches metrics from each target's endpoint. This is the Prometheus model.
- Push: each application, or its local agent, sends metrics to a collector or gateway. Examples are StatsD, Graphite, InfluxDB line protocol, Datadog agents, CloudWatch, and OTLP push from OpenTelemetry.
| Aspect | Pull (Prometheus) | Push (StatsD, OTLP, Datadog agent) |
|---|---|---|
| Target discovery | Server must know targets (service discovery) | Targets just need the collector's address |
| Health signal | Failed scrape = target down (up == 0), for free | Silence is ambiguous: dead, or just quiet? |
| Short-lived jobs | Can miss them (job ends before scrape) | Natural fit: push before exit |
| Networks and firewalls | Server must reach every target (hard across NAT, edge devices, other networks) | Targets dial out; easy through firewalls |
| Load control | Server controls rate; targets can't flood it | A misbehaving client can flood the collector; needs rate limits |
| Debuggability | Open /metrics in a browser to see current values | Must inspect collector side |
| Resolution | Fixed scrape interval (15 s typical) | Can push per event or at custom intervals |
| Multiple consumers | Several servers can scrape the same target | Client must send to each, or a fan-out collector |
Neither is universally better. Typical answers:
- Pull inside a Kubernetes cluster, or a data centre with good service discovery.
- Push for serverless functions, batch jobs, mobile and IoT devices, and telemetry crossing networks or organisations (SaaS monitoring).
Prometheus handles batch jobs with the Pushgateway, which holds the last pushed values for scraping. Use it only for service-level batch results, not as a general push proxy. It never forgets stale series, and it becomes a single point of failure.
The modern convergence is OpenTelemetry. Applications push OTLP to a nearby Collector, often an agent on the same node, or a sidecar. The Collector can also scrape Prometheus endpoints, then batch, filter and forward to any backend. Prometheus itself now accepts pushes through remote_write receivers and OTLP ingestion.
Push vs pull, in depth: staleness, reliability and the hidden costs of each#
Staleness and liveness.
- With pull, a target that vanishes produces a failed scrape.
up == 0is an alert in itself, and Prometheus marks the series stale within one interval. - With push, you need explicit heartbeats, or "absent" alerts (
absent(rate(jobs_completed_total[15m]))), to notice a source that stopped reporting.
A subtle point: a dead service emits no errors. Alerts based only on error rates go quiet exactly when things are worst. Always pair them with liveness or traffic-floor alerts. Amazon is often cited for alerting on order flow in a way that's quick to fire. One approach is to measure time since the last order. At high volume that value is very stable, so a sudden gap is detectable within seconds. Designing such a metric is the art of making a symptom observable quickly.
Aggregation location. StatsD-style push sends raw events (one UDP packet per increment) to an aggregator, which flushes totals every 10 seconds. That's simple in the client, but packets can be lost, and the aggregator becomes a hotspot. Prometheus-style clients aggregate in process (a counter in memory), so scraping costs the same whatever the request volume. The OTel SDK aggregates in process too, then pushes the aggregates periodically. That's the best of both, and it's why it's the default for new instrumentation.
Delta vs cumulative temporality. Cumulative counters (Prometheus) survive lost scrapes: the next scrape still has the total, so the rate is just averaged over a longer window. Delta pushes (StatsD, some OTel exporters) lose data permanently if a push is lost, but they're cheaper for backends that are stateless per series. OTel lets you choose per exporter. Use cumulative unless the backend wants deltas.
Scale. Pull's scrape load is centralised. One Prometheus can scrape a few thousand targets with millions of series. Beyond that, you shard by target (hashmod relabelling) or use agents that scrape locally and push upward. In practice, hierarchical systems mix both: pull at the leaf, push to the aggregation tier.
Distributed tracing with OpenTelemetry#
A trace records the path of one request through the system. It is a tree of spans. Each span is one timed operation (an HTTP handler, a database query, a queue publish, a function) with:
- a trace ID, shared by all spans in the request;
- a span ID, plus its parent span ID;
- a name, start and end times, and a status (OK or error);
- attributes, such as
http.route,db.system,tenant.idandorder.id; - events, which are timestamped logs within the span;
- links to other traces, for example for batch consumers.
Looking at a trace's waterfall shows instantly where the time went, and which call failed.
Tracing works by context propagation. When service A calls service B, A sends the trace context in request headers: the W3C traceparent header (a W3C Recommendation since 2020), formatted version-traceid-parentspanid-flags. B continues the same trace, with its span as a child of A's. For asynchronous flows, the context is put into message headers (Kafka record headers, SQS message attributes), so consumers can continue or link the trace. Baggage carries additional key-values, such as tenant ID, across all downstream services.
OpenTelemetry (OTel) is the CNCF standard, formed in 2019 by merging OpenTracing and OpenCensus. It provides:
- APIs and SDKs in all major languages;
- auto-instrumentation for common frameworks (HTTP servers and clients, gRPC, database drivers, Kafka clients), so you get spans with no code changes;
- semantic conventions, which are standard attribute names;
- OTLP, the wire protocol;
- the Collector, which receives, processes (batching, sampling, redaction, enrichment with Kubernetes metadata) and exports to any backend: Jaeger, Grafana Tempo, Zipkin, Honeycomb, Datadog, AWS X-Ray, Elastic.
OTel covers metrics and logs as well as traces, so one instrumentation library and one pipeline handle all three signals, with shared resource attributes.
Distributed tracing, in depth: sampling, Dapper's lessons and tracing asynchronous systems#
Origins. Google's Dapper paper (Sigelman et al., "Dapper, a Large-Scale Distributed Systems Tracing Infrastructure", Google technical report, 2010) set out the design principles that every modern tracer follows: low overhead, application-level transparency through instrumentation in shared RPC libraries, ubiquitous deployment, and sampling. Twitter's Zipkin (2012) and Uber's Jaeger (2015–2017) were open-source descendants.
Sampling. Keeping every span is costly. A request touching 30 services, with 3 spans each, at 50,000 requests per second, produces 4.5 million spans per second. There are three strategies.
- Head-based sampling: decide at the root, for example keep 1%, and propagate the decision in the
traceparentflags, so the trace is complete or absent. It's cheap and simple, but it misses rare errors, and slow requests are mostly dropped. - Tail-based sampling: buffer all spans of a trace in the collector tier until it completes (say 10–30 seconds), then decide. Keep 100% of errors, 100% of traces over the SLO threshold, and 1% of the rest. That captures what matters. The cost is the collector memory and the routing: all spans of a trace must reach the same collector, using a load-balancing exporter keyed by trace ID.
- Adaptive or rate-limited sampling: keep N traces per second per endpoint, so rare endpoints still get traced, and hot ones don't dominate.
Overhead. Creating a span costs on the order of microseconds or less in most SDKs, and exporting is batched asynchronously. Overhead is usually a small percentage of CPU, unless you trace extremely fine-grained operations. Put spans around network calls, database queries and meaningful units of work, not every function.
Asynchronous and batch work. A Kafka consumer processing a batch of 500 messages, each from a different trace, can't be the child of 500 parents. OTel uses span links: the batch span links to each message's producing span. For long workflows (sagas, Temporal workflows), traces of hours are impractical. Use a business correlation ID (order ID) across separate traces, and workflow-engine histories.
What traces reveal that nothing else does:
- Critical path analysis: which spans actually determine end-to-end latency, compared with those running in parallel.
- Dependency maps: service graphs built from span parent-child relations, the live architecture diagram.
- Fan-out and N+1 problems: a span with 200 sequential database children is obvious in a waterfall, and invisible in aggregate metrics.
- Queueing delays: a gap between the client span ending its send and the server span starting points to queueing, or a saturated thread pool.
Span metrics. Collectors can derive RED metrics (rate, errors, duration per service and operation) from all spans before sampling, using the OTel spanmetrics connector, or Tempo's metrics generator. You keep accurate metrics, and sampled traces for detail.
SLIs, SLOs, SLAs and error budgets#
These four terms come from Google's Site Reliability Engineering practice (Beyer, Jones, Petoff and Murphy, eds., Site Reliability Engineering, O'Reilly, 2016, plus The Site Reliability Workbook, 2018). They turn "is the service reliable enough?" into numbers.
-
SLI (Service Level Indicator): a measured ratio of good events to valid events, as users experience them. Examples:
- Availability: the proportion of HTTP requests that return non-5xx:
good = status < 500,valid = all requests excluding health checks. - Latency: the proportion of requests faster than a threshold, for example under 300 ms. Note that this is a ratio, not an average.
- Freshness: the proportion of reads served data less than 1 minute old.
- Correctness, durability, throughput for pipelines: the proportion of records processed correctly within 10 minutes.
Measure as close to the user as you can. Load-balancer logs or client RUM beat server-side metrics, which miss requests that never arrived.
- Availability: the proportion of HTTP requests that return non-5xx:
-
SLO (Service Level Objective): the target for an SLI over a window. For example, "99.9% of checkout requests succeed, and 99% complete under 300 ms, measured over a rolling 28 days." The SLO is an internal goal, set by product and engineering together.
-
SLA (Service Level Agreement): a contract with customers, with consequences, usually service credits, if it's missed. For example: "99.9% monthly uptime, or 10% credit." SLAs should be looser than SLOs, so you fix problems before they cost money. Many internal services have SLOs but no SLA.
-
Error budget: the allowed unreliability, 1 − SLO. A 99.9% SLO leaves a 0.1% budget, and the team may "spend" it on deploys, experiments, migrations and inevitable failures. The budget changes the conversation, from "never fail" to "how fast can we move while staying within the budget?"
The worked example (99.9% ≈ 43 minutes per month). A 30-day month has 30 × 24 × 60 = 43,200 minutes. A 99.9% availability SLO allows 0.1% of that: 43,200 × 0.001 = 43.2 minutes of full downtime per month. Equivalently, it allows 0.1% of requests to fail. At 1,000 requests per second, that's 2.592 billion requests per month, of which 2.59 million may fail.
| SLO | Budget per 30 days | Per year (approx.) | What it implies |
|---|---|---|---|
| 99% | 7.2 hours | 3.65 days | Manual recovery is OK; single region fine |
| 99.5% | 3.6 hours | 1.8 days | On-call during business hours plus alerts |
| 99.9% | 43.2 minutes | 8.8 hours | 24×7 on-call, automated rollback, multi-AZ |
| 99.95% | 21.6 minutes | 4.4 hours | Fast detection (minutes), no single points of failure |
| 99.99% | 4.3 minutes | 53 minutes | Automated failover, multi-region; humans are too slow to be in the loop |
| 99.999% | 26 seconds | 5.3 minutes | Very expensive; rarely justified outside core infrastructure |
The availability of dependencies multiplies. A service that depends on three others, each at 99.9%, can't exceed about 99.7% without redundancy or graceful degradation (High Availability Design).
Error budget policy. The budget only matters if it changes behaviour, so agree a written policy.
- When the budget is healthy, ship freely, and run chaos experiments.
- When more than 50% is burned early in the window, slow risky changes, and prioritise reliability fixes.
- When it's exhausted, freeze feature releases, except fixes, until the budget recovers.
- A single incident that consumes more than 20% of the budget requires a postmortem.
This aligns developers, who want velocity, with operators, who want stability, through one shared number.
SLIs, SLOs and error budgets, in depth: choosing targets, burn-rate maths and pitfalls#
Choosing a target. Don't pick 99.99% because it sounds good. Look at:
- what users notice: consumer apps often tolerate brief errors, and mobile networks are themselves far less reliable than 99.9%;
- historical performance: set the first SLO near what you already achieve, then tighten;
- cost: each extra nine roughly multiplies engineering and infrastructure effort;
- dependencies: you can't be more reliable than your critical path, without redundancy.
Different user journeys deserve different SLOs. Checkout might get 99.95%, search 99.9%, and recommendations 99%, because they can degrade gracefully.
Burn rate. Burn rate is how fast you consume the budget, relative to spending it evenly over the window. At burn rate 1, you use exactly 100% of the budget by the end of the window. For a 99.9% SLO, a 1.44% error rate is a burn rate of 14.4: you'd exhaust a 30-day budget in about 2 days, and burn 2% of it per hour. The SRE Workbook recommends multi-window, multi-burn-rate alerts:
| Severity | Burn rate | Long window | Short window | Budget consumed when it fires |
|---|---|---|---|---|
| Page | 14.4× | 1 hour | 5 minutes | 2% |
| Page | 6× | 6 hours | 30 minutes | 5% |
| Ticket | 1× | 3 days | 6 hours | 10% |
The long window gives significance, so a 30-second blip doesn't page. The short window makes the alert reset quickly once the problem is fixed. Both must exceed the threshold. In PromQL, with recording rules for error ratios:
- alert: CheckoutErrorBudgetFastBurn
expr: |
(job:slo_errors_ratio:rate1h{service="checkout"} > (14.4 * 0.001))
and
(job:slo_errors_ratio:rate5m{service="checkout"} > (14.4 * 0.001))
labels: { severity: page }
annotations:
summary: "Checkout burning error budget 14.4x (2% per hour)"
runbook: "https://runbooks.internal/checkout/error-budget"Low-traffic services. At 10 requests per minute, one failure is 10% for that minute, so burn-rate alerts become noisy. Options:
- longer windows;
- synthetic traffic (probes) to add volume;
- combining small services into one SLO;
- alerting on absolute counts ("more than 5 failures in 10 minutes").
Common SLO mistakes:
- measuring at the server, so requests dropped by the load balancer go uncounted;
- averaging latency instead of using threshold ratios;
- "time-based" availability (minutes up), which hides partial outages that affect 5% of users;
- too many SLOs, more than about 3–5 per service, so none gets attention;
- SLOs with no error-budget policy;
- calendar-month windows that "reset" reliability debt. Rolling windows are generally better for operations, and calendar windows match SLA reporting.
Request-based versus time-based. "99.9% of requests" weights by traffic, so an outage at peak costs more budget than one at 3 a.m., matching user impact. "99.9% of minutes good" is simpler to explain, and common in SLAs. Know which your SLA uses.
Alerting on symptoms#
An alert should page a human only when users are, or soon will be, hurting, and a human needs to act. Everything else is a ticket, a dashboard or a log. The classic failure is the opposite: hundreds of alerts on causes ("CPU > 80%", "disk 70% full", "one pod restarted") that fire constantly without user impact. On-call engineers learn to ignore them (alert fatigue), and then miss the real one.
- Symptoms are what users experience: errors, latency, unavailability, stale data, failed jobs. Alert on these, ideally through SLO burn rate. One symptom alert covers every cause, including ones you never predicted.
- Causes are why: high CPU, a full disk, a dead replica, an exhausted connection pool. Show these on dashboards, and use them while diagnosing. Alert on a cause only when it predicts imminent user impact that a symptom can't catch in time. For example, "the disk will be full in 4 hours at the current rate" (
predict_linear), certificate expiry, or a backup job that hasn't succeeded in 26 hours.
Rules that make alerting work:
- Every page is actionable and urgent. If the response is "wait and see", it isn't a page.
- Every alert has a runbook link: what it means, the dashboards, the likely causes, the mitigations (roll back, fail over, scale).
- Route by ownership. The team that owns the service gets the page. Use severity levels: page, ticket, info.
- Group and deduplicate. Alertmanager groups 200 pod alerts into one notification, and inhibition suppresses downstream alerts when an upstream one, such as "database down", is already firing.
- Track alert quality. Count pages per on-call shift. Google's SRE book suggests no more than about two incidents per 12-hour shift, so each can be handled properly. Review every page: was it actionable? Delete or tune the noisy ones.
- Test alerts. An alert that has never fired may be broken. Check expressions with unit tests (
promtool test rules), and with game days. - Alert on the absence of data for critical signals. If a service stops reporting, symptom alerts go silent too.
Golden signals, RED and USE methods#
Three checklists tell you what to measure, so every service gets a consistent baseline.
The four golden signals (from Google's SRE book), for any user-facing system:
- Latency: time to serve requests. Track successful and failed requests separately, because fast errors can make latency look better.
- Traffic: demand, such as requests per second, sessions, or messages per second.
- Errors: the rate of failed requests, whether explicit (5xx), implicit (a 200 with the wrong content), or policy-based (slower than the SLO counts as failure).
- Saturation: how "full" the service is, measured on the most constrained resource (CPU, memory, thread pools, queue depth). Saturation often predicts trouble before latency rises.
RED (Tom Wilkie, around 2015), for request-driven services. For each service and endpoint, measure:
- Rate: requests per second;
- Errors: failed requests per second, or the ratio;
- Duration: the latency distribution, as a histogram.
RED is the golden signals without saturation. It's easy to standardise: give every microservice a RED dashboard from the same template, and generate it automatically from span metrics or a service mesh (Istio and Linkerd emit RED for every service, with no code changes).
USE (Brendan Gregg, around 2012), for resources: CPUs, memory, disks, network interfaces, and also software resources such as thread pools, connection pools, locks and queues. For each resource, measure:
- Utilisation: the percentage of time busy, or the share of capacity used;
- Saturation: extra work waiting, such as run-queue length, swap, a pool's wait queue, or TCP backlog;
- Errors: device or operation errors, such as disk I/O errors, network drops and allocation failures.
USE is systematic for performance investigations. Walk every resource, check the three, and the bottleneck usually reveals itself.
| Method | Applies to | Measures | Use it for |
|---|---|---|---|
| Golden signals | User-facing services | Latency, traffic, errors, saturation | Top-level service health, SLO-adjacent dashboards |
| RED | Every request-driven microservice | Rate, errors, duration | Standard per-service dashboards, per-endpoint drill-down |
| USE | Hardware and software resources | Utilisation, saturation, errors | Capacity planning, bottleneck hunting, infrastructure dashboards |
How they fit together. An SLO burn alert (a symptom) pages you. The service's RED dashboard shows which endpoint has rising duration. Its trace shows time spent waiting for a database connection. The USE view of the connection pool shows 100% utilisation and a growing wait queue: saturation, the cause. The database's USE dashboard shows disk I/O saturation from a new unindexed query that came with the deploy at 14:02.
Front-end and website performance metrics. For web pages, the user-facing signals are Core Web Vitals, measured through RUM:
- LCP (Largest Contentful Paint), good at 2.5 s or less;
- INP (Interaction to Next Paint), which replaced FID in 2024, good at 200 ms or less;
- CLS (Cumulative Layout Shift), good at 0.1 or less.
They're assessed at the 75th percentile of page loads. Related metrics include TTFB (time to first byte), FCP (first contentful paint), page weight, request counts, and JavaScript error rate. Server metrics can be perfect while users suffer from slow third-party scripts or large images. Only client-side telemetry shows that.
Golden signals, RED and USE, in depth: saturation, queueing and the latency knee#
Why saturation matters most. From queueing theory, in an M/M/1 queue, the mean time in the system is 1 / (μ − λ). As utilisation ρ = λ/μ approaches 1, latency grows like 1 / (1 − ρ). At 50% utilisation, requests wait on average as long as their service time. At 90%, ten times the service time. At 95%, twenty times. That knee is why latency often looks fine until it suddenly isn't, and why alerts on rising saturation (queue depth, pool wait time) give earlier warning than latency itself. A target of 60–70% utilisation for latency-sensitive services leaves headroom for spikes and failover. Remember that losing one of three zones moves 33% more load onto the remaining two.
Utilisation lies when sampled coarsely. A CPU at "40% averaged over 1 minute" might be at 100% for 400 ms bursts every second, throttling a container under CFS quotas. Watch the throttling metrics (container_cpu_cfs_throttled_periods_total) in Kubernetes. Similarly, average disk utilisation hides I/O queue spikes. USE saturation metrics (queue lengths, throttling, waits) catch what utilisation averages miss.
Errors that don't look like errors:
- HTTP 200s with an error payload;
- empty search results caused by a failed backend;
- timeouts that clients retried successfully, which hide real failures and add load;
- degraded responses, such as serving fallbacks.
Instrument degraded responses as their own counter, so graceful degradation doesn't make the system look healthy while users get worse results (Resilience Patterns).
Business metrics as the ultimate symptom. Orders per minute, logins per minute, messages delivered and payments succeeded are often the best signals of all, because they integrate every failure mode. Compare against the same time last week, with seasonality bands, because a 30% drop at 2 p.m. on a Tuesday is an incident even if every technical metric is green.
Observability in practice: dashboards, incidents and cloud-native tools#
Dashboards that help. Build dashboards in layers:
- An SLO overview: each user journey's SLI, its budget remaining, and its burn rate.
- Per-service RED dashboards, from a shared template, with deploy annotations.
- USE dashboards for infrastructure and datastores.
- Debug dashboards for deep dives.
Put the most important signal top-left. Show rates and percentiles, not raw counters. Always use the same time axis across panels, and link to the matching logs and traces. A wall of 80 panels nobody understands is worse than six that answer "is it broken, where, and since when?" Keep dashboards as code (Grafana JSON or Jsonnet, Terraform), reviewed like any other change.
During an incident, telemetry supports a standard loop:
- detect: an alert, measured by MTTD, the mean time to detect;
- triage: impact and scope from the SLO and business metrics;
- localise: RED across services, the trace waterfall, the service map;
- check what changed: deploys, configuration and feature-flag events;
- mitigate: roll back or fail over, before full diagnosis;
- diagnose and fix, measured by MTTR, the mean time to recover or restore;
- review: a blameless postmortem.
The fastest mitigation is usually reverting the most recent change. That's why deploy markers on every graph, and one-click rollback, are among the highest-value observability investments (CI/CD and Deployment).
Health checks are telemetry too. Liveness probes (should the process be restarted?) and readiness probes (should it receive traffic?) feed orchestrators and load balancers (Containers and Kubernetes). Synthetic monitoring, or black-box probes, exercises real user flows from outside, every minute, from several regions: log in, search, add to cart. It catches DNS, certificate, CDN and routing failures that internal metrics can't see.
Cloud-native monitoring services.
| Concern | AWS | Google Cloud | Azure |
|---|---|---|---|
| Metrics and alarms | CloudWatch Metrics and Alarms; Amazon Managed Service for Prometheus | Cloud Monitoring; Managed Service for Prometheus | Azure Monitor Metrics; Managed Prometheus |
| Logs | CloudWatch Logs; OpenSearch Service | Cloud Logging | Azure Monitor Logs (Log Analytics) |
| Traces | AWS X-Ray; ADOT (AWS Distro for OpenTelemetry) | Cloud Trace | Application Insights |
| Dashboards | CloudWatch dashboards; Amazon Managed Grafana | Cloud Monitoring dashboards | Azure Workbooks; Managed Grafana |
| Audit trail | CloudTrail | Cloud Audit Logs | Activity Log |
Managed services are quick to start, and integrate with the platform's own services. Their costs scale with custom metrics, log ingestion and queries, so model them early. OpenTelemetry instrumentation keeps you portable between vendors and open-source backends.
Observing AI and LLM features. LLM-backed services and agents need extra telemetry:
- per call: tokens in and out, model and version, latency to the first token and in total, and cost;
- for agents: tool-call spans (which tool, arguments, outcome), retries and refusals;
- quality signals: user feedback and evaluation scores.
OpenTelemetry has published GenAI semantic conventions for these spans and metrics. Prompts and responses can contain PII, so capture them only with redaction and strict retention.
When to Use It#
Every production system needs observability. The question is how much, and which signals to invest in first. Concrete signals:
- Any production service: RED metrics, structured logs with request IDs, liveness and readiness checks, and at least one symptom-based alert, on error rate or latency against an SLO. That's the minimum, even for a single service.
- More than a handful of services, or any synchronous call chain three or more hops deep: add distributed tracing. Debugging latency across services without it means guessing. Auto-instrumentation makes the cost low.
- A customer-facing availability commitment (a 99.9% SLA, enterprise contracts): formal SLIs and SLOs, error-budget policy, burn-rate alerts, synthetic probes, and SLO reporting.
- Large fleets (thousands of hosts or pods, millions of series): a scalable metrics backend (Mimir, Thanos, VictoriaMetrics, or a SaaS), cardinality limits, recording rules and downsampling.
- High log volume (more than about 1 TB per day): a log pipeline with buffering (Kafka), sampling, tiered retention, and possibly Loki or ClickHouse instead of fully indexed search for everything.
- Multi-tenant platforms: tenant ID in traces and logs, and per-tenant SLIs for large customers, so you can answer "is customer X affected?"
- Regulated environments: audit logging with tamper resistance and long retention, plus PII redaction in all telemetry.
When NOT to Use It#
Observability isn't "collect everything". Over-collection has costs: money, performance, noise and privacy risk.
- Don't put unbounded identifiers in metric labels. User IDs, request IDs and raw URLs belong in logs and traces.
- Don't trace every function, or log every request at INFO, on high-volume paths. At 100,000 requests per second, that is terabytes per day of mostly useless data. Sample, and log errors and slow requests.
- Don't build your own metrics database or tracing backend unless observability is your product, or your scale truly demands it, as at Uber (M3) or Netflix (Atlas). Prometheus, Grafana's stack, or a SaaS will do.
- Don't alert on every cause metric. CPU at 85% on one pod isn't a page. A dashboard is enough.
- Don't adopt a full mesh or eBPF platform just for telemetry on a small system. Library instrumentation is simpler.
- Don't make SLOs for everything. Internal batch tools with one user may need only a failure alert.
- Don't keep everything forever. Debug logs from 18 months ago rarely help, and they increase breach and compliance exposure.
How to Implement It#
- Define what "working" means. List the critical user journeys (log in, search, checkout), and write one or two SLIs for each, with an SLO and an error-budget policy.
- Instrument with OpenTelemetry. Use auto-instrumentation for HTTP, gRPC, database and messaging clients. Add a few manual spans and attributes for business operations (tenant, order ID). Set resource attributes:
service.name,service.version,deployment.environment. - Emit RED metrics for every service and endpoint, using histograms with buckets around your SLO threshold. Add USE metrics for pools and queues. Use node and kube-state exporters for infrastructure.
- Use structured JSON logs to stdout, with the trace ID and span ID injected automatically, levels used with discipline, and PII redaction in the logger.
- Deploy a collection tier: an OTel Collector as an agent DaemonSet plus a gateway deployment; Fluent Bit for logs; Kafka as a buffer at scale. Batch, filter, sample (tail-based) and enrich there.
- Choose backends: Prometheus with Mimir or Thanos for metrics, Loki or Elasticsearch for logs, Tempo or Jaeger for traces, and Grafana on top. Or choose one SaaS platform. Set retention and downsampling.
- Write alerts: multi-window burn-rate pages for each SLO; absence and heartbeat alerts; a few predictive cause alerts (disk fill, certificate expiry, backup age). Each has a runbook. Route them through Alertmanager to PagerDuty or Opsgenie.
- Build dashboards as code: the SLO overview, RED per service, USE per resource, with deploy annotations.
- Add synthetic probes for key journeys from several regions, and RUM for web and mobile.
- Operate it: review pages weekly, prune noisy alerts and unused metrics, watch cardinality and cost, run game days, and practise the incident loop.
A minimal OpenTelemetry Collector pipeline: it receives OTLP, keeps errors and slow traces, and exports to metrics, logs and trace backends.
receivers:
otlp: { protocols: { grpc: {}, http: {} } }
processors:
memory_limiter: { check_interval: 1s, limit_percentage: 80 }
k8sattributes: {}
batch: { send_batch_size: 8192, timeout: 5s }
tail_sampling:
decision_wait: 10s
policies:
- { name: errors, type: status_code, status_code: { status_codes: [ERROR] } }
- { name: slow, type: latency, latency: { threshold_ms: 500 } }
- { name: baseline, type: probabilistic, probabilistic: { sampling_percentage: 2 } }
connectors:
spanmetrics: {} # RED metrics from 100% of spans, before sampling
exporters:
otlphttp/tempo: { endpoint: "http://tempo:4318" }
prometheusremotewrite: { endpoint: "http://mimir/api/v1/push" }
otlphttp/loki: { endpoint: "http://loki:3100/otlp" }
service:
pipelines:
traces/in: { receivers: [otlp], processors: [memory_limiter, k8sattributes], exporters: [spanmetrics] }
traces: { receivers: [otlp], processors: [memory_limiter, k8sattributes, tail_sampling, batch], exporters: [otlphttp/tempo] }
metrics: { receivers: [otlp, spanmetrics], processors: [memory_limiter, batch], exporters: [prometheusremotewrite] }
logs: { receivers: [otlp], processors: [memory_limiter, k8sattributes, batch], exporters: [otlphttp/loki] }| Technology | Fits when |
|---|---|
| Prometheus | Pull-based metrics in Kubernetes or data centres; PromQL alerting; up to a few million series per server |
| Grafana Mimir / Thanos / Cortex | Long-term, highly available, multi-tenant Prometheus-compatible storage on object storage |
| VictoriaMetrics | Prometheus-compatible, resource-efficient storage at high ingest rates |
| Grafana | Dashboards across many data sources, alerting, correlation between metrics, logs and traces |
| Elasticsearch / OpenSearch (ELK) | Full-text log search, security analytics, flexible ad-hoc queries; budget for indexing cost |
| Grafana Loki | Cheap log storage, label-indexed; queries scoped by service and time |
| ClickHouse | Columnar store for logs and events at scale with SQL aggregations |
| OpenTelemetry SDKs + Collector | Vendor-neutral instrumentation and pipelines for all three signals |
| Jaeger / Grafana Tempo / Zipkin | Open-source trace storage and UI; Tempo stores traces cheaply on object storage |
| Datadog / New Relic / Honeycomb / Dynatrace | SaaS: fast start, unified UI, high-cardinality analysis (Honeycomb); cost grows with volume |
| Alertmanager + PagerDuty / Opsgenie | Alert grouping, inhibition, routing, on-call schedules and escalation |
| Pyroscope / Parca | Continuous profiling to find CPU and memory hotspots in production |
| Fluent Bit / Vector / Fluentd | Lightweight log collection, parsing and routing agents |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Pull (scrape) | Free liveness, server controls load, easy debugging | Needs discovery and network reach; misses short jobs | Kubernetes or data-centre services |
| Push (agent or OTLP) | Works through NAT, for serverless and short jobs | Silence is ambiguous; clients can flood collectors | Serverless, batch, edge, SaaS backends |
| Self-hosted open source (Prometheus, Grafana, Loki, Tempo) | Low licence cost, full control, no vendor lock-in | You operate scaling, upgrades, HA and storage | Platform team exists; large scale where SaaS is costly |
| SaaS (Datadog and others) | Fast start, polished UX, managed scale | Cost grows with hosts, metrics, logs and spans; data leaves your environment | Small to mid teams; speed over cost |
| Full-text indexed logs (ELK) | Arbitrary search over any field | Storage and CPU heavy | Security, forensics, unpredictable queries |
| Label-indexed logs (Loki) | Very cheap ingestion and storage | Slow broad searches | Service-scoped debugging at high volume |
| Head-based trace sampling | Simple, cheap, complete traces | Misses rare errors and slow requests | Low to moderate traffic, starter setups |
| Tail-based trace sampling | Keeps the interesting traces | Collector memory, routing by trace ID | High traffic where errors are rare |
| Histograms | Aggregatable percentiles | Bucket-width error; cardinality × buckets | Latency SLIs across fleets |
| Summaries | Exact per-instance quantiles | Not aggregatable | Single-instance or per-process analysis |
| Raw high-resolution retention | Full detail for investigations | Storage grows linearly | Recent window (days to weeks) |
| Downsampled rollups | Fast long-range queries, cheap storage | Lose spikes and exact percentiles | Long-term trends, capacity planning |
Common Pitfalls#
- Alerting on causes, not symptoms. This creates alert fatigue, and still misses unanticipated failures.
- Averages for latency. Use percentiles from histograms, or threshold ratios as SLIs.
- Averaging percentiles across instances, or from summaries. That's mathematically wrong. Aggregate histogram buckets, then compute the quantile.
- Cardinality explosions from user IDs, request IDs, raw paths or error strings as labels. They take down the metrics backend for everyone.
- No trace ID in logs, so you can't jump from a slow trace to its logs, or the other way.
- Logging secrets and PII, which makes every log store a breach target and a GDPR problem.
- Silent failure: a dead service emits no errors. Alert on missing data, missing traffic, and
up == 0. - Monitoring that shares fate with what it monitors: alerting running in the same cluster or region that fails. Run meta-monitoring (a "dead man's switch" alert that always fires, and pages if it stops arriving) from outside.
- Dashboards nobody owns, with stale queries and 80 panels. No deploy annotations.
- Synchronous log shipping that blocks request threads when the pipeline is slow.
- SLOs without an error-budget policy, or SLAs tighter than SLOs.
- Only server-side metrics, blind to client, CDN, DNS and third-party script failures. Add synthetic probes and RUM.
Real-World Examples#
- Google formalised SLOs, error budgets, the four golden signals and symptom-based alerting in its SRE books (2016, 2018). Its Dapper paper (2010) defined modern distributed tracing, and Borgmon, its internal monitoring system, inspired Prometheus.
- Facebook's Gorilla (VLDB 2015) showed in-memory TSDB compression to about 1.37 bytes per sample, which shaped Prometheus's storage engine.
- SoundCloud created Prometheus in 2012. It joined the CNCF in 2016, and graduated in 2018.
- Uber built Jaeger for tracing (later donated to the CNCF), and M3 for metrics at very high cardinality and volume.
- Netflix built Atlas, an in-memory dimensional time-series system for operational metrics, and uses canary analysis that compares metrics between baseline and canary clusters before rolling out (Kayenta, open-sourced with Google in 2018).
- Twitter built Zipkin (2012), following Dapper.
- Amazon Prime Video wrote in 2023 about re-architecting its audio and video quality monitoring tool. It moved from distributed serverless components (Step Functions and Lambda) to a single process on ECS, which reduced that tool's infrastructure cost by about 90%. It's a reminder that monitoring pipelines are systems with their own cost and scaling trade-offs.
- Honeycomb popularised high-cardinality, event-based observability, and the "observability vs monitoring" framing (Majors, Fong-Jones and Miranda, Observability Engineering, O'Reilly, 2022).
Case studies that use this pattern#
- Metrics Monitoring Platform: ingesting millions of samples per second, TSDB storage, downsampling, alert evaluation and cardinality limits.
- Ad Click Aggregator: stream aggregation with event time and watermarks, pre-aggregated rollups for fast queries.
- Distributed Message Queue: consumer-lag and throughput SLIs, broker USE metrics.
- Payment System: business-metric alerting (payment success rate), audit logs, tracing across processors.
- Job Scheduler: heartbeat and absence alerts, freshness SLIs for scheduled work.
In the Interview#
Deep Dive: Designing a metrics monitoring platform at 5M samples per secondShow
Requirements recap. Ingest metrics (CPU, memory, latency, custom counters) from 500,000 servers. Dashboards with filters, aggregations and time ranges return in seconds, even over weeks. Alert rules ("p99 latency over 500 ms for 5 minutes") fire within a minute of emission. Notifications go to email, Slack and PagerDuty. The system is highly available, with eventual consistency acceptable for dashboards but reliable alerting. It handles late and out-of-order data.
Ingestion path. Agents on each host aggregate locally, and push batches every 10 seconds (compressed protobuf, around 10–20 KB per batch) to a stateless ingest gateway fleet behind a load balancer. The gateway authenticates, validates and enforces cardinality and rate limits, then writes to Kafka, partitioned by a hash of (tenant, metric, labels). At 5 million samples per second and about 150 bytes each, uncompressed, that's 750 MB/s. With compression (about 5×) and replication factor 3, Kafka sees roughly 450 MB/s of disk writes across the cluster, which fits a modest cluster of a few dozen brokers. Kafka absorbs spikes (a deploy restarting 100,000 hosts at once) and backend outages, so agents never block.
Storage. Ingesters consume their partitions, and hold the head of each series in memory (Gorilla-encoded chunks with a write-ahead log). With 50 million active series at about 4 KB of memory each, including the index, that's around 200 GB. Spread over 30 ingesters with replication factor 3, each holds about 20 GB. Every 2 hours, ingesters cut immutable blocks to object storage. Compactors merge blocks, deduplicate replicas, and produce downsampled 1-minute and 1-hour blocks, storing min, max, sum and count. Store gateways serve old blocks, with an index cache.
Query path. A query frontend parses PromQL-like queries, splits long ranges by day, serves cached results for completed days, and fans out to the ingesters (recent data) and store gateways (old data). It enforces per-tenant limits on series touched and samples scanned. It also chooses resolution: a 30-day panel at 1,000 pixels wide needs only about one point per 43 minutes, so it reads the 1-hour rollups. Recording rules precompute hot aggregations, such as the per-service p99, every 30 seconds.
Alerting path. The rule evaluators are separate from dashboard queriers, so heavy dashboard load can't delay alerts. They evaluate rules every 15–30 seconds against ingesters' recent data, and keep "for 5 minutes" pending state durably, so a restart doesn't reset timers. To get alert latency well under a minute, evaluate in a stream processor that consumes Kafka directly, keeping windowed state per rule, with event time and watermarks. Bound lateness to, say, 30 seconds. Then treat a late sample as "unknown", rather than a silent drop, for alert purposes. Alert state changes go to a notification service, which deduplicates by alert fingerprint, groups, applies silences and inhibitions, routes by team, and delivers at least once, with retries per channel and escalation if a page isn't acknowledged.
Availability and failure modes.
- An ingester crash is covered by RF = 3 and WAL replay.
- A Kafka partition backlog shows up as consumer lag, which is itself an alert.
- Evaluator failure: run two evaluators per rule shard, with deduplication downstream.
- Cardinality bomb: a new series is rejected at the gateway once the tenant's limit is exceeded, and the tenant is told.
- The monitor's own monitor: an independent, minimal stack in another region watches the platform, with a dead man's switch alert.
Cost levers. Downsampling (raw kept 15 days), aggressive compression, object storage for blocks, per-tenant quotas, and dropping unused metrics, found from query logs showing which series are never read.
Deep Dive: The mathematics of SLOs, burn rates and alert precisionShow
Budget arithmetic. For an SLO of target T over a window W, the error budget is (1 − T) × W of "bad time", or (1 − T) × N bad events out of N. With a burn rate b sustained for time t, the fraction of budget consumed is b × t / W. The SRE Workbook's 14.4× page derives from wanting a page when 2% of a 30-day budget is consumed within 1 hour: b = 0.02 × 720 h / 1 h = 14.4. For 5% in 6 hours, b = 0.05 × 720 / 6 = 6. For 10% in 3 days, b = 0.10 × 720 / 72 = 1.
Detection time versus precision. With a burn-rate threshold b and window w, an outage of total failure, where the error rate is 100% and the burn rate is 1/(1 − T) = 1,000 for 99.9%, triggers once the windowed average exceeds b × (1 − T). That takes w × b × (1 − T) = 1 h × 14.4 × 0.001 ≈ 52 seconds, plus the evaluation interval. A partial outage at a 2% error rate (burn 20) takes 1 h × 14.4/20 ≈ 43 minutes to cross a 1-hour average. That's why the short window exists alongside it: it stops the alert firing on a recovered problem still dragging the long average. There's also a 6-hour, 6× tier to catch slower burns. Lower thresholds catch more, but page on noise. Longer windows are more precise, but slower to detect, and slower to reset.
Composing SLOs across dependencies. A request that serially requires services with availabilities a₁…aₙ has availability at most ∏ aᵢ. Five dependencies at 99.95% give 0.9995⁵ ≈ 99.75%. Redundancy changes the picture: two independent replicas at 99% give 1 − 0.01² = 99.99%. Independence is the key assumption, and it's violated by shared deploys, configuration, regions and bugs. Correlated failures dominate real outages.
Latency SLO composition. Latencies don't compose by percentile. The p99 of a sum isn't the sum of the p99s, and a fan-out to k parallel backends makes the request as slow as the slowest. For k = 100 backends with independent latencies, the request's median is around each backend's p99.3, since 0.993¹⁰⁰ ≈ 0.5. This is the tail-at-scale effect. Mitigations are hedged requests, tied requests, and partial results (Dean and Barroso, 2013).
Statistical noise for small samples. With n requests in a window and a true error rate p, the observed rate's standard deviation is sqrt(p(1−p)/n). For a 99.9% SLO, alerting at 14.4× needs an observed rate above 1.44%. With n = 300 requests (5 minutes at 1 per second), a single error is 0.33%, and five errors, 1.67%, trigger it. Random clusters of five errors aren't rare at that volume. Low-traffic services need longer windows, synthetic traffic, or a minimum-count condition (and errors > 10).
Deep Dive: High-cardinality observability, exemplars and eBPFShow
The cardinality dilemma. Metrics are cheap because they aggregate away identity. But incidents are often about specific identities: one tenant, one app build, one availability zone, one shard. There are three approaches.
- Keep metrics low-cardinality, and put identities in traces and logs, with exemplars linking the two. An exemplar attaches a trace ID to a histogram bucket observation, so a click on a spike in the p99 panel opens a representative slow trace. Prometheus and OpenMetrics support exemplars, and Grafana shows them as dots on latency graphs.
- Wide events in a columnar store: each request produces one event with 50–300 attributes. Queries like "group p99 by tenant, build and AZ where route = /checkout" run directly on the events (Honeycomb, ClickHouse-based tools, Scuba at Facebook, described in Abraham et al., "Scuba: Diving into Data at Facebook", VLDB 2013). Storage is per event, with sampling and dynamic weighting to control cost. You can ask questions you didn't anticipate, without having predefined metrics.
- Selective high-cardinality metrics, such as per-tenant SLIs only for the top 500 tenants, with aggregation of the long tail into "other".
eBPF-based telemetry. eBPF lets small verified programs run inside the Linux kernel, attached to syscalls, network events and function entry points. Observability tools use it to capture HTTP, gRPC and database request metrics, and even traces, without changing application code, and to profile CPU across the whole fleet at low overhead. Examples are Cilium/Hubble for network flows, Pixie, Parca for profiling, and Grafana Beyla for auto-instrumentation. The trade-offs: it needs Linux kernels with eBPF support, and access to the hosts, which managed serverless platforms don't allow. Encrypted traffic needs uprobes on TLS libraries. Kernel-level capture lacks business context (tenant, order ID) that only the application knows. eBPF complements library instrumentation, rather than replacing it.
Profiling as the fourth signal. Continuous profilers sample stack traces, for example at about 100 Hz per process, and aggregate them into flame graphs per service, version and time. Google described fleet-wide profiling in "Google-Wide Profiling" (Ren et al., IEEE Micro, 2010). OpenTelemetry has added a profiling signal, so profiles share resource attributes and trace context with the other signals. Then you can go from a slow span to the CPU profile of exactly that code path.
Key Takeaways#
- Observability is being able to explain a system's behaviour from its telemetry. Metrics detect and alert, logs give event detail, traces connect requests across services. Correlate them through shared attributes, trace IDs in logs, and exemplars.
- Structure your logs (JSON, consistent fields, trace IDs, no PII), and ship them through a buffered pipeline to ELK/OpenSearch, Loki or ClickHouse, with tiered retention.
- Use the right metric type: counters (graph their rate), gauges, and histograms for latency (aggregatable percentiles). Never average percentiles. Prometheus scrapes, stores and alerts. Grafana visualises. Mimir and Thanos scale it.
- Pull gives free liveness and suits clusters. Push suits serverless, batch and edge. The OpenTelemetry Collector bridges both.
- Traces are trees of spans with context propagated through
traceparent. Instrument with OpenTelemetry, and tail-sample to keep errors and slow requests. - SLIs measure good/valid events, SLOs set targets, SLAs are contracts, and error budgets (99.9% ≈ 43.2 minutes per 30 days) balance velocity and reliability through a written policy.
- Page on symptoms, with multi-window burn-rate alerts. Show causes on dashboards. Every page is actionable and has a runbook. Alert on missing data, and monitor the monitor.
- Measure every service with the golden signals or RED, and every resource with USE. Saturation is the early warning, because latency explodes near full utilisation.
- Control cardinality and cost: bounded labels, downsampling, sampling and retention by value. Collect what answers questions, not everything.