All lessons · Guided routes

Capstone 4 of 10

Capstone 4: See inside it: logs, metrics, traces, alerts

Users say orders are sometimes failing, and nobody can tell how often or why. You make the service observable end to end, and prove that an alert fires when errors are injected.

What you build

  1. Logs

    JSON request logs with a trace id on every line.

    Lessons: Observability from Scratch: Signals, Context, and Decisions, Centralized Logging (ELK & Loki)

  2. Metrics

    Prometheus (v2.55.1) scrapes /metrics every 5 seconds: request counts by status and a latency histogram.

    Lessons: Prometheus

  3. Traces

    The service sends a span per request over OTLP to an OpenTelemetry Collector (0.115.1); one trace id joins the logs and the traces.

    Lessons: OpenTelemetry, OpenTelemetry: Instrumentation, Context, and Collectors

  4. Dashboard

    Grafana (11.3.0) is provisioned from files: a Prometheus data source and a rate, errors, duration dashboard.

    Lessons: Grafana

  5. Alerts

    An alert rule on the error ratio; the check restarts the service with 30% errors and waits for the alert to fire.

    Lessons: SLOs in Practice: SLIs, Error Budgets, and Multi-Window Burn-Rate Alerts

  6. Profiling

    cProfile shows where the service spends CPU building /metrics.

    Lessons: Continuous Profiling and Flame Graphs, Linux Performance Profiling: perf, Flame Graphs, and Off-CPU Time

Before you start

ToolVersion
docker24 or later
python33.10 or later
curlany
jq1.6 or later

Ports: 18084, 19090, 13000, 14318 on 127.0.0.1. Resources: About 600 MB of memory for the three containers.

What it creates (and the reset removes): containers cap-otel, cap-prom, and cap-graf (host network, listening on 127.0.0.1 only); one python3 orders.py process; ~/labs/capstones/obs. Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 04-observability

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

bash 04-observability/setup.sh
bash 04-observability/verify.sh
bash 04-observability/reset.sh

Expected output

This is a real run of run.sh 04-observability, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. Start the OpenTelemetry Collector, Prometheus (with alert rules), and Grafana (provisioned)
  Prometheus ready
  Grafana ready

== 2. Start orders with tracing on, and send traffic
  121 requests sent (one with a known trace ID)

== Logs
  PASS  121 JSON request log lines
  PASS  the known trace ID is in the logs

== Metrics
  PASS  Prometheus scrapes orders (up = 1)
  PASS  request rate is measured: 0.91 requests per second

== Traces (OpenTelemetry)
  PASS  the Collector received 161 spans named GET /orders
  PASS  the span with the known trace ID arrived, so logs and traces join on it

== Dashboard
  PASS  Grafana's Prometheus data source is healthy
  PASS  the provisioned dashboard exists with 3 panels

== Alerts: inject errors and watch the alert fire
  PASS  OrdersHighErrorRate is firing (30% of requests fail)
  PASS  the error ratio query in the dashboard shows the problem

== Profiling: where does the service spend CPU when building /metrics?
  PASS  the profile names metrics_text as the hot path
           75001 function calls in 0.019 seconds
       3000    0.013    0.000    0.019    0.000 ~/labs/capstones/obs/orders.py:68(metrics_text)

RESULT: all checks passed

The files

04-observability/conf/alerts.yml
groups:
  - name: orders
    rules:
      - alert: OrdersHighErrorRate
        # share of /orders requests that failed over the last minute
        expr: |
          sum(rate(http_requests_total{route="/orders",status=~"5.."}[1m]))
            / sum(rate(http_requests_total{route="/orders"}[1m])) > 0.05
        for: 0s
        labels: {severity: page}
        annotations: {summary: "More than 5% of /orders requests are failing"}
      - alert: OrdersSlow
        expr: histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{route="/orders"}[1m]))) > 0.5
        for: 1m
        labels: {severity: ticket}
04-observability/conf/grafana/dashboards/dashboards.yaml
apiVersion: 1
providers:
  - name: capstone
    folder: Capstone
    type: file
    options: {path: /etc/grafana/provisioning/dashboards}
04-observability/conf/grafana/datasources/prometheus.yaml
apiVersion: 1
datasources:
  - name: Prometheus
    uid: prom
    type: prometheus
    access: proxy
    url: http://127.0.0.1:19090
    isDefault: true
04-observability/conf/otel-collector.yaml
# Receives OTLP over HTTP from the orders service and prints each span (debug exporter).
receivers:
  otlp:
    protocols:
      http: {endpoint: "127.0.0.1:14318"}
processors:
  batch: {timeout: 1s}
exporters:
  debug: {verbosity: detailed}
service:
  pipelines:
    traces: {receivers: [otlp], processors: [batch], exporters: [debug]}
  telemetry:
    metrics: {level: none}
04-observability/conf/prometheus.yml
global:
  scrape_interval: 5s
  evaluation_interval: 5s
rule_files: [/etc/prometheus/alerts.yml]
scrape_configs:
  - job_name: orders
    static_configs: [{targets: ["127.0.0.1:18084"]}]
04-observability/reset.sh
#!/usr/bin/env bash
# Stops the service and removes the cap-otel, cap-prom, and cap-graf containers and the work folder.
source "$(dirname "$0")/../lib.sh"
WORK="$HOME/labs/capstones/obs"
[ -f "$WORK/service.pid" ] && kill "$(cat "$WORK/service.pid")" 2>/dev/null || true
docker rm -f cap-otel cap-prom cap-graf > /dev/null 2>&1 || true
rm -rf "$WORK"
echo "capstone 4 reset: service stopped, containers cap-otel, cap-prom, cap-graf removed, $WORK removed"
04-observability/setup.sh
#!/usr/bin/env bash
# Capstone 4, observability: logs -> metrics -> traces -> OpenTelemetry -> dashboards -> alerts -> profiling.
# The orders service runs locally (port 18084) and sends spans over OTLP; Prometheus (19090),
# Grafana (13000), and an OpenTelemetry Collector (14318) run as containers on the host network.
source "$(dirname "$0")/../lib.sh"
need docker curl jq python3
work obs
for p in 18084 19090 13000 14318; do port_free "$p"; done
cp -r "$(dirname "$0")/conf" "$APP_SRC/orders.py" "$WORK/"
cd "$WORK"

say "1. Start the OpenTelemetry Collector, Prometheus (with alert rules), and Grafana (provisioned)"
docker run -d --name cap-otel --network host -v "$WORK/conf/otel-collector.yaml:/etc/otelcol/config.yaml:ro" \
  otel/opentelemetry-collector:0.115.1 > /dev/null
docker run -d --name cap-prom --network host -v "$WORK/conf/prometheus.yml:/etc/prometheus/prometheus.yml:ro" \
  -v "$WORK/conf/alerts.yml:/etc/prometheus/alerts.yml:ro" prom/prometheus:v2.55.1 \
  --config.file=/etc/prometheus/prometheus.yml --web.listen-address=127.0.0.1:19090 > /dev/null
docker run -d --name cap-graf --network host -e GF_SERVER_HTTP_PORT=13000 -e GF_SERVER_HTTP_ADDR=127.0.0.1 \
  -e GF_AUTH_ANONYMOUS_ENABLED=true -e GF_AUTH_ANONYMOUS_ORG_ROLE=Viewer -e GF_SECURITY_ADMIN_PASSWORD=capstone-only \
  -v "$WORK/conf/grafana:/etc/grafana/provisioning:ro" grafana/grafana:11.3.0 > /dev/null
wait_for http://127.0.0.1:19090/-/ready 60 && echo "  Prometheus ready"
wait_for http://127.0.0.1:13000/api/health 90 && echo "  Grafana ready"

say "2. Start orders with tracing on, and send traffic"
PORT=18084 VERSION=1.0.0 OTLP_URL=http://127.0.0.1:14318/v1/traces nohup python3 orders.py > service.log 2>&1 &
echo $! > service.pid
wait_for http://127.0.0.1:18084/readyz 20
for i in $(seq 120); do curl -s -o /dev/null http://127.0.0.1:18084/orders; done
curl -s -o /dev/null -H "traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" http://127.0.0.1:18084/orders
echo "  121 requests sent (one with a known trace ID)"
04-observability/verify.sh
#!/usr/bin/env bash
# Checks capstone 4: logs, metrics, traces, dashboard, an alert that fires on injected errors, profiling.
source "$(dirname "$0")/../lib.sh"
need docker curl jq python3
work obs
cd "$WORK"
P=http://127.0.0.1:19090/api/v1
q() { curl -fsS --data-urlencode "query=$1" "$P/query" | jq -r '.data.result[0].value[1] // "none"'; }

say "Logs"
n=$(grep -c '"msg": "request"' service.log)
[ "$n" -ge 121 ] && ok "$n JSON request log lines" || bad "only $n request log lines"
check "the known trace ID is in the logs" grep -q 0af7651916cd43dd8448eb211c80319c service.log

say "Metrics"
for _ in $(seq 20); do [ "$(q 'up{job="orders"}')" = 1 ] && break; sleep 2; done
[ "$(q 'up{job="orders"}')" = 1 ] && ok "Prometheus scrapes orders (up = 1)" || bad "the orders target is not up"
# rate() needs two scrapes that differ, so keep a little traffic flowing while we poll
for _ in $(seq 15); do
  for i in $(seq 10); do curl -s -o /dev/null http://127.0.0.1:18084/orders; done
  r=$(q 'sum(rate(http_requests_total{route="/orders"}[1m]))')
  [ "$r" != none ] && [ "$r" != 0 ] && break; sleep 2
done
if [ "$r" != none ] && [ "$r" != 0 ]; then ok "request rate is measured: $(printf '%.2f' "$r") requests per second"; else bad "no request rate (got $r)"; fi

say "Traces (OpenTelemetry)"
sleep 2
spans=$(docker logs cap-otel 2>&1 | grep -c 'Name *: GET /orders')
[ "$spans" -ge 100 ] && ok "the Collector received $spans spans named GET /orders" || bad "only $spans spans reached the Collector"
check "the span with the known trace ID arrived, so logs and traces join on it" bash -c "docker logs cap-otel 2>&1 | grep -q 0af7651916cd43dd8448eb211c80319c"

say "Dashboard"
check "Grafana's Prometheus data source is healthy" bash -c "curl -fsS -u admin:capstone-only http://127.0.0.1:13000/api/datasources/uid/prom/health | jq -e '.status == \"OK\"'"
check "the provisioned dashboard exists with 3 panels" bash -c "curl -fsS -u admin:capstone-only http://127.0.0.1:13000/api/dashboards/uid/orders-red | jq -e '.dashboard.panels | length == 3'"

say "Alerts: inject errors and watch the alert fire"
kill "$(cat service.pid)" 2>/dev/null; sleep 1
PORT=18084 VERSION=1.0.1 FAIL_RATE=0.3 nohup python3 orders.py >> service.log 2>&1 &
echo $! > service.pid
wait_for http://127.0.0.1:18084/readyz 20
state=none
for _ in $(seq 30); do
  for i in $(seq 20); do curl -s -o /dev/null http://127.0.0.1:18084/orders; done
  state=$(curl -fsS "$P/alerts" | jq -r '[.data.alerts[] | select(.labels.alertname == "OrdersHighErrorRate")][0].state // "none"')
  [ "$state" = firing ] && break; sleep 2
done
[ "$state" = firing ] && ok "OrdersHighErrorRate is firing (30% of requests fail)" || bad "the alert did not fire (state: $state)"
check "the error ratio query in the dashboard shows the problem" bash -c "[ \"\$(curl -fsS --data-urlencode 'query=sum(rate(http_requests_total{route=\"/orders\",status=~\"5..\"}[1m])) / sum(rate(http_requests_total{route=\"/orders\"}[1m])) > 0.05' $P/query | jq '.data.result | length')\" = 1 ]"

say "Profiling: where does the service spend CPU when building /metrics?"
python3 - <<'PY' > profile.txt
import cProfile, pstats, io, importlib.util, sys
spec = importlib.util.spec_from_file_location("orders", "orders.py"); m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
for i in range(400):
    m.observe("/orders", "GET", 200 if i % 7 else 500, i / 4000)
pr = cProfile.Profile(); pr.enable()
for _ in range(3000):
    m.metrics_text()
pr.disable()
s = io.StringIO(); pstats.Stats(pr, stream=s).sort_stats("cumulative").print_stats(5); print(s.getvalue())
PY
check "the profile names metrics_text as the hot path" grep -q "metrics_text" profile.txt
grep -m3 -E "metrics_text|function calls" profile.txt | sed 's/^/  /'
summary

If it fails

SymptomCauseFix
"Prometheus scrapes orders" failsHost networking is not available (Docker Desktop before 4.34 on macOS or Windows).Run it inside WSL or Linux, or enable host networking in Docker Desktop settings.
The alert stays "pending" or "none"Prometheus needs two scrapes with errors before rate() changes.The check waits up to two minutes; on a very slow machine run verify again.
Grafana login promptAnonymous viewing is on; the admin password is set only for this lab.Log in as admin with the password in setup.sh, or just view.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

bash 04-observability/reset.sh

It removes: containers cap-otel, cap-prom, and cap-graf (host network, listening on 127.0.0.1 only); one python3 orders.py process; ~/labs/capstones/obs. Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSAmazon Managed Service for Prometheus, Amazon Managed Grafana, and AWS Distro for OpenTelemetry sending traces to X-Ray.
AzureAzure Monitor managed service for Prometheus, Azure Managed Grafana, and Application Insights through OpenTelemetry.
Google CloudGoogle Cloud Managed Service for Prometheus, Cloud Trace through the OpenTelemetry Collector, and Cloud Monitoring dashboards.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
CorrelationYou can go from a log line to its trace by the trace id.You can go from an alert to the failing requests' traces.
MetricsRate, errors, and duration are on the dashboard.Every panel answers a question someone on call would ask.
AlertsThe alert fires on real errors and not on normal traffic.The alert is based on an SLO burn rate, as in capstone 6.
Cost and cardinalityYou know which labels each metric has.You can estimate the series count and keep it bounded.

Take it further

Then test what you know with the assessments.

Next capstone: A pipeline that ships only what it can trust. All capstones · Guided routes