Notes
All notes

Observability (API Design #13)

03:12. PagerDuty: “checkout error rate above 5%.” You open the dashboard: errors, yes — but checkout calls six services. Which one? You grep logs on three machines, find a stack trace in payments, can’t tell which request it belonged to, and notice the deploy that “only changed logging” went out at 22:00. It takes two hours to learn what a good system tells you in two minutes: trace abc123 → payments → INSERT … duplicate key, started with the 22:00 deploy.

Observability is the property of a system that lets you answer “why is it doing that?” from the outside. This chapter covers the three pillars — logs, metrics, traces — and the layer that makes them actionable: SLIs, SLOs, and error budgets, plus the alerting discipline that pages on user pain instead of CPU graphs.

By the end you will be able to instrument an endpoint so a stranger can debug it at 3 a.m., and compute the error budget that decides whether this week’s release ships.

The three pillars, and what each is for

They are complementary, not redundant: the metric tells you p95 spiked at 22:00; the trace shows it’s the fraud-score span; the log inside that span shows the timeout. Any pillar alone leaves you reconstructing the other two by hand at 3 a.m.

Structured logs and correlation IDs

The single highest-leverage observability change costs nothing: emit logs as JSON with a request id on every line. Free-text logs (“user clicked thing”) are write-only; structured logs are queryable:

import logging, uuid, json, time
from fastapi import FastAPI, Request

app = FastAPI()
log = logging.getLogger("api")

@app.middleware("http")
async def observe(request: Request, call_next):
    rid = request.headers.get("x-request-id", str(uuid.uuid4()))
    start = time.monotonic()
    response = await call_next(request)
    ms = (time.monotonic() - start) * 1000
    log.info(json.dumps({
        "request_id": rid, "method": request.method, "path": request.url.path,
        "status": response.status_code, "ms": round(ms, 1),
        "api_key_id": getattr(request.state, "key_id", None),   # Ch. 7 hook
    }))
    response.headers["x-request-id"] = rid       # client can quote it in bug reports
    return response

The correlation id (request id, trace id) is the thread that ties the pillars together: accept it from the client or generate it at the edge, pass it through every internal call (X-Request-ID, or the W3C traceparent header), and log it everywhere. Now “request abc123” retrieves the full story from every service it touched — and the customer’s bug report (“I got an error at 14:32, id abc123”) becomes a one-line query instead of an afternoon.

One warning that belongs to both this chapter and Chapter 15: logs are data, and data has rules. Redact secrets (Chapter 7’s key prefixes) and PII at the logger, not in the retention policy.

Metrics, SLIs, SLOs, and error budgets

Chapter 10’s RED metrics (rate, errors, duration) are the raw material. An SLI (service level indicator) turns one into a proportion of good events, e.g. “fraction of requests served in under 500 ms without 5xx” over a window:

\[ \text{SLI} = \frac{\text{good events}}{\text{total events}} \]

An SLO is the target on the SLI — say 99.9% over 30 days — and the error budget is its complement, the allowance of bad events you’re permitted while still meeting the SLO:

\[ \text{budget} = 1 - \text{SLO} = 0.1\% \;\; \Rightarrow \;\; 43.2 \text{ bad minutes per 30 days} \]

The budget is a management tool, not just math. If this month consumed 20% of the budget, ship features; if it consumed 90%, freeze releases and spend the remainder on reliability deliberately. The error budget ends the oldest argument in engineering — “move fast” vs “be stable” — by pricing instability in a currency both sides agreed on in advance.

Computing the SLI from metrics you already have is a few lines:

def sli_30d(requests: list[dict], latency_budget_ms: float = 500) -> float:
    good = sum(1 for r in requests
               if r["status"] < 500 and r["ms"] <= latency_budget_ms)
    return good / len(requests)

budget_left = (sli_30d(reqs) - 0.999) / (1 - 0.999)   # fraction of budget remaining

Choose the window deliberately: 30-day rolling windows smooth out bad afternoons (and slow your reaction to them); weekly windows react fast but whipsaw release policy. Most teams land on 28–30 days.

Distributed tracing: the waterfall

A trace records one request’s journey as timed spans: each service opens a span, does work, closes it, and links children to the trace id. Rendered as a waterfall:

\begin{tikzpicture}[font=\rmfamily\scriptsize]
  \draw[->, thick] (0,0) -- (10.2,0) node[right] {ms};
  \foreach \x/\l in {0/0, 2/50, 4/100, 6/150, 8/200, 10/250}
    \node[below] at (\x,0) {\l};
  \fill[blue!25]    (0.2,0.5)  rectangle (9.2,0.9);  \node[anchor=west] at (0.2,1.15) {edge: POST /checkout};
  \fill[green!25]   (0.8,1.5)  rectangle (2.2,1.9);  \node[anchor=west] at (2.3,1.7) {users.auth 20};
  \fill[green!25]   (2.4,2.3)  rectangle (7.0,2.7);  \node[anchor=west] at (7.1,2.5) {payments.charge 115};
  \fill[orange!30]  (2.8,3.1)  rectangle (6.6,3.5);  \node[anchor=west] at (6.7,3.3) {fraud.score 95 (p99!)};
  \fill[gray!20]    (7.2,4.1)  rectangle (8.8,4.5);  \node[anchor=west] at (8.9,4.3) {inventory.hold 40};
\end{tikzpicture}

One glance replaces the log-grep expedition: the checkout’s 220 ms is mostly fraud scoring, which is itself mostly waiting. Sampling keeps costs sane (record 1–10% of healthy traces, but always keep errors and slow outliers — tail-based sampling). The trace is also where Chapter 11’s sync chains become visible as what they are: serial bars begging to be parallelized or event-ified.

You do not hand-roll any of this. OpenTelemetry is the vendor-neutral standard — one instrumentation emits traces, metrics, and logs to whatever backend you choose (Jaeger, Grafana, Datadog, Honeycomb), so the vendor can change without re-instrumenting the fleet:

from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor

FastAPIInstrumentor().instrument_app(app)   # spans for every route
RequestsInstrumentor().instrument()         # child spans for outgoing calls

Two lines and every route emits timed spans, every outgoing HTTP call becomes a child span carrying the trace context forward — the propagation that makes the waterfall a single tree instead of six unrelated timelines.

The bill: what telemetry costs

Observability is metered by volume, so volume is a design decision. Logs are the expensive pillar: at request rate \(\lambda\), average \(s\) bytes per structured log line, and \(k\) lines per request, you generate

\[ V_{\text{day}} = \lambda \cdot s \cdot k \cdot 86{,}400 \text{ bytes/day} \]

— at 500 req/s, 1 KB lines, 2 lines per request, that’s ~86 GB/day, and at SaaS logging prices ($0.10–0.50/GB ingested) a real line item. The levers: sample routine success logs (keep all errors), log at the edge in full and inside services at lower verbosity, and keep high-cardinality detail out of metrics (labels like user_id explode a metrics backend long before logs do). Spend telemetry budget where debugging actually happens: errors, slow outliers, and the edges between services.

Alerting: page on pain, not on parts

Classic alerting pages on machine symptoms — CPU 90%, disk 85%, a pod restarted. Some of those matter; none of them is the user’s problem, and each false page teaches the on-call to ignore the next one. SLO-based alerting pages on burn rate: how fast you’re consuming the error budget relative to how fast you’re allowed to:

\[ \text{burn rate} = \frac{\text{observed error rate}}{\text{budgeted error rate}} \]

A burn rate of 1 consumes the budget exactly on schedule; 14.4 consumes a month’s budget in two days — page now. A burn rate of 2 over a slow window files a ticket for business hours. The multi-window trick (fast alert on 1 h + 5 min burn, slow alert on 3-day burn) catches both the catastrophe and the leak. Symptom alerts don’t disappear — they become dashboard annotations for the person investigating the pain alert.

The 3 a.m. story, replayed

Same page, same night, with this chapter in place. The burn-rate alert fires at 03:12 with the trace id of a failing checkout, not a CPU graph. You open the trace: payments.charge is the red span, and its logs — found by the trace id, not by grep — show duplicate key on a constraint introduced by the 22:00 deploy. The error budget for the week is 60% spent, so the playbook says roll back first, fix forward in the morning. Total time to diagnosis: minutes. The difference was never “better engineers at 3 a.m.”; it was correlation ids, traces, and an SLO doing their jobs while everyone slept.

Pitfalls

QQuestionSelf-check

A dashboard shows error rate doubled but every service’s CPU is fine — walk the three pillars to the root cause. Your SLO is 99.9% over 30 days and this month’s budget is 80% spent by day 10 — what does the error budget tell the team to do, and what burn rate does that spending imply? Why is “alert on CPU > 90%” an anti-pattern for an API?

ASolution

Metrics localize when and which endpoint; traces show which span in the request tree eats time or errors; the logs inside that failing span (found via the trace/correlation id) carry the exception and context. 80% of budget spent in one-third of the window is a burn rate of about \(0.8 / (1/3) \approx 2.4\) — you’re consuming budget 2.4× faster than allowed, so the policy answer is: slow feature releases, direct engineering to reliability work, or the remaining 20% won’t stretch across the month. CPU is a machine symptom, not user pain: plenty of outages (a bad deploy returning instant 500s) show low CPU, and plenty of high-CPU moments (a batch job) hurt nobody — page on SLO burn rate, keep CPU as investigation context.

Next: API Lifecycle Management (API Design #14) — versioning, deprecation, idempotency, and RFC 7807 errors: running an API for years without breaking trust.