System Design

Core Concepts

Observability: Metrics, Logs and Traces

A request counter costs the same at 10 requests a second as at 10,000. A log line or a trace costs something on every request. Page on the first, debug with the second, and price each by what it multiplies.

Why you are doing this at all

A system that serves 10,000 requests a second can describe itself in three ways. It can count its requests and record their latency in a few numbers per route. It can write a log line at each step of each request. Or it can record a trace: the path of one request through every service it touched, with the time spent in each.

A metric is a number tracked over time, such as a count of requests. It's kept as one time series for each combination of its labels, the named values attached to it, such as route and status. A log is a record of one event, written when the event happens. A trace is the record of one request across services. It's a tree of spans, where a span is one piece of work, such as a handler or an outgoing call, with its start and end times.

The three cost different amounts. A counter costs the same at 10 requests a second as at 10,000, because each request adds one to a number that already exists. A log line or a span is a new record for every request.

Back of envelopeOne day of each signal, for one system
The question is which signal can afford to cover every
request. The system serves 10,000 requests a second on
average, through 6 services on 600 pods. Each pod
serves about 10 routes.

Metrics, scraped every 15 s, about 2 B a sample
  request counter   600 pods × 10 routes × 5 statuses =  30,000
  latency histogram, 12 series each
                    600 pods × 10 routes × 12         =  72,000
  series                                              = 102,000
  per day           102,000 / 15 × 86,400 × 2 B       ≈  1.2 GB

Logs: 5 lines per service, 6 services, 300 B a line
  per request       30 × 300 B                        =    9 KB
  per day           10,000 × 9 KB × 86,400            ≈  7.8 TB

Traces: 20 spans per request, about 500 B a span
  per request       20 × 500 B                        =   10 KB
  per day, all      10,000 × 10 KB × 86,400           ≈  8.6 TB
  per day, 1%                                         ≈   86 GB
  ─────────────────────────────────────────────────────────────
  Double the traffic on the same pods and the metrics
  stay at 1.2 GB a day, while logs and traces double.
  Autoscaling adds pods, and so adds series: metric
  cost follows pods, not requests. Metrics can count
  every request. Logs and traces are where you choose
  what to keep.

That gap decides what each signal is for. A metric tells you that something is wrong, and for how many users, at a cost set by how many series you keep rather than how many requests you serve. A log or a trace tells you why, for one request, at a cost paid on every request. Page on the first, debug with the second, and don't make either one do the other's job.

Most mistakes in this area are one signal doing the other's job. A user ID added as a metric label turns one series into one per user. An alert that runs a log search every minute scans gigabytes to count something a counter already knows. A count of errors taken from traces sampled at 1 percent comes out 100 times too low, unless each trace records its sample rate.

One request, recorded three ways
One request passes through three services (1). Each service adds one to its request counter and to one bucket of its latency histogram (2), in purple. The same request also writes log lines (3) and spans (4), in orange, and each one is a new record that has to be shipped, indexed and kept.One request passes through three services (1). Each service adds one to its request counter and to one bucket of its latency histogram (2), in purple. The same request also writes log lines (3) and spans (4), in orange, and each one is a new record that has to be shipped, indexed and kept.
A metric adds to a number that exists; a log line or a span is a new record. One request passes through three services (1). Each service adds one to its request counter and to one bucket of its latency histogram (2), in purple. The same request also writes log lines (3) and spans (4), in orange, and each one is a new record that has to be shipped, indexed and kept.

When you don't need all three

A single service on a handful of servers doesn't need tracing. Each request runs in one process, so its log lines already tell the whole story, and a request ID on every line is enough to group them. Tracing becomes worth its cost once one request crosses services owned by different teams, because then no single log shows where the time went.

In a design interview, observability is usually one short deep dive near the end, as in the rate limiter and WhatsApp breakdowns. This page is the general method behind those answers.

Building the backends is a different problem. Metrics and monitoring, log aggregation and search and distributed tracing are breakdowns of their own. Time-series storage covers how metric data is stored and queried.

The three signals, and what each one costs

Metrics: one number per series, whatever the traffic

A service exposes three kinds of metric.

  • A counter only goes up: requests served, errors, bytes sent. The monitoring system computes a rate from it, such as requests per second over the last 5 minutes.
  • A gauge goes up and down: memory in use, open connections, messages waiting.
  • A histogram counts how many values fell into each range, such as requests that took between 100 and 200 ms. Percentiles are computed from it later.

Google's site reliability engineering (SRE) workbook recommends counters for anything that counts events. A counter lets the monitoring system compute a rate afterwards over any window, up to a month long. The burn-rate alerts later on this page use windows of up to 3 days.

Each distinct set of label values is its own series, and series are what a metrics backend pays for. Time-series storage prices a series in memory, in the index and in every query. So a label is safe when its values are few and fixed. The workbook gives an example of each side. App Engine made the HTTP status code a label, because there are few codes. A team that needed entity IDs, with millions of values, kept them in logs instead.

A bounded ID, such as a customer, can still be a label if its series are summed across pods before they're stored, which time-series storage works through. User and request IDs have no bound, so they stay in logs.

Metrics are also fast: with a 15-second scrape and a rule that runs every minute, a problem reaches a graph within a minute or two. So Google's alerts and dashboards run on metrics, and its engineers use logs to find the root cause. To page on a rare event, the workbook says, increment a counter when it happens and alert on the counter, not on a log search.

Logs: a record for every event

A log line records one event with its details. A structured log line carries those details as named fields, such as route=/v1/charges http_status=500 duration=0.009, so a log search can filter and group by them.

Each line has a level. DEBUG is detail a developer reads while fixing something. INFO is a normal event, WARN something unusual that the code handled, and ERROR a failure. Run production at INFO, so DEBUG lines cost nothing until someone turns them on.

High-cardinality fields, ones with many distinct values, belong in logs. A customer ID, an order ID or a request ID is one more field on a line, and it costs the same whether there are 10 customers or 10 million. The cost moves to the line instead. Every request writes its lines whether anyone reads them or not.

Stripe adds one line to the usual ones. At the end of each request, each service writes a canonical log line. It's one long line with the request's key facts: the route, status, user, duration, number of database queries, and whether the rate limiter allowed it. In Stripe's example, a question like "which users are being rate limited most?" needs facts spread across several lines of a request. With one line per request, it becomes a single filter and a count by user.

Traces: one request across services

A trace records one request as a tree of spans. The first span, at the edge of the system, is the root. Each span stores the trace ID, its own span ID, its parent's span ID, a name, its start and end times, and any attributes the code adds. Every span of one request shares the trace ID, so a tracing backend such as Jaeger can assemble the tree once the spans arrive.

The model comes from Dapper, Google's tracing system, described in a 2010 paper. Dapper put its code inside the shared libraries for RPCs (remote procedure calls), threads and callbacks, so applications were traced without changing their own code. OpenTelemetry, the open standard for this, ships libraries that wrap HTTP servers, clients and database drivers.

A trace answers a question no other signal can: where did this request's time go? A metric shows that the checkout p99, the latency that 99 percent of checkouts come in under, has gone up. A trace of one slow checkout shows which call took the time, and whether the calls ran one after another or in parallel.

How the three connect

Moving from one signal to the next is slow unless they share an ID. Two links make the move direct.

Trace IDs in logs. Every log line written while handling a request carries that request's trace ID and span ID. From a trace, one search then finds every line it wrote, across all services. Without the ID, you match lines by timestamp and guess.

Exemplars on metrics. An exemplar is one example request attached to a metric: the value it recorded, the time, and its trace ID. A latency histogram that keeps an exemplar per bucket lets you click from a spike on a graph to a trace of a request inside it.

From a spike on a graph to the line that explains it
The p99 graph jumps at 10:42 (1), and the histogram bucket for that minute carries an exemplar, the purple dot, with trace ID 4bf9. The trace (2) shows the request spent 2.1 of its 2.4 seconds in one call to inventory, in red. Searching the logs for trace_id=4bf9 (3) finds the line that explains it, a pool timeout in red.The p99 graph jumps at 10:42 (1), and the histogram bucket for that minute carries an exemplar, the purple dot, with trace ID 4bf9. The trace (2) shows the request spent 2.1 of its 2.4 seconds in one call to inventory, in red. Searching the logs for trace_id=4bf9 (3) finds the line that explains it, a pool timeout in red.
A shared trace ID turns three searches into two clicks. The p99 graph jumps at 10:42 (1), and the histogram bucket for that minute carries an exemplar, the purple dot, with trace ID 4bf9. The trace (2) shows the request spent 2.1 of its 2.4 seconds in one call to inventory, in red. Searching the logs for trace_id=4bf9 (3) finds the line that explains it, a pool timeout in red.

What to measure: RED, USE and the four golden signals

Three checklists name what to measure. They overlap, and each fits a different kind of thing.

  • RED, for each service: the rate, errors and duration of the requests it serves.
  • USE, for each resource: utilisation, saturation and errors.
  • The four golden signals, for a user-facing system: latency, traffic, errors and saturation.

Tom Wilkie created RED in 2015, as a monitoring rule for microservices. For every service, track the requests per second, the requests that fail, and the distribution of how long they take. Every service then has the same three graphs, so an engineer on call can read the dashboard of a service they didn't write.

Brendan Gregg's USE method looks at resources instead: CPUs, disks, network links, and software limits such as a connection pool. Utilisation is the share of time the resource was busy. Saturation is work it couldn't serve yet, usually a queue, such as threads waiting for a connection. Errors is the count of error events. The two work together: RED shows that duration went up, and USE finds why, such as a connection pool with all 50 connections in use and 12 threads waiting.

The SRE book's four golden signals are RED plus saturation, and the book adds two details. Measure the latency of failed requests apart from successful ones, because a fast error pulls the average down and a slow error is worse than a fast one. And watch the p99 over a short window, such as a minute, because rising latency is often the first sign of saturation.

Some parts of a design don't serve requests, and RED doesn't fit them. A queue consumer is healthy when the oldest message waiting is young. Message queues vs event streams argues for alerting on that age rather than on the backlog's size. A database replica is healthy when its replication lag, in seconds, is small.

SLIs, SLOs and error budgets

A service level indicator (SLI) measures what users get. The SRE workbook recommends writing every SLI as a ratio: good events divided by all events. "The share of checkout requests that succeeded" and "the share of home page loads under 300 ms" are both SLIs.

A service level objective (SLO) is a target for an SLI over a window, such as 99.9 percent of checkout requests succeeding over 30 days. A service level agreement (SLA) is a contract that says what happens when a target is missed, such as a refund. The SRE book's test is simple: if missing the target has no stated consequence, it's an SLO.

Where you measure decides what the SLI can see. An application server never sees a request that failed before it arrived. So the workbook's worked example measures at the load balancer, or in the page's own JavaScript, as latency numbers that matter also argues.

The error budget is what the SLO allows to fail: 0.1 percent of requests, for a 99.9 percent SLO. Google's SRE teams use it to decide about releases. While budget remains, releases go out. When an outage or a bad release uses it up, releases stop for a while, and the team works on reliability instead.

Back of envelopeThe error budget of a 99.9 percent SLO
The question is what the budget can absorb in a month.
Same system: 10,000 requests a second, and an SLO of
99.9 percent of requests succeeding over 30 days.

  requests in 30 days   10,000 × 86,400 × 30   =   25.9B
  budget, 0.1%          25.9B × 0.001          =   25.9M failed
  as a full outage      30 × 24 × 60 × 0.001   =   43.2 minutes

A bad release fails every request it serves, and is
rolled back after 40 minutes
  shipped to everyone   40 / 43.2              ≈     93%
  shipped to a canary on 5% of traffic
    failed              0.05 × 10,000 × 2,400 s =   1.2M
    share of budget     1.2M / 25.9M           ≈    4.6%
  ─────────────────────────────────────────────────────────
  The same bug costs most of the month, or a twentieth of
  it. Before anything else, the budget pays for a canary.

A canary is a release sent to a small share of traffic first, so a bad one fails few requests. Deployments: blue-green and canary covers how to run one.

At 99.999 percent, the workbook notes, a full outage spends the month's budget in 26 seconds, faster than many monitoring systems collect a sample. No alert can defend that, so five nines has to come from the design, such as sending every change to 1 percent of users first.

Alerting on burn rate, not on causes

The SRE book separates a symptom, what is broken for users, from a cause, the reason. "Users are getting errors" is a symptom. "The database refuses connections" is a cause. Page a person on symptoms. Causes go on dashboards for diagnosis, because many causes never reach a user, and a cause nobody predicted has no alert at all.

The book's tests for a page are strict. It has to be urgent, it has to be something a person can act on, and users have to be affected now or soon. A page that always gets the same scripted response should be automated instead.

Burn rate turns the error budget into an alert. It's how fast you're spending the budget, compared with spending it evenly over the window. At burn rate 1, a 99.9 percent SLO sees 0.1 percent errors and runs out on day 30. At burn rate 10, it sees 1 percent and runs out in 3 days.

A month of error budget
The budget starts the month at 100 percent. Background errors of 0.03 percent spend it slowly, at burn rate 0.3, the purple slope. The canary from the worksheet costs 4.6 percent on day 6 (1), and a 10-minute full outage, 10 of the month's 43.2 minutes, costs 23 percent on day 14 (2). The dashed yellow line is burn rate 1, which ends at zero on day 30. The month ends with about 42 percent left.The budget starts the month at 100 percent. Background errors of 0.03 percent spend it slowly, at burn rate 0.3, the purple slope. The canary from the worksheet costs 4.6 percent on day 6 (1), and a 10-minute full outage, 10 of the month's 43.2 minutes, costs 23 percent on day 14 (2). The dashed yellow line is burn rate 1, which ends at zero on day 30. The month ends with about 42 percent left.
The slope of the line is the burn rate. The budget starts the month at 100 percent. Background errors of 0.03 percent spend it slowly, at burn rate 0.3, the purple slope. The canary from the worksheet costs 4.6 percent on day 6 (1), and a 10-minute full outage, 10 of the month's 43.2 minutes, costs 23 percent on day 14 (2). The dashed yellow line is burn rate 1, which ends at zero on day 30. The month ends with about 42 percent left.

The SRE workbook's starting point for a 99.9 percent SLO over 30 days is three rules. Each one has a long window and a short one, and fires only when the error rate over both is above its threshold.

severitylong windowshort windowburn rateerror ratebudget spent when it fires
page1 hour5 minutes14.41.44%2%
page6 hours30 minutes60.6%5%
ticket3 days6 hours10.1%10%
Back of envelopeHow fast each rule fires
The question is how long each error rate runs before
someone hears about it, against how long the budget
lasts. SLO 99.9 percent over 30 days, or 43,200 minutes.
Times are before scrape and evaluation delays.

  error   budget lasts   first rule to fire     fires after
  100%    43 minutes     1 h page, over 1.44%          52 s
   10%    7.2 hours      1 h page                   8.6 min
    2%    36 hours       1 h page                    43 min
    1%    3 days         6 h page, over 0.6%          3.6 h
  0.5%    6 days         3 d ticket, over 0.1%       14.4 h
  ─────────────────────────────────────────────────────────
  Each rule fires once the same share of the budget is
  gone: 2, 5 or 10 percent. So a total outage pages in
  under a minute, and an error rate the budget survives
  for days opens a ticket instead of waking anyone.

The long window makes the alert wait until a set share of the budget is gone. The short window makes it stop soon after the errors stop.

Ten minutes of 15 percent errors, through two windows
Errors run at 15 percent for 10 minutes, the red band. The 1-hour average, in purple, crosses the 1.44 percent threshold at about 6 minutes and stays above it until about 64 minutes. The 5-minute average, in blue, crosses within a minute and falls back below at about 14.5 minutes. Requiring both, the alert fires from 6 to 14.5 minutes, the green bar. The 1-hour window alone would fire until minute 64, the grey bar.Errors run at 15 percent for 10 minutes, the red band. The 1-hour average, in purple, crosses the 1.44 percent threshold at about 6 minutes and stays above it until about 64 minutes. The 5-minute average, in blue, crosses within a minute and falls back below at about 14.5 minutes. Requiring both, the alert fires from 6 to 14.5 minutes, the green bar. The 1-hour window alone would fire until minute 64, the grey bar.
The long window decides when to fire; the short window decides when to stop. Errors run at 15 percent for 10 minutes, the red band. The 1-hour average, in purple, crosses the 1.44 percent threshold at about 6 minutes and stays above it until about 64 minutes. The 5-minute average, in blue, crosses within a minute and falls back below at about 14.5 minutes. Requiring both, the alert fires from 6 to 14.5 minutes, the green bar. The 1-hour window alone would fire until minute 64, the grey bar.

Percentiles come from histograms

Latency numbers that matter explains why a latency target is a percentile, such as the p99, and why a fleet's p99 comes from merged histograms, never from averaged ones.

So latency is recorded as a histogram. Each server counts requests into fixed ranges called buckets, such as up to 100 ms, 100 to 200 ms, and so on. Counts add up exactly across servers and across time. A percentile read from them is an estimate. The backend knows which bucket the p99 falls in, and guesses where inside it. The guess can be off by up to the width of that bucket.

Prometheus has two types for this. A summary computes chosen percentiles inside each server, accurately, but they can't be combined across servers or windows later. A histogram exports the bucket counts, which can be. Prometheus's docs now recommend native histograms, whose buckets are narrow and set by a growth factor, over both summaries and histograms with fixed buckets.

For an SLI, a count is better than a percentile. "99 percent of checkouts under 300 ms" needs only the number of checkouts at or under 300 ms. A bucket boundary at exactly 300 ms gives that number with no estimate at all. The SRE workbook says the same: count the slow requests rather than approximate them from a histogram.

Cardinality, sampling and retention

Each signal's bill is set by what it multiplies.

  • Metrics multiply label values: pods × routes × statuses × buckets.
  • Logs multiply requests × lines per request × bytes per line × days kept.
  • Traces multiply requests × spans per request × sample rate × days kept.

Sampling keeps a share of traces and drops the rest. It decides once per trace, not once per span, or traces arrive with holes in them.

Head sampling decides at the root, before the request runs. The usual form compares a hash of the trace ID with the sample rate, so any service that sees the same trace ID makes the same choice. The root's decision also travels with the request as a flag.

Tail sampling decides after the trace has finished, in a collector that has received all its spans. So it can keep every trace with an error, or every trace slower than a threshold. OpenTelemetry's docs name the cost: the collectors have to hold every trace in memory until they decide, and at volume that can take dozens or hundreds of machines.

OpenTelemetry also describes head sampling in front of tail sampling, to protect the pipeline at very high volumes. That cuts the load, but a trace the head drops is never exported. The tail sampler sees only what the head kept, so errors survive only at the head rate. If the goal is to keep every error, treat the two as alternatives.

When the sampling decision is made
Ten requests, each drawn as a bar as long as it took. With head sampling (1), each is kept or dropped as it starts, the dot at its left end, so the slow request and the failed one, in red, are dropped along with most of the others. With tail sampling (2), the decision is the dot at the right end, made once the request has finished, so both are kept, in green, along with one ordinary request.Ten requests, each drawn as a bar as long as it took. With head sampling (1), each is kept or dropped as it starts, the dot at its left end, so the slow request and the failed one, in red, are dropped along with most of the others. With tail sampling (2), the decision is the dot at the right end, made once the request has finished, so both are kept, in green, along with one ordinary request.
Head sampling decides before the outcome is known; tail sampling decides after. Ten requests, each drawn as a bar as long as it took. With head sampling (1), each is kept or dropped as it starts, the dot at its left end, so the slow request and the failed one, in red, are dropped along with most of the others. With tail sampling (2), the decision is the dot at the right end, made once the request has finished, so both are kept, in green, along with one ordinary request.

Dapper's numbers show what head sampling is good for. Its first production version sampled uniformly, one trace in 1,024. That was enough for high-traffic services, because a pattern that shows up once in such a system shows up thousands of times. Low-traffic services lost too much at that rate. So Dapper began moving to a target number of sampled traces per second. Each trace records the probability it was sampled with, so that tools can still count correctly.

Retention follows reads. Keep the last few days of logs in a search index such as Elasticsearch. Move older logs to object storage such as S3, where they're cheap to keep and slow to search.

The telemetry path can fail too. During an incident, errors write more lines and retries create more spans, so the pipeline is busiest when you need it most. Decide in advance what it drops first: DEBUG lines, then sampled successful requests, and never the error lines or the counters behind the SLIs.

A slow or failed log write must not fail the request it describes. Write logs and spans asynchronously, and drop them when the buffer is full, so a full disk delays the telemetry and not the request. Stripe wraps the code that writes its canonical line, so a problem building the line never fails a request, and someone is told right away.

Context propagation and the traceparent header

A trace exists only if every hop passes the trace ID on. Context propagation is the mechanism. The caller puts the trace ID and its own span ID in the request it sends. The callee reads them and starts a new span, with the caller's span as its parent.

The W3C Trace Context standard, a W3C Recommendation since 2020, fixes the HTTP header for this. It's called traceparent, and it has four fields separated by dashes.

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
  • Version, 00.
  • Trace ID, 16 bytes written as 32 hex digits. It's the same on every hop of the request.
  • Parent ID, 8 bytes as 16 hex digits: the span that made this call. It changes at every hop.
  • Flags, 8 bits. The 2020 standard defines one flag, sampled. It carries the root's sampling decision to every service further down.

Any hop that doesn't forward the header breaks the trace in two. Two common causes are a proxy that drops unknown headers, and an HTTP client written by hand. A message on a queue has to carry the same fields in its headers, so that the consumer can start its span from them. Otherwise the trace ends at the producer.

Sampled tracing is cheap. In Dapper, creating and ending a span took about 200 nanoseconds, and sampling below 1 trace in 16 changed latency by less than the measurement's error.

The method

Seven steps, in the order you'd say them in a design round.

1. Name two or three SLIs that users feel. Write each as good events over all events, and say where it's measured. For an API, that's success rate and latency at the load balancer. For a pipeline, it's the share of items processed within 5 minutes of arriving, with the age of the oldest unprocessed item on the dashboard.

2. Set an SLO for each, and work out the error budget in failed requests and in minutes of full outage.

3. Page on burn rate, with a fast rule and a slow one. Everything else goes to dashboards or tickets.

4. Put RED on every service and USE on every bounded resource. Add the age and lag signals the design has, such as replication lag and queue age.

5. Price every label before adding it. Use labels with few, fixed values. A bounded ID, such as a customer, needs its series summed across pods before storage. User and request IDs go in log fields.

6. Write one structured line per request per service, with the trace ID, and decide how long each kind of log stays searchable.

7. Propagate trace context through every hop, including queues. Then pick one sampling decision. Head sampling at a low rate is cheap. Tail sampling keeps every error and slow trace, but needs collectors that receive every span.

Worked examples, start to finish

Each of these four examples breaks a different obvious answer.

A checkout service that pages too often and too late

The system from the worksheets serves 10,000 requests a second. Today it pages on causes: CPU above 80 percent on any pod, the database connection pool above 90 percent, and an error rate above 1 percent for 5 minutes. The engineer on call gets pages that need no action. Meanwhile a payment bug that fails 8 percent of checkouts runs for hours without a page.

So what should page?

Naive

Alert on every cause, and on a fixed error rate

It's tempting because each alert matches a past incident, and CPU and pool usage are easy to read. But a cause fires whether or not users are affected. A batch job that pushes one pod's CPU to 85 percent pages someone, and no user notices anything.

A fixed error threshold fails both ways. The SRE workbook works through the simplest version: page when the error rate over 10 minutes is above the SLO's 0.1 percent. It could fire up to 144 times a day while the service still meets its SLO. With the threshold at 1 percent, as here, an error rate of 0.8 percent never pages, though it spends the month's budget in under 4 days.

Senior

One SLO for the service, paged on burn rate over two windows

Define one availability SLI at the load balancer, set a 99.9 percent SLO, and page with the workbook's three burn-rate rules. CPU and pool usage move to the dashboard, where they explain a page instead of causing one.

This is the workbook's recommended setup. Every page now means the budget is burning fast. The cost is that one SLI averages every request together. A kind of request that is a small share of traffic can fail badly and barely move the total. The next tier asks whether every request should count the same.

Staff

An SLO for each class of request, by what a failure costs the user

The premise to question is that every failed request costs the user the same. The SRE book gives an example: failing a new user's sign-up is not the same as failing a background poll for new email. Checkout is 1 percent of this system's traffic, and it's the only part that takes money.

Back of envelopeAn 8 percent checkout failure, seen by two SLOs
The question is whether one SLO for the whole service
can see a checkout failure. Checkout is 1 percent of
traffic, and its payment step fails 8 percent of
checkouts. The usual background errors of 0.03 percent
continue.

  checkouts            1% × 10,000/s            =     100/s
  failed               8% × 100/s               =       8/s
One SLO for all requests, 99.9 percent
  error rate           0.03% + 8 / 10,000       =   0.11%
  burn rate            0.11% / 0.1%             =     1.1
  pages                none: under 0.6% and 1.44%
  3-day ticket fires   (0.1% − 0.03%) / 0.08% × 72 h
                                                ≈    63 h
  failed by then       8 × 63 × 3,600           ≈    1.8M
Checkout's own SLO, 99.9 percent
  error rate           8 / 100                  =      8%
  burn rate            8% / 0.1%                =      80
  1 h page fires       1.44% / 8% × 60 min      ≈  11 min
  ─────────────────────────────────────────────────────────
  The service-wide SLO opens a ticket after about 2.6
  days, once 1.8 million checkouts have failed.
  Checkout's own SLO pages in 11 minutes.

The workbook warns against tuning alerts per service, so don't give every endpoint its own rules. Group request types into a few classes with similar needs. The workbook's example has five, from CRITICAL at 99.99 percent to NO_SLO for features users can't see. Then apply the same burn-rate rules to every class.

What you give up: more SLOs to agree and maintain, and someone has to decide which class each new endpoint joins. A class with little traffic gets noisy, because each failure is a large share of it.

A service that logs every step of every request

The same system's services log the way Stripe's example request does: about five lines per request in each service, at INFO. That's 30 lines across six services, and all of them go into Elasticsearch for 30 days. So what should be kept, and for how long?

Back of envelopeWhat each logging policy keeps, and what it costs
The question is what each policy costs a day, and what
it can still answer. 10,000 requests a second, 30 lines
of 300 B per request, as in the first worksheet. 0.03
percent of requests fail, and about 1 percent fail or
run slower than the p99.

Keep everything
  per day                                         ≈  7.8 TB
  30 days in the index   30 × 7.8 TB              ≈  233 TB
Keep every ERROR line, and every line of 1% of
requests, chosen by trace ID
  sampled lines          1% × 7.8 TB              ≈   78 GB
  ERROR lines, at most   0.03% × 7.8 TB           ≈  2.3 GB
  per day                                         ≈   80 GB
A 600 B canonical line per service for every request,
plus every line of the failed and slow ones
  canonical lines        10,000 × 6 × 600 B × 86,400
                                                  ≈  3.1 TB
  full detail            1% × 7.8 TB              ≈   78 GB
  per day                                         ≈  3.2 TB
  ─────────────────────────────────────────────────────────
  Sampling costs about a hundredth of keeping
  everything, but keeps a successful request's lines
  1 time in 100. Canonical lines cost about 40 percent
  of everything, and keep a row for every request.
Naive

Keep every line, and buy a bigger index

Nothing changes in the code, and any question about any request can be answered. But the bill is 7.8 TB a day, 233 TB in the index at any time. Almost all of it describes successful requests that nobody reads. During an incident, every search runs over all of it.

Senior

Keep every ERROR line, sample whole requests by trace ID, and tier the retention

Keep every ERROR line, and every line of 1 percent of requests. Choose that 1 percent by a hash of the trace ID, so every service keeps the lines of the same requests. That's about 80 GB a day. Keep 7 days in the index and move older logs to object storage.

This is the standard answer, and it cuts the bill about a hundredfold. The cost is the question it can't answer. "Which customers saw a slow checkout page between 10:40 and 10:50?" has no answer for 99 of every 100 requests, because their lines were never written. A slow request that didn't fail is no better off, because each line was kept or dropped as it was written, before anyone knew the request would be slow. The next tier asks whether the lines were the right unit to keep.

Staff

One canonical line for every request, and detail only when it went wrong

The premise to question is that a log is the lines developers wrote while coding. Design the record per request instead. Every service writes one canonical line for every request, with the trace ID, route, status, customer, duration and release version. The other lines are held in memory for the length of the request, and sent to Elasticsearch only if the request failed or ran slow in this service.

Detail held per request, written only when it goes wrong
Each request's five detailed lines are held in a buffer in memory (1), in purple. Request A succeeds, so its buffer is dropped, in grey, and only its canonical line is written (2). Request B fails, so its buffer is written in full to Elasticsearch, in red, along with its canonical line (3). Every canonical line goes to ClickHouse.Each request's five detailed lines are held in a buffer in memory (1), in purple. Request A succeeds, so its buffer is dropped, in grey, and only its canonical line is written (2). Request B fails, so its buffer is written in full to Elasticsearch, in red, along with its canonical line (3). Every canonical line goes to ClickHouse.
Every request leaves one row; only failed or slow requests leave the full story. Each request's five detailed lines are held in a buffer in memory (1), in purple. Request A succeeds, so its buffer is dropped, in grey, and only its canonical line is written (2). Request B fails, so its buffer is written in full to Elasticsearch, in red, along with its canonical line (3). Every canonical line goes to ClickHouse.

That's 3.2 TB a day, about 40 percent of keeping everything, and every request has a row. Send the canonical lines to a column store such as ClickHouse. There, a row per request costs the same however many customers there are, as time-series storage shows for per-customer error rates.

What you give up: the canonical line is a schema every service must fill, and renaming a field breaks everyone's queries. Each service decides from its own part of the request. If orders fails a request after payments finished its part cleanly, payments drops its buffered lines. Only the canonical lines, and the trace if it was sampled, show what happened there.

A process that crashes loses the buffered lines of the requests it was running, and those are the ones you'd most want. A crash handler can flush the buffers, but a process that is killed outright gets no chance to. And it's 40 times the senior tier's storage, to answer per-request questions for every request instead of 1 in 100.

A failed checkout that the traces never caught

The system head-samples 1 percent of traces. A customer reports that their checkout hung for 8 seconds at 10:42 and then failed. Support finds the request's canonical line, which gives the trace ID. The tracing backend has no trace with that ID.

So how should traces be sampled?

Naive

Trace every request

Then no sampling rule can lose a trace. But the first worksheet puts it at 8.6 TB of spans a day. Dapper measured a 16.3 percent rise in a search cluster's average latency from recording them all.

Senior

Head sampling at 1 percent, by trace ID

The root decides by hashing the trace ID, and the sampled flag carries the decision to every service. Whole traces are kept or dropped together, at 86 GB a day. OpenTelemetry calls this the most common form of head sampling.

Back of envelopeWhat 1 percent head sampling keeps
The question is whether 1 percent is enough. Errors are
0.03 percent of requests, and the customer's failed
checkout was one of them.

  errors                0.03% × 10,000/s         =    3/s
  error traces kept     1% × 3/s × 60            ≈  1.8 a minute
  one given request     kept                     =    1 in 100
  ─────────────────────────────────────────────────────────
  About two error traces a minute are enough to see a
  pattern. For one customer's request, the trace was
  never recorded 99 times in 100.

This is the standard answer, and it's right for patterns. The cost is that the decision is made before the request runs, so the root drops a trace without knowing that the request will fail. The next tier moves the decision.

Staff

Tail sampling: decide after the request finishes

The premise to question is that the decision has to be made at the root. Send every span to a set of collectors that holds each trace until it's complete. Then keep every trace with an error, every trace slower than the p99, and 1 percent of the rest.

Back of envelopeSizing the tail-sampling collectors
The question is what deciding late costs. Every span
goes to the collectors, and each trace is held for 30 s
before the decision.

  spans arriving        10,000 × 20              = 200,000/s
  bytes arriving        200,000 × 500 B          = 100 MB/s
  traces held           10,000 × 30 s            = 300,000
  memory, at least      300,000 × 10 KB          ≈   3 GB
  (spans take more room decoded than on the wire, and
  the samplers' trace limit must cover all 300,000, or
  they evict traces before deciding)
Kept: every failed or slow trace (about 1%), and 1% of
the rest
  share kept            1% + 1% × 99%            ≈     2%
  per day               1.99% × 8.6 TB           ≈ 172 GB
  ─────────────────────────────────────────────────────────
  Storage is twice head sampling's 86 GB, and every
  failed checkout has a trace. The new cost is a set of
  collectors that takes 100 MB/s and holds 300,000
  traces, at least 3 GB, in memory.

All spans of one trace must reach the same collector, or no collector sees the whole trace. So the collectors are arranged in two layers. The first routes each span by a hash of its trace ID, and the second holds traces and decides.

Tail-sampling collectors in two layers
Services send every span (1) to the first layer, which hashes each trace ID to choose a sampler (2). Each sampler holds its traces for 30 seconds (3), in purple, then sends the failed, slow and 1 percent sampled ones to Jaeger (4), in green. The rest are dropped, in grey.Services send every span (1) to the first layer, which hashes each trace ID to choose a sampler (2). Each sampler holds its traces for 30 seconds (3), in purple, then sends the failed, slow and 1 percent sampled ones to Jaeger (4), in green. The rest are dropped, in grey.
Routing by trace ID puts every span of a trace in one place. Services send every span (1) to the first layer, which hashes each trace ID to choose a sampler (2). Each sampler holds its traces for 30 seconds (3), in purple, then sends the failed, slow and 1 percent sampled ones to Jaeger (4), in green. The rest are dropped, in grey.

What you give up: a stateful set of collectors to size, run and watch, with all span traffic crossing the network to reach it. A trace can't be searched until its wait is over, and a span that arrives after the decision gets no say in it. Adding or removing a sampler sends some traces in flight to a different machine, which splits them. An exemplar is picked when a request is measured, before the decision, so it can point at a trace the samplers dropped.

When the collectors fall behind, OpenTelemetry's docs say they may have to fall back to simpler sampling. And a head sampler in front, added to cut the load, brings back the problem this tier solves: the samplers see only the traces the head kept.

A p95 that reads 295 ms when requests take 220

Prometheus's docs work through this case. The SLO is 95 percent of requests within 300 ms, and the latency histogram has fixed buckets at 100, 200, 300 and 450 ms. Nearly every request takes about 220 ms, so the true p95 is about 220 ms.

The histogram knows only that most requests fell between 200 and 300 ms. Prometheus assumes they're spread evenly across that bucket, and estimates the p95 at 295 ms. The dashboard shows a service 5 ms from breaking its SLO, when it has 80 ms to spare.

Then a routing change adds 100 ms to every request. The true p95 is about 320 ms, just over the SLO. The requests now land in the 300 to 450 ms bucket, and the estimate is 443 ms. An engineer reading the graph sees a service 143 ms over its target, when it's 20 ms over.

A p95 estimated from buckets
Before the change (1), requests cluster at 220 ms, in blue. With fixed buckets, the p95 is placed near the top of the 200 to 300 ms bucket, at 295 ms, in red. A native histogram's bucket there is about 20 ms wide, so its estimate is 228 ms, in green (2). After 100 ms is added (3), the fixed-bucket estimate jumps to 443 ms, and the native one reads 323 ms (4). The dashed yellow line is the 300 ms target.Before the change (1), requests cluster at 220 ms, in blue. With fixed buckets, the p95 is placed near the top of the 200 to 300 ms bucket, at 295 ms, in red. A native histogram's bucket there is about 20 ms wide, so its estimate is 228 ms, in green (2). After 100 ms is added (3), the fixed-bucket estimate jumps to 443 ms, and the native one reads 323 ms (4). The dashed yellow line is the 300 ms target.
The estimate can be anywhere in the bucket the true value falls in. Before the change (1), requests cluster at 220 ms, in blue. With fixed buckets, the p95 is placed near the top of the 200 to 300 ms bucket, at 295 ms, in red. A native histogram's bucket there is about 20 ms wide, so its estimate is 228 ms, in green (2). After 100 ms is added (3), the fixed-bucket estimate jumps to 443 ms, and the native one reads 323 ms (4). The dashed yellow line is the 300 ms target.

The decision has two parts. The SLI comes from a classic histogram with a boundary at 300 ms, exported beside the native one, or from a native histogram with custom buckets that include 300 ms. Its count of requests at or under 300 ms is exact, on every server. The p95 on the dashboard comes from the native histogram's narrow buckets, whose estimate here is 228 ms.

Where it goes wrong

These are ordered by how often they come up.

1. An unbounded ID in a metric label

A user, request or order ID makes one series per value, with no limit. The rate limiter and URL shortener breakdowns both show how that takes a metrics backend down during an incident. Count the label product first. Keep unbounded IDs in log fields, and sum a bounded one, such as a customer, across pods before storage.

2. Measuring only at the application server

A request that fails before it reaches the server doesn't exist in the server's metrics. Measure SLIs at the load balancer or in the client, and add a synthetic check from outside the system.

3. Standard alert rules on a low-traffic service

At 10 requests an hour, 30 days hold 7,200 requests, so a 99.9 percent SLO allows 7 failures. One failed request is 10 percent of that hour's traffic and 13.9 percent of the month's budget, so it pages. The workbook's options are synthetic traffic, grouping the service with related ones, retries in the client, or a lower SLO.

4. Counting from samples

A count, or a rate per second, taken from 1 percent of traces or log lines is 100 times too low. Tail sampling keeps every error, every slow trace and 1 percent of the rest, so even the share of requests that failed comes out wrong, and no single factor fixes it. Count with metrics, and use samples to explain. If you must count from samples, store each one's sample rate and weight by it, as Dapper's traces do.

5. Monitoring that fails with the system

In December 2021, congestion on AWS's internal network in us-east-1 cut off the real-time monitoring data its operations teams used, and they worked from logs instead. The same congestion stopped the AWS status dashboard from failing over to its standby region. Run the probes and the alerting path somewhere the thing they watch can't take down, such as another region. Multi-region and disaster recovery covers the dependencies a failover forgets.

If you memorise nothing else

factwhy it matters
A metric costs per series; a log line or span costs per requestmetrics count everything, logs and traces choose what to keep
Labels with few, fixed values; a bounded ID only if summed across pods firstuser and request IDs go in log fields, where a new value costs nothing extra
Trace ID on every log line, exemplars on histogramsone click from a graph to a trace to the lines
RED for services, USE for resourceswhat callers get, and which resource is short
An SLI is good events over all eventscount at the load balancer or the client
A 99.9 percent SLO over 30 days allows 43.2 minutes of full outagea canary on 5 percent turns 93 percent of the budget into 4.6
Page on symptoms, not causescauses go on the dashboard the page links to
Burn rate 14.4 over 1 hour and 5 minutes, 6 over 6 hours and 30 minutes, 1 over 3 days to a ticketeach fires after 2, 5 or 10 percent of the budget
The short window is what stops the alerta 1-hour window alone fires for most of an hour after the fix
A percentile from buckets can be off by the bucket's width220 ms read as 295 with fixed buckets
Summaries can't be merged across serversexport histograms, put a boundary at the SLO threshold
Head sampling decides before the outcome is known1 percent keeps 1 in 100 of the failures you'll be asked about
Tail sampling holds every trace until it's completeall spans of a trace must reach one collector
traceparent: version, 16-byte trace ID, 8-byte parent ID, flagsthe trace ID stays, the parent ID changes at each hop
One canonical line per request per serviceevery request queryable, for about 40 percent of the bytes

What is expected at each level

Mid-level

Know what each signal is for: metrics for alerting and dashboards, logs for the detail of an event, traces for one request across services. Know that a label with unbounded values multiplies series, and that latency is a percentile from a histogram, not an average. Define an SLI and an SLO.

You aren't expected to design burn-rate alerts or sampling without being asked. If asked "how would you find out why one request was slow?", a good mid-level answer is a trace ID passed between services and written on every log line.

Senior

You lead this part of the discussion, and three things must come up without prompting.

SLIs that users feel, measured where users are. Two or three, as ratios, at the load balancer or the client, with an SLO and its error budget in numbers.

Alerts on burn rate, not on causes. A fast rule and a slow one, and causes moved to dashboards.

The cost of each signal. Which labels are allowed, what the logs keep and for how long, and the trace sample rate.

Two things are disqualifying: a user or request ID in a metric label, and paging on CPU.

Staff+

Producing a correct design is still the bar. A staff answer stands out by deciding what each signal must answer, and paying only for that.

Split SLOs by what a failure costs the user, with a handful of request classes and the same alert rules for each.

Design the per-request record. One canonical line per request per service, with the trace ID, and full detail kept only for failed or slow requests.

Move the sampling decision to where the outcome is known, and size the collectors this needs.

Keep the monitoring out of the failure it watches: probes and alerting in another region, and telemetry that can never fail or delay a request.

And say what you would not build. Each of these can cost a team a quarter.

One is an in-house tracing backend before every hop propagates trace context, because a backend can't join a trace whose IDs were dropped. Another is a log search index sized to keep every line for 30 days, when canonical lines answer per-request questions for every request, for 40 percent of the storage. Another is a separate alert config for each of 100 endpoints. And the last is a 99.999 percent SLO that no alert can defend.

Sources

Every figure about a real system on this page comes from these documents. The worksheets work out the rest from the inputs they state.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.