All lessons · Guided routes

Capstone 6 of 10

Capstone 6: Run an incident from alert to postmortem

A release goes out on a Friday afternoon and a quarter of orders start failing. You measure it against the SLO, page on the burn rate, run the incident with clear roles, find the cause, roll back, prove recovery, and write a blameless postmortem.

What you build

  1. SLI and SLO

    Availability of /orders, 99.5% over 30 days, and the error budget that follows from it.

    Lessons: SLOs in Practice: SLIs, Error Budgets, and Multi-Window Burn-Rate Alerts, Engineering Metrics: KPI, KRI, OKR, SLA, SLI, SLO, and Error Budgets

  2. Burn-rate alert

    The bad release (2.0.0, 25% errors) burns the budget about 28 times faster than allowed; the fast-burn alert pages.

    Lessons: SLOs in Practice: SLIs, Error Budgets, and Multi-Window Burn-Rate Alerts

  3. Incident command

    An incident record with a commander, an operations lead, a communications lead, and timed updates.

    Lessons: Incident Management and On-Call, Incident Command, Communications, Status Pages, and Postmortems

  4. Diagnosis

    Errors split by version point at 2.0.0; the logs show what changed.

    Lessons: Root Cause Analysis

  5. Mitigation and recovery

    Roll back to 1.0.0 and prove the error rate returns under the SLO.

    Lessons: When One Fails, Another Steps In

  6. Postmortem

    A blameless postmortem with timeline, impact in budget minutes, causes, and actions with owners.

    Lessons: Incident Command, Communications, Status Pages, and Postmortems

Before you start

ToolVersion
python33.10 or later

Ports: 18086 on 127.0.0.1. Resources: Under 100 MB of memory; standard library only.

What it creates (and the reset removes): one python3 orders.py process; ~/labs/capstones/sre (incident record and postmortem). Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 06-sre-incident

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

python3 06-sre-incident/sre.py setup
python3 06-sre-incident/sre.py verify
python3 06-sre-incident/sre.py reset

Expected output

This is a real run of run.sh 06-sre-incident, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. The SLO: 99% of /orders requests succeed over 30 days; burn-rate alerts page at 14.4x and ticket at 6x
   version 1.0.0: 200 requests, availability 100.00%
== 2. A deploy: version 2.0.0, with a bug that fails 25% of requests
   version 2.0.0: 300 requests, availability 73.33%
== SLI and error budget
  PASS  1.0.0 meets the SLO: 100.00% of 200
  PASS  2.0.0 misses it: 73.33% of 300
   burn rate 26.7x: at this rate the month's budget lasts 1.1 days (27 hours)
== Alerting (multi-window burn rate)
  PASS  the fast-burn alert fires and pages (26.7x >= 14.4x)
== Incident command
  PASS  roles assigned (commander, communications, operations) and a status update posted
== Diagnosis: what changed, and does the error follow it?
  PASS  error rate by version: {'1.0.0': 0.0, '2.0.0': 26.7}: the errors start with 2.0.0
== Mitigation: roll back
  PASS  recovered: 100.00% of 300 requests, burn rate 0.0x
   error budget for these 800 requests: 8.0 failures allowed, 80 spent (1000%)
== Postmortem
  PASS  postmortem written with impact, a 6-entry timeline, cause, and owned action items

RESULT: all checks passed

The files

06-sre-incident/sre.py
#!/usr/bin/env python3
"""Capstone 6, SRE incident: SLI/SLO -> alert -> error-budget burn -> incident command -> diagnosis ->
mitigation -> rollback -> recovery -> postmortem.

Against a real local service (orders.py on port 18086). Standard library only; ~/labs/capstones/sre.
  python3 sre.py setup     SLO, version 1.0.0 healthy, then a bad deploy (2.0.0, 25% errors)
  python3 sre.py verify    measure, alert, command, diagnose, roll back, recover, write the postmortem
  python3 sre.py reset
"""
import json
import os
import shutil
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "..", "app", "orders.py")
WORK = os.path.expanduser("~/labs/capstones/sre")
PORT = 18086
URL = f"http://127.0.0.1:{PORT}"
SLO = {"service": "orders", "sli": "share of /orders requests that return a non-5xx status", "objective": 99.0, "window_days": 30,
       "alerts": [{"name": "fast burn", "long": 60, "short": 5, "burn": 14.4, "action": "page"},
                  {"name": "slow burn", "long": 360, "short": 30, "burn": 6, "action": "ticket"}]}
FAILS = []


def p(*x): return os.path.join(WORK, *x)
def ok(m): print("  PASS ", m)
def bad(m): FAILS.append(m); print("  FAIL ", m)
def ts(): return time.strftime("%H:%M:%S", time.gmtime())


def start(version, fail_rate):
    env = dict(os.environ, PORT=str(PORT), VERSION=version, FAIL_RATE=str(fail_rate))
    proc = subprocess.Popen([sys.executable, APP], env=env, stdout=open(p("service.log"), "a"), stderr=subprocess.STDOUT, start_new_session=True)
    open(p("service.pid"), "w").write(str(proc.pid))
    for _ in range(50):
        try:
            urllib.request.urlopen(URL + "/readyz", timeout=1); return
        except OSError:
            time.sleep(0.1)


def stop():
    try:
        os.kill(int(open(p("service.pid")).read()), signal.SIGTERM); time.sleep(0.5)
    except (OSError, ValueError):
        pass


def traffic(n):
    for _ in range(n):
        try:
            urllib.request.urlopen(URL + "/orders", timeout=2).read()
        except urllib.error.HTTPError as e:
            e.close()
        except OSError:
            pass


def requests_since(mark):
    """The SLI, from the service's own JSON request logs: lines after line number `mark`."""
    rows = []
    for k, line in enumerate(open(p("service.log"))):
        if k < mark:
            continue
        try:
            e = json.loads(line)
        except json.JSONDecodeError:
            continue
        if e.get("msg") == "request" and e.get("route") == "/orders":
            rows.append(e)
    return rows


def lines(): return sum(1 for _ in open(p("service.log")))


def sli(rows):
    good = sum(1 for r in rows if r["status"] < 500)
    return (good / len(rows) * 100) if rows else 100.0, len(rows), len(rows) - good


def burn(rows):
    a, n, badn = sli(rows)
    return (badn / n) / (1 - SLO["objective"] / 100) if n else 0.0


def setup():
    shutil.rmtree(WORK, ignore_errors=True); os.makedirs(WORK)
    json.dump(SLO, open(p("slo.json"), "w"), indent=1)
    print("== 1. The SLO: 99% of /orders requests succeed over 30 days; burn-rate alerts page at 14.4x and ticket at 6x")
    start("1.0.0", 0); traffic(200)
    open(p("marks.json"), "w").write(json.dumps({"v1": 0}))
    a, n, b = sli(requests_since(0)); print(f"   version 1.0.0: {n} requests, availability {a:.2f}%")
    print("== 2. A deploy: version 2.0.0, with a bug that fails 25% of requests")
    m = lines(); stop(); start("2.0.0", 0.25); traffic(300)
    json.dump({"v1": 0, "v2": m, "deploy_at": ts()}, open(p("marks.json"), "w"))
    a, n, b = sli(requests_since(m)); print(f"   version 2.0.0: {n} requests, availability {a:.2f}%")


def verify():
    marks = json.load(open(p("marks.json")))
    timeline = [f"{marks['deploy_at']} orders 2.0.0 deployed"]
    print("== SLI and error budget")
    v1, v2 = requests_since(0)[:0] or [r for r in requests_since(0) if r["version"] == "1.0.0"], [r for r in requests_since(marks["v2"]) if r["version"] == "2.0.0"]
    a1, n1, b1 = sli(v1); a2, n2, b2 = sli(v2)
    (ok if a1 >= SLO["objective"] else bad)(f"1.0.0 meets the SLO: {a1:.2f}% of {n1}")
    (ok if a2 < SLO["objective"] else bad)(f"2.0.0 misses it: {a2:.2f}% of {n2}")
    br = burn(v2)
    days = SLO["window_days"] / br if br else float("inf")
    print(f"   burn rate {br:.1f}x: at this rate the month's budget lasts {days:.1f} days ({days * 24:.0f} hours)")
    print("== Alerting (multi-window burn rate)")
    fired = [a for a in SLO["alerts"] if br >= a["burn"]]
    (ok if fired and fired[0]["action"] == "page" else bad)(f"the fast-burn alert fires and pages ({br:.1f}x >= 14.4x)")
    timeline.append(f"{ts()} fast-burn alert fired (burn {br:.1f}x); on-call paged")
    print("== Incident command")
    inc = {"id": "INC-2026-1128-01", "severity": "SEV-2", "commander": "asha", "communications": "ravi", "operations": "lee",
           "status_page": "Degraded: some orders fail; we are investigating", "started": ts()}
    json.dump(inc, open(p("incident.json"), "w"), indent=1)
    (ok if all(inc[k] for k in ("commander", "communications", "operations", "status_page")) else bad)("roles assigned (commander, communications, operations) and a status update posted")
    timeline.append(f"{ts()} incident {inc['id']} declared, {inc['severity']}; roles assigned")
    print("== Diagnosis: what changed, and does the error follow it?")
    by = {}
    for r in requests_since(0):
        by.setdefault(r["version"], [0, 0]); by[r["version"]][0] += 1; by[r["version"]][1] += r["status"] >= 500
    rates = {v: round(e / n * 100, 1) for v, (n, e) in by.items()}
    (ok if rates.get("1.0.0", 1) == 0 and rates.get("2.0.0", 0) > 10 else bad)(f"error rate by version: {rates}: the errors start with 2.0.0")
    timeline.append(f"{ts()} cause identified: errors only in version 2.0.0 ({rates.get('2.0.0')}%)")
    print("== Mitigation: roll back")
    m = lines(); stop(); start("1.0.0", 0); traffic(300)
    timeline.append(f"{ts()} rolled back to 1.0.0")
    rec = requests_since(m)
    ar, nr, brr = sli(rec)
    (ok if ar >= SLO["objective"] and burn(rec) < 1 else bad)(f"recovered: {ar:.2f}% of {nr} requests, burn rate {burn(rec):.1f}x")
    timeline.append(f"{ts()} recovery confirmed; burn rate below 1x")
    budget = (1 - SLO["objective"] / 100) * (n1 + n2 + nr)
    spent = b1 + b2 + brr
    print(f"   error budget for these {n1 + n2 + nr} requests: {budget:.1f} failures allowed, {spent} spent ({spent / budget * 100:.0f}%)")
    print("== Postmortem")
    pm = ["# Postmortem: " + inc["id"], "", "Blameless. Times in UTC.", "", "## Impact", f"- {b2} of {n2} order requests failed during version 2.0.0 ({100 - a2:.1f}%).",
          f"- Error budget: {spent} of {budget:.1f} allowed failures for this traffic ({spent / budget * 100:.0f}%).", "", "## Timeline", *[f"- {t}" for t in timeline], "",
          "## Cause", "Version 2.0.0 shipped a defect that failed a quarter of /orders requests. No canary stage caught it before full rollout.", "",
          "## What went well", "- The fast-burn alert paged within one evaluation.", "- Errors by version pointed at the deploy at once; rollback took one step.", "",
          "## Action items", "| Action | Owner | Due |", "|---|---|---|", "| Add a canary stage that compares error rates before full rollout | team-orders | next sprint |",
          "| Run the failing request in the test suite | team-orders | this week |", "| Rehearse rollback in the monthly game day | sre | next game day |"]
    open(p("postmortem.md"), "w").write("\n".join(pm) + "\n")
    text = open(p("postmortem.md")).read()
    (ok if all(s in text for s in ("## Impact", "## Timeline", "## Cause", "## Action items", "Owner")) and len(timeline) >= 5 else bad)(f"postmortem written with impact, a {len(timeline)}-entry timeline, cause, and owned action items")
    print("\nRESULT:", "all checks passed" if not FAILS else f"{len(FAILS)} check(s) failed")
    sys.exit(1 if FAILS else 0)


def reset():
    if os.path.exists(p("service.pid")):
        stop()
    shutil.rmtree(WORK, ignore_errors=True)
    print(f"capstone 6 reset: service stopped, {WORK} removed")


if __name__ == "__main__":
    {"setup": setup, "verify": verify, "reset": reset}.get(sys.argv[1] if len(sys.argv) > 1 else "", lambda: sys.exit(__doc__))()

If it fails

SymptomCauseFix
"port 18086 is in use"An earlier run is still going.python3 sre.py reset, then run again.
The burn rate differs from the pageThe 25% failure is random, so each run measures a slightly different rate.That is expected; the check only needs it above the paging threshold.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

python3 06-sre-incident/sre.py reset

It removes: one python3 orders.py process; ~/labs/capstones/sre (incident record and postmortem). Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSCloudWatch SLOs (Application Signals) with burn-rate alarms, and Incident Manager for response plans and timelines.
AzureAzure Monitor alerts on SLO queries, with action groups paging on call.
Google CloudCloud Monitoring SLOs with burn-rate alerting policies.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
DetectionThe alert fires on burn rate, not on a single error.Fast and slow burn windows are both defined.
CommandRoles and an update cadence are in the record.Communications are written for customers, not engineers.
RecoveryRecovery is proven by measurement after the rollback.You know how much error budget the incident cost.
LearningThe postmortem is blameless and has owned actions.Each action prevents a class of incident, not just this one.

Take it further

Then test what you know with the assessments.

Next capstone: A small internal developer platform. All capstones · Guided routes