Learnings

Cloud and DevOps

Observability: Logs, Metrics and Traces

How to see what a service is doing in production: structured logs, Prometheus metrics and OpenTelemetry traces, then the alerts, SLOs and dashboards built on them. One small bank API with a planted slow endpoint and a planted failure is observed for real (Python 3.9, prometheus-client 0.26, OpenTelemetry SDK 1.41, Prometheus 3.16 in Docker), and all output is pasted from those runs.

The three signals

Part 1 of 6 · what each signal answers, and the service being observed

Monitoring, observability and the three signals

The three signals

Monitoring answers questions you chose in advance: is it up, is it slow. Observability is being able to answer a new question about a running system from what it already emits, without shipping code first.

Every request leaves all three behind.
QuestionSignalCost
How many, how fast, is it getting worse?MetricsLow and flat: one number per series, whatever the traffic
What exactly happened in this request?LogsGrows with traffic: you pay per line stored
Where did this request spend its time, across services?TracesGrows with traffic: usually sampled

Interview point: metrics say that something is wrong, traces say where, logs say why.

The demo service

The three signals

Two standard-library HTTP servers: bank-api on port 8610 with SQLite, and a downstream ledger on 8611. This is the one place in app.py where a request emits all three signals.

RouteDoesPlanted behaviour
GET /accounts, GET /accounts/{id}List, read one404 for an unknown id
POST /depositAdd rupeesNone
POST /transferCalls ledger, then moves rupeesThe ledger rejects every 5th entry: 502
GET /accounts/{id}/statementRead a statementEvery 10th call sleeps 1.2 s in the query
GET /metricsPrometheus scrapeNot counted, logged or traced

Logs

Part 2 of 6 · one structured line per event, tied to its request

Structured JSON versus text

Logs

The same two events, a deposit and a failed transfer, first with a plain text format and then as one JSON object per line.

  • Text needs a regex per message. JSON is queried by field: level = ERROR and route = /transfer.
  • Keep msg constant and put the variables in fields, so lines group by message.
  • The text lines lost the account, amount, status and error: a format string prints only the fields it names.

Levels

Logs

LevelBelongs hereIn the demo
DEBUGDetail for the developer. Off in production, switchable at run time.Not used
INFOA business event finished, or a request ended normallydeposit done, request done 2xx
WARNINGUnexpected but handled: client errors, retries, fallbacksrequest done 404
ERRORThis request failed and the fault is ours or a dependency'srequest done 502, entry rejected
CRITICALThe process cannot continueNot used

Trap: logging an exception at every layer and re-raising turns one failure into five ERROR lines. Log it once, where it is handled.

The logging module itself is covered in Debugging and Logging.

A request id on every line

Logs

The handler sets a ContextVar once per request, and a logging filter copies it onto every record. No function has to pass the id along.

  • A ContextVar is separate per thread and per asyncio task, so concurrent requests do not mix ids.
  • The id crosses services as the X-Request-Id header: the third line comes from the other process.

What never to log

Logs

Logs are copied to more systems, read by more people and kept longer than the database they describe.

NeverLog instead
Passwords, tokens, API keys, Authorization and cookie headersWhether one was present, or a short fingerprint
Card numbers, CVV, full bank account numbersLast four digits, or an internal id
Names, emails, phone numbers, addressesAn opaque id such as ACC-1001
Whole request and response bodiesSize, plus the few fields you chose

In the demo: the accounts table holds owner names such as Sandhya Agrawani, but no log line, metric label or span attribute carries one. A deletion request cannot reach a log archive, so keep personal data out of it.

Volume and sampling

Logs

The same 200 requests were sent twice, the second time with LOG_SAMPLE=10, which adds this filter to the handler.

RunLinesBytesINFOERROR
All lines28060,9562728
LOG_SAMPLE=10327,181248
  • Unsampled, that is 305 bytes per request: about 26 GB a day at 1,000 requests a second.
  • Every error survives, and metrics still count every request.
  • Better: decide once per request, so a kept request keeps all its lines. The trace's sampled flag is a ready-made decision.

Where logs go in containers

Logs

The app writes lines to stdout and nothing else. Files, rotation and shipping belong to the platform.

The collector adds pod, container and node labels on the way.
  • Set PYTHONUNBUFFERED=1, or the last lines before a crash stay in a buffer.
  • Collectors: Fluent Bit, Vector, the OpenTelemetry Collector. Stores: Loki, Elasticsearch, a cloud log service.
  • Not run for this page: the service ran on the host with stdout redirected to app.log. The runtime side is in Docker.

Metrics

Part 3 of 6 · cheap numbers over time, scraped by Prometheus and queried with PromQL

Counter, gauge, histogram, summary

Metrics

TypeHoldsQuery withUse for
CounterA total that only goes uprate()Requests, errors, rupees deposited
GaugeA value right nowAs is, avg_over_time()In-flight requests, queue depth, memory
HistogramCounts per bucket, plus sum and counthistogram_quantile()Latency, sizes
SummarySum and count, quantiles computed in the clientrate(sum) / rate(count)Rarely: prefer a histogram

Trap: the Python client's Summary exports only count and sum, as the last two lines show. Client-side quantiles also cannot be combined across instances, and histogram buckets can.

How each type behaves over time

Metrics

Counter, scrape by scrape: it only climbs. A restart drops it to 0, and rate() corrects for that.
Gauge: moves both ways. Read it as it is. A spike between two scrapes is never seen.
Histogram: buckets are cumulative, so one observation raises every bucket it fits under.

Instrumenting the service

Metrics

Four metrics are defined once at import time and updated in the request path. After one deposit and five transfers, /metrics returns this.

  • Names carry the unit and kind: _seconds, _total. Base units only, never milliseconds.
  • The route label is the template /accounts/{id}, never the raw path.
  • Trimmed: seven middle buckets, the /deposit histogram, _created timestamps, comment lines and the client's own python_* series.

Labels and the cardinality trap

Metrics

Every distinct combination of label values is its own time series, held in memory by the app and by Prometheus. Here 200 different account ids are requested, first with the route template as the label and then with the raw path.

  • 15 series became 3,000: 200 paths times 15 lines each (1 counter, 12 histogram lines, 2 timestamps).
  • Cost is the product of all label value counts. One unbounded label is enough to run Prometheus out of memory.
  • Never a label: user or account id, request id, raw path, email, error message text. Those belong in logs and spans.

The pull model and a scrape config

Metrics

The service only exposes /metrics. Prometheus decides what to scrape and how often, and stores every sample with a timestamp.

Prometheus pulls. Targets never need to know where it lives.
  • Pull gives a free health signal: up == 0 means the scrape failed.
  • job and instance are added by Prometheus. Queries below are shown without the docker exec tut-prometheus prefix.
  • Jobs too short-lived to be scraped push to a Pushgateway instead. Here static_configs stands in for service discovery.

PromQL: rate and error ratio

Metrics

A load generator ran four workers for four minutes, cycling through the five routes. These queries were evaluated at one instant, 150 seconds in (the --time flag and @ timestamps are trimmed).

  • rate(x[1m]) is the per-second increase averaged over the last minute, corrected for counter resets.
  • A ratio is a sum of rates over a sum of rates. Never average per-instance ratios: a quiet instance would weigh as much as a busy one.
  • 4% overall looks mild. Split by route, it is one route failing 20% of the time.

p95, and why averages hide the tail

Metrics

The statement route answers in well under a millisecond nine times out of ten, and in 1.2 seconds the tenth time.

  • The average, 120 ms, describes no request at all. The median says "fast" and p95 says "one request in ten takes over a second".
  • histogram_quantile interpolates inside a bucket: the true 1.2 s is reported as 1.75 s because it falls in the 1 to 2.5 bucket (and 0.2 ms as 2.8 ms). Put bucket bounds near your SLO threshold.
  • Across all routes p95 is 4.9 ms and the slow route vanishes. Aggregate buckets with sum by (le, route), and never average percentiles.

RED and USE

Metrics

RED is for things that serve requests. USE is for resources that can fill up.

REDMeasureIn the demo
RateRequests per secondrate(bank_http_requests_total[1m])
ErrorsFailed requests per second, or as a ratioThe same counter with status=~"5.."
DurationLatency distributionThe duration histogram
USEMeasureExamples
UtilisationShare of the resource in useCPU 80%, 18 of 20 pool connections
SaturationWork waiting for itRun queue length, requests waiting for a connection
ErrorsError events of the resourceDisk errors, OOM kills, refused connections

Golden signals and the metrics every service needs

Metrics

The four golden signals are latency, traffic, errors and saturation: RED plus the "S" of USE.

MetricTypeAnswers
Requests by method, route, statusCounterTraffic and errors
Request duration by routeHistogramLatency, and the SLO
In-flight requestsGaugeSaturation of the service
Calls to each dependency by outcome, with durationCounter, histogramIs it us or them
Pool in use and max, queue depthGaugeSaturation before it hurts
Process CPU, memory, GC, open filesFrom the client libraryUSE for the process
build_info{version} set to 1GaugeWhich deploy is running

Seen in this run: the demo has no dependency metric, so finding the ledger fault later takes a trace. Also, prometheus-client exports process_* only on Linux: on macOS the scrape had just python_gc_* and python_info.

Traces

Part 4 of 6 · one request followed across services with OpenTelemetry

Trace, span, parent and child

Traces

A span is one timed operation with a name, a start, an end and attributes. A trace is every span that shares one trace id, linked into a tree by parent_id.

One successful transfer: five spans in two processes, one trace id.
  • A span is exported when it ends, so children print before parents. The root has parent_id null and comes last in its process.
  • The ledger's span names a parent in another process: that link travelled in an HTTP header.

Context propagation and traceparent

Traces

The caller injects the W3C traceparent header and the callee extracts it before starting its span. This is the header the ledger received on a failing transfer.

FieldValueMeaning
version00Format version
trace-ide00d8de4de231f77bbeb0401cd746d6216 bytes, the same in every service
parent-idab8f5e9a7da9dd188 bytes: the caller's span, here POST ledger /entries
flags0101 means sampled: keep recording downstream

Trap: the trace breaks at any hop that drops the header: a queue, a thread pool, a hand-written HTTP client. For queues, carry it in the message metadata.

OpenTelemetry in Python

Traces

The SDK needs a provider, a processor and an exporter. The console exporter prints about 28 lines of JSON per span by default, so a formatter cuts it to one line.

  • The error status is set on each span where it happened, so the failing hop is visible without reading logs.
  • Production uses BatchSpanProcessor with an OTLP exporter. SimpleSpanProcessor exports inside the request.
  • Not run for this page: the opentelemetry-instrumentation-* packages, which create such spans automatically.

Linking logs to traces

Traces

The logging filter also stamps the current trace id on every record. A trace id copied from a span finds the log lines of both services.

  • Trace says where: the ledger call. Log says why: journal write timeout.
  • With tracing everywhere, the trace id can replace a home-made request id.

Head versus tail sampling

Traces

Head samplingTail sampling
DecidedAt the first span, before anything is knownAfter the trace has finished
ByThe SDK, for example 5% by trace idThe Collector, which buffers whole traces
KeepsA random shareAll errors and slow traces, a share of the rest
CostAlmost noneMemory, and all spans of a trace must reach one Collector
WeaknessMost rare failures are thrown awayMore moving parts to run

Note: the head decision is the 01 flag in traceparent, so every service downstream agrees. The demo keeps every trace.

The OpenTelemetry pipeline

Traces

OpenTelemetry is an API, SDKs, a wire protocol (OTLP) and a Collector. It produces and moves telemetry, and stores none of it.

Not run for this page: the demo exports to the console, with no Collector.
  • Vendor neutral means the code is instrumented once. Changing backend is Collector configuration, with no redeploy of services.
  • The Collector is the one place to drop personal data, sample and add environment labels.
  • Backends: Jaeger or Tempo for traces, Prometheus for metrics, Loki for logs, or one product for all three.

Alerts and SLOs

Part 5 of 6 · deciding when a human is woken up

Symptom versus cause, and a good alert

Alerts and SLOs

A symptom alert fires on what users feel (errors, slow responses) and is worth a page. A cause alert fires on something that might lead there (high CPU, a restarted pod) and belongs on a dashboard.

A good alert isTestIn the rule below
About usersWould a customer notice?Share of requests answered 5xx
ActionableIs there something to do right now?Roll back, fail over, shed load
UrgentCan it wait until morning? Then it is a ticket.severity: page
DocumentedDoes it link to a runbook?runbook annotation
StableDoes one bad scrape trigger it?for: 1m

A Prometheus alerting rule, pending then firing

Alerts and SLOs

Prometheus evaluates the expression every 5 seconds. The alert must stay true for the whole for period before it fires.

Only firing alerts are sent to Alertmanager.
  • Printed by a small script polling /api/v1/alerts every 2 seconds.
  • Pending 10 s after the load began, firing 58 s later, and inactive 58 s after the load stopped, once the 1m window had emptied.
  • Not run for this page: Alertmanager, which groups, silences and routes firing alerts to a pager or chat.

Alert fatigue: page, ticket or nothing

Alerts and SLOs

Every page that needed no action teaches the on-call engineer to ignore the next one.

Route toWhenExample
PageUsers are affected now and a human can fix itError ratio burning the budget fast
TicketNeeds work within daysDisk full in 5 days, certificate expires in 2 weeks
Dashboard onlyUseful context, no action by itselfCPU at 85%, one pod restarted
  • If the usual response is acknowledge and go back to sleep, it is not a page.
  • Review pages weekly: fix the cause, tune the rule or delete it.

SLI, SLO and error budget

Alerts and SLOs

TermDefinitionFor the bank API
SLIA measured ratio of good events to all eventsRequests not answered 5xx, over all requests
SLOThe target for that SLI over a window99.9% over 30 days
Error budgetWhat the SLO allows to fail: 100% minus the SLO0.1% of requests
SLAA contract with penalties, looser than the SLO99.5%, refund below it

Related: choosing SLOs at design time, and what each extra nine costs, is in Reliability. The 31 requests a second is the rate measured in the load run.

Burn rate

Alerts and SLOs

Burn rate is the error ratio divided by the budget. At 1 the budget lasts exactly the window, and at 2 it lasts half of it.

Burn rateHeld forBudget usedBudget gone inAction
14.41 hour2%50 hoursPage
66 hours5%5 daysPage
13 days10%30 daysTicket
40.4 (the demo)4 minutes0.4%18 hoursPage
  • An SLO replaces a pile of threshold alerts with one question: is the budget burning too fast?
  • Check a long and a short window together (1 h and 5 min), so the alert fires on a real burn and clears soon after the fix.
  • Budget left decides the roadmap: plenty means ship faster, none means stabilise first.

Using it

Part 6 of 6 · dashboards, an incident from alert to root cause, and a cheat sheet

What a service dashboard needs

Using it

One screen per service, read top to bottom: what users feel first, possible causes below.

Rows of a service dashboard, in reading order.
  • In Grafana each panel is a PromQL query, with variables for service and environment so one dashboard serves every service.
  • Draw the SLO threshold as a line and deploys as vertical markers: "what changed?" is the first incident question.
  • Not run for this page: Grafana.

Reading a dashboard during an incident

Using it

Traffic, errors, latency, saturation: then narrow down where.
  • Narrow by one label at a time: route, status, instance, version.
  • Mitigate before diagnosing: a rollback that restores the SLO comes before knowing why.

From alert to root cause in five steps

Using it

The incident from the load run, using app.log, ledger.log and spans.log written during it.

Each step uses the cheapest signal that can answer it.
  • Root cause: the ledger times out writing its journal. bank-api is healthy and reports the failure correctly as 502.
  • Over the run the ledger wrote 1,193 entries and rejected 298: every fifth, which matches the 20% on the route.
  • The slow statements are found the same way, and the trace ends in one span: db.query at 1,200.3 ms out of 1,200.6.

Cheat sheet

Using it

NeedUse
Request ratesum by (route) (rate(bank_http_requests_total[5m]))
Error ratiosum(rate(bank_http_requests_total{status=~"5.."}[5m])) / sum(rate(bank_http_requests_total[5m]))
p95 latencyhistogram_quantile(0.95, sum by (le, route) (rate(bank_http_request_duration_seconds_bucket[5m])))
Burn rate, 99.9% SLOError ratio / 0.001
Target downup == 0
Log fields on every linets (UTC), level, service, msg, request_id, trace_id
Log fields on the access lineroute, status, ms, error
Span attributes to standardiseservice.name, http.request.method, http.route, http.response.status_code, db.system, plus span status
Propagation headertraceparent: 00-<trace-id>-<parent-id>-01

Back to Cloud and DevOps.