Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 11 / Stage 3

Reliability and observability

Goal: Know what your service is doing, and keep it doing it when its dependencies fail — percentiles, timeouts, circuit breakers, correlation IDs, and alerts users would agree with. Time: ~3.5 hours · Needs: Python 3.14+, the course venv

What you will learn

  • Logs, metrics and traces: what each answers
  • Latency percentiles: p50, p95, p99, and why the mean misleads
  • Timeouts on every outbound call
  • Retries and circuit breakers
  • Correlation IDs across services
  • Dashboards and alerts on symptoms users feel
  • Debugging on someone else's systems

Topics in this part

Practice

Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.

Exercise 1: A percentile helper

Write latency_report(samples) returning a dict with mean, p50, p95, p99 (using statistics.quantiles). Feed it a seeded distribution with a 1% tail of 5-second requests and print the report — the gap between mean and p99 should be obvious.

Show the solution to Exercise 1
# Exercise 1: mean vs tail, measured
import random, statistics

def latency_report(samples):
    q = statistics.quantiles(samples, n=100)
    return {"mean": round(statistics.mean(samples)), "p50": round(q[49]),
            "p95": round(q[94]), "p99": round(q[98])}

random.seed(11)
samples = [random.gauss(150, 25) for _ in range(990)] + [random.uniform(4500, 5500) for _ in range(10)]
print(latency_report(samples))

Exercise 2: Budgeted timeouts

Write budget_timeouts(user_budget_s, hops) that splits a user-facing latency budget across N sequential downstream calls, reserving 20% headroom, and returns the per-hop timeout. Show the result for a 3 s budget across 1, 2 and 4 hops.

Show the solution to Exercise 2
# Exercise 2: split a user budget across sequential hops
def budget_timeouts(user_budget_s, hops):
    usable = user_budget_s * 0.8          # 20% headroom for our own work
    return round(usable / hops, 2)

for hops in (1, 2, 4):
    print(f"3s budget, {hops} hop(s): {budget_timeouts(3.0, hops)}s per call")

Exercise 3: Breaker recovery

Extend the lesson's CircuitBreaker so a successful call in the half-open state closes the circuit (reset failures). Simulate: 3 failures, cooldown passes, dependency recovered, then two healthy calls — show the states along the way.

Show the solution to Exercise 3
# Exercise 3: a success in half-open closes the circuit
class CircuitBreaker:
    def __init__(self, threshold=3, cooldown_s=30.0, clock=None):
        self.threshold, self.cooldown, self.clock = threshold, cooldown_s, clock
        self.failures, self.opened_at = 0, None

    def state(self):
        if self.opened_at is None:
            return "closed"
        return "open" if self.clock() - self.opened_at < self.cooldown else "half-open"

    def call(self, fn):
        if self.state() == "open":
            return "skipped: circuit open"
        half_open = self.state() == "half-open"
        try:
            result = fn()
            self.failures, self.opened_at = 0, None     # success closes the circuit
            return result + (" (circuit closed again)" if half_open else "")
        except Exception as e:
            self.failures += 1
            if self.failures >= self.threshold:
                self.opened_at = self.clock()
            return f"failed: {e}"

now = [0.0]
breaker = CircuitBreaker(clock=lambda: now[0])
healthy = [False]
def acme():
    if not healthy[0]:
        raise ConnectionError("Acme API timeout")
    return "ok"

for t, up in [(0, False), (1, False), (2, False), (3, False), (35, True), (36, True)]:
    now[0], healthy[0] = t, up
    print(f"t={t:>2}s state={breaker.state():9s} ->", breaker.call(acme))

Exercise 4: Correlation middleware (conceptually)

Write with_request_id(handler) that generates an 8-char id when the caller supplies none, passes it to the handler, and returns (response, request_id). Log two fake events inside the handler carrying the id and show both log lines share it.


Show the solution to Exercise 4
# Exercise 4: one id follows the request through every log line
import json, uuid

def with_request_id(handler, request_id=None):
    rid = request_id or uuid.uuid4().hex[:8]
    return handler(rid), rid

def handler(rid):
    lines = []
    for msg in ("fetch started", "fetch finished"):
        lines.append(json.dumps({"msg": msg, "request_id": rid}))
    return lines

lines, rid = with_request_id(handler)
for line in lines:
    print(line)
assert all(rid in line for line in lines)
print("both lines share", rid)

Mini-project: Observable sync service

Wrap the Part 8 sync in observability: JSON logs with a correlation ID per run, latency recorded per request with a percentile report at the end, and the circuit breaker around the (simulated) Acme API — demonstrated once healthy and once with the API failing hard.

A solution is in solutions/mini_observable_sync.py.

Stretch: add a dashboard spec and two alerts (error rate, p95 latency), each with a runbook link.

Common mistakes

Mistake Why it hurts Fix
Reporting mean latency The suffering 2% are invisible p50 / p95 / p99
No timeout on an outbound call A hung dependency stalls the whole service Explicit timeout on every call, sized to the caller's budget
Retrying into an outage You help take the dependency down Circuit breaker around retried calls
Logs without a shared ID Multi-service failures are unsearchable Correlation ID in every line and header
Alerting on CPU Pages without user pain; real pain unpaged Alert on error rate, latency, freshness
Experimenting in the customer's prod Trust, audit, and uptime all at risk Evidence first; reproduce lower; narrate changes

Quick recap

  • Logs say what happened, metrics say how much and how fast, and traces say where the time went.
  • Percentiles tell the truth about latency; the mean does not.
  • Give every outbound call a timeout, and name that timeout in the error message.
  • A circuit breaker moves from closed to open for a cooldown, then to half-open, and from there back to closed — or open again.
  • Give each request one correlation ID and carry it in every log line and header.
  • Alert on symptoms with runbooks attached; debug on their systems with evidence first.

Checklist

  • I ran the percentile example and can explain mean vs p99 in one sentence.
  • I traced the breaker through closed, open, and half-open.
  • I know what timeout each outbound call in my mini-project needs.
  • I added a correlation ID to logs and headers.
  • I can name my service's three symptom alerts.

Read more: Python statistics.quantiles · httpx timeouts

Search the guide