37 · Structured logging and service metrics
Run it in Colab View the .ipynb
You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.
- 1. Purpose
- 2. Conceptual explanation
- 2.1 Three kinds of telemetry, three different questions
- 2.2 Structured logs
- 2.3 The golden signals, and what to measure for an ML service
- 2.4 Histograms, percentiles and cardinality
- 2.5 SLIs, SLOs and error budgets
- 2.6 How a request flows through the service, and where the exception goes
- 2.7 Connection to other domains
- 2.8 An industry example (illustrative composite, not a documented case)
- 2.9 Limitations and misconceptions
- 3. Worked example: two log lines and two instances (SYNTHETIC)
- 4. Guided lab
- 5. Independent challenge: SLOs you can defend
- 6. Progressive hints
- 7. Assessment
- 8. Reflection and review
- Verification record
- Record your progress
Week 7 · day 1 · 2 h essential path + up to 1 h optional · lab files: labs/w7d1_service_logging_metrics/
Objective. Emit structured request and prediction logs with correlation ids; define the service’s golden signals (traffic, errors, latency, saturation).
# --- Setup: works on your laptop AND in Google Colab ----------------------------
# In Colab this clones the course repository and installs the requirements (about a
# minute, first run only). On your own machine it just finds the repository. Every
# command in this notebook runs from the repository root. Safe to re-run.
import os
import subprocess
import sys
from pathlib import Path
if "google.colab" in sys.modules:
if not Path("/content/mlengineering").exists():
subprocess.run(["git", "clone", "--depth", "1",
"https://github.com/berdakh/mlengineering.git",
"/content/mlengineering"], check=True)
os.chdir("/content/mlengineering")
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"-r", "requirements.txt"], check=True)
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
Unit id w7d1_service_logging_metrics · Week 7, day 1 · Handbook:
H15.1 Service logs and metrics
· Content status: see STATUS.md
1. Purpose
Objective. Make the flowguard API observable: every request gets a correlation id and exactly one
structured (JSON) access-log line, every scored request gets one prediction event that summarises the
input without copying it, and GET /metrics exposes the service’s golden signals (traffic, errors,
latency, saturation) in the Prometheus text format. Then answer “what happened to request X?” from the
log alone.
Why an applied ML engineer needs it. Week 6 ended with a container you could start, stop, roll back and load-test. Once it runs unattended, the only things you will ever know about it are what it wrote down. Two habits decide whether an incident takes ten minutes or a day: logs that a program can filter by key (not sentences you grep with regular expressions), and metrics with a small, fixed set of labels that can be aggregated across instances. ML services add a third: the model’s own behaviour (which version answered, how many samples were scored, how many crossed the threshold) must be recorded next to the HTTP facts, without logging the payload.
Deliverables.
lab/src/flowguard/observability.py: the JSON formatter, the input summary, and the histogram (tasks 1-2).lab/src/flowguard/api.py: the observability middleware,/metrics, the prediction event (task 3).lab/src/flowguard/logquery.py: the request-timeline query behindpython -m flowguard.cli logs(task 4).challenge/slo.pyandchallenge/SLO.md: SLIs, objectives, an error budget and a paging rule.
Completion criteria.
python wb.py check w7d1passes (18 checks: log format, request ids, one access line per request for 200/404/422/500/503, no raw sample values in logs, parseable metrics, counters that move by the right amount, cumulative buckets, an in-flight gauge that returns to baseline after errors, bounded label cardinality, the query tool).lab/replay_demo.pyruns against real SKAB data and you can read its output (task 5).python wb.py check w7d1 --challengepasses, and yourSLO.mdsurvives the rubric in assessment.md (section 7 of this notebook).- You can explain, without notes, why a request id must never be a metric label, and why the access log of a request that crashed the handler is written by code that runs after the exception.
Prerequisites. w1d4 (the logging module: loggers, handlers,
formatters), w5d4 (the service and its request-id middleware),
w5d5 (TestClient, concurrency), w6d4
(latency percentiles). No new packages. For task 5: python project/get_skab.py.
Time budget (2 h essential).
| Activity | Minutes |
|---|---|
| Read section 2 | 25 |
| Worked example | 10 |
| Guided lab: tasks 1-2 (formatter, histogram) | 25 |
Guided lab: task 3 (middleware, /metrics, prediction event) |
30 |
| Guided lab: tasks 4-5 (log query, real replay) | 15 |
Challenge: start slo.py |
5 |
| Assessment and reflection | 10 |
Optional extension: finish SLO.md; run the replay with --workers 2 and explain why the counters halve; add a flowguard_request_bytes histogram |
up to 60 |
2. Conceptual explanation
2.1 Three kinds of telemetry, three different questions
- Metrics are pre-aggregated numbers: counts, sums, bucketed distributions, current values. They answer “how much and how often” and they are what alerts are written on. Their cost grows with the number of distinct label combinations (series), not with traffic.
- Logs are records of individual events. They answer “what exactly happened” and their cost grows with traffic. They are where you go after a metric tells you something is wrong.
- Traces follow one request through several services (API gateway, feature store, model server). The
flowguardservice is a single process, so this lesson stops at a correlation id propagated in theX-Request-IDheader: it is the field that later joins logs to traces (OpenTelemetry concept, not built here).
The common mistake is to use one for the job of another: computing an error rate by counting log lines (slow, and breaks when logs are sampled), or putting a request id into a metric label (section 2.4).
2.2 Structured logs
A structured log line is a JSON object with stable keys, one event per line:
{"ts":"2026-11-22T18:06:50.975+00:00","level":"INFO","logger":"flowguard.access","event":"access","request_id":"replay-demo-0001","method":"POST","route":"/predict","path":"/predict","status":200,"duration_ms":9.097,"model_version":"flowguard-z-1.0.0"}
Rules this lesson enforces:
eventis a constant name (access,prediction,model_loaded), never an interpolated sentence. Values go in their own keys. A query is thenevent == "prediction" and n_exceeding > 0, not a regular expression that breaks when someone rewords a message.- One line per event.
json.dumpsescapes newlines, so a multi-line exception message cannot split a record into fragments that a log shipper reads as separate events. - Every event of a request carries its
request_id. The id comes from the client’sX-Request-IDheader if it is well-formed (so the caller can quote it in a ticket), otherwise the service generates one; either way it is returned in the response header and body. - Log a summary of the input, never the input. For
/predictthat isn_samples, the time span, and the outcome (n_scored,n_warming_up,n_exceeding,max_score). Raw payloads are a privacy and security liability (in other domains they contain personal data; here they would expose plant operating data), they multiply storage cost by the request size, and they make the log unreadable. If you need payloads for debugging or retraining, that is a separate, access-controlled, sampled data capture with a retention policy, not the application log. - Never log secrets. Authorization headers, tokens, connection strings. The safest way is to never log headers wholesale.
Levels in production. INFO for the normal access and prediction events, WARNING for a request
answered 5xx, ERROR for an unhandled exception (with the traceback, server-side only), DEBUG off by
default. At high traffic, INFO access logs are often sampled (say 1 in 100 for 2xx, all errors);
counters must therefore come from metrics, never from counting log lines.
2.3 The golden signals, and what to measure for an ML service
The four golden signals (from Google’s SRE book; recalled, not re-verified this session) are traffic (requests per second), errors (rate of failed requests), latency (distribution of durations, separately for successes and failures) and saturation (how full the service is: requests in flight, queue length, CPU, memory). The RED method (Rate, Errors, Duration) is the same idea for request-driven services; USE (Utilisation, Saturation, Errors) is for resources such as CPU and disk.
flowguard’s metrics, which are part of this lab’s contract:
| Metric | Type | Labels | Signal |
|---|---|---|---|
flowguard_http_requests_total |
counter | method, route, status |
traffic and errors |
flowguard_http_request_duration_seconds |
histogram | route |
latency |
flowguard_http_requests_in_flight |
gauge | none | saturation |
flowguard_model_info |
gauge (value 1) | model_version |
which model is serving |
flowguard_prediction_score |
histogram | none | model behaviour (input to w7d2/w7d3) |
flowguard_predicted_samples_total |
counter | outcome |
warming up / below / exceeding |
Counter only increases; rates are computed by the monitoring system from the difference between scrapes (and it tolerates restarts, which reset counters to zero). Gauge goes up and down. Histogram counts observations in fixed buckets and also keeps their sum and count, from which any quantile can be estimated later.
2.4 Histograms, percentiles and cardinality
In the Prometheus text format each bucket line x_bucket{le="0.05"} 38 means “38 observations were
less than or equal to 0.05 s”: buckets are cumulative, and the mandatory le="+Inf" bucket equals
x_count (Prometheus exposition-format docs, verified from their source). The left panel below is what
people expect; the right panel is what /metrics actually serves, from the real replay in task 5.
Figure 1 (real replay of two SKAB test runs through the reference service). All 38 /predict requests
finished within 25 ms; the cumulative series is flat from there on and its last value is _count.
Two consequences:
- Quantiles are estimated from buckets by interpolating inside the bucket that contains them
(
histogram_quantileassumes observations are spread uniformly inside a bucket). The estimate is only as good as the bucket boundaries, so put boundaries where your decisions are:flowguardhas a bucket edge at 250 ms because that is the latency SLO threshold, which makes “fraction slower than 250 ms” exact. - Percentiles cannot be averaged; bucket counts can be summed. Two instances’ p99s say nothing about the p99 of their combined traffic. Summing the bucket counts first and then estimating gives the right answer up to bucket resolution (worked example, Figure 2).
Figure 2 (SYNTHETIC, worked example).
Cardinality. Every distinct combination of label values is a separate time series that the
monitoring system stores forever. Labels must come from small, fixed sets: route templates
(/predict), status codes, method, model version. Never a request id, a raw URL path (a scanner hitting
random paths creates a new series per path), a machine id across a large fleet, or a user id. The lab
labels unknown routes as unmatched for exactly this reason. Per-request detail belongs in logs.
2.5 SLIs, SLOs and error budgets
- An SLI (service level indicator) is a ratio of good events to valid events, for example “share of
valid
/predictrequests answered without a server error” or “share of successful requests answered within 250 ms”. - An SLO is a target for an SLI over a window: 99.5 % over 30 days.
- The error budget is what the SLO allows to fail:
(1 - target) x valid events. At 1,728,000 requests per 30 days and 99.5 %, that is 8,640 bad requests. - The burn rate is
observed bad fraction / (1 - target). A burn rate of 1 spends exactly the whole budget over the window; 14.4 sustained for one hour spends 2 % of a 30-day budget.
Paging on a single short window pages on every blip; paging on a single long window pages late and keeps paging after the fix. The multi-window rule pages only when a long window (significance) and a short window (still happening) both burn fast. Figure 3 shows it on a synthetic month: a 3-hour partial outage pages for 168 minutes, a 4-minute total outage does not page at all, and the month ends with 42 % of the budget spent. The factors 14.4/1 h/5 min and 6/6 h/30 min are the SRE workbook’s values as recalled (not re-verified here); you derive your own in the challenge.
Figure 3 (SYNTHETIC: 40 requests/minute, base error rate 0.1 %, SLO 99.5 %).
What these SLOs cannot see. A service can meet every SLO while every prediction is wrong. Model quality needs labels, which arrive late (w7d3); input change needs distribution monitoring (w7d2).
2.6 How a request flows through the service, and where the exception goes
The non-obvious part: in Starlette, a handler registered for Exception runs in ServerErrorMiddleware,
which sits outside your middleware. So when the endpoint raises, call_next does not return a 500
response; it raises. Bookkeeping written after call_next only (the natural first attempt) silently
skips every crash: no access line, no 500 in the counter, and an in-flight gauge that leaks one unit per
crash. The fix is try/finally. (Verified by experiment with FastAPI 0.165 / Starlette 1.7 before
writing this section; 422 and 404 do come back as responses, because their handlers live in the inner
ExceptionMiddleware.)
Multiple workers. Each uvicorn worker process has its own in-memory registry. A scrape reaches one
worker, so counters look halved with two workers. prometheus_client has a multiprocess mode for this;
it is not used here, and the extension asks you to observe the effect.
2.7 Connection to other domains
Well-run lab experiments already follow the right pattern at a different scale: each trial or recording carries a metadata record (subject, session, settings, protocol, software version) that is stored next to the data and is what you filter on later. A trial id that links stimulus log, sensor stream and classifier output is a correlation id. What changes in a service: events arrive continuously from many sources, nobody reads them unless something is wrong, and the volume forces summaries (metrics) rather than complete records.
2.8 An industry example (illustrative composite, not a documented case)
A team running a demand-forecasting API logged every request body “temporarily” while debugging. Six
months later the logs held most of the company’s order history, outside the access controls of the
order database, and the log bill exceeded the compute bill. Meanwhile their only error alert counted
ERROR lines, which stopped firing when a refactor changed the log level of a common failure. The fix
had three parts: summaries instead of payloads, error metrics from a counter rather than from log lines,
and an SLO-based alert on the counter.
2.9 Limitations and misconceptions
- “More logs are better.” Unread logs cost money and hide the line you need. Log events you would act on or query by.
- “Average latency is fine for an SLO.” Averages hide the slow tail that users feel; the SLI is a share of requests under a threshold.
- “The metric says 99.9 % available, so the model works.” Availability and latency say nothing about prediction quality.
- “Log the request so we can retrain on it.” Retraining data needs labels, consent, retention and versioning: a data pipeline, not a log statement.
- This lesson’s registry is in-process and resets on restart, which counters tolerate by design; a real
deployment would use
prometheus_clientand a Prometheus server, which produce the same text format.
3. Worked example: two log lines and two instances (SYNTHETIC)
example/two_instances.py is self-contained (standard library and NumPy only). A recommendation service
runs on two instances: A is healthy and busy (9,000 requests, about 20 ms), B is degraded and quiet
(1,000 requests, about 300 ms).
!python labs/w7d1_service_logging_metrics/example/two_instances.py
Output (exact; deterministic seed):
1) Two log lines for the same request
text: 2026-03-01 10:00:01 INFO request abc123 for user 42 took 312ms (status=200) model=v3
json: {"ts": "2026-03-01T10:00:01Z", "event": "access", "request_id": "abc123", "status": 200, "duration_ms": 312, "model_version": "v3"}
regex on text -> 312 ms (breaks the day someone writes 'took 0.3s'); json -> 312 ms, by key
(the text line also leaked a user id; structured logging makes such fields explicit and reviewable)
2) Latency across two instances
p99 instance A: 49.9 ms (9,000 requests)
p99 instance B: 1007.9 ms (1,000 requests)
mean of the two p99s: 528.9 ms <- not a percentile of anything
true p99 of all 10,000 requests: 587.9 ms
p99 from summed histogram buckets: 721.9 ms <- lands in the right bucket (500-1000 ms); the position inside it is interpolated
share of all requests slower than 250 ms: 6.7% (from buckets: 6.7%, exact because 250 ms is a bucket edge)
Interpretation. The mean of the p99s happens to be in the right region here and far off in other mixes; it has no meaning. The bucket estimate (722 ms) is in the right bucket but 134 ms high, because interpolation assumes observations are spread evenly between 500 and 1,000 ms. The share above 250 ms is exact from buckets, because 250 ms is a bucket edge: choose boundaries at your SLO thresholds.
4. Guided lab
lab/ holds the week-5 service (src/, models/, splits/) extended to package version 0.6.0. Given:
metrics classes Counter, Gauge, Registry, ServiceMetrics (the metric names), configure_logging,
log_event, cli.py, replay_demo.py. Yours: the functions marked TODO w7d1.
Task 1 (10 min): JsonFormatter.format and summarise_samples in observability.py. The docstrings
are the specification. Checkpoint:
import logging, sys; sys.path.insert(0, "labs/w7d1_service_logging_metrics/lab/src")
from flowguard.observability import JsonFormatter
r = logging.LogRecord("flowguard.x", 20, "", 1, "demo", None, None); r.fields = {"a": "b\nc"}
print(JsonFormatter().format(r)) # one line, with "a":"b\nc"
Task 2 (15 min): Histogram.observe and Histogram.render. Store per-bucket counts internally;
make the rendered le lines cumulative and end with +Inf, then _sum and _count.
Debugging: if the checks say “bucket counts must be cumulative”, print render() for observations
[0.003, 0.003, 0.04]: the le="0.005" line must say 2, le="0.05" 3, and every later line 3.
Task 3 (30 min): api.py.
- 3a. Extend the middleware (read section 2.6 first). One
try/finallyaroundcall_next; in thefinallyblock:in_flight.dec(),requests.inc(method=..., route=_route_label(request), status=...),latency.observe(...), onelog_event(access_logger, "access", ...). UseWARNINGfor 5xx. - 3b.
GET /metricsreturningmetrics.render()asPlainTextResponsewithmedia_type=METRICS_CONTENT_TYPE,include_in_schema=False. - 3c. In
/predict, observe every non-null score, count samples by outcome, and log onepredictionevent with the fields listed in the TODO.
Checkpoint:
!python wb.py check w7d1
Debugging guidance. “expected exactly one access event … got 0” for status 500: your bookkeeping runs
only when call_next returns. “in-flight gauge is 3”: you decrement on the success path only. “raw
sample value 31.987654 appears in the logs”: something logs the body (look for model_dump or
body.samples in a log call). “N request-counter series after random paths”: you used the raw path as a
label. Tests in checks/ build their own synthetic bundle (n_burn = 20, threshold 3.0) and capture
logs through your configure_logging into a string buffer.
Task 4 (5 min): logquery.parse_lines and find_request. Then:
python -m flowguard.cli logs --file <log> --request-id <id> # with PYTHONPATH=labs/w7d1_service_logging_metrics/lab/src
Task 5 (10 min): replay real data. With your lab complete and SKAB downloaded:
!python labs/w7d1_service_logging_metrics/lab/replay_demo.py
It starts uvicorn on 127.0.0.1, replays test experiments valve1/13 and other/14 as a plant client
would (re-sending the run so far every 60 samples), sends three bad requests on purpose, scrapes
/metrics and queries one request id. The reference solution printed (timings vary by machine and run):
chosen request: status 200, X-Request-ID replay-demo-0001
== golden signals from results/service.log ==
requests (all routes) 41
predict requests 38
traffic, predict req/s over the replay 62.6
errors: 4xx (client) 2
errors: 5xx (server) 0
latency p50 ms (200s) 8.24
latency p95 ms (200s) 14.81
latency max ms (200s) 22.3
saturation: server RSS at the end (kB) 98156
== selected lines of results/metrics.txt ==
flowguard_http_requests_total{method="GET",route="/readyz",status="200"} 1
flowguard_http_requests_total{method="GET",route="unmatched",status="404"} 1
flowguard_http_requests_total{method="POST",route="/predict",status="200"} 36
flowguard_http_requests_total{method="POST",route="/predict",status="422"} 2
flowguard_http_request_duration_seconds_bucket{route="/predict",le="0.05"} 38
flowguard_http_request_duration_seconds_count{route="/predict"} 38
flowguard_http_requests_in_flight 1
flowguard_model_info{model_version="flowguard-z-1.0.0"} 1
flowguard_predicted_samples_total{outcome="below"} 13961
flowguard_predicted_samples_total{outcome="exceeding"} 2624
flowguard_predicted_samples_total{outcome="warming_up"} 3520
== python -m flowguard.cli logs --file results/service.log --request-id replay-demo-0001 ==
request replay-demo-0001: 2 event(s)
2026-11-22T18:06:50.973+00:00 INFO prediction machine_id=valve1/13, model_version=flowguard-z-1.0.0, n_samples=600, n_exceeding=0, max_score=2.9803
2026-11-22T18:06:50.975+00:00 INFO access method=POST, route=/predict, status=200, duration_ms=9.097, model_version=flowguard-z-1.0.0
Read it critically (these are the points the assessment asks about):
- The two 422s are the sentinel value (
flow_rate = -9999) and the missingsamplesfield; the 404 isGET /predict/valve1/13, recorded underroute="unmatched", not under its path. in_flightis 1, not 0: the scrape itself is in flight while the registry is rendered.flowguard_predicted_samples_totalcounts samples processed, not distinct samples: a client that re-sends the run every minute is counted again each time. 2,624 “exceeding” are not 2,624 distinct anomalous seconds. Know what your counter counts before you put it on a dashboard.- The prediction event logs
max_scoreand counts, not one of the 600 sensor readings. - Duration grows with request size (Figure 4): a client that keeps re-sending a growing run is a latency problem in waiting, which is the argument for the stateful streaming endpoint of w5d3/w5d4.
Figure 4 (real replay; one point per successful /predict request). The outliers are single requests,
the kind of tail a percentile SLI catches and an average hides.
# Run the automated checks on your guided lab.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check
check("w7d1")
5. Independent challenge: SLOs you can defend
Read challenge/README.md. You implement the SLI, budget, burn-rate and multi-window
paging arithmetic in challenge/slo.py (inputs are the lab’s access events) and write challenge/SLO.md:
who depends on the service, the SLIs and what counts as valid, targets with rationale, a worked budget,
an alerting policy, and what the SLOs do not cover.
Acceptance: python wb.py check w7d1 --challenge (known-answer arithmetic, which events are excluded,
both-windows paging, a filled document) and the SLO rubric in assessment.md (section 7 of this notebook).
The challenge brief
Task. Define service level objectives for the flowguard prediction API and implement the arithmetic
that turns them into an error budget and a paging decision. Work alone; the hints are in ../hints/,
but this challenge only counts as independent if you do not open hint 3.
Part A: slo.py (auto-graded)
Implement the five functions in slo.py. Their inputs are the JSON access events your lab writes
(event == "access", with route, status, duration_ms). The module docstring of the starter gives
the definitions; in short:
availability_sli(events) -> (good, valid)over/predictaccess events. Decide (and the checks enforce) which statuses are not the service’s fault.latency_sli(events, threshold_ms) -> (good, valid). Decide which requests are valid for a latency SLI.error_budget(target, valid),burn_rate(bad, valid, target).should_page(window_counts, target, rules): the multi-window rule of the lesson, section 2.5.
Part B: SLO.md (rubric-graded)
Fill the six sections of the template. Use numbers: a traffic assumption, targets, a worked budget, windows and burn-rate factors. Justify each choice from what the plant engineer needs and from what you measured in w6d4 and in this lesson’s replay; say what the SLOs do not cover.
Acceptance criteria
python wb.py check w7d1 --challengepasses.SLO.mdscores at least “meets” on every row of the SLO rubric in../assessment.md.
# Run the automated checks on your independent challenge.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check
check("w7d1", challenge=True)
6. Progressive hints
Hint 1: concepts · Hint 2: approach · Hint 3: partial implementation
Open one hint at a time, only after a real attempt.
Hint 1 concept
* A structured log line is a dictionary serialised once. Build the dictionary, then `json.dumps` it; never build JSON by string concatenation. * Prometheus histogram buckets answer "how many observations were <= this bound". Each line therefore includes all the smaller buckets. Keep per-interval counts internally if you like, but render running totals. * In Starlette, an exception raised inside the endpoint is handled by the *outermost* middleware. From your middleware's point of view `call_next` raises; it does not return a 500. * A label value must come from a small set you could write down in advance. * For the challenge: an SLI is good events / valid events. Ask "whose fault was it?" to decide validity, and "what does the user feel?" to decide what good means.Hint 2 approach
**Formatter.** Start the payload with the four fixed keys, then copy `getattr(record, "fields", {})` without overwriting them. Add `exc_type` from `record.exc_info[0].__name__` when `exc_info` is set. **Histogram.** Internally, a list of `len(buckets) + 1` counts per label key (the last one for +Inf) and a running sum. `observe` increments the first bucket whose bound is >= value. `render` walks the list with a running total. **Middleware.** Set `status = 500` before `try`. Inside `try`, `response = await call_next(request)`, take `response.status_code`, set the header, `return response`. Put all bookkeeping in `finally`. The route label is `_route_label(request)`, read in `finally` (routing has happened by then). **Prediction event.** Count while you build `results`; call `summarise_samples(body.samples)` and spread its dict into `log_event(...)`. **Log query.** `json.loads` inside `try`; count failures and non-dicts; filter by `request_id`. **Challenge.** Filter to `/predict` access events first. Availability: drop 4xx from valid, good is `< 500`. Latency: valid is status 200 only. Burn rate: divide by `1 - target`. Paging: loop over rules, both windows `>=` factor.Hint 3 partial
Opening this hint means the lab counts as guided practice, not independent work. ```python # observability.py -- Histogram def observe(self, value, **labels): key = self._key(labels) with self._lock: counts = self._counts.setdefault(key, [0] * (len(self.buckets) + 1)) for i, upper in enumerate(self.buckets): if value <= upper: counts[i] += 1 break else: counts[-1] += 1 self._sum[key] = self._sum.get(key, 0.0) + float(value) def render(self): lines = self.header() for key, counts in sorted(self._counts.items()): running = 0 for upper, c in zip((*self.buckets, math.inf), counts): running += c lines.append(f"{self.name}_bucket{_labels(self.labelnames, key, (('le', _fmt(upper)),))} {running}") # ... then _sum and _count lines return lines ``` ```python # api.py -- the shape of the middleware status = 500 start = now() metrics.in_flight.inc() try: response = await call_next(request) status = response.status_code response.headers[REQUEST_ID_HEADER] = request.state.request_id return response finally: duration = now() - start route = _route_label(request) metrics.in_flight.dec() # requests.inc(...), latency.observe(...), log_event(access_logger, "access", level, ...) ``` ```python # challenge/slo.py def burn_rate(bad, valid, target): if valid <= 0: return 0.0 return (bad / valid) / (1.0 - target) ```7. Assessment
assessment.md (section 7 of this notebook): reasoning questions, a design-choice explanation, the rubrics and a system-design interview rep on observability.
Assessment questions
Answer in writing before opening solutions/labs/w7d1_service_logging_metrics/assessment_answers.md.
Reasoning questions
- Your middleware increments
flowguard_http_requests_totalafterawait call_next(request)returns. In production the 500 count stays at zero during an incident in which users see 500s. Explain the mechanism and the fix. - The replay shows
flowguard_http_requests_in_flight 1although no prediction is running. Why, and why does the check accept 0 or 1 rather than requiring 0? - A dashboard shows “p99 latency = average over instances of each instance’s p99”. Give a concrete case where this hides a breach of a 250 ms SLO, and the correct computation.
- Why is the latency SLI computed over status-200 requests only, while the availability SLI counts 503 as bad and excludes 422?
flowguard_predicted_samples_total{outcome="exceeding"}reached 2,624 in the replay. Can you conclude that 2,624 seconds of the two runs were above the threshold? What would you need to log or count instead?- Name two fields you deliberately do NOT log in the prediction event, and the reason for each.
Design-choice explanation (write 150-250 words)
You need per-machine visibility for a fleet of 120,000 pumps: which machines get errors, which get slow
responses. A colleague proposes a machine_id label on the request counter and latency histogram.
Explain what you would do instead, what each piece answers, and what it costs.
Rubric (open-ended answers)
| Criterion | Does not meet | Meets | Exceeds |
|---|---|---|---|
| Mechanism | Names a symptom (“errors not counted”) | Explains that the exception propagates out of call_next because the Exception handler sits in the outermost middleware |
Also explains why 422/404 behave differently and what the in-flight gauge does |
| Metrics reasoning | Treats percentiles as averageable or labels as free | Correctly separates bucket sums from percentile averages and bounded from unbounded labels | Quantifies cardinality or uses the bucket-edge argument for exact SLIs |
| Logging judgement | Logs payloads or relies on log-line counts for rates | Summaries in logs, counts from metrics, correlation by request id | Adds sampling, retention or access-control considerations |
| SLO (challenge) | Targets without rationale; 4xx counted against the service | SLIs with valid/good definitions, numeric targets and budget, two-window paging | Derives factors from budget fractions; states what the SLO cannot see and how that is covered |
Interview rep (15 minutes, system design: observability)
Prompt (say your answer aloud or write it, then compare with the rubric in the answers file). You are about to put a real-time card-fraud scoring API into production: about 2,000 requests per second, p99 budget 80 ms, scores consumed by a rules engine that blocks or allows payments. Labels (chargebacks) arrive 30-90 days later. Design the logs, metrics and alerts for the first release. What do you log per request, what are your metrics and their labels, what pages a human at 3 a.m., and what can you NOT know from any of this on day one?
8. Reflection and review
You should now be able to, without notes: write a JSON log formatter and explain why event is a
constant; propagate a correlation id; instrument a service with counters, a cumulative histogram and a
gauge whose bookkeeping survives unhandled exceptions; keep label cardinality bounded; estimate a
quantile from buckets and say when it is exact; and turn an SLO into an error budget and a multi-window
paging rule.
Reflection prompt. In the last system or project you worked on, which question about a past run could you not answer because nothing recorded it? Which of the fields in this lesson’s prediction event would have answered it?
Later retrieval question (for the w7d7 review). A colleague adds machine_id as a label on
flowguard_http_requests_total “so we can see which pump is failing”. The fleet has 120,000 machines.
What goes wrong, and where should that breakdown come from instead?
Next. w7d2: the service is up and fast, but is the data it receives still the data the model was built for?
Verification record
Executed on the authoring machine (shared Linux container), 2026-11-22: Python 3.13, FastAPI 0.165.0, Starlette 1.7.0, uvicorn 0.54.0, httpx 0.28.1, pydantic 2.13.5, matplotlib 3.11.2 (figures only).
python tools/verify_checks.py labs/w7d1_service_logging_metrics: the reference passes both parts; 7 lab mutants and 4 challenge mutants are rejected, each by its intended check. The shipped starter fails 15 of 18 lab checks (the 3 that pass test the w5d4 request-id behaviour the starter already has) and all 5 challenge checks.- The exception path of section 2.6 was established by a standalone FastAPI experiment before the lab was
written, and is what the
no_finally_on_errorandinflight_leak_on_errormutants exercise. lab/replay_demo.py(reference solution) ran against the real SKAB files; the output in task 5 is copied from that run, andpgrepconfirmed no server was left running. Figures 1 and 4 come from the same run’sresults/files throughfigures/make_figures.py; Figures 2-3 are synthetic and exact.- Prometheus facts (cumulative
lebuckets,+Inf=_count,text/plain; version=0.0.4, label cardinality guidance,histogram_quantileinterpolation) were checked against the source of the Prometheus documentation on GitHub (prometheus/docsdocs/instrumenting/exposition_formats.md,docs/practices/naming.md,docs/practices/histograms.md;prometheus/prometheusdocs/querying/functions.md). - Not verified: the golden-signals and burn-rate factor attributions (SRE book and workbook, from
memory);
prometheus_client’s multiprocess mode (not installed); behaviour with more than one worker beyond the reasoning in section 2.6; Python 3.11/3.12; the time budget.
Record your progress
Tick only what is true. Passing the supplied checks is guided practice; mark independent only for work done without hints or solutions.
from mlcourse.progress import mark, note
# mark("w7d1", "reading")
# mark("w7d1", "guided")
# mark("w7d1", "independent")
# note("w7d1", "what tripped me up today")