TExcelTAD

Observability Exercises

Each exercise is a small piece of observability 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: increase() with counter resets

Topics: rate(), irate() & increase(), Metric Types

Given counter samples (time, value), return the total increase, treating any drop as a restart from zero (no extrapolation). Then return the per-second rate over the time the samples span.

python · try it yourself
samples = [(0, 100), (15, 160), (30, 220), (45, 10), (60, 70), (75, 130), (90, 5), (105, 50)]

def increase(samples):
    # TODO: add up positive differences; after a drop, the new value itself is the increase
    return samples[-1][1] - samples[0][1]

def per_second(samples):
    return increase(samples) / (samples[-1][0] - samples[0][0])

print("increase:", increase(samples))
print(f"rate: {per_second(samples):.3f}/s")
increase: -50
rate: -0.476/s

Expected output:

text
increase: 300
rate: 2.857/s
Show solution
python
def increase(samples):
    total = 0
    for (_, prev), (_, cur) in zip(samples, samples[1:]):
        total += cur - prev if cur >= prev else cur
    return total

Two restarts (220 → 10, 130 → 5). Prometheus does the same reset handling inside rate(), then extrapolates to the window's edges, which is why its numbers are slightly larger.

Exercise 2: histogram_quantile

Topics: Histograms & Quantiles

Given cumulative buckets (upper_bound, count) ending with +Inf, estimate a quantile like Prometheus: find the bucket holding rank q × total, interpolate linearly inside it (the first bucket starts at 0), and return the highest finite bound if the rank falls into +Inf.

python · try it yourself
INF = float("inf")
buckets = [(0.05, 700), (0.1, 900), (0.25, 960), (0.5, 990), (1.0, 998), (INF, 1000)]

def histogram_quantile(q, buckets):
    # TODO: rank = q * total; find the bucket; interpolate between its lower and upper bound
    return 0.0

for q in (0.5, 0.9, 0.99, 0.999):
    print(f"p{q * 100:g}: {histogram_quantile(q, buckets):.4f}")
p50: 0.0000
p90: 0.0000
p99: 0.0000
p99.9: 0.0000

Expected output:

text
p50: 0.0357
p90: 0.1000
p99: 0.5000
p99.9: 1.0000
Show solution
python
def histogram_quantile(q, buckets):
    total = buckets[-1][1]
    rank = q * total
    lower, below = 0.0, 0
    for bound, count in buckets:
        if count >= rank:
            if bound == INF:
                return lower                      # highest finite bound
            return lower + (bound - lower) * (rank - below) / (count - below)
        lower, below = bound, count
    return lower

p99.9 lands in +Inf (2 requests above 1 s), so the answer is just "at least 1 s". Add a bucket above your timeout.

Exercise 3: an Alertmanager routing tree

Topics: Alertmanager: Routing & Grouping

Implement routing: an alert enters the root; among the root's child routes, take every match in order until one without continue; if no child matched, the root's receiver gets it. (One level of children is enough.)

python · try it yourself
ROOT = {"receiver": "catch-all", "routes": [
    {"match": {"severity": "page"}, "receiver": "pagerduty", "continue": True},
    {"match": {"team": "db"}, "receiver": "db-slack"},
    {"match": {"severity": "ticket"}, "receiver": "tickets"},
]}

def route(alert, root):
    # TODO: walk root["routes"]; all keys in "match" must equal the alert's labels
    return [root["receiver"]]

for alert in ({"severity": "page", "team": "links"}, {"severity": "page", "team": "db"},
              {"severity": "ticket", "team": "db"}, {"severity": "ticket", "team": "links"}, {"severity": "info"}):
    print(alert, "->", ",".join(route(alert, ROOT)))
{'severity': 'page', 'team': 'links'} -> catch-all
{'severity': 'page', 'team': 'db'} -> catch-all
{'severity': 'ticket', 'team': 'db'} -> catch-all
{'severity': 'ticket', 'team': 'links'} -> catch-all
{'severity': 'info'} -> catch-all

Expected output (compare with the real amtool config routes test results in the Alertmanager lesson):

text
{'severity': 'page', 'team': 'links'} -> pagerduty
{'severity': 'page', 'team': 'db'} -> pagerduty,db-slack
{'severity': 'ticket', 'team': 'db'} -> db-slack
{'severity': 'ticket', 'team': 'links'} -> tickets
{'severity': 'info'} -> catch-all
Show solution
python
def route(alert, root):
    receivers = []
    for r in root["routes"]:
        if all(alert.get(k) == v for k, v in r["match"].items()):
            receivers.append(r["receiver"])
            if not r.get("continue"):
                break
    return receivers or [root["receiver"]]

Exercise 4: a cardinality budget

Topics: Labels & Cardinality

A team proposes new metrics. For each, compute the worst-case series count (product of label value counts × targets × series per metric: 1 for counters and gauges, buckets + 2 for histograms) and flag any above the budget of 10,000.

python · try it yourself
TARGETS = 20
BUDGET = 10_000
proposals = [
    ("linkly_redirects_total", "counter", {"code": 3, "cache": 2}, 0),
    ("linkly_request_duration_seconds", "histogram", {"route": 5, "code": 6}, 12),
    ("linkly_link_clicks_total", "counter", {"short_code": 250_000}, 0),
    ("linkly_db_query_duration_seconds", "histogram", {"query": 8}, 10),
]

def series(kind, labels, buckets):
    # TODO
    return 0

for name, kind, labels, buckets in proposals:
    n = series(kind, labels, buckets)
    print(f"{name:34} {n:>11,}  {'OVER BUDGET' if n > BUDGET else 'ok'}")
linkly_redirects_total                       0  ok
linkly_request_duration_seconds              0  ok
linkly_link_clicks_total                     0  ok
linkly_db_query_duration_seconds             0  ok

Expected output:

text
linkly_redirects_total                     120  ok
linkly_request_duration_seconds          8,400  ok
linkly_link_clicks_total             5,000,000  OVER BUDGET
linkly_db_query_duration_seconds         1,920  ok
Show solution
python
from math import prod

def series(kind, labels, buckets):
    per_metric = buckets + 2 if kind == "histogram" else 1
    return prod(labels.values()) * TARGETS * per_metric

Clicks per short code belong in the database or in logs (count_over_time in Loki), not in Prometheus.

Exercise 5: errors by message from JSON logs

Topics: Structured JSON Logging, LogQL Metric Queries

Count ERROR lines by msg (skipping lines that aren't JSON) and return the top two, most frequent first, the way topk(2, sum by (msg) (count_over_time({…} | json | level="ERROR" [5m]))) would.

python · try it yourself
import json

LINES = """{"level":"ERROR","msg":"create link failed","error":"timeout"}
{"level":"INFO","msg":"redirect"}
{"level":"ERROR","msg":"redis unavailable"}
panic: runtime error: index out of range
{"level":"ERROR","msg":"create link failed","error":"timeout"}
{"level":"WARN","msg":"slow redirect"}
{"level":"ERROR","msg":"invalid url"}
{"level":"ERROR","msg":"create link failed","error":"conn refused"}
{"level":"ERROR","msg":"redis unavailable"}""".splitlines()

def top_errors(lines, k):
    # TODO: parse each line (skip invalid JSON), keep level == "ERROR", count by msg
    return []

for msg, n in top_errors(LINES, 2):
    print(f"{n} {msg}")
print("done")
done

Expected output:

text
3 create link failed
2 redis unavailable
done
Show solution
python
from collections import Counter

def top_errors(lines, k):
    counts = Counter()
    for line in lines:
        try:
            rec = json.loads(line)
        except json.JSONDecodeError:
            continue
        if rec.get("level") == "ERROR":
            counts[rec["msg"]] += 1
    return counts.most_common(k)

The panic line is skipped here, but in real life it's the most important line of all: alert on non-JSON lines too.

Exercise 6: fix the alert test

Topics: Unit Testing Rules with promtool, Alerting Rules

This test fails. The rule is right; the test has two mistakes. Fix the test file so promtool test rules prints SUCCESS (you can edit the session and run it).

bash · try it yourself
cat > rules.yml <<'YML'
groups:
  - name: linkly
    rules:
      - alert: LinklyRedirectsStopped
        expr: sum(rate(linkly_redirects_total[5m])) == 0
        for: 10m
        labels: {severity: page}
YML
cat > test.yml <<'YML'
rule_files: [rules.yml]
tests:
  - interval: 1m
    input_series:
      - series: 'linkly_redirects_total{instance="api-1"}'
        values: '0+100x10 1000x30'        # traffic, then nothing from minute 10 on
    alert_rule_test:
      - eval_time: 18m
        alertname: LinklyRedirectsStopped
        exp_alerts:
          - exp_labels: {severity: page, instance: api-1}
YML
promtool test rules test.yml
  FAILED:
    alertname: LinklyRedirectsStopped, time: 18m, 
        exp:[
            0:
              Labels:{alertname="LinklyRedirectsStopped", instance="api-1", severity="page"}
              Annotations:{}
            ], 
        got:[]

Expected output:

text
  SUCCESS
Show solution
  1. sum(...) removes every label, so the alert has no instance: expect {severity: page} only.
  2. The counter stops growing at 10 m, but rate(…[5m]) only reaches 0 once the window no longer contains any growth (about 14 m), and for: 10m adds ten more minutes: the alert fires around 24 m, not at 18 m. Use eval_time: 26m (and add a check at 18 m with exp_alerts: []).
yaml
    alert_rule_test:
      - eval_time: 18m
        alertname: LinklyRedirectsStopped
        exp_alerts: []
      - eval_time: 26m
        alertname: LinklyRedirectsStopped
        exp_alerts:
          - exp_labels: {severity: page}

Test yourself

In Exercise 2, why is p99.9 reported as exactly 1.0?

  1. The data is wrong
  2. The rank falls in the +Inf bucket, so the highest finite bound is returned
  3. Rounding
  4. Because of linear interpolation

In Exercise 6, why does the alert fire only around 24 minutes?

  1. promtool is slow
  2. The 5-minute rate window must contain no more growth (about 14 m), then for: 10m must elapse
  3. Alerts fire at fixed times
  4. The interval is 1m