Module 8 · Information Systems · Lesson 10 · Week 9

Instruction session · Wednesday, December 9, 2026 · one hour of demonstration, one hour of application

Metrics and Telemetry

The package of Lesson 7 runs the model in one command, but a run is only described by what it prints. This session gives the DataApp the three signals of observability, metrics, traces and logs, linked by the identifiers they share, and then closes the loop: a controller compares the indicators with their objectives and acts on the DataApp, calling a person only when it cannot correct it.

Metrics · PrometheusTraces · OpenTelemetry and TempoLogs · JSON and LokiCorrelationSLI and SLOClosed loop

Project ritual

Daily · 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda · two hours
Three signals and one loop, then your DataApp

In the first hour the professor builds the reference of lab/lesson-10/ live with a coding agent, in four steps: the metrics, the traces and logs, the stack that links them and the controller that closes the loop. In the second hour each group applies the same method to its own DataApp.

0:22 · step 01MetricsAgent: telemetry.pyTypes, labels, push and exporter; the info metric of the run
0:30 · step 02Traces and logsAgent: observability.pySpans of run, task, request and SQL; JSON lines with the span
0:38 · step 03Stack and correlationAgent: stack/Collector, Tempo, Loki, Grafana; from the alert to the log line
0:46 · step 04Closed loopAgent: control.pySensor, comparator, controller, actuators and guardrails
1:00 · groupsYour DataAppEach groupThe three signals and one loop for one SLO
Where the work happensOn the computer: the virtual environment of the package, Docker Compose for six containers (Prometheus, Pushgateway, OpenTelemetry collector, Tempo, Loki and Grafana) and the browser on Grafana.
0:15 · The three signals
Each signal answers a different question

A metric is a number kept over time, cheap to store and to evaluate, which says that something changed. A trace is the path of one execution as a tree of timed spans, which says where. A log is a record of a discrete event, which says what the program knew at that moment.

Metrics

Is something wrong?

tcg_run_success 0, tcg:price_freshness_seconds. Aggregated by design, so the cost does not grow with the number of runs, only with the number of series. Prometheus evaluates them every 15 s and fires the alerts.

Traces

Where did it go wrong?

One run of 30.6 s is a trace of 38 spans: the run, 13 tasks, 20 requests to the source and 4 SQL files. The failing span carries the status ERROR, the attempts and the exception. Stored in Tempo.

Logs

What exactly happened?

JSON lines such as task.fail, with the attempt and the error text, written inside the span they describe. Stored in Loki and in out/logs/, and searched by any field.

The common errorThree tools that do not share identifiers give three partial views. The value of the signals is in the path from one to the other, which the next slide shows.
0:18 · Correlation
Three identifiers link the signals

The run_id names one run of the DataApp, the trace_id names its trace and the span_id names one operation inside it. Each signal carries the identifiers that lead to the next one, so the person on call goes from the alert to the line that explains it without guessing.

HopWhereIdentifier that leads onRehearsal of 08/11/2026
1 · alertPrometheus, TcgRunFailedits description reads tcg_run_info{run_id, trace_id}"Run e44b5b8a34eb, trace 5d1d4930…"
2 · metricGrafana, table of tcg_run_infothe trace_id is a link to Tempoone series per instance, replaced at each push
3 · traceTempo, 17 spansthe span with status ERROR and its span_idtask extract_sets: 3 events "attempt failed"
4 · log lineLoki, | span_id="ba8fc2d7…"each line has the trace_id, a link back3 lines: ConnectionError: fault injected
CardinalityThe run_id is never a label of every metric, because each run would create new series. It lives in one info metric, tcg_run_info, and in the traces and logs, which are built to hold one record per event.

Step 01 · 0:22 · Metrics

Every run describes itself in numbers

The first step instruments the run without touching the layers: a module of telemetry owns the metrics, the client of the source is wrapped so that every request is timed, the run pushes at the end and an exporter reads the state of the warehouse.

Files

telemetry.py, pipeline.py, cli.py (--push, metrics), tests/test_telemetry.py.

Review before moving on
  • Does out/metrics.prom show the rows 7, 1490, 657, 896, 1153, 1414 and 1831?
  • Is there one series of tcg_run_info, with the run and the trace?
  • Do the etls still not import prometheus_client?
Prompt 01 · CREATE
[C] Character
You are a data engineer who operates pipelines in production. The package
tcg-dataapp of Lesson 7 runs the whole model in one command, but nobody
knows how a run went unless they read the terminal. The first of the three
signals is the metric: numbers kept over time, which a machine evaluates
every fifteen seconds even when nobody is looking.

[R] Request
Instrument the package with prometheus_client (version 0.4.1):
1. src/tcg_dataapp/telemetry.py with a class RunMetrics(run_id) that owns a
   CollectorRegistry of its own and holds:
   - tcg_task_attempts_total{task,status}, tcg_task_duration_seconds{task},
     tcg_task_rows{task};
   - tcg_source_request_duration_seconds{endpoint} (histogram, buckets 0.1
     to 16 s) and tcg_source_request_errors_total{endpoint};
   - tcg_quality_value{measure}, tcg_run_success, tcg_run_duration_seconds,
     tcg_run_failed_tasks, tcg_run_last_success_timestamp_seconds (pushed
     only after a success);
   - tcg_run_info{run_id,trace_id} = 1, an info metric that names the run
     and its trace, so an alert can lead to the trace.
2. An InstrumentedClient with the methods of TcgcsvClient that times every
   call, so the etls layer does not import prometheus_client.
3. tcg-dataapp run --push URL: pushadd to a Pushgateway (job tcg_dataapp),
   because a run of forty seconds ends before most scrapes; the same text
   goes to out/metrics.prom.
4. tcg-dataapp metrics: an exporter on port 9108 whose collector reads the
   warehouse at each scrape (rows and newest timestamp per tag, fact rows
   and grain keys, last run) and reports tcg_warehouse_readable 0 instead of
   failing while a run holds the DuckDB file.
5. Tests with the FakeClient: a good run, a failed run, the push and the
   exporter.

Facts measured on 08/11/2026 (confirm before use):
- a real run: tcg_task_rows 7, 1490, 657, 896, 1153, 1414 and 1831;
  fact_rows = fact_grain_keys = 5951; 13 requests; tcg_run_success 1.

[E] Example
tcg_task_rows{task="extract_prices_2026-11-07"} 1831.0
tcg_run_info{run_id="16fb5bb50f14",trace_id="5fddbb48a70b11fdd1df9bc8c0d4cf26"} 1.0

[A] Adjustments
- Names in snake_case with the prefix tcg_ and the unit as suffix; every
  timestamp in Unix seconds.
- Labels with few values only (task, status, endpoint, measure). The run_id
  appears only in tcg_run_info, which keeps a single series per instance
  because each push replaces it.
- Call disable_created_metrics().

[T] Type of output
The files, the output of pytest and the lines of out/metrics.prom without
the buckets.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 01 · Theory
Metric types, and why a batch job pushes

The type says how the number may change and which functions make sense over it. Prometheus pulls from its targets every 15 s; a run of 30 s has no endpoint after it ends, so it pushes to a Pushgateway, which is scraped in its place.

TypeBehaviourIn tcg-dataapp
Counteronly grows; read with rate()tcg_task_attempts_total{task,status}, tcg_source_request_errors_total
Gaugeany value, up or downtcg_task_rows, tcg_run_success, the freshness read by the exporter
Histogramcounts per bucket, plus sum and counttcg_source_request_duration_seconds{endpoint}, 0.1 to 16 s
Infoa gauge always 1, whose labels are the datatcg_run_info{run_id, trace_id}
Push keeps the last good timepushadd replaces only the metrics being sent, and the time of the last success is sent only after a success, so a failed run does not erase it.

Step 02 · 0:30 · Traces and logs

The path of one run, and what it said

The second step adds the other two signals with OpenTelemetry. The package calls only the API; the command line installs the SDK, which writes JSON lines to a file and, with an endpoint, sends spans and log records to a collector.

Files

observability.py, spans in pipeline.py, telemetry.py and processors/gold.py, tests/test_signals.py.

Review before moving on
  • Is a run one trace, with the 13 tasks as children of the root?
  • Does a failing task end with status ERROR, its attempts as events and the exception?
  • Does the log line of the failure carry the span_id of its task?
Prompt 02 · CREATE
[C] Character
You are the same data engineer. The metrics say that a run failed and how
long each task took, but not where inside the run the time went, nor what
the program said when it failed. Those are the other two signals: the trace,
which records the path of one run as a tree of spans, and the log, which
records discrete events. They are useful together only if they share
identifiers.

[R] Request
Add traces and structured logs with OpenTelemetry (opentelemetry-sdk and
opentelemetry-exporter-otlp-proto-http):
1. src/tcg_dataapp/observability.py:
   - tracer() and logger() over the OpenTelemetry API, so the package does
     nothing extra until a provider is installed;
   - a JsonFormatter that writes one JSON object per line with ts (Unix
     seconds), level, msg, service, run_id, trace_id and span_id of the
     active span, and the fields passed in extra=;
   - setup(log_path, otlp_endpoint): the JSON lines go to
     out/logs/tcg-dataapp.jsonl; with TCG_OTLP_ENDPOINT, the spans go to
     /v1/traces and the log records to /v1/logs of the collector, with a
     batch processor; flush() at the end of each command.
2. Spans:
   - tcg_dataapp.run, the root, with tcg.run_id, tcg.trigger and tcg.sets;
   - task <name>, one per task, with an event "attempt failed" per failed
     attempt, the exception recorded and the status ERROR when the task
     fails for good; skipped tasks get tcg.status = skipped;
   - tcgcsv.<endpoint>, one per request, kind CLIENT, with the server and
     the number of records, from the InstrumentedClient;
   - sql <file>, one per SQL file of build_gold, with db.statements.
3. Log lines run.start, task.ok, task.fail, task.skip and run.end, written
   inside the span they describe, with a contextvar for the run_id.
4. tcg-dataapp run prints the trace_id next to the run_id, and
   RunMetrics.finish receives the trace_id for tcg_run_info.
5. tests/test_signals.py with an InMemorySpanExporter installed once in
   conftest.py: a run is one trace whose tasks are children of the root; a
   failure marks its span and skips the dependents; every log line of a run
   has its run_id and trace_id, and the line of a failing attempt has the
   span_id of its task.

[E] Example
{"ts": 1794146637.498, "level": "error", "msg": "task attempt failed",
 "run_id": "e44b5b8a34eb", "trace_id": "5d1d4930...", "span_id": "ba8fc2d7eb92ef1c",
 "event": "task.fail", "task": "extract_sets", "attempt": 3,
 "error": "ConnectionError: fault injected: source_down"}

[A] Adjustments
- The processors and the etls call only the OpenTelemetry API; the SDK is
  configured by the command line and by the tests, never by a library.
- Spans of requests do not record the URL with parameters, only the
  server and the endpoint.
- A JSON log line never carries data of the source, only counts and errors.

[T] Type of output
The files, the output of pytest, one trace printed as a tree (name,
duration, status) and the last five lines of the JSON log.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 02 · Theory
A span is an operation with a time, a parent and a status

Each span records its start and end, its parent, attributes that describe it, events that happened inside it and a status. The tree of spans of one run shows the time that each part took and the exact place of a failure.

the trace of a good run (38 spans, 30.6 s)
tcg_dataapp.run                     30.6 s  run_id 16fb5bb50f14
├─ task extract_sets                 1.07 s
│  └─ tcgcsv.groups                         1 request
├─ task extract_products             7.02 s
│  └─ tcgcsv.products  × 7
├─ task extract_prices_2026-03-01    3.01 s
│  └─ tcgcsv.archive                        records 657
├─ ...  (5 more extractions)
├─ task build_gold                   0.05 s
│  └─ sql 01_dimensions.sql … sql 04_live_reports.sql
├─ task check_quality                0.08 s
└─ task write_report                 0.17 s
a JSON log line of the failed run
{"ts": 1794146686.73,
 "level": "error",
 "msg": "task attempt failed",
 "run_id": "e44b5b8a34eb",
 "trace_id": "5d1d4930…6173a2",
 "span_id": "ba8fc2d7eb92ef1c",
 "event": "task.fail",
 "task": "extract_sets",
 "attempt": 2,
 "error": "ConnectionError: fault
           injected: source_down"}

Step 03 · 0:38 · Stack and correlation

From the alert to the line that explains it

The third step brings up six containers and links them. The DataApp sends traces and logs to one address, the OpenTelemetry collector, which routes each signal; Grafana reads the three stores and turns the identifiers into links.

Files

stack/compose.yaml, otel/config.yaml, tempo/tempo.yaml, grafana/provisioning/datasources/datasources.yml, prometheus/rules.yml.

Review before moving on
  • Does promtool test rules print SUCCESS, with the trace in TcgRunFailed?
  • With TCG_FAULT=source_down, does the alert name the run and the trace?
  • Does "Logs for this span" open exactly the lines of the failing span?
Prompt 03 · CREATE
[C] Character
You are the same data engineer, now responsible for the place where the
three signals are read. A person on call receives an alert and must reach
the line that explains it in less than a minute: from the alert to the
metric, from the metric to the trace, from the failing span to its log lines.

[R] Request
Write stack/ with Docker Compose and verify the path of correlation:
1. compose.yaml with Prometheus v3.15.0, Pushgateway v1.11.2, the
   OpenTelemetry collector contrib 0.141.0 (OTLP on 4317 and 4318), Tempo
   2.10.10 (traces), Loki 3.6.3 (logs, with its OTLP endpoint) and Grafana
   13.2.4, with anonymous access and viewers allowed in Explore.
2. otel/config.yaml: the traces pipeline exports to Tempo, the logs
   pipeline to http://loki:3100/otlp.
3. grafana/provisioning/datasources/datasources.yml:
   - Tempo with tracesToLogsV2 to Loki, filtering by the span:
     {service_name="tcg-dataapp"} | span_id="${__span.spanId}";
   - Loki with a derived field on the structured metadata trace_id that
     opens the trace in Tempo.
4. prometheus.yml (Pushgateway with honor_labels, the exporter) and
   rules.yml with the recording rule tcg:price_freshness_seconds and the
   alerts TcgRunFailed, TcgNoSuccessfulRun, TcgRunTooSlow, TcgPricesStale,
   TcgGrainBroken and TcgExporterDown. The description of TcgRunFailed
   reads the run_id and the trace_id from tcg_run_info with the template
   function query.
5. The dashboard: the panels of the run, a table of tcg_run_info whose
   trace_id is a link to Tempo, a table of traces with an error and a panel
   of the error and warning lines from Loki.
6. A run that fails on purpose (TCG_FAULT=source_down) and the path, with
   the commands and the answers: alert → trace_id → span with status ERROR
   → its log lines in Loki.

Facts measured on 08/11/2026 (confirm before use):
- a good run with --with-today: 38 spans in Tempo, 15 log lines in Loki;
- the failed run: TcgRunFailed fired with "Run e44b5b8a34eb, trace
  5d1d4930...", the span task extract_sets had 3 events "attempt failed",
  and Loki returned its 3 lines by span_id.

[E] Example
curl -s -G localhost:3100/loki/api/v1/query_range \
  --data-urlencode 'query={service_name="tcg-dataapp"} | span_id="ba8fc2d7eb92ef1c"'

[A] Adjustments
- promtool check config and promtool test rules must pass, run from the
  image of Prometheus; rules_test.yml covers TcgRunFailed with its trace.
- Port 3000 may be taken: GRAFANA_PORT=3001.
- docker compose down -v at the end.

[T] Type of output
The files, the output of promtool, and a table with the four hops of the
path (where, query or click, what it returned).

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 03 · Result
Three stores, three query languages

Each signal has its store and its language, and the questions of the person on call cross them. Values of the rehearsal of 08/11/2026.

Signal and storeQueryAnswer
metrics · Prometheustopk(3, tcg_task_duration_seconds)products 9.52 s, prices of 07/11 8.12 s, of today 6.83 s
metrics · Prometheustcg_gold_fact_rows - tcg_gold_fact_grain_keys0: the grain is intact
traces · Tempo (TraceQL){name="tcg_dataapp.run" && status=error}the runs with source_down and duplicate_prices
traces · Tempo (TraceQL){name=~"tcgcsv.*" && duration > 3s}the archives of the past dates
logs · Loki (LogQL){service_name="tcg-dataapp"} | trace_id="5d1d…"17 lines: 4 errors, 12 skipped tasks, 1 start
logs · Loki (LogQL)… | event="control.tick"one line per decision of the controller
Alerts on symptomsTcgRunFailed, TcgNoSuccessfulRun (26 h), TcgPricesStale (36 h), TcgGrainBroken, TcgRunTooSlow (120 s) and TcgExporterDown, each tested with promtool before it reaches production.
0:42 · Control theory
The elements of a closed loop

A closed loop measures the output of a process, compares it with a reference and acts on the process to reduce the difference. Each element of the diagram has a counterpart in the DataApp, and the observability of the previous steps is only one of them: the sensor.

The closed loop of the DataApp The setpoint, the SLO, enters a comparator that subtracts the SLI measured by the sensor. The error goes to the controller, which chooses an action; the actuator applies it to the plant, the DataApp and its source. The sensor measures the plant again, and the measurement returns to the comparator: that return is the feedback. setpointSLO: 36 h Σ+− controllerdecide() actuatorsrerun · breaker · quarantine plantDataApp + tcgcsv.com sensormetrics · traces · logs → SLI escalation to a persononce, when the guardrails are spent error feedback: SLI
Comparator

error = SLI − SLO. A positive error is a violation: data older than 36 h, a source failing above 50 %, a grain broken.

Controller

decide(), a pure function of the SLIs, the state and the clock, which returns one action per tick.

Feedback

The next tick reads the effect of the last action. Without it, the system acts blindly, which is an open loop.

0:44 · Observability is not control
Observability alone does not close the loop

Metrics, traces and logs measure the process and show it. A dashboard and an alert give the measurement to a person, who then decides and acts. The loop closes only where something compares the measurement with the setpoint and acts on the process.

Open loopLoop closed by a personAutomatic closed loop
In the DataAppcron runs the DataApp at 06:00, whatever happenedthe alert calls the person on call, who reruns or fixestcg-dataapp control reruns, opens the breaker or quarantines
Sensornonemetrics, traces and logsthe same SLIs, read every tick
Decisionfixed in advancea person, when awake and availablea rule, tested, every 5 minutes
Time to actthe next dayminutes to hoursone tick
Riskstale or wrong data for a dayfatigue, nights, holidaysacting wrongly fast, which the guardrails limit
The person stays in the loopThe controller handles the failures that have a known and safe action. Everything else, and every failure that persists, is escalated once to a person, with the trace of what the controller tried.
0:45 · Stability
A loop that acts must not oscillate

An automatic action changes the process that the sensor reads next. A rerun against a source that is down fails again; a threshold crossed back and forth turns the action on and off at every tick. Guardrails bound what the controller may do, so its failure modes are slow and visible.

Hysteresis

A dead band on the freshness

The data becomes stale above 36 h and fresh again only below 30 h. Between them, the previous state holds, so a value near the threshold does not flap.

Backoff

A circuit breaker on the source

When the source fails, the controller stops calling it. It probes after 300 s, then 600 s, then 1,200 s, and escalates at the fourth opening.

Budget and cooldown

At most 3 reruns in 6 h

Reruns are at least 600 s apart. When the budget is spent, the problem is not transient, and the controller escalates.

Escalation once

Then it holds

After escalating, the controller holds every automatic action until the SLIs recover or a person runs control --acknowledge.

Step 04 · 0:46 · Closed loop

A controller that reads the SLIs and acts

The last step writes the controller and the faults that rehearse it. The decision is a pure function, so every rule has a test with a fake clock; the actions run in the real DataApp, and each tick is itself a trace, a log line and a metric.

Files

control.py, faults.py, config.py (setpoints and guardrails), cli.py (control), tests/test_control.py.

Review before moving on
  • Does a source down open the breaker and escalate once, with no rerun?
  • Is a duplicated batch quarantined, with gold back to rows = keys and the frozen report kept?
  • Do the 25 tests pass, the 7 of the loop included?
Prompt 04 · CREATE
[C] Character
You are a reliability engineer who knows control theory. Everything built
so far is the sensor and the display of a loop: the DataApp is measured and
a person is warned. The loop is still open, because nothing compares the
measurement with the setpoint and acts on the process. Close it, and make
sure that it cannot oscillate nor act forever without a person.

[R] Request
Write src/tcg_dataapp/control.py and the command tcg-dataapp control:
1. Setpoints in config.py, from TCG_* variables: freshness 36 h (and 30 h
   to leave the stale state: hysteresis), run duration 120 s, error rate of
   the source 50 %, plus the grain and the success of the last run.
2. sense(con, now): the SLIs read from the warehouse (newest price, last
   run of ops.pipeline_runs with its failed tasks and the class of the
   error: source, quality or other; error rate of the extractions; grain).
3. errors(): SLI minus SLO; decide(sli, state, settings, now, history): a
   pure function that returns one action:
   - quarantine when the quality gate failed: move every batch that is not
     in ops.good_batches (tag, timestamp, rows, md5 digest, recorded by
     the last good run) to quarantine.db_ingestion, rebuild and check gold;
     the frozen reports are tables and stay as they are; a second
     quarantine within the window also escalates;
   - open_breaker when the source failed; hold while it is open; probe
     after a backoff that doubles at every opening; escalate at the fourth
     opening;
   - rerun (with the prices of today) when the data is stale or the run
     failed for another reason, with a cooldown of 600 s and a budget of 3
     reruns per 6 h; escalate when the budget is spent;
   - resolve when every SLI is back within its SLO; none otherwise.
4. Escalation happens once: it sets state.escalated, optionally posts to
   TCG_ESCALATION_WEBHOOK, and every later tick holds until the SLIs
   recover or a person runs tcg-dataapp control --acknowledge.
5. The loop is observable: a span control.tick with control.sense and
   control.act <action> (the rerun is a child of it), one JSON log line,
   one row of ops.controller_actions with the trace_id, and the metrics
   tcg_controller_* pushed as job tcg_controller.
6. faults.py: TCG_FAULT=source_down or duplicate_prices, applied to the
   client of the run and of the probe.
7. tests/test_control.py with a fake clock: stale data is rerun and the
   loop settles; a source down opens, backs off and escalates once without
   any rerun; a source that returns closes the breaker alone; a bad batch
   is quarantined and a repeated one escalates without oscillating; a
   failure without a specific actuator is rerun within the budget.

[E] Example
tick 4a1b2d5ed253  open_breaker the source failed: error rate 100% against an SLO of 50%
      → breaker open for 20 s (opening 1)
tick df512f4b8f19  probe        backoff elapsed; probing the source
      → probe failed (ConnectionError); breaker open for 80 s (opening 3) · escalated to a person

[A] Adjustments
- decide() never touches the database or the clock: everything comes in
  its arguments, so each rule has a test.
- Protection (quarantine) is not limited by the budget; remediation
  (rerun, probe) is.
- An SLI without an actuator, such as the duration of the run, is only
  measured and alerted: say so in the code.

[T] Type of output
The files, the output of pytest, and a real rehearsal with short
guardrails (TCG_BREAKER_BACKOFF=20, --interval 10) for source_down and for
duplicate_prices, with the line of each tick.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 04 · Theory
One actuator per failure, each with its limit

Each failure has an action that is safe to repeat and a limit beyond which the action stops helping. Protection, which keeps a wrong number from being served, comes before remediation, which tries to bring the data back.

Failure measuredActuatorGuardrailEscalates when
data older than 36 hrerun with the prices of today600 s of cooldown, 3 per 6 hthe budget is spent
the source fails above 50 %circuit breaker: hold, probe after a doubling backoffno rerun while openthe fourth opening
a batch breaks the quality gatequarantine every batch not in the last good state; rebuild and check goldprotection, outside the budgetthe second quarantine in 6 h
the run takes more than 120 snonealways: an alert to a person
Last known good stateA successful run records each batch of db_ingestion with its rows and an md5 digest in ops.good_batches. The quarantine moves every batch that differs to quarantine.db_ingestion, so the views of gold serve the last good numbers again; the frozen reports are tables and are not touched.
Step 04 · Result
The loop in the rehearsal of 08/11/2026

The real DataApp with a fault injected and short guardrails: a backoff of 20 s, ticks every 10 s and escalation at the third opening of the breaker.

TCG_FAULT=source_down · control --interval 10 --ticks 9
open_breaker  error rate 100%, SLO 50%  → open 20 s
hold          breaker open 9 s more
probe         probe failed             → open 40 s
hold · hold · hold
probe         probe failed             → open 80 s
                                         escalated to a person
hold · hold   waiting for a person
              (a person reruns the DataApp)
resolve       breaker closed, escalation resolved
none          every SLI within its SLO
TCG_FAULT=duplicate_prices · 9,613 rows for 7,782 keys
transient
quarantine  3 batches, 5,159 rows
            gold 5,951 rows = 5,951 keys
            frozen September: 1,226 rows kept
rerun       ok: 7,782 rows
none        every SLI within its SLO

persistent, within 6 h
quarantine  gold 5,951 = 5,951
            second quarantine → escalated
hold · hold · hold · hold
The loop is observable tooA tick that reruns is one trace of 41 spans: control.tick, control.sense, control.act rerun and the whole run under it. TcgControllerEscalated fired in Prometheus when the controller gave up.
0:58 · The same idea at scale
Closed loops in the tools you will meet

The controller of the DataApp is small, but its structure is the one of the control loops that run most production systems: a declared desired state, a measurement of the current state, and an action that reduces the difference.

Kubernetes

Reconciliation loop

Each controller compares the desired state of a resource with the observed state and acts until they match: a Deployment of three replicas recreates a pod that died.

Kubernetes

Horizontal Pod Autoscaler

A setpoint of CPU or of a custom metric, a sensor in the metrics API, and an actuator on the number of replicas, with a stabilisation window against oscillation.

Alertmanager

Webhook to remediation

An alert sent to a webhook that runs a playbook closes the loop for a known failure; routing, grouping and silences are its guardrails.

SRE

Error budget

The SLO allows a measured amount of failure. While budget remains, changes go out; when it is spent, releases stop. It is a feedback loop on how a team works.

1:00 · Second hour
Three signals and one loop for your DataApp

Each group applies the method to its own DataApp, the package of Lesson 7 or the flow of Lesson 8, with prompt 05. The measure of success is a failure rehearsed on purpose and followed from the alert to the log line, and one SLO whose loop either recovers or escalates once.

The three signals
  • metrics of each run, pushed, with an info metric of the run and the trace
  • one span per run, task, call to the source and transformation
  • JSON lines with run_id, trace_id and span_id
  • three alerting rules, each with a promtool test
One closed loop
  • one SLO with its setpoint and dead band
  • the sensor, the actuator and what it changes
  • cooldown, budget and the condition to escalate
  • a test that breaks the DataApp and proves the loop
Next sessionLesson 11 turns the DataApp into technical infographics: charts chosen for the data and dashboards built for the people who read them.
Self-study
Self-study for this session

Readings and a video assigned on Adalove for this week, on the metric types of Prometheus, its architecture and its relation with OpenTelemetry, with the reading material of the session.

About this session

Metrics and Telemetry · 09/12/2026 · Prof. Afonso

Learning objective

By the end of the session, students should be able to instrument a DataApp with metrics, traces and structured logs linked by run, trace and span identifiers, follow a failure from the alert to the log line that explains it, and close the loop on one SLO with a controller that compares the indicator with its setpoint, acts within guardrails and escalates to a person when it cannot recover.

Session strategy

Demonstration followed by application. In the first hour the professor builds the observability of the Lesson 7 package live with a coding agent and four CREATE prompts, injecting faults to follow a failure through the three signals and to watch the controller recover or escalate, and distinguishes observability, the sensor and display of the loop, from control, which compares and acts. In the second hour each group applies the method to its own DataApp with prompt 05.

Session structure

  1. Daily — 15 min
  2. The three signals and their correlation (7 min)
  3. Step 01 — metrics in Prometheus (8 min)
  4. Step 02 — traces and structured logs with OpenTelemetry (8 min)
  5. Step 03 — the stack; from the alert to the log line (4 min)
  6. The closed loop, and why observability alone does not close it (4 min)
  7. Step 04 — the controller of the DataApp with injected faults (14 min)
  8. Second hour — the groups apply it to their DataApp (60 min)