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
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.
| Question | Signal | Cost |
|---|---|---|
| How many, how fast, is it getting worse? | Metrics | Low and flat: one number per series, whatever the traffic |
| What exactly happened in this request? | Logs | Grows with traffic: you pay per line stored |
| Where did this request spend its time, across services? | Traces | Grows with traffic: usually sampled |
Interview point: metrics say that something is wrong, traces say where, logs say why.
The demo service
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.
| Route | Does | Planted behaviour |
|---|---|---|
GET /accounts, GET /accounts/{id} | List, read one | 404 for an unknown id |
POST /deposit | Add rupees | None |
POST /transfer | Calls ledger, then moves rupees | The ledger rejects every 5th entry: 502 |
GET /accounts/{id}/statement | Read a statement | Every 10th call sleeps 1.2 s in the query |
GET /metrics | Prometheus scrape | Not counted, logged or traced |
Logs
Part 2 of 6 · one structured line per event, tied to its request
Structured JSON versus text
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
msgconstant 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
| Level | Belongs here | In the demo |
|---|---|---|
DEBUG | Detail for the developer. Off in production, switchable at run time. | Not used |
INFO | A business event finished, or a request ended normally | deposit done, request done 2xx |
WARNING | Unexpected but handled: client errors, retries, fallbacks | request done 404 |
ERROR | This request failed and the fault is ours or a dependency's | request done 502, entry rejected |
CRITICAL | The process cannot continue | Not 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
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
ContextVaris separate per thread and per asyncio task, so concurrent requests do not mix ids. - The id crosses services as the
X-Request-Idheader: the third line comes from the other process.
What never to log
Logs are copied to more systems, read by more people and kept longer than the database they describe.
| Never | Log instead |
|---|---|
Passwords, tokens, API keys, Authorization and cookie headers | Whether one was present, or a short fingerprint |
| Card numbers, CVV, full bank account numbers | Last four digits, or an internal id |
| Names, emails, phone numbers, addresses | An opaque id such as ACC-1001 |
| Whole request and response bodies | Size, 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
The same 200 requests were sent twice, the second time with LOG_SAMPLE=10, which adds this filter to the handler.
| Run | Lines | Bytes | INFO | ERROR |
|---|---|---|---|---|
| All lines | 280 | 60,956 | 272 | 8 |
LOG_SAMPLE=10 | 32 | 7,181 | 24 | 8 |
- 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
The app writes lines to stdout and nothing else. Files, rotation and shipping belong to the platform.
- 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
| Type | Holds | Query with | Use for |
|---|---|---|---|
| Counter | A total that only goes up | rate() | Requests, errors, rupees deposited |
| Gauge | A value right now | As is, avg_over_time() | In-flight requests, queue depth, memory |
| Histogram | Counts per bucket, plus sum and count | histogram_quantile() | Latency, sizes |
| Summary | Sum and count, quantiles computed in the client | rate(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
rate() corrects for that.Instrumenting the service
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
routelabel is the template/accounts/{id}, never the raw path. - Trimmed: seven middle buckets, the
/deposithistogram,_createdtimestamps, comment lines and the client's ownpython_*series.
Labels and the cardinality trap
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
The service only exposes /metrics. Prometheus decides what to scrape and how often, and stores every sample with a timestamp.
- Pull gives a free health signal:
up == 0means the scrape failed. jobandinstanceare added by Prometheus. Queries below are shown without thedocker exec tut-prometheusprefix.- Jobs too short-lived to be scraped push to a Pushgateway instead. Here
static_configsstands in for service discovery.
PromQL: rate and error ratio
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
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_quantileinterpolates 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
RED is for things that serve requests. USE is for resources that can fill up.
| RED | Measure | In the demo |
|---|---|---|
| Rate | Requests per second | rate(bank_http_requests_total[1m]) |
| Errors | Failed requests per second, or as a ratio | The same counter with status=~"5.." |
| Duration | Latency distribution | The duration histogram |
| USE | Measure | Examples |
|---|---|---|
| Utilisation | Share of the resource in use | CPU 80%, 18 of 20 pool connections |
| Saturation | Work waiting for it | Run queue length, requests waiting for a connection |
| Errors | Error events of the resource | Disk errors, OOM kills, refused connections |
Golden signals and the metrics every service needs
The four golden signals are latency, traffic, errors and saturation: RED plus the "S" of USE.
| Metric | Type | Answers |
|---|---|---|
| Requests by method, route, status | Counter | Traffic and errors |
| Request duration by route | Histogram | Latency, and the SLO |
| In-flight requests | Gauge | Saturation of the service |
| Calls to each dependency by outcome, with duration | Counter, histogram | Is it us or them |
| Pool in use and max, queue depth | Gauge | Saturation before it hurts |
| Process CPU, memory, GC, open files | From the client library | USE for the process |
build_info{version} set to 1 | Gauge | Which 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
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.
- A span is exported when it ends, so children print before parents. The root has
parent_idnull 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
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.
| Field | Value | Meaning |
|---|---|---|
| version | 00 | Format version |
| trace-id | e00d8de4de231f77bbeb0401cd746d62 | 16 bytes, the same in every service |
| parent-id | ab8f5e9a7da9dd18 | 8 bytes: the caller's span, here POST ledger /entries |
| flags | 01 | 01 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
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
BatchSpanProcessorwith an OTLP exporter.SimpleSpanProcessorexports inside the request. - Not run for this page: the
opentelemetry-instrumentation-*packages, which create such spans automatically.
Linking logs to 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
| Head sampling | Tail sampling | |
|---|---|---|
| Decided | At the first span, before anything is known | After the trace has finished |
| By | The SDK, for example 5% by trace id | The Collector, which buffers whole traces |
| Keeps | A random share | All errors and slow traces, a share of the rest |
| Cost | Almost none | Memory, and all spans of a trace must reach one Collector |
| Weakness | Most rare failures are thrown away | More 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
OpenTelemetry is an API, SDKs, a wire protocol (OTLP) and a Collector. It produces and moves telemetry, and stores none of it.
- 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
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 is | Test | In the rule below |
|---|---|---|
| About users | Would a customer notice? | Share of requests answered 5xx |
| Actionable | Is there something to do right now? | Roll back, fail over, shed load |
| Urgent | Can it wait until morning? Then it is a ticket. | severity: page |
| Documented | Does it link to a runbook? | runbook annotation |
| Stable | Does one bad scrape trigger it? | for: 1m |
A Prometheus alerting rule, pending then firing
Prometheus evaluates the expression every 5 seconds. The alert must stay true for the whole for period before it fires.
firing alerts are sent to Alertmanager.- Printed by a small script polling
/api/v1/alertsevery 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
Every page that needed no action teaches the on-call engineer to ignore the next one.
| Route to | When | Example |
|---|---|---|
| Page | Users are affected now and a human can fix it | Error ratio burning the budget fast |
| Ticket | Needs work within days | Disk full in 5 days, certificate expires in 2 weeks |
| Dashboard only | Useful context, no action by itself | CPU 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
| Term | Definition | For the bank API |
|---|---|---|
| SLI | A measured ratio of good events to all events | Requests not answered 5xx, over all requests |
| SLO | The target for that SLI over a window | 99.9% over 30 days |
| Error budget | What the SLO allows to fail: 100% minus the SLO | 0.1% of requests |
| SLA | A contract with penalties, looser than the SLO | 99.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
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 rate | Held for | Budget used | Budget gone in | Action |
|---|---|---|---|---|
| 14.4 | 1 hour | 2% | 50 hours | Page |
| 6 | 6 hours | 5% | 5 days | Page |
| 1 | 3 days | 10% | 30 days | Ticket |
| 40.4 (the demo) | 4 minutes | 0.4% | 18 hours | Page |
- 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
One screen per service, read top to bottom: what users feel first, possible causes below.
- 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
- 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
The incident from the load run, using app.log, ledger.log and spans.log written during 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.queryat 1,200.3 ms out of 1,200.6.
Cheat sheet
| Need | Use |
|---|---|
| Request rate | sum by (route) (rate(bank_http_requests_total[5m])) |
| Error ratio | sum(rate(bank_http_requests_total{status=~"5.."}[5m])) / sum(rate(bank_http_requests_total[5m])) |
| p95 latency | histogram_quantile(0.95, sum by (le, route) (rate(bank_http_request_duration_seconds_bucket[5m]))) |
| Burn rate, 99.9% SLO | Error ratio / 0.001 |
| Target down | up == 0 |
| Log fields on every line | ts (UTC), level, service, msg, request_id, trace_id |
| Log fields on the access line | route, status, ms, error |
| Span attributes to standardise | service.name, http.request.method, http.route, http.response.status_code, db.system, plus span status |
| Propagation header | traceparent: 00-<trace-id>-<parent-id>-01 |
Back to Cloud and DevOps.