SRE Exercises
Each exercise is a small piece of SRE logic written as a pure function, with the calls already in place. Run
the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked
TODO until the output matches the expected output, then compare with the solution. The last exercise is a real
promtool test with a bug to fix.
Exercise 1: An availability SLI with exclusions
Topics: Choosing SLIs, Computing SLIs from Request Logs
Count valid and good events. Health checks and load-test traffic (user agent containing loadtest) are not valid;
client errors (4xx) are not valid except 429; good means status below 500 and not 429.
RECORDS = [ # (route, status, user agent)
("GET /cart", 200, "Mozilla/5.0"), ("GET /healthz", 200, "kube-probe/1.37"),
("POST /checkout", 503, "Mozilla/5.0"), ("GET /cart", 404, "Mozilla/5.0"),
("POST /checkout", 201, "Mozilla/5.0"), ("POST /checkout", 429, "Mozilla/5.0"),
("GET /cart", 200, "k6/1.4 (loadtest)"), ("GET /cart", 500, "Mozilla/5.0"),
("POST /checkout", 201, "Mozilla/5.0"), ("GET /cart", 200, "Mozilla/5.0"),
]
def availability(records):
# TODO: skip invalid records, count valid and good ones
return len(records), len(records)
good, valid = availability(RECORDS)
print(f"{good}/{valid} = {good / valid:.1%}")10/10 = 100.0%
Expected output:
4/7 = 57.1%Show solution
def availability(records):
valid = good = 0
for route, status, ua in records:
if route == "GET /healthz" or "loadtest" in ua:
continue
if 400 <= status < 500 and status != 429:
continue
valid += 1
good += status < 500 and status != 429
return good, validThree of the ten records are not valid (the probe, the load test, the 404). Of the seven valid ones, the 503, the 429 and the 500 are bad.
Exercise 2: Burn rate and budget forecast
Topics: Error Budgets, Burn Rate
Given the requests so far in a 28-day window, return the burn rate, the share of the whole window's budget
already used (burn rate × elapsed days / window days), and a verdict: budget exhausted when the share is 100% or
more, otherwise how many more days the remaining budget lasts at the current burn rate.
def burn_report(slo, valid, bad, elapsed_days, window_days=28):
# TODO: compute the burn rate, the share used and the verdict
return 0.0, 0.0, "TODO"
for slo, valid, bad, elapsed in [(0.999, 2_000_000, 500, 7), (0.999, 2_000_000, 7_600, 7), (0.995, 400_000, 4_400, 14)]:
burn, used, verdict = burn_report(slo, valid, bad, elapsed)
print(f"SLO {slo:.1%}, day {elapsed}: burn rate {burn:.2f}, budget used {used:.0%}, {verdict}")SLO 99.9%, day 7: burn rate 0.00, budget used 0%, TODO
SLO 99.9%, day 7: burn rate 0.00, budget used 0%, TODO
SLO 99.5%, day 14: burn rate 0.00, budget used 0%, TODO
Expected output:
SLO 99.9%, day 7: burn rate 0.25, budget used 6%, lasts 105.0 more days at this rate
SLO 99.9%, day 7: burn rate 3.80, budget used 95%, lasts 0.4 more days at this rate
SLO 99.5%, day 14: burn rate 2.20, budget used 110%, budget exhaustedShow solution
def burn_report(slo, valid, bad, elapsed_days, window_days=28):
burn = (bad / valid) / (1 - slo)
used = burn * elapsed_days / window_days # share of the window's budget spent so far
if used >= 1:
return burn, used, "budget exhausted"
days_left = (1 - used) * window_days / burn if burn else float("inf")
return burn, used, f"lasts {days_left:.1f} more days at this rate"The second service looks fine on a "99.6% success" dashboard, yet at burn rate 3.8 it has 0.4 days of budget left after one week.
Exercise 3: Page, ticket or nothing?
Topics: Multi-Window, Multi-Burn-Rate Alerts
Given the current burn rate for every window, return the highest severity whose rule fires (both its long and
short window above the threshold), or none.
RULES = [ # (severity, long window, short window, burn rate)
("page", "1h", "5m", 14.4), ("page", "6h", "30m", 6),
("ticket", "1d", "2h", 3), ("ticket", "3d", "6h", 1),
]
def decide(burn):
# TODO: check the rules in order
return "?"
CASES = {
"outage in progress": {"5m": 900, "30m": 300, "1h": 160, "2h": 80, "6h": 27, "1d": 7, "3d": 2.3},
"outage fixed 10m ago": {"5m": 0.3, "30m": 100, "1h": 150, "2h": 75, "6h": 25, "1d": 6.5, "3d": 2.2},
"steady slow leak": {"5m": 4, "30m": 4, "1h": 4, "2h": 4, "6h": 4, "1d": 4, "3d": 2},
"yesterday's incident": {"5m": 0.4, "30m": 0.5, "1h": 0.4, "2h": 0.5, "6h": 0.4, "1d": 3.5, "3d": 1.4},
"short blip": {"5m": 60, "30m": 10, "1h": 5, "2h": 2.6, "6h": 1, "1d": 0.6, "3d": 0.5},
}
for name, burn in CASES.items():
print(f"{name:<22} -> {decide(burn)}")outage in progress -> ?
outage fixed 10m ago -> ?
steady slow leak -> ?
yesterday's incident -> ?
short blip -> ?
Expected output:
outage in progress -> page
outage fixed 10m ago -> page
steady slow leak -> ticket
yesterday's incident -> none
short blip -> noneShow solution
def decide(burn):
for severity, long_w, short_w, threshold in RULES:
if burn[long_w] > threshold and burn[short_w] > threshold:
return severity
return "none""Outage fixed 10 minutes ago" still pages: the 5-minute window has recovered, but the 6-hour/30-minute rule holds until the 30-minute window drops below 6. That's the reset time of that rule. Yesterday's incident keeps the 1-day and 3-day windows high, but the short windows show it's over, so nothing fires.
Exercise 4: Full jitter within a deadline
Topics: Retries, Backoff & Jitter Under Load, Timeouts & Deadlines
full_jitter returns the delay before each retry: a random value between 0 and min(cap, base × 2^n), rounded to
3 decimals, drawn from the given generator. total_within returns how many of those delays fit, in order, into a
time budget.
import random
def full_jitter(attempts, base, cap, rng):
# TODO: one rng.uniform(...) per attempt
return [0.0] * attempts
def total_within(delays, budget):
# TODO: add delays in order while the total stays within the budget
return len(delays)
rng = random.Random(42)
for client in range(3):
d = full_jitter(6, base=0.1, cap=2.0, rng=rng)
print(f"client {client}: {d} retries that fit in 2 s: {total_within(d, 2.0)}")client 0: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] retries that fit in 2 s: 6
client 1: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] retries that fit in 2 s: 6
client 2: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] retries that fit in 2 s: 6
Expected output:
client 0: [0.064, 0.005, 0.11, 0.179, 1.178, 1.353] retries that fit in 2 s: 5
client 1: [0.089, 0.017, 0.169, 0.024, 0.35, 1.011] retries that fit in 2 s: 6
client 2: [0.003, 0.04, 0.26, 0.436, 0.353, 1.179] retries that fit in 2 s: 5Show solution
def full_jitter(attempts, base, cap, rng):
return [round(rng.uniform(0, min(cap, base * 2 ** n)), 3) for n in range(attempts)]
def total_within(delays, budget):
total, used = 0.0, 0
for d in delays:
if total + d > budget:
break
total += d
used += 1
return usedThe three clients retry at different moments although they failed together, which is the point of jitter.
Exercise 5: Trace a circuit breaker
Topics: Circuit Breakers
Each character of the input is the outcome the dependency would give (+ success, x failure). The breaker
opens after 3 consecutive failures, then rejects the next 2 calls without calling (R in the trace), then lets one
probe through (half-open): a successful probe closes it, a failed one opens it again. Return the trace and the
final state.
def breaker(outcomes, fail_limit=3, open_calls=2):
# TODO: track state, consecutive failures and calls left to reject
trace = ["+" if ok else "x" for ok in outcomes]
return "".join(trace), "closed"
for seq in ["+++x+x++", "+xxx+++++", "xxxxxxxx+++", "xxx++x+++"]:
outcomes = [c == "+" for c in seq]
trace, final = breaker(outcomes)
print(f"{seq:<12} -> {trace:<12} final state {final}")+++x+x++ -> +++x+x++ final state closed
+xxx+++++ -> +xxx+++++ final state closed
xxxxxxxx+++ -> xxxxxxxx+++ final state closed
xxx++x+++ -> xxx++x+++ final state closed
Expected output:
+++x+x++ -> +++x+x++ final state closed
+xxx+++++ -> +xxxRR+++ final state closed
xxxxxxxx+++ -> xxxRRxRR+++ final state closed
xxx++x+++ -> xxxRRxRR+ final state closedShow solution
def breaker(outcomes, fail_limit=3, open_calls=2):
state, fails, rejected_left, trace = "closed", 0, 0, []
for ok in outcomes:
if state == "open":
if rejected_left > 0:
rejected_left -= 1
trace.append("R") # rejected without calling
continue
state = "half-open"
trace.append("+" if ok else "x")
if state == "half-open":
state = "closed" if ok else "open"
fails, rejected_left = 0, open_calls
continue
fails = 0 if ok else fails + 1
if fails >= fail_limit:
state, rejected_left = "open", open_calls
return "".join(trace), stateIn the third sequence the first probe fails (x after RR), so the breaker opens again and only the second
probe closes it.
Exercise 6: Fix the burn-rate rule
Topics: Burn-Rate Alert Rules & Their Tests
The rules below belong to a 99.9% SLO, and the test describes a 30-minute incident (about 9% errors) from minute
61. The test expects a page 9 minutes into the incident, but it fails. Find the bug in rules.yml and fix it so
that the test passes.
cat > rules.yml <<'YML'
groups:
- name: checkout-slo
rules:
- record: job:slo_errors_per_request:ratio_rate5m
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[5m])) / sum by (job) (rate(http_requests_total[5m]))
- record: job:slo_errors_per_request:ratio_rate1h
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[1h])) / sum by (job) (rate(http_requests_total[1h]))
- alert: CheckoutErrorBudgetBurn
expr: |
job:slo_errors_per_request:ratio_rate1h > (14.4 * 0.01)
and
job:slo_errors_per_request:ratio_rate5m > (14.4 * 0.01)
labels:
severity: page
YML
cat > test.yml <<'YML'
rule_files: [rules.yml]
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'http_requests_total{job="checkout",code="200"}'
values: '0+1999x180'
- series: 'http_requests_total{job="checkout",code="500"}'
values: '0+1x60 260+200x29 6061+1x89'
alert_rule_test:
- eval_time: 1h8m
alertname: CheckoutErrorBudgetBurn
exp_alerts: []
- eval_time: 1h9m
alertname: CheckoutErrorBudgetBurn
exp_alerts:
- exp_labels: {job: checkout, severity: page}
- eval_time: 1h40m
alertname: CheckoutErrorBudgetBurn
exp_alerts: []
YML
promtool test rules test.yml 2>&1 | grep -v '^