Lesson 19 of 28Production ownership
Observability as a Developer
Instrument the feature in your own PR, read the dashboards after you deploy, and go from an alert to the exact log line in minutes.
Your change is merged, versioned and deployed. This unit is about owning it once real users depend on it. You shipped "restore saved carts" on Tuesday. On Thursday a support ticket says some customers open the app and find an empty cart. Two very different afternoons can follow. In one, you open the log store, filter on the event your feature emits, split it by app version and cart format, and find the bug in ten minutes. In the other, you add print statements, wait for a deploy, wait for it to happen again, and spend two days guessing. The difference was decided weeks earlier, in the PR, by whether you made your feature observable. This lesson is about that habit and about the dashboards, traces and log queries you will use every week.
The three signals, in one minute
You already know the parts. Metrics are cheap numbers over time (request rate, error count, a latency histogram), good for alerts and trends. Logs are individual events, ideally structured JSON, good for the exact error and its context. Traces follow one request through every service as a tree of timed spans, good for finding where the time went. Logging and Observability in the Python Backend course shows how to emit all three from Python, and Observability, SLIs, and SLOs in System Design covers what to promise users and when to page. This lesson skips the theory and stays on your desk: what you add to your code, what you look at, and in what order.
The four questions you will actually ask
Almost every production investigation is the same four questions, in this order. Each one has a signal that answers it best.
- Is it broken? A metric. Error rate, latency percentiles, or the SLI for the journey. If the graph is flat, the ticket may be one unlucky user, not an outage.
- Since when? A metric again, over a longer range, with deploy markers drawn on the graph. "It started at 13:02 and we deployed at 13:00" solves half of all investigations.
- For whom? This needs high-cardinality fields: app version, region, customer tier, feature flag state, cart format. Metrics cannot hold those cheaply, so you slice structured logs or traces instead.
- Why? A trace for one bad request, then the log lines for that trace id. This is where you see the slow query, the null field, the timeout.
Juniors tend to jump straight to question 4: they grep for errors and read stack traces. Seniors spend the first two minutes on questions 1 to 3, because the answer to "for whom" usually narrows the cause to one code path before they open any code.
Match each question to the signal that answers it best.
From alert to log line: one slow request
Here is the path you will walk most often. The checkout latency alert fires mid-afternoon. Step through it.
The page names a symptom: checkout p99 is burning its error budget. Its runbook link opens the right dashboard, so you do not start from a blank search box.
Each hop in that walk only works if something was set up in advance: the alert had a runbook link, the dashboard had deploy markers, every span carried service.version, and logs carried the trace_id. None of that is the platform team's job alone. Most of it lands in feature PRs.
To make "read the waterfall" concrete, here is a tiny tracer with a fake clock. It records nested spans the way an OpenTelemetry SDK does and draws them as a backend would. Change the cart to 20 items and watch one span take over the request.
Press Run (⌘ Enter) to see what happens.Learn to read three shapes in a real waterfall. A staircase of identical short spans is N+1. A long bar with no children is waiting on something you did not instrument, often a lock, a pool or a slow external call. A gap between sibling spans is time spent in your own code between calls, such as serialising a huge response. Each points to a different fix.
Instrumenting your feature in the PR
Treat telemetry as part of the feature, like tests. Before you open the PR, ask: "If this breaks at 3 a.m., what will the person on call need to see?" Usually that is four things.
- One structured log event at each decision point. Not a line per step. One event with a stable name and fields that explain the outcome.
- One or two metrics for the feature. A counter with an
outcomelabel, and a histogram if the feature has latency worth watching. These are what you put on a dashboard and, later, maybe an alert. - A span around the expensive call, with attributes that explain it (how many items, cache hit or miss). Auto-instrumentation already covers incoming HTTP, database drivers and HTTP clients. You add spans for your own business logic.
- Errors recorded with context, on the span and in the error tracker, never swallowed.
Here is what that looks like with the OpenTelemetry Python API and a structured logger. Package names and setup change between releases, so take the wiring from the official OpenTelemetry docs. The calls below are the stable part.
import time
import structlog
from opentelemetry import metrics, trace
from opentelemetry.trace import Status, StatusCode
log = structlog.get_logger()
tracer = trace.get_tracer(__name__)
meter = metrics.get_meter(__name__)
restores = meter.create_counter(
"cart.restores", unit="{restore}", description="Saved cart restore attempts by outcome"
)
restore_duration = meter.create_histogram(
"cart.restore.duration", unit="ms", description="Time to restore a saved cart"
)
def restore_cart(user_id: str, cart_id: str) -> Cart:
started = time.perf_counter()
with tracer.start_as_current_span("cart.restore") as span:
span.set_attribute("cart.id", cart_id) # high cardinality is fine on spans
try:
saved = load_saved_cart(cart_id)
span.set_attribute("cart.format", saved.format)
span.set_attribute("cart.items", len(saved.items))
cart = rebuild(saved)
outcome = "restored" if cart.items else "empty"
except CartNotFound:
outcome = "not_found"
raise
except Exception as exc:
outcome = "error"
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR))
raise
finally:
# Bounded labels only: a handful of outcomes, never user or cart ids.
restores.add(1, {"outcome": outcome})
restore_duration.record((time.perf_counter() - started) * 1000, {"outcome": outcome})
log.info("cart.restore", outcome=outcome, cart_id=cart_id, user_id=user_id)
return cartNotice where each detail went. cart_id sits on the span and the log event, where per-request detail belongs. The metric carries only outcome, a label with four possible values. If your logger is wired to the tracing context (most setups do this), the log event also carries the trace_id, which is what lets you jump between the two.
Now the payoff. When the empty-cart ticket arrives, this is the query you run. Here it is in plain Python over the kind of JSON lines a log store returns.
Press Run (⌘ Enter) to see what happens.Three group-bys, and you know the bug is in how 4.12.0 rebuilds old v1 carts, that it started with the deploy, and which trace to open. With a log line like "Restored cart for user 123 (3 items)" you would be writing regular expressions instead.
What to log, and what never to log
Log levels are a contract with whoever reads the logs. ERROR means something failed and a person may need to look. WARNING means something unexpected happened and the code coped. INFO is for business events like the one above. DEBUG is usually off in production. If your service logs ERROR for a user typing a wrong password, real errors drown, and alerts on error logs become useless.
Prefer one wide event per unit of work over many narrow lines. A single cart.restore event with ten fields is easier to query, cheaper to store and easier to join than ten lines that each say one thing. Some teams call these canonical log lines.
Some data must never reach a log: passwords, tokens and API keys, session cookies, full card numbers, and anything you are not allowed to keep. Logs are copied to many systems, kept for weeks and read by many people, so a secret in a log is a leaked secret. For personal data, log an internal id rather than an email address or name. Most teams also scrub known fields in the logger or the OpenTelemetry Collector as a second line of defence. Review this in PRs like you review SQL injection.
log.info('login', email=email, password_ok=False, token=request.headers['Authorization']). What is the most important change to ask for?Naming things so others can find them
Telemetry is a shared language. If your service calls it status, another calls it http_status and a third code, no dashboard can compare them. OpenTelemetry semantic conventions give standard names for common things: http.request.method, http.response.status_code, http.route (the template, like /carts/{id}, never the raw path), and resource attributes such as service.name, service.version and deployment.environment.name. Auto-instrumentation uses these already. Use them for your own fields where one exists, and agree on a team prefix for business fields (cart.format, order.total_items).
service.version deserves a special mention. Set it to your release tag or git SHA on every service. It is what turns "latency went up" into "latency went up on the new version only", which is the fastest root cause there is.
Before you add a label to a metric, count the series it creates. Every unique combination of label values is its own time series, and a histogram multiplies that again by its buckets.
How many time series (ignoring the sum and count series) does this histogram create?
import math
labels = {"http.route": 30, "http.request.method": 4, "status_class": 5}
buckets = 12
print(math.prod(labels.values()) * buckets)The dashboards you actually check
You will not stare at dashboards all day. You will check three, at predictable moments.
- Right after your deploy. Open your service's dashboard and watch the first 15 to 30 minutes, grouped by version if you deploy gradually. Error rate, p95 and p99 latency, and your feature's own counter. If your team uses canary releases, this comparison may be automated, but look anyway the first few times. Most bad deploys show up in that window.
- When something pages or a ticket arrives. The service dashboard first, as in the walk above.
- A few days after launch. Your feature's counters tell you whether it works for real users: how many restores, what share come back empty, how often it errors. Product managers love these numbers, and they are often the first evidence that you shipped something that matters.
A dashboard that people can read in an emergency has a shape. The top row answers "are users OK?": the journey's SLIs or RED metrics (rate, errors, duration). The middle splits that by endpoint or feature. The bottom shows dependencies and resources: database latency, pool saturation, queue depth. Deploys and flag changes are drawn as markers. Panel titles are questions ("Are checkouts failing?") or plain names with units, never internal jargon. Twelve clear panels beat sixty.
If your feature needs an alert, it should fire on a symptom users feel, such as the share of empty restores, not on a cause like CPU. It needs an owner and a link to a runbook. READMEs and docs people use covers how to write one, and Being On Call covers what happens when it fires.
Sampling and cost, from where you sit
Two facts change how you debug. First, most companies sample traces. If your team keeps 5% of traces with head sampling, the exact request a customer complains about is probably not there, though one like it will be. Tail sampling keeps every error and slow trace, so errors are usually findable. Ask your platform team which you have, before you need it. Second, logs cost money by volume. A log line inside a loop that runs a million times an hour can show up on an invoice. Log once per unit of work, sample noisy success events if needed, and never log whole request or response bodies by default.
A support ticket says some users see errors on the new export feature. Put a sensible investigation in order.
- Tap the steps below in the right order.
- span
- One timed unit of work inside a trace, with a name, a duration, attributes and a parent span.
- exemplar
- A sample trace id attached to a metric data point, so you can jump from a slow bucket on a graph to a real slow request.
- deploy marker
- An annotation on a dashboard graph showing when a release or flag change happened, so changes in behaviour can be matched to it.
- semantic conventions
- OpenTelemetry's standard attribute names, such as http.route and service.version, so telemetry from different services can be compared.
- cardinality
- The number of distinct values a label can take. High-cardinality fields belong on spans and logs, not metric labels.
- N+1 query
- Running one query per item instead of one query for all items. In a trace it looks like a staircase of identical short spans.
- wide event
- One structured log event per unit of work carrying many fields, instead of many narrow log lines.