Structured logging, sampling, and distributed tracing

Metrics tell you something is wrong, traces tell you where, logs tell you why. Sampling decisions and cost control are the whole operational story.

Read the briefing
About 8 min to read 8 drills

What to remember

  1. Metrics → traces → logs, in that order. Cheap and aggregate first, expensive and specific last.
  2. Structured logs or you are grepping prose. Key-value from the start; retrofitting parsers onto free text never finishes.
  3. Tail-based sampling keeps the interesting traces. Head-based sampling throws away the slow request you needed. Cost more where it matters.
  4. A trace ID in every log line is the join key. Without it, correlation is manual and slow at exactly the wrong moment.
  5. Log volume is a budget with an owner. Ingest cost grows faster than traffic; retention tiers and sampling are engineering decisions.

The big picture

Logs, traces and metrics are three views of the same requests: metrics aggregate millions of them, logs record the events of one, and traces join one request's events across every service with timing. Interviewers use this node to test whether you can make the three joinable (one identifier carried everywhere), keep the volume affordable (levels, sampling, retention) without ever losing the failures, and read a trace waterfall correctly instead of blaming the largest child span.

The mental model

One request, one id. The id is minted once at the edge and copied onto every log line, every span and every outgoing call; metrics summarise what all requests did, logs say what one request did, traces say where its time went. Everything you pay for — ingestion, indexing, retention — is per byte, so the job is to keep the bytes that answer questions and drop the rest, with one rule that never bends: keep everything that went wrong.

In depth

Structured logs are a schema, not a format

A structured log line is a record with typed fields, not a sentence with numbers in it. Whether the encoding is JSON or logfmt matters less than the contract: every line from every service carries the same core fields — ts, level, service, version, trace_id, request_id, msg — plus typed, consistently named context such as user_id, order_id, status, duration_ms. A good line looks like this:

{"ts":"...","level":"error","service":"payments","version":"2.14.1",
 "request_id":"7f3a...","trace_id":"4bf9...","msg":"psp call failed",
 "psp":"acme","status":502,"duration_ms":30004,"attempt":2}

The value is that every field can be filtered, aggregated and joined: level=error service=payments status=502 | count by psp is a query, whereas grep "PSP call failed" | awk is an afternoon. The failure mode is interpolation: "payment 8812 for user 42 failed after 30004ms" hides three fields inside a string that no index can use and that changes shape every time someone edits the message. Keep msg a constant, low-cardinality phrase and put the variables in fields.

Two more rules pay off in incidents. Name quantities with their unit (duration_ms, bytes_out, never time or size), and log the service version on every line so a regression can be attributed to a build without a deploy-log lookup. Enforce the schema with a shared logging library and a CI check rather than a style guide: the schema is a contract precisely because it is shared by teams that never talk to each other, and the first incident that crosses a team boundary is where an inconsistent field name costs an hour.

Levels and volume: what a log line costs

Levels have operational meanings, not aesthetic ones. INFO records request-scoped events you would want during an incident: request received, dependency called, decision made. WARN is degraded-but-handled — a retry that succeeded, a fallback taken, a deprecated path used. ERROR is a failure that needs a human or a ticket, so it must be rare and actionable; an ERROR that fires a thousand times an hour and nobody reads is noise wearing a red badge. DEBUG is off in production and switched on per component for minutes through a dynamic toggle that reverts itself, because a static flag left on at 02:00 is how one service triples the fleet's volume.

Volume is money and risk. Back of the envelope: 10,000 requests/s × 3 lines × 300 bytes ≈ 9 MB/s ≈ 780 GB/day before compression, each byte ingested, indexed and retained at a price. At DEBUG the same service can emit 30 lines per request and twenty times the bytes. Beyond cost, the pipeline itself has limits: a backend that rate-limits drops lines from every team, including the ERROR lines you need most, and a host writing hundreds of MB/s of logs competes with the application for disk I/O; JSON serialisation shows up in CPU profiles, and local disks fill.

The controls are mechanisms rather than reminders: a per-service log budget with an alert on the rate of change so a 3× jump pages the owning team instead of the platform; DEBUG only via a time-boxed toggle; collector-side priority so level >= ERROR is never sampled or dropped under pressure; and de-duplication of repeated messages so "same line 4,000 times in 10 s" becomes one line with a count.

Distributed traces: spans, context and the waterfall

A distributed trace is a tree of spans sharing one trace id. Each span records an operation — a handler, an RPC, a database call — with a start time, a duration, a parent span id and attributes. Context travels between services in the W3C traceparent header:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^
             version   trace-id (16 bytes)        parent-id      flags (01 = sampled)

Each hop keeps the trace id, sets parent-id to its own span, and forwards the header on every outgoing call — including as a message attribute through a queue, otherwise the consumer starts a new, unjoinable trace. tracestate carries vendor data alongside.

Reading a waterfall is subtraction. A span's self time is its duration minus the union of its children; a root of 850 ms whose children sum to 154 ms spent about 700 ms doing something no span describes — waiting for a connection from a pool, a lock, a GC pause, DNS resolution or a TLS handshake for a fresh connection, serialisation, or a library call nobody instrumented. The fix is a span around that code, not optimising the largest child. Two more shapes to recognise: a child that starts before its parent or ends after it is clock skew between hosts, and a fan of many short sequential children under one parent is an N+1 call pattern that should be batched. Traces answer "where did this one request's time go", which metrics (aggregates) and logs (events without timing structure) cannot.

Sampling: head, tail, and the rule about errors

Nobody keeps every trace at scale: 10,000 requests/s with 10 spans each at ~500 bytes is 50 MB/s, terabytes a day of data almost nobody reads. Sampling decides what to keep, and where the decision is made is the whole design.

Head-based sampling decides at the root span, before the request has done anything: keep 1%, uniformly, and propagate the decision in the traceparent sampled flag so every downstream span agrees. It is cheap and stateless — and blind to outcome, so a failed request is kept at the same 1% as a successful one. The arithmetic bites: at 1% sampling and a 0.1% error rate, one traced failure appears per 100,000 requests, so the trace for the specific failure a customer reports almost never exists.

Tail-based sampling makes the decision after the trace completes: a collector tier buffers spans for a decision window of tens of seconds, then keeps 100% of traces with an error or latency above a threshold and a small share of the rest. The costs are memory to hold in-flight traces and a routing rule that sends every span of one trace to the same collector (load-balance by trace id). Mismatched rates are a third failure: if one service samples at 10% and its callers at 1%, traces arrive with missing branches.

Logs are sampled differently — by level (never sample ERROR) and by de-duplicating repeats — and never at the root of a request, because the log line you need is the one written at the failure point. The rule that survives every design: keep everything that went wrong, sample what went right.

Correlation: the lifecycle of a request id

The single most valuable field in an incident is an identifier that is identical on every log line, span and metric exemplar for one request. Its lifecycle is short and unforgiving. The edge mints it (or accepts one from a trusted client) and returns it in a response header so a support ticket can carry it. Middleware reads-or-creates it on every incoming request, puts it into the logging context so every line in that request's scope carries it automatically, and copies it onto every outgoing call: HTTP headers, gRPC metadata, message attributes on queues, even a comment on database queries (/* request_id=7f3a */ SELECT ...) so slow-query logs join too. A hop that regenerates the id — "for security", or because a library defaulted to a fresh UUID — cuts one story into two that can only be re-joined by guessing at timestamps.

In practice the request id and the trace id are often the same value and W3C traceparent is the propagation mechanism; a separate X-Request-ID survives in systems where tracing is sampled away, because logs are not. Metric exemplars close the loop: a histogram bucket can carry the trace id of one observation, so a latency spike on a dashboard links to a concrete trace.

The investigation pattern then becomes mechanical: person → edge log (user id, status, request id) → one query for that id across every service → the last line written is where it died. Make the pattern a mechanism: a shared middleware, a CI check that every service uses it, the id printed on the customer's error page, and a rehearsal in staging with an injected failure so the lookup takes five minutes on the day it matters.

Cost and retention tiers

Observability data is priced per byte three times — ingested, indexed and retained — and the levers map onto those three. Ingest less: sampling, level discipline, dropping fields nobody queries (a 2 KB stack trace attached to every INFO line is a classic). Index less: index only the fields you filter on (level, service, request id, status) and keep the rest as unindexed payload. Retain less, in tiers: days in hot storage for incidents, weeks in cold storage for trend questions, months in archive only where compliance demands it. High-cardinality identifiers belong here rather than in metric labels because these systems index by id and charge by byte, whereas Prometheus charges by series and dies by cardinality. A sizing habit worth practising: bytes per day = requests per day × lines per request × bytes per line, then multiply by retention days and a replication factor; anything in the terabytes-per-day range needs an owner and a budget before it needs a vendor, and the owner's first question should be which fields actually get queried.

Myths and facts

Myth: A distributed trace is a stack trace across services.

Fact: It is a tree of timed spans for one request, propagated through headers; it shows where time went and which call failed, not the code path inside a crash.

Myth: Sampling 1% of traces keeps 1% of the errors, which is plenty.

Fact: Errors are rare, so 1% head sampling keeps almost none of the traces you actually need; tail-based sampling keeps every error and slow trace and samples the successes.

Myth: Each service should generate its own request id for its own logs.

Fact: The id must be propagated, never regenerated; a hop that mints a new one splits the request into two unjoinable stories. Generate only when none arrived.

Myth: More logging is always safer.

Fact: Volume is cost, disk I/O and pipeline rate limits that drop other teams' errors; the signal is the schema and the id, not the byte count.

Myth: If we need per-user debugging we can put the user id in a metric label.

Fact: Unbounded ids multiply series and take Prometheus down; per-user and per-request detail belongs in logs and traces, which are indexed by id.

Myth: A big gap in a trace waterfall means the tracing clocks are wrong.

Fact: Clock skew shows as children starting before their parent; a hole between consecutive children of one span is uninstrumented time in the parent — pool waits, locks, GC, serialisation.

How pros do it

  • One log schema across services with mandatory fields (timestamp, level, service, version, trace id, request id, constant msg) enforced by a shared library and a CI check.
  • Read-or-create the request id in edge middleware, forward it on every outgoing call and queue message, return it in a response header and show it on error pages.
  • Use tail-based sampling for traces so every error and slow trace is kept, and never sample ERROR-level logs.
  • Enable DEBUG only through a dynamic, time-limited toggle that reverts itself; keep per-service log budgets with an alert on rate of change.
  • Instrument the caller's own work (spans around pool acquisition, serialisation, locks, outbound calls) so a waterfall has no unexplained holes.
  • Protect ERROR lines with priority in the collector pipeline, index only the fields you filter on, and tier retention hot/cold/archive.

Questions people ask

When do I reach for logs versus traces versus metrics?

Metrics for 'is the service healthy and how much' (aggregates, alerts). Traces for 'where did this one request's time go across services'. Logs for 'what exactly happened in this request at this point', including detail that never becomes a span. In an incident you start from a metric, find a request id, and pivot to logs and traces.

What sampling rate should I use for traces?

Decide by what you must keep, not by a percentage: keep 100% of errors and slow traces with tail-based sampling, then sample successes at whatever rate the budget allows (often 1–10%). If you only have head-based sampling, size the rate so a rare error still shows up daily — at 0.1% errors and 1% sampling that is one traced failure per 100,000 requests.

What is the difference between a request id and a trace id?

Often the same value in practice. The trace id is defined by the tracing spec and propagated in traceparent; a request id is any opaque identifier you log and return to clients. Keeping a request id in logs even when traces are sampled means the logs always join, because logs are not sampled the way traces are.

How do I keep the request id through a queue?

Put it in the message attributes or headers (not the payload body), and have the consumer read it into its logging and tracing context before doing anything else. The consumer's span should link to the producer's; a consumer that starts a fresh id breaks the join at the queue.

How do I estimate what logging will cost?

requests/day × lines per request × bytes per line gives bytes/day; multiply by retention days and replication. 100 M requests/day × 3 lines × 300 B ≈ 90 GB/day, so 30 days hot at 3× replication is about 8 TB before indexes. Then ask which fields are ever queried and drop the rest.

What exactly is in the traceparent header?

Four dash-separated hex fields: version (00), a 16-byte trace id, an 8-byte parent span id, and one flags byte whose low bit is the sampled flag. Every hop copies the trace id, replaces the parent id with its own span id, and forwards it; tracestate carries vendor data alongside.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Answer out loud

Explain to a new graduate what a distributed trace is and why a request id is the single most valuable field during an incident. Three to five sentences, in plain language, defining any term you use.

In short

A strong answer says a trace is a tree of timed steps sharing one id, and that the request id must be passed on at every hop, never made new.

What a strong answer does
  • trace concept: A tree of timed spans sharing one trace id, each knowing its parent, carried in request headers across services and queues; answers where the time or the failure was for one request.
  • correlation value: One id minted at the edge and carried on every hop joins logs, traces and metrics for a single request across every service, turning an hour of timestamp-matching into one query; must be propagated, never regenerated.
  • communication: A concrete analogy or example, concept before consequence, every term defined in passing, the one rule stated last.
Why

The audience switch is the test: the same mechanism (spans, parent ids, propagation in headers, one id joining every signal) explained without vocabulary the listener has not met. Graders reward a concrete analogy, defining "span" and "propagate" in passing, and closing with the operational rule — propagate, never regenerate — rather than a list of tools.

The common mistake

Describing a trace as 'a stack trace across services' or as 'logging with extra fields'. It is a tree of timed spans sharing one id, propagated in headers, and it answers where the time went.

Read the docs

2 Pick the strongest answer

Your tracing pipeline samples 1% of traces at the root span (head-based). The API serves 10,000 requests/s with an error rate of 0.1%. Engineers complain that only about 1 in 100 failed requests has a trace, so debugging a specific failure is luck. Which change fixes this, and what does it cost?

  1. Log the error with the trace id and stop relying on traces for failures. The log line says it failed; the trace shows where, across services. With 1% head sampling, the trace id in the log points at a trace that was dropped 1 in 100 of the time inverted — almost always.
  2. Raise head sampling to 100% for the API service only. Head sampling decides at the root before the outcome exists, so 100% keeps every successful trace too — the volume tail sampling avoids — and mismatched rates across services produce broken traces.
  3. Configure the head sampler to keep only traces whose status is error. At the root the request has just started; its status is unknown until every span has finished, which is exactly why head-based samplers can only be uniform or attribute-based.
  4. Move to tail-based sampling: buffer every span until the trace completes (or a decision timeout), then keep 100% of traces with an error or latency over threshold and 1% of the rest. Cost: a collector tier that holds in-flight traces in memory and routes all spans of one trace to the same collector (hash by trace id). Only a decision made after the trace has finished can see its outcome; the price is buffering and consistent routing, which is why tail sampling is a separate tier.
In short

Switch to tail-based sampling so every error and slow trace is kept; the cost is a collector tier that buffers spans and routes each trace to one collector.

Why

Head-based sampling makes the keep/drop decision when the root span starts, so it is cheap and uniform but blind to whether the request will fail or be slow — the traces you most want survive at the same rate as the boring ones. Tail-based sampling moves the decision to after the trace completes, which requires a collector tier that buffers spans for a decision window and receives every span of a given trace (load-balance by trace id). The rule in production is: never sample errors away; keep every error and slow trace, sample the successes.

Read the docs

3 Pick the strongest answer

Structured logs for one failed request show request_id=7f3a… at the API gateway and in orders, but payments (called by orders) logs request_id=c91e… for the same call, and its downstream ledger logs c91e… too. Which service has the bug, and what is the rule it broke?

  1. payments is right to regenerate it — accepting ids from upstream is an injection risk. The id is opaque and only logged; validate its length and character set if you must, but breaking correlation costs far more in every incident than the theoretical risk.
  2. Nothing is wrong — each service should mint its own request id for its own logs, and you join them by timestamp. At thousands of requests per second a timestamp identifies nothing; the whole point of a correlation id is to make the join exact.
  3. The gateway is at fault: it should log the ids of all downstream calls so they can be mapped. The gateway never sees an id that payments invents two hops later; propagation is the only mechanism that links hops, which is exactly what traceparent formalises.
  4. payments mints a new id instead of reading the incoming header, so the join breaks at that hop and everything downstream is orphaned from the edge id. Rule: the edge mints the id once; every hop reads it from the incoming request or message, attaches it to every log line and every outgoing call, and generates one only when none arrived. Correlation works only if one identifier survives every hop; a hop that regenerates it splits one request into two unjoinable stories.
In short

The payments service is at fault: it made a new id instead of passing on the one it received, so the join breaks at that hop.

Why

A request id has a lifecycle: minted at the edge (or accepted from a trusted client), carried in a header (X-Request-ID or the W3C traceparent), placed into the logging context so every record in every service carries it, and forwarded on every outgoing call, queue message and even as a comment on database queries. One hop that regenerates the id turns a single query for request_id=7f3a… into two disconnected fragments, and the investigator has to guess the link by time — which is how a five-minute lookup becomes a two-hour one. Middleware that reads-or-creates the id is a one-line mechanism; a lint that every service uses it is the guardrail.

Read the docs

4 Read the output

The root span took 850 ms. Where did the time go, and what is your next step?

trace_id=4bf92f3577b34da6a3ce929d0e0e4736   root: POST /checkout   status=200

span                                parent          start(ms)   dur(ms)
checkout-api  POST /checkout        -                   0        850
  auth        ValidateToken         checkout-api        2         18
  cart        GetCart               checkout-api       22         35
  pricing     Quote                 checkout-api       60         41
  payments    Authorize             checkout-api      705         38
    psp       HTTP POST /authorize  payments          712         27
  orders      CreateOrder           checkout-api      748         22
  1. payments is slow — it starts at 705 ms. A span's start is when it was called; payments itself took 38 ms. The delay happened before the call, inside the caller.
  2. The gap is clock skew between hosts, so the trace cannot be trusted. Skew shifts child spans relative to their parent, but the children here are consistently ordered and the root's 850 ms is measured on one clock; a single 600 ms hole between two children of the same span is missing instrumentation, not skew.
  3. About 700 ms is unattributed inside checkout-api itself: its direct children sum to 154 ms, and there is a 604 ms gap between pricing returning (101 ms) and payments starting (705 ms) with no span at all. The time is in the caller — an uninstrumented call, a lock or thread-pool wait, a GC pause — so wrap the code between Quote and Authorize in a span, and check that pod's GC and lock metrics at this timestamp. A trace only attributes time that has a span; a gap between children on the same parent is time the parent spent without calling anything instrumented.
  4. pricing is the slowest downstream call at 41 ms, so optimise the pricing service. Removing pricing entirely would save 41 of 850 ms; the tail lives in the gap, not in any child.
In short

About 700 ms is a gap inside checkout-api with no span, so add a span around the code between pricing and payments instead of tuning a child.

Why

Read a waterfall by subtracting: root duration minus the union of its children is time the service spent on its own thread — serialisation, waiting for a connection from a pool, a mutex, garbage collection, or a library call nobody wrapped in a span. Here 850 − 154 leaves ~700 ms, almost all in one hole between 101 ms and 705 ms. The next step is not to optimise any child but to instrument the hole (a span around that code block, or the runtime's GC/lock metrics for that pod at that time). Interviewers look for whether you attribute time to the caller rather than to whichever child looks largest.

Read the docs

5 Scenario: what do you do next?

14:20. Support forwards a complaint: a customer (email known) saw "Something went wrong" on checkout at about 14:02. Six services are involved (gateway → checkout-api → cart, pricing, payments, orders). The error-ratio dashboard is flat at a normal 0.08% 5xx. The customer wants an answer today.

Step 1. Where do you start?

  1. Open the tracing UI, filter POST /checkout around 14:02 and sort by duration. Thousands of traces per minute, sampling may have dropped this one, and you have no way to recognise it without the id.
  2. Tell support the dashboards show normal error rates, so it was probably the customer's connection. 0.08% of a busy checkout is real failures every second; an aggregate ratio cannot see one user. Dismissing the report throws away a real signal.
  3. grep every service's logs for the email address between 14:00 and 14:05. Downstream services never see the email, and unstructured grep across six services is hours of work; the join key is the id, not the user.
  4. At the edge: query the gateway's structured logs for the customer's user_id (looked up from the email) with status >= 500 between 14:00 and 14:05 to get the request_id and trace_id of that one request. Everything else follows from that id. The edge is the one place that knows both who the user was and which request failed; one exact query yields the join key for all six services.

Step 2. The gateway log yields request_id=7f3a… trace_id=4bf9… status=502 upstream=checkout-api duration_ms=30004. Searching the tracing backend for that trace id returns nothing. What next?

  1. Restart checkout-api — a 502 from the gateway means it crashed. One 502 eighteen minutes ago is not evidence of a crash; a restart teaches you nothing and can hurt in-flight requests.
  2. Follow the request id through structured logs of all six services in one query (request_id=7f3a…), ordered by time: the last service that logged it and what it said is where the request died, and 30,004 ms says a 30 s timeout expired somewhere. Note the trace was head-sampled away as a finding for later. Logs survive sampling; the id makes the cross-service join exact; the duration already tells you to look for a deadline-exceeded at one hop.
  3. The trace does not exist, so the request cannot be investigated; close the ticket. The trace is one of three signals; the logs carry the same id and are complete.
  4. Ask the customer to retry and send a browser HAR file. The evidence is already in your own logs; punting to the user delays the answer and may not reproduce.

Step 3. Logs show checkout-api logged payments call timed out after 30000ms; payments logged the request arriving at 14:02:07 and psp connection reset at 14:02:08, then never logged a response. Found. For the retro: what do you fix so this takes five minutes next time instead of two hours?

  1. Keep 100% of traces for 90 days so nothing is ever missing. At this traffic that is tens of terabytes for traces nobody will read; tail sampling keeps the ones that matter at a fraction of the cost.
  2. Ask engineers to log more. More volume without a shared id is more to search, not more to join; and a reminder is not a mechanism.
  3. Mechanisms: tail-based sampling so every error and slow trace is kept; a middleware check (enforced in CI) that every service reads and logs the request id on every line; the request id shown on the customer's error page and returned in a response header so support hands it to you directly; and an alert on checkout requests hitting the 30 s timeout — a symptom the 5xx ratio hides. Verify by injecting a failure in staging and timing the lookup. Each item removes a step that cost time today, is enforceable, and the plan says how it will be proven — not a request to be more careful.
  4. Raise the payments timeout to 60 s so the request would not have failed. A 60 s wait is not a success, the PSP reset was the actual fault, and longer timeouts hold threads and connections hostage.
In short

Start at the edge: find the user's failed request in the gateway logs to get its request id, then follow that id through every service's logs.

Why

The whole exercise is a join: the edge maps a person to a request id, the id maps the request to its log lines in every service, and the last line written tells you where it died — even when the trace was sampled away. The systemic fixes remove today's friction: keep the traces that matter (tail sampling), make the id universal (middleware plus a check), give the id to the people who report problems (error page, response header), and alert on the specific symptom (timeouts) the aggregate error ratio smooths over.

Read the docs

6 Design round

Design the pipeline behind an ads click-through-rate (CTR) dashboard. Two logs arrive from the serving fleet: a query log with one record per ad impression (query_id, ad_id, campaign_id, timestamp; ~300 bytes) and a click log with one record per click (query_id, ad_id, timestamp; ~100 bytes). Volume is 10 billion impressions per day; clicks are about 1% of impressions. The dashboard shows CTR per ad and per campaign over the last hour and the last day, no more than 5 minutes stale. Give the numbers, the design, its failure modes, and how you would verify it.

  • A click can arrive up to 10 minutes after its impression (client latency, retries).
  • Numbers feed billing review: each click must count exactly once — never zero, never twice.
  • Commodity machines: 32 cores, 128 GB RAM, 4 TB disk, 10 Gbps NIC.
In short

A strong answer partitions both streams by the join key, bounds the window by the 10-minute late-click limit, dedups clicks, writes idempotently, and checks with a daily batch.

A strong answer covers
  • Turns requirements into numbers: 10 B/day ≈ 116 k impressions/s average (~350 k/s at a 3× peak); ≈ 35 MB/s ≈ 3 TB/day of query log; ≈ 1.2 k clicks/s ≈ 10 GB/day; a 15-minute join window holds ~100 M impressions (≈ 4 GB if only query_id, ad_id, campaign_id are kept).
  • Chooses the join key (query_id + ad_id) and partitions both streams by hashing it so an impression and its clicks land on the same worker; states the late-click window and what happens to clicks arriving after it.
  • Achieves exactly-once effects: de-duplicates clicks by (query_id, ad_id), makes aggregate writes idempotent (keyed by minute bucket and partition offset), and reconciles streaming totals against an exact daily batch over the raw logs.
  • Aggregates into per (ad_id, campaign_id, minute) counts that the dashboard reads, with hour and day roll-ups; explains that the 5-minute freshness forces streaming over hourly batch, while raw logs are kept for reprocessing.
  • Sizes the fleet with justification (join workers with N+1, an aggregate store, log collectors — tens of machines) and states how a worker's state is recovered (replay from a durable partitioned log).
  • Names failure modes (a hot campaign or skewed partition, a worker dying mid-window, clock skew between click and query fleets) and a verification plan (replay a recorded day, compare streaming CTR with batch CTR within tolerance, kill a worker during replay).
What a strong answer does
  • estimation and sizing: Impressions/s (average and peak), bytes/s and per day for both logs, join-window state size, aggregate size, machine count — each derived and rounded with justification.
  • design quality: Partitioned streaming join with a late-click window, click de-duplication, idempotent aggregate writes, batch reconciliation, replay-based recovery, hot-key handling.
  • communication: Requirements restated, numbers, design, failure modes, verification, tradeoffs with a decision.
Why

This is the SRE Workbook's NALSD shape: requirements → numbers → a design whose every component is sized by those numbers. The scoring hinges on three insights — the join key decides the partitioning, the late-click bound decides the window state and therefore memory, and exactly-once effects come from de-duplication plus idempotent writes plus batch reconciliation, not from a transport promise. Candidates who reach for a tool name before the arithmetic, or who never say what happens to a click that arrives 11 minutes late, miss what the interviewer is measuring.

Read the docs

7 Quick recall

Quick one: head-based or tail-based trace sampling — which one can guarantee that every error trace is kept?

In short

Tail-based sampling, because it decides after the trace has finished and can see that it failed.

Accepted

tail-based · tail · tail based

Why

Tail-based: the keep-or-drop decision is made after the trace completes, so the sampler can see the error or the latency and keep 100% of those while sampling the successes. Head-based decides at the root span before the outcome exists, so errors survive at the same rate as everything else. The cost of tail sampling is a collector tier that buffers in-flight spans and routes every span of one trace to the same collector.

Read the docs

8 Scenario: what do you do next?

07:50. The logging pipeline's ingestion-cost alert fired: volume rose from 1.2 TB/day to 3.6 TB/day starting at 02:10. The collectors report otelcol_exporter_send_failed_log_records climbing fleet-wide — the backend is rate-limiting and about 15% of lines are being dropped. The checkout on-call says they cannot find their ERROR logs from an incident at 06:30.

Step 1. First move?

  1. Restart the collectors — send-failed counters usually mean a stuck buffer. The failures are backend rate limiting, not a stuck buffer; a restart discards what is buffered, including the errors on-call is looking for.
  2. Break volume down by service and log level for the last 12 hours (backend query or the collectors' per-source counters): the 3× jump has a start time, so find the service whose volume tripled at 02:10 and what changed then — deploy, config push, log level. The alert gives you a time and a magnitude; a per-service, per-level breakdown turns that into a name in one query.
  3. Raise the backend ingestion quota to 5 TB/day so the drops stop. Pays triple to keep ingesting noise and does not find the cause; it may become a short stopgap once you know what the volume is.
  4. Set the fleet-wide collector to sample 50% of all logs. That samples ERROR lines away for every team, including the checkout incident you need to explain.

Step 2. The search service has been at DEBUG since a 02:10 config push (a debug flag left on) and is emitting 2.3 TB/day of cache lookup key=… lines — nearly two thirds of total volume. What now?

  1. Drop all search logs at the collector until tomorrow. Discards search's own WARN and ERROR lines; the problem is one level of one service, so the filter should be that narrow.
  2. Leave it — the search team says DEBUG is useful for their investigation. 2.3 TB/day starves every other team's logs and risks disk I/O on the hosts; DEBUG is for minutes on a component, not days on a fleet.
  3. Stop it at the source and at the collector: revert search's log level to INFO (a config push, no deploy), and until that propagates add a collector filter dropping level=debug from search only. Confirm drops stop and checkout's ERROR lines are flowing again. Targets exactly the noise, keeps everyone's errors, is reversible, and takes effect in minutes.
  4. Delete the last 12 hours of search logs from the backend to free quota. Rate limiting is about incoming bytes per second, not stored bytes; deletion is irreversible and changes nothing about the inflow.

Step 3. Volume is back to 1.3 TB/day. In the retro, which systemic fix do you propose?

  1. Tell teams not to leave DEBUG on in production. A reminder; the next engineer under pressure at 02:00 will do the same thing.
  2. A per-service log budget with an alert on each service's rate of change, so a 3× jump pages the owning team rather than the platform; DEBUG only through a dynamic, time-limited toggle that auto-reverts (say 30 minutes) instead of a static config flag; and collector-side priority so level >= ERROR is never dropped under rate limiting. Verify: flip DEBUG in staging and watch the auto-revert and the per-service alert fire. Detects the next one early at the right owner, removes the foot-gun that caused this one, and protects the signal that matters most — with a test.
  3. Buy a bigger logging plan. Money does not stop the next flag; it just raises the price of the next incident.
  4. Ban DEBUG logging from the codebase. DEBUG is valuable when scoped to a component for minutes; the fix is control over when it is on, not removing it.
In short

Break volume down by service and level to find the tripled service, drop only its DEBUG lines, then add per-service log budgets and a DEBUG toggle that auto-reverts.

Why

Log volume incidents are diagnosed by breakdown (service × level over time) and mitigated by the narrowest filter that removes the noise while protecting errors — at the source first, at the collector while the source catches up. The durable fixes are mechanisms: budgets with owner-facing alerts, DEBUG as a time-boxed toggle rather than a flag someone must remember to unset, and a pipeline that sheds INFO/DEBUG before it ever sheds ERROR.

Read the docs

Next lesson Distributed systems: consensus, replication, consistency, idempotency, queues, caches, and failure handling
Drill · Structured logging, sampling, and distributed tracing
0:00

Loading…