Skip to content

Lesson 18 of 38Running in production

Observability, SLIs, and SLOs

Define reliability in numbers users feel, spend an error budget on purpose, alert on burn rate, and trace one slow request across twenty services.

15 min read0/5 questions

You have built the pieces of a distributed system. This unit is about keeping one healthy once real users depend on it. It is 3 a.m. and your phone goes off: "CPU above 80% on api-7". You open the laptop, look around, and find nothing wrong. Users were fine. Next week a bad deploy makes 4% of checkouts fail for two hours, and nothing pages at all, because CPU was normal. This is the most common state of monitoring at real companies: lots of dashboards, lots of noise, and no clear answer to the only question that matters, "are users having a bad time right now?" This lesson is about answering that question with numbers, and about finding out why when the answer is yes.

Monitoring vs observability

Monitoring watches for failures you predicted: disk full, process down, queue too long. You decide the checks in advance. Observability is the ability to answer questions you did not predict, from the outside, using the data the system already emits. "Why are checkouts slow only for Android users in Brazil on the new app version?" is not a dashboard anyone built. An observable system lets you slice its telemetry by those dimensions and find out in minutes.

That data comes in four kinds of signal:

SignalWhat it isGood forWeak at
MetricsNumbers aggregated over time: counters, gauges, histogramsCheap, fast, alerting, trendsDetail on one request
LogsTimestamped events, ideally structured JSONThe exact error and contextCost at volume, aggregation
TracesThe path of one request across services, as a tree of timed spansWhere the time wentEvery request is too costly to keep
ProfilesWhere CPU and memory go, sampled continuously in productionWhich function is hotCross-service causes

The Python Backend course (Logging and Observability) shows how to emit these from code. This lesson is the system-level view: what to measure, what to promise, and when to wake someone up.

SLIs, SLOs, and SLAs

Three terms that interviewers expect you to use precisely.

  • An SLI (service level indicator) is a measurement of how users experience the service. The best form is a ratio: good events divided by valid events. "The proportion of checkout requests that returned a non-5xx response in under 300 ms."
  • An SLO (service level objective) is your internal target for an SLI over a window: "99.9% of checkout requests are good, measured over a rolling 30 days."
  • An SLA (service level agreement) is a contract with customers, with consequences (usually service credits) when you miss it. The SLA is always looser than the SLO, so you notice trouble long before you owe anyone money.

Two details make SLIs useful instead of decorative.

Measure as close to the user as you can. A server-side metric misses requests that never reached the server: DNS failures, a broken load balancer, a crashed pod. The load balancer's logs are better. Real user monitoring from the browser or app is better still, though noisier.

Choose SLIs from user journeys, not from components. Users do not care that Redis is healthy. They care that they can log in, search, and pay. Pick the three to five journeys that matter, and give each an availability SLI and a latency SLI. "Valid events" matters too: exclude health checks, bots you deliberately block, and 4xx responses caused by the client, or one broken integration can burn your whole budget.

Quick check
Which of these is the best SLI for a search page?
Need a nudge? A hint rules out a wrong answer.

Error budgets

An SLO of 99.9% is also a statement that 0.1% of requests may fail. That 0.1% is your error budget, and it changes how a team argues. Instead of "reliability vs features" as a matter of opinion, the budget decides. Budget left? Ship, experiment, run the risky migration. Budget spent? Freeze feature launches and spend the time on reliability until the window recovers. Writing that rule down in advance, agreed by engineering and product, is called an error budget policy. Without one, the SLO is just a number on a slide.

The budget also tells you that 100% is the wrong target. Users cannot tell 99.999% from 100%, because their own Wi-Fi and phone fail far more often than that. Every extra nine costs real engineering, and a team that never spends its budget is moving too slowly.

Pythonerror_budget.py
WINDOW_MIN = 30 * 24 * 60 # a rolling 30-day window, in minutes print("SLO budget allowed bad minutes in 30 days")for slo in [0.99, 0.995, 0.999, 0.9995, 0.9999]: budget = 1 - slo print(f"{slo:.2%} {budget:.2%} {budget * WINDOW_MIN:8.1f}") # Burn rate = observed error rate / budgeted error rate.slo = 0.999budget = 1 - slofor label, bad, total in [("normal hour", 30, 100_000), ("bad deploy", 1_500, 100_000), ("slow leak", 700, 100_000)]: rate = bad / total burn = rate / budget hours_to_empty = 30 * 24 / burn print(f"{label:12} error rate {rate:.2%} burn {burn:4.1f}x budget gone in {hours_to_empty:6.1f} h")
Output
Press Run (⌘ Enter) to see what happens.

Memorise two numbers: 99.9% over 30 days is about 43 minutes of full downtime, and 99.99% is about 4.3 minutes. (Over an average calendar month these become 43.8 and 4.4.) At four nines, no human can even get to a laptop before the budget is gone, so that target implies automated detection and rollback. Also note that availability multiplies: a service that calls three dependencies in series, each at 99.9%, cannot be better than about 99.7% itself.

Predict the outputPython

How many minutes of full outage does a 99.95% SLO allow over 30 days?

print(round((1 - 0.9995) * 30 * 24 * 60, 1))
Need a nudge? Hints walk you through it.

Alerting on burn rate

Now the 3 a.m. page. The rule from Google's SRE practice: alert on symptoms, not causes. High CPU is a cause that may or may not hurt anyone. A rising error ratio on checkout is a symptom users already feel. Page on symptoms. Put causes on dashboards, where you look at them after the page tells you something is wrong.

The naive symptom alert, "error rate above 0.1% for 5 minutes", still fails. It fires on short blips that barely touch the budget, and it misses a slow leak at 0.5% that eats the whole month in six days. The fix is to alert on burn rate: how fast you are spending the budget relative to the pace that would use exactly all of it by the end of the window. A burn rate of 1 spends the budget in 30 days. A burn rate of 14.4 spends 2% of the monthly budget in one hour.

The Google SRE Workbook recommends several windows at once:

Burn rateLong windowShort windowBudget spentAction
14.4x1 hour5 minutes2%Page
6x6 hours30 minutes5%Page
1x3 days6 hours10%Ticket

The short window is there so the alert stops soon after the problem stops. Both windows must be over the threshold to fire. Without the short window, an incident that ended 40 minutes ago would keep the one-hour alert red. Some teams make the 6x tier a ticket rather than a page; the right line depends on how fast your team can respond.

Run the numbers from the code above against this table. The bad deploy at 15x pages within minutes. The slow leak at 7x would never trip a 14.4x alert, but the 6-hour tier catches it with days of budget still left.

What to put on the dashboard: golden signals, RED, and USE

When the page fires, you need to find the cause fast. Three checklists help you decide which metrics to collect.

  • The four golden signals (Google SRE): latency, traffic, errors, and saturation (how full the most constrained resource is). Count the latency of failed requests separately, because a fast error can make the average look better.
  • RED for every request-driven service: Rate, Errors, Duration. One row of three graphs per service, and the on-call can scan twenty services in a minute.
  • USE for every resource (CPU, memory, disk, connection pool, queue): Utilisation, Saturation, Errors. A database connection pool at 100% utilisation with 40 requests waiting is the classic hidden bottleneck.
Match the pairs0/5 matched

Match each observation to the method that names it.

Choose an item, then its match on the other side.

Percentiles: why averages lie

Latency is never a single number. Most requests are fast, and a few hit a lock, a garbage collection pause, a cold cache, or a retry. The average blends them into a number that describes nobody. Use percentiles: p50 is the median user, p99 is the worst 1 in 100, p99.9 the worst 1 in 1,000.

Pythonpercentiles.py
import randomimport statistics random.seed(42) def pct(data, p): data = sorted(data) return data[min(len(data) - 1, int(p / 100 * len(data)))] # 990 fast requests and 10 that hit a slow path (a lock, a GC pause, a cold cache).latencies = [random.uniform(20, 60) for _ in range(990)] + [random.uniform(900, 1500) for _ in range(10)]print(f"mean {statistics.mean(latencies):5.0f} ms p50 {pct(latencies, 50):5.0f} ms p99 {pct(latencies, 99):5.0f} ms") # Two servers. You cannot average their p99s to get the fleet p99.a = [random.uniform(20, 60) for _ in range(9_000)] + [random.uniform(800, 1000) for _ in range(1_000)]b = [random.uniform(20, 60) for _ in range(1_000)]avg_of_p99 = (pct(a, 99) + pct(b, 99)) / 2print(f"server A p99 {pct(a, 99):.0f} ms, server B p99 {pct(b, 99):.0f} ms")print(f"average of p99s {avg_of_p99:.0f} ms true fleet p99 {pct(a + b, 99):.0f} ms") # Fan-out: one page waits for N backend calls. Each call is slow 1% of the time.for n in [1, 10, 100]: print(f"fan-out {n:>3}: chance at least one call is slow = {1 - 0.99 ** n:.0%}")
Output
Press Run (⌘ Enter) to see what happens.

Three lessons are in that output.

The mean looks healthy while 1% of users wait a full second. Heavy users make the most requests, so they are the most likely to hit the tail. The p99 is often what your best customers feel.

You cannot average percentiles. Averaging the two servers' p99s gives about 519 ms, but the real fleet p99 is close to 1 second, because server A handles ten times the traffic. The same trap catches you when you average per-minute p99s into an hourly p99. The fix is to record histograms (counts per latency bucket), which you can add together, and compute percentiles from the merged buckets. Prometheus histograms and OpenTelemetry's exponential histograms exist for this reason.

Fan-out turns the tail into the common case. If rendering a page calls 100 backends and waits for all of them, a 1-in-100 slow call hits 63% of page loads. This is the "tail at scale" problem (Dean and Barroso, 2013), and it is why large systems care about p99.9 of their internal services. You will meet one fix, hedged requests, in Reliability Patterns.

Distributed tracing

Metrics tell you checkout p99 doubled. They do not tell you which of the 20 services behind checkout got slow. A trace does. Each unit of work is a span: a name, a start time, a duration, attributes, and a parent. All spans of one request share a trace ID, and the tracing backend assembles them into a waterfall.

The hard part is context propagation: every service must pass the trace ID on to the next, across HTTP, gRPC, and queues. The standard is the W3C Trace Context traceparent header:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             version - trace id (32 hex) - parent span id (16 hex) - flags (01 = sampled)
One checkout request becoming one trace
BrowserAPI gatewayCheckoutInventoryPaymentsPOST /checkouttraceparent: 00-4bf9...-a1-01reserve (same trace id)ok, 18 mscharge (same trace id)ok, 1,240 ms201 Created201 Created

The gateway starts a new trace: trace id 4bf9..., root span POST /checkout.

1/8

Messages on a queue need the same treatment: put traceparent in the message headers so the consumer's spans link to the producer's trace. Forget it and every async hop starts a fresh, disconnected trace.

Sampling. Keeping every span of every request is expensive at scale. Head sampling decides at the start of the trace ("keep 1%") and passes the decision in the flags byte, so all services agree. It is cheap but random: it throws away 99% of your errors along with 99% of the boring requests. Tail sampling buffers the whole trace and decides at the end: keep every trace with an error or a duration over 2 s, plus 1% of the rest. It keeps the interesting traces, but it needs a component that sees all spans of a trace before deciding, which costs memory.

OpenTelemetry (OTel) is the vendor-neutral standard for all of this: APIs and SDKs for traces, metrics, and logs in every major language, a wire protocol (OTLP), and the Collector, a service that receives telemetry, processes it (batching, filtering, tail sampling, removing personal data), and exports it to whichever backend you use. Instrument with OTel and you can switch from one vendor to another by changing Collector config, not code. Continuous profiling is being added as a further OTel signal; check the project's status page for how mature it is when you read this.

A practical habit: put the trace ID in every log line. Then a slow span takes you to the exact logs for that request, and an error log takes you to the full trace.

Cardinality: the bill nobody expects

In Prometheus and most metric systems, every unique combination of label values is a separate time series, stored and indexed on its own. http_requests_total{route, method, status} with 50 routes, 4 methods, and 10 status codes is at most 2,000 series. Add a user_id label with 5 million users and you have created up to 10 billion series. The metrics backend runs out of memory, or the vendor bill explodes.

The rule: metric labels must have bounded, small sets of values (route templates like /users/:id, not raw paths; status class, region, version). High-cardinality detail (user ID, order ID, request ID) belongs in traces and logs, which are built to store per-event data. If you need "errors for this one customer", that is a query over traces or structured logs.

Quick check
A teammate adds customer_id as a label on the request latency histogram so support can see each customer's p99. What is the problem?
Need a nudge? A hint rules out a wrong answer.

Exercise: SLOs for the URL shortener

Go back to the URL Shortener case study. Redirects run at about 11,500 per second on average and must be fast. Write two SLOs and work out the error budget before you open the answer.

A model answer

Availability SLI: the proportion of GET /{key} requests, measured at the load balancer, that return a redirect or a 404 (a missing key is a correct answer) rather than a 5xx or a timeout. SLO: 99.9% over a rolling 30 days.

Latency SLI: the proportion of redirects served in under 50 ms at the load balancer. SLO: 99% over 30 days. Not 99.9%: a cache miss to the database is allowed to be slower now and then.

Budget: 11,500 requests per second for 2,592,000 seconds is about 29.8 billion redirects in 30 days. 0.1% of that is about 29.8 million failed redirects allowed, or about 43 minutes of total outage.

Alerts: page when the availability burn rate is above 14.4x over 1 hour and 5 minutes. The create-link API is a separate journey with its own, looser SLO, because users retry a failed create but never see a failed click.

Put it in order5 steps

Put the steps for adopting SLOs on a service in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
SLI
Service level indicator: a ratio of good events to valid events that reflects what users experience.
SLO
Service level objective: an internal target for an SLI over a window, such as 99.9% over 30 days.
error budget
The failure an SLO allows (1 minus the SLO). Spent on releases and risk; when it runs out, reliability work comes first.
burn rate
How fast the error budget is being spent, relative to the rate that would use exactly all of it by the end of the window.
percentile
The latency below which a given share of requests fall. p99 is the slowest 1 in 100. Merge histograms, never average percentiles.
trace context
The W3C traceparent header that carries the trace id and parent span id between services so spans join into one trace.
cardinality
The number of distinct label-value combinations of a metric. Each one is a separate time series.