BEGINNERPROJECTCHAPTER 06

Project: instrument the demo app end to end

From a dark system to three correlated signals and a dashboard per service, then find the bug a colleague planted using nothing else

150 MINOBSERVABILITYUPDATED 2026-11-02

The brief

You start from a fresh clone with OTEL_SDK_DISABLED=true, the state the demo app was in during the first chapter. By the end you have:

  1. All three signals on. The OpenTelemetry SDK enabled in gateway, orders and payments; structured JSON logs carrying trace_id and span_id; the request counter and duration histogram exposed on /metrics and scraped; spans flowing through the Collector to Tempo.
  2. Correlation by trace id. From a log line in Loki, you can open the trace in Tempo in one click. From a trace, you can find its log lines. From a slow bucket on the latency histogram, you can reach a trace that landed in it.
  3. One Grafana dashboard per service, each with three panels: request rate, error ratio, p95 duration. Three dashboards, nine panels, built from the PromQL you wrote in the metrics chapter.
  4. A diagnosis. Partway through, a colleague enables a fault. You find it using the telemetry you built, write up what you saw in each signal, and name the code path, before you look at the code or the environment.

Budget 150 minutes: about 60 for instrumentation, 30 for dashboards, 30 for the investigation, 30 for the write-up. If instrumentation runs long, finish it; the investigation is pointless on a half-instrumented system, which is a lesson in itself.

What correlation means in practice

The three signals are correlated when one id appears in all of them. The trace id is that id, and each signal has a place for it.

In logs, it is a field: {"ts": ..., "level": "info", "msg": "order created", "trace_id": "4bf9...", "span_id": "00f0...", "order_id": 1234, "items": 3}. The logging chapter set this up; the SDK makes the current span’s ids available and the JSON formatter writes them. In Loki the record arrives over OTLP, so trace_id is structured metadata beside the line rather than text in it, and a derived field in the data source configuration matches that field and turns it into a link to Tempo. In Grafana that is Connections → Data sources → Loki → Derived fields: name trace_id, type Label, label trace_id, internal link to the Tempo data source, query ${__value.raw}. A regex such as "trace_id":\s*"(\w+)" is the variant for stores that keep the JSON text.

In traces, the id is the trace itself. Tempo’s data source has the reverse link: “Trace to logs” with the Loki data source selected, which runs a LogQL query for the trace id over the span’s time range, padded by a few seconds. Map the tag service.name to the Loki label service_name, and because the trace id is structured metadata, use a custom query that filters on it as a label: {${__tags}} | trace_id="${__trace.traceId}".

In metrics, the link is an exemplar: a trace id attached to a histogram observation. The Python client records exemplars when Histogram.observe is called with an exemplar={"trace_id": ...} argument and Prometheus is started with --enable-feature=exemplar-storage, which the lab stack’s compose file sets. The client only exposes exemplars in the OpenMetrics format, so the lab’s /metrics handler in services/common/metrics.py, which always serves the classic text format, needs to serve prometheus_client.openmetrics.exposition.generate_latest when Prometheus asks for it; that is part of the optional exercise. In Grafana, a histogram panel with exemplars enabled shows them as dots; hovering one gives a link to the trace. Exemplars are optional for this project, and worth doing if you have time, because they are the only path from an aggregate to an example.

The dashboards

One dashboard per service, three panels each: the RED method, which module two formalises. The queries are the three from the metrics chapter with job pinned to the service:

sum(rate(http_requests_total{job="orders"}[1m]))
sum(rate(http_requests_total{job="orders", status=~"5.."}[1m]))
  / sum(rate(http_requests_total{job="orders"}[1m]))
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{job="orders"}[1m])))

Set units (requests/s, percent 0.0 to 1.0, seconds) and give the error panel a threshold line at 1 %. Build the orders dashboard first, export its JSON, and make the other two by replacing the job name; Grafana’s dashboard variables make this one dashboard with a $service selector, which is better still. Save them into grafana/dashboards/, which the lab’s dashboard provider loads, so a fresh clone gets them.

A fourth panel earns its place on the orders dashboard once you have found the fault. Think about which one as you go.

The investigation

When the three dashboards are up and the load generator has run for ten minutes, a colleague (the lab step below plays the part) changes one environment variable and restarts a service. They tell you only that checkout “feels slower for some people”. You have the three dashboards, Explore for Loki and Tempo, and the Prometheus UI. You do not have the code, compose.yaml, or docker compose config.

Work in the SRE book’s order. Metrics first: which service’s duration moved, when, and did rate or errors move with it. Traces next: pull a slow trace from that service in that window and read the waterfall; what grew, what multiplied, what is new. Logs last: open the log lines for that trace and read what the code says it was doing; a count, a size, a flag. Then form a hypothesis that explains all three, and only then check it against the code.

Write it up in a page: the three observations, the hypothesis, the code path, and the fix. The rubric below is what a complete write-up contains.

Rubric

A complete answer has every row. A strong one also has the last two.

area complete when
signals on curl :8080/metrics shows http_requests_total and http_request_duration_seconds_bucket; Tempo shows ten-span checkout traces across three services; Loki shows JSON lines with trace_id from all three services
correlation a trace id copied from a Loki line opens the trace in Tempo; the trace’s “logs for this span” button returns the matching lines; (optional) exemplars appear on the orders histogram panel
dashboards three dashboards or one with a $service variable; rate, error ratio, p95 per service; units set; error threshold drawn; provisioned from grafana/dashboards/ so they survive docker compose down -v
metric observation orders p95 rose at the minute the fault was enabled; gateway p95 rose by the same amount; payments did not move; request rate and error ratio flat on all three. The write-up names the minute
trace observation a slow orders trace shows N consecutive SELECT or INSERT spans with db.system=postgresql, each 1 to 5 ms, under POST /orders, where N equals the order’s item count, in place of one span. The write-up states N for the trace examined and that payments’ subtree is unchanged
log observation the orders log line for that trace carries items equal to N, and traces with higher items are slower; VIP users (ids divisible by 97, items*3) are the slowest, which is the “some people”
hypothesis orders runs one database round trip per item instead of one batched statement: an N+1. Named before looking at code or environment
code path and cause the item loop in orders’ create-order handler; FAULT_N_PLUS_ONE=1 in the orders service environment
the fourth panel (strong) p95 duration of POST /orders split by an item-count bucket, or a panel of rate(db_client_operations_total{job="orders"}[1m]) / rate(http_requests_total{job="orders"}[1m]), database calls per request, which is flat at 3 before the fault (insert the order, insert its items, update its status) and tracks item count after
what would have found it faster (strong) an alert on database calls per request, or a trace-derived metric on span count per trace; one sentence on why p95 alone was slow to show it, since most users have few items

The exact span pattern

Before the fault, the orders subtree of a checkout with items=3 is:

orders   POST /orders                [server]
orders     INSERT orders             [client, db.system=postgresql]
orders     INSERT order_items        [client, db.system=postgresql]   ← one statement, 3 rows
orders     POST .../charge           [client]
orders     UPDATE orders             [client, db.system=postgresql]   ← status = paid

Tempo names the database spans by operation (INSERT, UPDATE) and the client span POST; the table names are in db.statement.

After FAULT_N_PLUS_ONE=1, for the same request:

orders   POST /orders                [server]
orders     INSERT orders             [client]
orders     INSERT order_items        [client]   ← row 1
orders     INSERT order_items        [client]   ← row 2
orders     INSERT order_items        [client]   ← row 3
orders     POST .../charge           [client]
orders     UPDATE orders             [client]

For a VIP user with items=30, there are 30 of them, each a few milliseconds plus a network round trip to Postgres, so the orders span grows by 60 to 150 ms and the gateway span with it. Every span is individually fast and individually innocent, which is why no per-query alert fires and why the shape of the trace, not any one span, is the finding.

LAB Instrument, correlate, dashboard, then find the planted N+1 LONG · ~150 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2a fresh clone of the ATLAS repo (git clone, not your working copy from earlier chapters)curl, jq and a browserabout 3 GB of RAM free for the stacka text editor

1. Start dark and confirm it.

cd labs/observability
docker compose --profile telemetry down -v    # the volumes are shared by every clone: start from empty stores
docker compose --profile telemetry up -d --build
curl -s 'http://localhost:8080/checkout?user=42&items=3' | jq .
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/metrics
docker compose logs --no-log-prefix gateway | tail -2
The checkout works. /metrics returns 200 and already has http_requests_total and http_request_duration_seconds: the Prometheus middleware is always on, and it is the one signal chapter one had. The log lines are plain text with no trace id, and Loki has nothing, because logs reach it only over OTLP from the SDK. In Grafana at http://localhost:3000, Explore → Tempo → search for { resource.service.name = "gateway" } returns nothing. This is the system from chapter one.

2. Turn the SDK and structured logs on, for all three services. Edit compose.yaml and set, in the shared x-otel-env block the three services inherit, the two values whose defaults keep them dark (the endpoint is already there):

  OTEL_SDK_DISABLED: "false"
  LOG_FORMAT: "json"
  OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317

Keep this edit: from here on the services in this clone start with all three signals on.

Then:

docker compose --profile telemetry up -d --build gateway orders payments
sleep 20
curl -s 'http://localhost:8080/checkout?user=42&items=3' | jq .
curl -s http://localhost:8081/metrics | grep -c '^http_request_duration_seconds_bucket'
docker compose logs --no-log-prefix orders | tail -1 | jq '{trace_id, span_id, items}'
The bucket count is 14 (13 bounds plus +Inf, for the one method, route and status combination); the log line is JSON with a 32-character trace_id and a 16-character span_id, and items: 3. In Prometheus http://localhost:9090/targets the three service jobs are UP. In Tempo, the same search now returns traces, and the newest for user 42 has ten spans across three colours. If any service shows no spans, check docker compose logs otel-collector for a refused connection: the exporter endpoint must be the Collector’s gRPC port, 4317, not the HTTP one.

3. Check the correlation. The lab provisions both links, so read them rather than build them: in Grafana, Connections → Data sources → Loki → Derived fields shows trace_id matching the trace_id label with an internal link to Tempo; Tempo → Trace to logs shows data source Loki, tag service.name → service_name, and the custom query {${__tags}} | trace_id="${__trace.traceId}". Both are in grafana/provisioning/datasources/datasources.yaml. Test them:

curl -s 'http://localhost:8080/checkout?user=97&items=2' | jq .

In Explore → Loki run {service_name="orders"} | user = "97" and click the View trace link on the newest line. No parser: the Loki line is the message (order paid) and user is structured metadata.

The Loki line expands with a trace_id field and a View trace button; clicking it opens the ten-span trace in a split pane. In the trace, the “Logs for this span” button on the orders server span runs the reverse query and returns the orders log lines for that request. Note that user 97 is a VIP: items=2 arrives at orders as items=6, and the log line says so.

4. Build the dashboards. Create a dashboard named orders RED with three time-series panels using the three queries from the brief, units reqps, percentunit and s, and a red threshold at 0.01 on the error panel. Add a dashboard variable service of type Query, data source Prometheus, query label_values(http_requests_total, job), and replace job="orders" with job="$service" in all three panels. Export it (Share → Export → Save to file, with “Export for sharing externally” off) into grafana/dashboards/red.json. The provider in grafana/provisioning/dashboards/dashboards.yaml reads that directory every 10 seconds, so there is nothing to restart:

ls grafana/dashboards/
Within ten seconds the dashboard is in the ATLAS lab folder without you importing it, with a service dropdown listing gateway, orders and payments. At the default 5 requests per second, rate shows about 5 on each service, error ratio is 0 or empty, and p95 is highest on gateway and lowest on payments. Let it run for ten minutes so there is a baseline to compare against.

5. The colleague. Run this and do not read it; copy it from the page into a terminal you then close:

FAULT_N_PLUS_ONE=1 docker compose --profile telemetry up -d --build orders

Note the time. Open the orders dashboard and wait two minutes. Then investigate in the order metrics → traces → logs, without opening compose.yaml or the code, and write down one observation per signal before forming a hypothesis.

On the dashboard, orders p95 steps up within one to two minutes of the restart; by how much depends on the laptop, typically from around 30 ms to 60 to 120 ms. Gateway p95 moves by the same amount; payments is flat; rate and errors are flat everywhere. In Tempo, { resource.service.name = "orders" && span:duration > 80ms } returns the slow ones: open one and the orders subtree has a row of identical INSERT order_items spans, as many as the order has items, with the payments subtree the same size as before. Click through to the logs: items equals the number of spans, and the slowest traces belong to users 97, 194, 291, …, whose item counts are tripled. The hypothesis you should reach: orders inserts items one statement at a time. Only now open services/orders/app.py and compose.yaml to confirm the loop and the variable.

6. Write it up and add the fourth panel. Add a panel to the orders dashboard that would have shown this faster than p95 did:

sum(rate(db_client_operations_total{job="orders"}[1m]))
  / sum(rate(http_requests_total{job="orders", route="/orders"}[1m]))
Database operations per request: flat at 3 before the fault (insert the order, insert its items in one statement, update its status), and climbing to the mean item count plus two after it, because each item becomes its own INSERT. The orders service counts every statement it runs in db_client_operations_total, labelled by operation. Restore the service with docker compose --profile telemetry up -d --build orders (no fault variable) and watch the panel fall back to 3.
Turn the fault back on, then add LOG_FORMAT: text to orders’ own environment: block (after <<: *otel-env, so it overrides the shared value) and run FAULT_N_PLUS_ONE=1 docker compose --profile telemetry up -d orders. Repeat the investigation. Nothing in Loki changes: LOG_FORMAT only decides what the container writes to stdout, and Loki receives records over OTLP with their fields attached either way. That is the case for shipping logs as structured records from the SDK rather than parsing text. Then try the opposite: put LOG_FORMAT back and set OTEL_SDK_DISABLED: "true" on orders only. The trace now jumps from the gateway client span to nothing, and payments starts a new root trace, exactly as in the tracing chapter; the N+1 is invisible in traces entirely. Orders’ lines vanish from Loki too, because the OTLP log handler is part of the SDK; docker compose logs orders still says items and the metric still says orders is slow, and you are back to correlating by timestamp. Whichever signal you remove, the investigation takes longer than the fix. Remove both overrides and run docker compose --profile telemetry up -d orders before moving on.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: OpenTelemetry: the data model, SDK, API and semantic conventions →