Skip to content
Tech Interview Prep
Technical interview guide

Monitoring, Logging & Tracing

The three pillars of observability, and what question each one is actually good at answering.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: OpenTelemetry, W3C Trace Context, Prometheus, and Google SRE current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Compare metrics, logs, and traces for incident investigation.

Answer

What a strong candidate says first

Metrics are pre-aggregated numbers on a fixed interval: they answer how bad, how wide, since when, and they are the only signal cheap enough to alert on. Traces are causal span trees: they answer which hop in the call graph burned the time. Logs are per-event records: they answer what exactly happened on this one request. The investigation order follows the cost: alert on a metric, pull a representative trace, read the logs for that trace ID.

The comparison

MetricsTracesLogs
Answersscope, rate, saturation, SLO burnwhich hop, queue vs computeexact error, payload, ordering
Cost driveractive series × samplesspans/s × span sizebytes/s
Typical defaultsPrometheus scrape_interval 1m (shipped example config 15s), local TSDB retention 15d, 5m lookbackOTel SDK default sampler parentbased_always_on; Jaeger default remote strategy probabilistic 0.001; Collector tail_sampling decision_wait 30sLoki retention_period 744h (31d); Elasticsearch guidance 10–50 GB per shard
Fails bycardinality explosionbroken context propagation, head samplingvolume, no correlation key

Where the numbers bite

Cardinality: one metric name, http_requests_total{method,path,status,instance}, with 5 methods × 200 paths × 10 statuses × 50 instances is 500,000 active series. Single-node Prometheus is sized in the low millions of active series; one instrumentation line just spent a quarter of it.

Sampling: 5,000 rps × 50 spans per trace = 250,000 spans/s. At 1% head sampling that is 2,500 spans/s; at roughly 1 KB per span, 2.5 MB/s ≈ 216 GB/day. Head sampling at 1% also drops 99% of the slow requests you are investigating: use tail sampling with an error/latency policy, or accept that the trace you need may not exist.

Log volume: 5,000 rps × 200 B per line = 1 MB/s ≈ 86 GB/day, before replication. Keep errors at 100%, sample debug.

Worked trace (hypothetical figures)

14:02. Alert: checkout-api p99 of http_request_duration_seconds (default buckets include 1 and 2.5) goes 180 ms → 1.4 s. An exemplar on the slow bucket carries a trace ID (Prometheus 2.26+).

The trace shows 1.35 s of the 1.4 s inside one postgres.query span on orders-db; the parent charge_card span is 40 ms. The time is in the database call, not the payment provider.

Logs filtered by that trace ID, 14:01:58: pq: sorry, too many clients already. Pool max is 20, 60 concurrent checkouts. Root cause is pool exhaustion, not slow queries.

Detection that would have fired earlier: alert on pool wait time or pg_stat_activity count, not on request latency.

Failure modes and what the trio misses

  • Metrics cannot tell you which of 50 pods is bad unless you label by pod, and pod × path is exactly the cardinality explosion above.
  • Traces need traceparent (W3C Trace Context: 128-bit trace ID, 64-bit span ID) propagated through every hop; one service that drops the header splits one trace into several and the causal path is gone.
  • Logs without a trace ID are a grep exercise; clock skew across hosts reorders them.
  • None of the three shows CPU burn inside a process: that is continuous profiling (pprof), the fourth signal you reach for when the trace says "this span is slow" but not why.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Design production metrics for an HTTP service.

Answer

Assumptions to state up front: Prometheus-style pull scraping every 15 s, service behind an L7 load balancer, ~50 route templates, SLO of p99 < 200 ms and 99.9% non-5xx over 30 days. On OTel plus a vendor backend the same shapes apply.

Core answer. Four families, each with one job:

  • http_requests_total: counter, labels route, method, status_class (2xx/3xx/4xx/5xx), region. Increment once per request after routing, so the label is the route template, not the URL.
  • http_request_duration_seconds: histogram, same labels, buckets 0.05, 0.1, 0.2, 0.5, 1, 2, 5. The 0.2 edge is the SLO boundary; histogram_quantile interpolates linearly inside a bucket, so putting an edge on the SLO caps the error there.
  • http_inflight_requests and http_queue_depth: gauges, for concurrency and bounded-pool saturation.
  • Dependency metrics: db_query_duration_seconds histogram and db_errors_total counter, labelled by operation name (get_user), never by SQL text.
Go
var reqs = prometheus.NewCounterVec(prometheus.CounterOpts{
    Name: "http_requests_total",
}, []string{"route", "method", "status_class", "region"})

var dur = prometheus.NewHistogramVec(prometheus.HistogramOpts{
    Name:    "http_request_duration_seconds",
    Buckets: []float64{0.05, 0.1, 0.2, 0.5, 1, 2, 5},
}, []string{"route", "method", "status_class", "region"})

// after routing, not before:
route := mux.CurrentRoute(r).GetPath() // "/users/{id}", not "/users/8842"

Why averaged percentiles lie. A percentile is not linear, so the mean of ten instances' p99 is a number no instance ever observed. If nine instances sit at 80 ms and one is stuck at 900 ms, the true fleet p99 is ~900 ms; the average reports 162 ms and hides the incident. Aggregate the buckets across instances first, then take the quantile: histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))).

Why counter resets matter. rate() assumes monotonicity and repairs decreases by adding the pre-reset value back. Trace a 60 s window, samples every 15 s: 100, 130, 160, 5, 35. Deltas are 30, 30, -155, 30; the -155 is a restart, so add 160 back. Total 30+30+0+30+160 = 250 over 60 s ≈ 4.17/s: correct, because the last pre-restart sample (160) was scraped. If the process dies between scrapes, that tail is lost and rate() undercounts by up to one interval. That is why you alert on up == 0 and scrape gaps, not just on the rate.

Cardinality is the budget. 50 routes × 5 methods × 6 status classes × 3 regions = 4,500 series per metric. Add a version label with 20 live deploys and you are at 90,000: enough to blow a Prometheus head block. Keep version out of the request path; emit it as a separate low-cardinality build_info gauge with value 1.

Failure modes and detection. Raw URL or user ID as a label: series count climbs with traffic. Alert on count(count by (__name__)({__name__=~".+"})) growth. Unknown status codes collapsing into one bucket: assert the sum of status_class equals http_requests_total without the label. Retries double-counting: separate logical_requests_total from physical_attempts_total and alert when the ratio drifts. Missing instances: up == 0 for > 2 intervals.

What would change the decision. If you need per-request trace linkage, add exemplars rather than more labels. If the SLO tightens to p99 < 50 ms, re-cut the buckets around 0.05. If cardinality is already near budget, drop region to a separate aggregate metric.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a structured logging schema and lifecycle.

Answer

Core answer

Assume a multi-service backend emitting 10^4–10^5 events/s into one store, with PII in a few fields and a compliance retention floor. The schema is a small set of typed fields; everything else is a namespaced attribute bag. The lifecycle is producer → local collector → bounded buffer → store → tiered retention, with a drop counter at every hop.

fieldtypeboundwhy
tsRFC 3339 UTC, nsfixedcorrelation across hosts; store UTC, render local
sevenum, syslog 0–7fixedfilterable; don't invent your own scale
eventdotted string64 Bstable name, e.g. db.query.failed
schema_versionintfixedlets queries branch on shape
service.name, deployment.environmentstring64 BOTel semantic conventions; join key
trace_id, span_idhex32 / 16 charsW3C Trace Context sizes; links log to trace
error.codestring enum32 Bstable, countable; never the message
messagestring8 KiB, truncated with markerhuman fallback only
attrs.*typed1 KiB/value, 32 keysthe escape hatch

Two rules do most of the work. Timestamps: wall clock for correlation, monotonic for durations. NTP-synced hosts still drift tens of milliseconds, so never compute a duration by subtracting two wall-clock stamps. Error identity: error.code is a closed enum you can count and alert on; the message is prose that changes every deploy.

Redact and bound at the producer, not the query layer:

Python
import json, re
MAX = 64
SECRET = re.compile(r"(?i)(authorization|api[_-]?key|password)")

def emit(event, **fields):
    out = {"event": event, "ts": "2024-05-01T12:00:00.123456Z", "sev": "INFO"}
    for k, v in fields.items():
        if SECRET.search(k):
            out[k] = "[redacted]"
        else:
            s = str(v)
            out[k] = s if len(s) <= MAX else s[:MAX] + f"...(+{len(s)-MAX})"
    return json.dumps(out, separators=(",", ":"))

emit("login.failed", user="u_42", api_key="sk-live-abc", reason="bad_password")

Trace: user is 4 chars, kept. api_key matches api[_-]?key, replaced before serialization. reason is 12 chars, kept. The call returns:

{"event":"login.failed","ts":"2024-05-01T12:00:00.123456Z","sev":"INFO","user":"u_42","api_key":"[redacted]","reason":"bad_password"}

Redacting at source means the secret never reaches the buffer or the store, so a query-layer bug can't leak it. The cost is real: when you need the value to debug, it's gone, which is why you hash or tokenize identifiers you must correlate, and keep the raw value only in a separate, tightly-scoped store.

Lifecycle and failure modes:

  • Producer → collector: authenticate producers (mTLS) so a compromised pod can't forge another service's events.
  • Collector → store: bounded queue (e.g. 1000 batches) with a drop counter. Exporter outage fills the queue; detection is the drop counter going non-zero and queue size pinned at max. Consequence: trace gaps, not lost traces. The trace still exists, its logs don't.
  • Store: tiered retention, e.g. 30 days hot, 400 days cold for audit. Deletion must be provable; a "delete" that only hides rows fails an audit.
  • Query: authorize and audit reads; isolate tenants at the row level.

Failure modes worth a test each: a newline in a field forging a second line in a line-oriented sink (assert encoded output has no raw \n); duplicate delivery on retry (dedupe on trace_id+event+ts); clock skew reordering an incident timeline (alert on NTP offset); schema drift (old schema_version still queryable).

When to log less: at 10^5 events/s, debug-level logs are the cost driver. Sample them (e.g. 1 in 100, always keeping errors and anything with a trace_id you're actively debugging) rather than dropping fields. If a field is only ever read by a human, it belongs in message, not a typed column: typed columns you don't query are just bytes and cardinality.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Instrument distributed tracing for HTTP and messaging workflows.

Answer

Core answer

Two things decide the design: where a unit of work starts and ends, and whether the consumer continues the producer's causal operation or merely relates to it. Everything else follows.

Use OpenTelemetry with W3C Trace Context. traceparent is 00-<32 hex trace-id>-<16 hex span-id>-<2 hex flags>, and the SDK's default propagator is the tracecontext,baggage composite, so the same header rides HTTP requests and message headers. Pin your semantic-convention version: messaging.operation became messaging.operation.type in the 1.25 conventions, and dashboards break silently when it moves.

HTTP. One SERVER span per request, one CLIENT span per outbound call. Name the span {method} {route}: GET /orders/{id}, never GET /orders/8f3a…, because raw paths explode cardinality. Attributes: http.request.method, url.full, server.address, server.port, http.response.status_code, error.type on failure.

Messaging. PRODUCER span around the publish, CONSUMER span around the handler. Attributes: messaging.system (kafka, rabbitmq, aws_sqs), messaging.destination.name, messaging.consumer.group.name, messaging.message.id, and messaging.kafka.message.offset for Kafka.

The parent-vs-link decision is the whole question:

SituationModelWhy
Consumer continues one producer's operationExtract traceparent from the message header; consumer span is a childOne causal chain; publish-to-process latency is visible
One message has several causes (fan-in)Consumer span with one link per producer spanPicking one parent would be arbitrary
Batch of N messages handled togetherOne CONSUMER span with N linksN children make a star and inflate span count
Recurring/scheduled jobNew root span per iteration, link to the previousOtherwise one trace grows forever

That last row is the one people miss. A job every 10 s with 20 spans per run, kept in a single trace, is 172,800 spans/day in one trace; backends and UIs fall over long before that.

Python
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Link

tracer = trace.get_tracer("billing")
links = [Link(ctx) for ctx in producer_contexts]   # one per record in the batch

with tracer.start_as_current_span(
    "orders.created process", kind=SpanKind.CONSUMER, links=links
) as span:
    span.set_attribute("messaging.system", "kafka")
    span.set_attribute("messaging.destination.name", "orders.created")
    span.set_attribute("messaging.consumer.group.name", "billing")
    span.set_attribute("messaging.batch.message_count", len(records))
    for record in records:
        handle(record)

Queue wait is not processing time. The consumer span starts when the handler picks the message up, so a 40 ms handler looks healthy while end-to-end p99 is 6 s because the queue backed up. Record the broker's enqueue timestamp as an attribute on the producer span and subtract.

Bounded attributes. OTel's default span limits are 128 attributes, 128 events, 128 links per span; anything past that is dropped silently. Never put payloads, headers or secrets in spans: put messaging.message.id and look the body up. Retry attempt as an integer, outcome as error.type, not free text.

Sampling. The default head sampler is parentbased_always_on: 100%. At 5,000 spans/s that is 432M spans/day; at ~1 KB/span, roughly 430 GB/day. Head sampling at 1% cuts that but drops the rare failures, so the usual shape is head sampling for volume plus tail sampling in the Collector (tail_sampling with latency, status_code and probabilistic policies) to keep every error and slow trace. Tail sampling buffers whole traces in memory, so bound it with decision_wait and num_traces.

Failure modes worth testing. A proxy that strips traceparent splits one trace into two: detect by comparing child-span counts to request counts. Redelivery produces two consumer spans with the same messaging.message.id; that is correct, don't dedupe. A DLQ publish should be a new PRODUCER span linked to the failed consumer span. A host 30 s off shows negative durations: check start_time against the parent's end_time before trusting a waterfall. A third-party call gives you a CLIENT span and no SERVER span; that is expected.

When not to. Health checks, cache hits and metrics scrapes at 100 rps cost more to trace than the traces are worth. Sample them out or drop them at the Collector.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Correlate logs and traces across services.

Answer

Core answer (first 90 seconds)

Assume OpenTelemetry SDKs and W3C Trace Context over HTTP plus a queue. Correlation has two halves: propagate trace context across every hop, and stamp the current trace/span IDs onto every log record so a log line can be joined to a trace.

Propagation is a carrier problem. On inbound HTTP, extract traceparent (and tracestate) into a Context, start a server span as a child of the remote span context, and make that span current for the handler. On outbound calls, inject the current context into the carrier. The header is fixed-format:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             ^v ^trace-id (16 bytes)          ^parent-id (8 bytes) ^flags

Version 00, 32 hex trace ID, 16 hex span ID, flags byte where 0x01 = sampled. All-zero trace or span IDs are invalid; a malformed or unsupported-version header means start a new trace rather than propagate garbage.

Log correlation is the second half: the logging integration reads the active span from context and adds trace_id, span_id, trace_flags to each record. In Java that's MDC (%X{trace_id} in the pattern); in Python it's a logging filter reading trace.get_current_span(). No active span means empty fields: that's the signal you're logging outside a span.

Mechanism: why context is the hard part

Context is stored per-execution (ThreadLocal in Java, contextvars in Python, context.Context in Go). It does not follow work onto a thread pool, an executor, or a new task, so the span started on the request thread is invisible to the worker that logs. Fix by wrapping the task with the captured context: Java Context.current().wrap(runnable), Python contextvars.copy_context().run(...), Go pass ctx explicitly. This is the most common cause of orphan spans.

Links vs child spans

A child span asserts the parent's lifetime contains the child's and the relationship is 1:1. That's false for a batch consumer reading 500 messages from 500 traces, or async work that starts after the producer span ended. Use a span link instead: links=[Link(producer_span_context)].

SituationUseWhy
HTTP call, 1:1, child nested in parentchild spanparent lifetime contains child
Batch consumer, N producersspan link per producercardinality isn't 1:1
Async work after producer span endedspan linkchild would outlive parent
Retry of the same requestnew span, same trace IDattempts are distinct work

Sampling trade-off

Default SDK sampler is parentbased_always_on; a ratio sampler is parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.01. Head sampling is cheap and consistent across services (the sampled flag rides in traceparent), but you can't decide on error or latency. Tail sampling in the collector can, at the cost of buffering every trace for decision_wait (default 30s) and requiring trace-ID-affinity routing so all spans of a trace land on one collector. If you head-sample at 1%, logs still carry trace_id but no spans exist for 99% of them: decide whether that's acceptable, or log the sampled flag so you can filter.

Failure modes and detection

  • Orphan spans: parent span ID not found in the backend. Alert on the ratio.
  • Logs missing trace_id: logging outside a span, or context lost across a thread hop.
  • Queue delay: producer span ended before consumer started. Link, not child.
  • Retries: new span per attempt, same trace ID; don't reuse span IDs.
  • Untrusted headers: bound tracestate (W3C caps it at 32 list-members) and baggage size, strip at the edge, never put PII in baggage, never use trace IDs for auth or idempotency.

Test nested concurrency, retries, missing/invalid headers, third-party calls, and log emission outside a span.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design observability for a database dependency.

Answer

Clarify, then answer. I'd ask three things before drawing anything: what user-facing SLO covers the endpoint that depends on this database, is the dependency a single primary or a replicated/sharded set, and which pool library sits in front of it. I'll assume a Postgres 15 primary, a Java service on HikariCP, a 99.9% availability SLO on the read path, and OpenTelemetry plus Prometheus for telemetry. If any of those differ, the shape of the answer holds but the numbers move.

The answer in one line: instrument the call at three layers (pool, client call, server) and page only on the user-facing symptom, using the lower layers for diagnosis.

Layer 1, the pool. HikariCP defaults to maximumPoolSize=10 and connectionTimeout=30000 ms. Those two numbers decide most incidents. Export hikaricp.connections.active, .idle, .pending, .timeout, and the hikaricp.connections.acquire timer. The signal that matters is pending climbing while active is pinned at max: that is saturation, and acquire p99 walking toward 30 s is the countdown to SQLTransientConnectionException. Alert on pending > 0 sustained for 30 s, not on active == max: a full pool with no waiters is just a busy pool.

Layer 2, the client call. One CLIENT span per call carrying db.system=postgresql, db.operation.name, db.namespace, and db.query.text (db.statement/db.operation in older semconv). Propagate context so the span is a child of the HTTP span: that is what lets you answer "which endpoint burned the budget." Record duration as a histogram with explicit buckets; the Prometheus defaults stop at 10 s and are useless below 5 ms, so use 1, 2.5, 5, 10, 25, 50, 100, 250, 500 ms, 1, 2.5, 5, 10 s. Split the span into pool-acquire, network, and server execution so you can say which one moved. If you can't separate them, say so rather than guessing.

Layer 3, the server. Correlate with pg_stat_statements, which normalizes literals to $1, $2: fingerprinting for free, and the reason you don't ship raw db.query.text with bind values. Keep the fingerprint (a hash of the normalized shape) as the metric label; keep full text only in sampled traces; never log credentials or bind values.

Artefacts. A trace that separates the layers (illustrative):

POST /orders            142 ms
├─ pool.acquire          38 ms   ← waiting, pool at 10/10
├─ db.query INSERT       96 ms   db.system=postgresql
└─ serialize response     8 ms

And the signal set (thresholds illustrative: set them from your own baseline):

signalsourcealert
hikaricp.connections.pendingMicrometer> 0 for 30 s
hikaricp.connections.acquire p99Micrometer timer> 250 ms for 5 min (ticket)
client duration p99OTel histogram> 2x baseline for 5 min
error rate by SQLSTATEspans/logs> 1% for 5 min
pg_stat_statements.mean_exec_timePostgrestop-10 query > 100 ms

Trade-offs. Fingerprinting controls cardinality but loses the literal that made a query slow; keep raw text in traces at ~1% sampling, not in metrics. Paging on user impact: error-budget burn of 14.4x over 1 h or 6x over 6 h: keeps on-call focused, but it delays detection of a pool leak that hasn't hit users yet, so pair it with a slow-burn ticket on acquire p99.

Failure modes. Pool exhaustion: pending climbs, acquire p99 approaches 30 s, then SQLTransientConnectionException. Deadlock and serialization failure: SQLSTATE 40P01 and 40001, both retryable. Log the code, not the message. Timeout after commit: the client sees a timeout but the write landed; without an idempotency key the retry duplicates it. Retry storms: cap retries and add jitter, or a 30 s outage becomes a 5-minute one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Create observability for asynchronous queues and background jobs.

Answer

Assumptions first: at-least-once delivery, a broker that exposes per-queue backlog (SQS, Kafka, RabbitMQ, Redis-backed Sidekiq/Celery), and workers you control. If the broker is fully managed and gives you only CloudWatch, you still own the consumer-side spans and the business reconciliation.

The 90-second answer. Instrument four moments (enqueue, wait, attempt, terminal outcome) with a label set you can afford: queue, outcome, attempt_bucket. Never label by job id. Propagate W3C traceparent in the message attributes (OpenTelemetry SDK does this for you) so the consumer span is a child of the producer span, and use span links, not parent, for redeliveries and batch fan-in: a retry's true cause is the earlier attempt, not the new consumer span. Alert on the age of the oldest eligible message, not on queue depth. Depth is a proxy that lies when consumers are fast but one poison message blocks a partition. The SLO I'd write: 99% of jobs reach a terminal state within 5 minutes of becoming eligible; page when oldest_eligible_age_seconds > 300 for 5 minutes.

Metrics. Counters: jobs_enqueued_total, jobs_completed_total{outcome="success|failed|dead_letter"}, jobs_retried_total. Gauges: queue_backlog, oldest_eligible_age_seconds, in_flight. Histograms with buckets 10ms/50ms/100ms/500ms/1s/5s/30s/2m/10m for job_wait_seconds (enqueue to first attempt start) and job_processing_seconds (attempt start to terminal). attempt_bucket is 1, 2, 3-5, 6+: bounded cardinality that still shows a retry storm. Retry-storm alert: rate(jobs_retried_total[5m]) / rate(jobs_completed_total[5m]) > 0.05. Any non-zero increment of jobs_completed_total{outcome="dead_letter"} pages, because a DLQ is work that will never finish without a human.

Traces. Producer span POST /checkout, trace-id 4bf92f3577b34da6a3ce929d0e0e4736, span-id 00f067aa0ba902b7. Message attribute traceparent = 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. Consumer span email-send process, span-id a1b2c3d4e5f60718, parent 00f067aa0ba902b7, kind CONSUMER. Attempt 1 span smtp.send attempt=1 runs 0.9s and errors. The retry is a new message; its consumer span carries a link to the attempt-1 span, so the trace shows two attempts under one logical job without pretending the second attempt was caused by the first consumer span. Attempt 2 runs 1.1s and fails; the worker publishes to the DLQ and increments jobs_completed_total{queue="email-send",outcome="dead_letter"}.

Logs. One structured line per state transition: {job_id, queue, attempt, from, to, failure_code, ts}. failure_code is a small enum (SMTP_421, LEASE_EXPIRED, SCHEMA_INVALID): never the payload, never a free-text exception. That enum is what turns the failure breakdown into a dashboard instead of a grep.

Failure modes and what changes the decision. Duplicate delivery: count dedupe hits (jobs_deduped_total); a spike means your idempotency key is wrong, not that the broker is broken. Poison message: SQS redrive maxReceiveCount (commonly 3–5) moves it to the DLQ; if oldest_eligible_age_seconds climbs while in_flight is flat, a poison message is blocking a partition. The case where depth alone looked fine. Worker loss: lease expiry, visible as in_flight dropping with no matching jobs_completed_total. Quiet periods: absence of metrics is invisible, so run a deadman switch (Healthchecks.io, Cronitor) that pages when no jobs_completed_total increment arrives for 2× the expected period. Business completeness: reconcile per business key. An order with status=paid and no email_sent event after 10 minutes is a bug that every task-level metric above will call a success.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you define SLIs and SLOs for a user-facing HTTP API and derive an error budget from your telemetry?

Answer

Start by naming the user journey and the measurement point, because that decides everything else. For a public HTTP API the two SLIs that carry most of the signal are availability and latency, both expressed as ratios of good events to valid events over a window.

Availability SLI: good = the response completed with a status the user considers success; valid = every request that reached the service, excluding ones we deliberately reject before doing work (malformed, unauthenticated). Latency SLI: good = request served under 300 ms; valid = the same denominator. Measure at the edge, the load balancer or a synthetic probe, because server-side counters never see DNS failures, TLS handshakes that die, or connection refused.

PromQL, assuming a request counter and a duration histogram:

promql

availability over 5m

sum(rate(http_requests_total{job="api",code!~"5.."}[5m])) / sum(rate(http_requests_total{job="api"}[5m]))

latency: fraction served under 300ms

sum(rate(http_request_duration_seconds_bucket{job="api",le="0.3"}[5m])) / sum(rate(http_request_duration_seconds_count{job="api"}[5m]))

Two traps in the second query: le="0.3" only exists if you configured that bucket. Prometheus's defaults are .005 .01 .025 .05 .1 .25 .5 1 2.5 5 10, so either use le="0.25" or add the bucket. And rate() on the bucket is correct because histogram buckets are cumulative counters; never average per-instance ratios, always sum numerator and denominator separately.

Target and window: 99.9% availability over a rolling 30 days. Budget = 0.001 × 30 × 24 × 60 = 43.2 minutes of full outage, or, at 2,000 rps, 0.001 × 2,000 × 2,592,000 ≈ 5.18M failed requests. Rolling windows avoid the calendar-month cliff where the budget resets and everyone relaxes on the 1st.

Burn rate is the only number worth alerting on. burn = observed error ratio / (1 − SLO). At 99.9%, a 0.1% error ratio is burn 1.0: the budget is exhausted in exactly 30 days. Multiwindow alerting: burn > 14.4 over 1h (2% of budget in an hour) pages; burn > 6 over 6h (5%) pages or tickets; burn > 1 over 3 days (10%) tickets. Each fast alert is paired with a short window (5m or 30m) so it clears quickly after recovery.

promql (sum(rate(http_requests_total{job="api",code=~"5.."}[1h])) / sum(rate(http_requests_total{job="api"}[1h]))) / 0.001 > 14.4

Failure modes: low-traffic services where one failure is 20% of the window. Add a request-count floor and lengthen the window, or the alert flaps. Missing telemetry: a scrape gap must not be counted as good; mark the SLI unknown and alert on staleness separately. Aggregating with avg() across instances. And an SLI that measures something the user doesn't feel (CPU, queue depth): those are causes, not SLIs.

Release policy: budget remaining > 50% → ship normally; 0–50% → ship with reliability work attached; exhausted → feature freeze until the burn stops, with exceptions logged. Don't page on budget exhaustion itself: it's a trailing indicator; page on burn rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design actionable alerting from observability signals.

Answer

What I'd say in the first two minutes

I'd assume a request-edge SLO, say 99.9% over 30 days, metrics already scraped, and Alertmanager-style routing. If there's no SLO, say so, because this design keys off the error budget; without one I'd fall back to absolute error thresholds and lose the "how fast will we run out" signal.

I'd page on error-budget burn rate, ticket the slow burn, and leave everything else on dashboards. Paging rules stay few.

Why burn rate, and why two windows

burn rate = error rate / (1 - SLO). At 99.9% the budget rate is 0.1%, so burn rate 14.4 means 1.44% of requests are failing. Budget consumed = burn rate * window / 720h.

long windowshort windowburn ratebudget consumedaction
1h5m14.42%page
6h30m65%page
3d6h110%ticket

The long window is the evidence; the short one is the reset. Require both to fire: a 90-second blip cannot sustain a one-hour average, and once the burn stops, the 5-minute window clears the page in about five minutes instead of holding it open for the rest of the hour. Short-only flaps; long-only pages you about something already fixed.

Trace it

200 req/s, 99.9% over 30 days. Total requests = 200 * 86,400 * 30 = 518.4M; budget = 518,400 failures. One hour is 720,000 requests, so the 14.4 pair fires at 1.44% errors = 10,368 failures = 2.0% of budget. The 6h pair fires at 0.6% of 4,320,000 = 25,920 failures = 5.0%. Same arithmetic in both rows.

What the page must carry

Labels: severity, service, slo, cluster, owner. Annotations: current value against threshold, window, start time, data freshness, the burn-rate query, dashboard link, runbook link, one exemplar trace ID. Test: can the responder tell within five minutes whether a user is affected? If not, the payload is missing something.

Routing, dedup, inhibition

group_by [alertname, cluster, service], group_wait 30s, group_interval 5m, repeat_interval 4h. A shorter repeat_interval trains people to ignore the second page.

Inhibit on dependency direction: a database-primary-down alert silences service alerts labelled dependent_on=db-prod. The mechanism is fan-out: one shared dependency failure otherwise emits pages equal to the number of callers, so 40 callers wake 40 people for one incident.

Failure modes

  • Flap: pages per shift climbing while incidents stay flat. Detect by comparing alert count to ticket count weekly.
  • NoData: the metrics path dies and every dashboard looks green. Detect with absent() on a recording rule, and route Alertmanager's Watchdog alert to an external dead-man's switch that pages when the heartbeat stops.
  • Low traffic: at 20 req/min the 0.1% budget rate is one failing request every 50 minutes, so a single 500 pages the team. Detect by listing pages from services under roughly 1 req/s; gate those on an absolute error count instead.
  • Masked incident: an inhibition rule swallowing an independent failure that coincided with the dependency outage. Detect in post-incident review by checking whether any rule suppressed a firing alert.

When not to use it

If a component has no degraded mode and sits in every request path, a burn-rate page is too slow to be the only line of defence. Add a cause-level alert owned by that component's team and keep the symptom page as backstop.

Measurement

Precision = pages that led to action / total pages. Recall comes from backtesting: replay 90 days of past incidents and normal deploys through the rules and count which ones would have paged. Target at most two pages per 12-hour shift, the SRE book's on-call figure; if under a quarter of pages produce an action, the rules are noise.

What would change my decision

A batch or internal tool with bounded blast radius drops the page tiers entirely and keeps only the ticket tier; a service with fewer than roughly 1 req/s moves to count-based thresholds. If the SLO is availability measured by a synthetic probe rather than request ratio, the same windows apply but the error rate is probe failures, not 5xx.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Investigate a latency regression with metrics, traces, and logs.

Answer

What I'd say first (60–120 seconds)

Assume a p99 latency alert on a checkout API with a 300 ms SLO, fired 4 minutes ago, and a deploy 25 minutes ago. First I confirm the alert is real and user-facing: which percentile, which routes, which regions, and whether the metric is fresh. A 15 s scrape interval means the last point is at most 15 s old, and a 5-minute rate window means the regression must be at least that old to show. Then I segment before I dig: latency by route, region, version, and outcome. A regression confined to one version is a deploy; one confined to one AZ across all versions is infrastructure; one that hits every route equally is usually a shared dependency or the network.

Why segmentation beats staring at the aggregate

A single p99 hides the shape. If p99 goes 180 ms → 640 ms but p50 is flat, you have a tail problem: a subset of requests, not a uniform slowdown. If p50 moves too, it's systemic. I pull the histogram, not the summary:

PROMQL
histogram_quantile(0.99,
  sum by (le, route, version) (
    rate(http_request_duration_seconds_bucket[5m])))

From bucket to trace

Percentiles tell you that the tail moved; they can't tell you why. Exemplars close that gap: OpenTelemetry attaches a trace_id to histogram buckets, so I jump from the exact p99 bucket to the trace that landed in it instead of guessing. That's the reason to prefer exemplars over re-querying percentiles: the percentile is an aggregate with no identity; the exemplar carries the one request that proves the shape.

Say the trace shows 640 ms total, and the arithmetic splits it:

total            640 ms
  queue wait     610 ms   (pool acquire)
  service time    30 ms   (handler + DB)
  dependency       0 ms   (no downstream span)

610 of 640 ms is queue wait with flat service time. That is saturation, not a slow dependency. If instead service time were 600 ms and queue wait 10 ms, I'd walk the child spans (the DB call, the fanout, the retry) because the time is inside the work, not waiting for a slot.

Logs

I pull logs only for the suspect trace IDs and span IDs, not the whole corpus. Correlated logs give the error and state detail spans don't carry (pool size, active connections, retry reason). Searching the corpus blindly costs money and returns noise.

Trade-offs: roll back vs mitigate forward

Roll back when the regression correlates with a deploy, the deploy is the only changed variable, and revert is fast (minutes). Mitigate forward when rollback would drop a fix you need, or when the cause is capacity: adding replicas or raising the pool size relieves queue wait, but raising pool size can just move the queue to the database, so I check DB connection limits before I do it.

Failure modes to name

Head-based sampling at 1% means the slow trace may never be captured: use tail-based sampling or exemplars. Clock skew between hosts makes span durations negative or inflated; check parent/child timestamps before trusting a span. A renamed route label silently breaks the baseline comparison, so verify the label set matches.

Close the loop

Mitigate or roll back, then verify user-facing latency and error budget recovery, not just the alert clearing. Preserve the query and trace, and if the failure was invisible to existing signals, add the signal or a regression test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design observability for a new user-facing service.

Answer

First I'd pin down the shape of the service and the promise it makes. Assume a user-facing HTTP API doing roughly 50k requests/min on Kubernetes, six engineers on call, and a stated SLO of 99.9% availability over 30 days. That SLO is the spine of the whole design: 99.9% gives a 0.1% error budget, which is 43.2 minutes of full outage per 30-day window. Everything below exists to tell you, fast, whether you're spending that budget.

Metrics: the RED signals plus saturation. For every route: request rate, error rate split by status class, and a latency histogram, not an average. Averages hide the tail; I care about p50/p95/p99, and I set histogram buckets around the SLO threshold so the p99 is accurate near the line that matters. Saturation is the leading indicator: CPU throttling (container_cpu_cfs_throttled_seconds_total), connection-pool in-use vs max, and queue depth. The trap here is label cardinality. Never put user_id, raw URL path, or request body into a Prometheus label: use the route template (/orders/{id}), not the concrete path. A single unbounded label can take a Prometheus instance from 200k to millions of series and OOM it.

Logs. Structured JSON, one event per state transition or error, with stable fields: service.name, trace_id, span_id, http.route, http.status_code, error.type. Never log auth headers, tokens, or request bodies: that's a privacy and compliance problem, not just noise. The trace_id is what lets you jump from a log line to the full trace.

Traces. OpenTelemetry SDK, W3C traceparent propagation. The real work is context propagation across async boundaries (message queues, thread pools, background jobs) where a missing inject/extract silently fragments a trace into disconnected single spans.

Sampling is the main trade-off. Head sampling (decide at the root, e.g. 10%) is cheap and stateless but blind: it drops the rare failure you actually need. Tail sampling in the OTel Collector lets you keep 100% of error traces and traces over 2s, and 1% of the healthy ones. At 50k req/min that's the difference between ~72M spans/day at full capture and roughly 1M/day with tail policies. The cost: the collector must buffer whole traces and route all spans of a trace to the same instance (load-balancing exporter keyed on trace ID), which means memory and a stateful tier. If you can't run that, head-sample and accept the blind spot.

Correlation. Exemplars attach a trace_id to a histogram bucket, so a p99 spike on a Grafana panel links straight to a slow trace. Resource attributes (service.name, k8s.pod.name, deployment.environment) tie all three signals to the same identity.

Alerts: burn rate, not raw thresholds. Page on a fast burn: 14.4x over 1 hour (that consumes 2% of the budget in an hour). Ticket on a slow burn: 6x over 6 hours. Each alert carries a runbook and a dashboard link. A raw "error rate > 1%" alert either fires constantly or misses slow bleeds.

Failure modes and how you'd see them. Exporter/backend outage: the collector buffers, then drops once its queue fills. Watch otelcol_exporter_send_failed_spans and queue size, not the app. Cardinality explosion: prometheus_tsdb_head_series climbing and scrape durations rising. Broken context: the ratio of single-span traces jumps. Sampling blind spot: error counts in logs diverge from error counts in traces.

When not to do this. A low-traffic internal service doesn't need tail sampling or burn-rate alerting: 100% head sampling and a simple error-rate alert are cheaper and sufficient. Don't build the stateful collector tier until volume or a real missed-incident justifies it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Control metric-cardinality growth in a multi-tenant system.

Answer

Assumptions: multi-tenant SaaS, one shared Prometheus per region, tenants are customers, 15s scrape interval, 15d retention. The numbers below are illustrative, not measured.

Core answer (first 90 seconds). Cardinality is the product of the value domains of a metric's labels. You bound it by shrinking each domain, not by buying more RAM. Three moves, in order. First, never put an unbounded value in a label: user ID, request ID, raw URL, exception message, timestamp, pod name. Second, collapse the values you do need into bounded classes: route templates (/api/v1/users/:id), status classes (1xx–5xx), a fixed error-code enum, tenant tier (free/pro/enterprise). Third, enforce a ceiling at three points (SDK, collector, backend) so a bad deploy fails loudly instead of quietly melting the TSDB. Then alert on series creation and churn, and send per-request investigation to logs and traces, where high-cardinality dimensions are cheap.

Mechanism. Cardinality = product of domains. A request metric with 50 tenants × 200 routes × 5 status classes × 4 methods = 200,000 series. At 15s that is 4 samples/min per series, so 800,000 samples/min. Add user_id with 1M users and the same metric becomes 2×10¹¹ series, not a tuning problem, a non-starter. The tenant label is the multiplier: drop it and the metric is 4,000 series; keep it and every other label's domain multiplies by 50.

Trade-offs. The tenant label is what buys per-tenant SLOs and per-tenant billing, so you usually keep it, but then every other label multiplies by tenant count, and one noisy tenant can dominate the TSDB. Alternatives: a Prometheus per tenant (hard isolation, N× operational cost, no cross-tenant queries), or keep the tenant label only for the top N tenants and aggregate the long tail into tenant="other" (loses per-tenant detail for small customers). Recording rules do not reduce stored cardinality, they add series, but they cut query cost by pre-computing the rollups dashboards actually read.

Failure modes. (1) A new label ships with an unbounded domain: a version or build_sha label with hundreds of values multiplies every existing series. Detect: scrape_series_added jumps right after a deploy. (2) Churn from short-lived pods with random names: series are created and abandoned faster than they expire, so head series grows even at a flat sample rate. Detect: rate(prometheus_tsdb_head_series_created_total[1h]) high while prometheus_tsdb_head_series climbs. (3) A scrape exceeds sample_limit and Prometheus drops the whole target: you lose that tenant's metrics entirely, not just the excess. Detect: up == 0 with scrape_samples_scraped absent for that target.

Artefact 1: label domains.

LabelBounded domainExample valuesCardinality impact
tenant50tenant_001..tenant_05050
route200/api/v1/users/:id200
status51xx,2xx,3xx,4xx,5xx5
method4GET,POST,PUT,DELETE4

Total = 50 × 200 × 5 × 4 = 200,000 series.

Artefact 2: relabel config.

YAML
scrape_configs:
  - job_name: app
    metric_relabel_configs:
      # drop an unbounded label entirely
      - action: labeldrop
        regex: user_id
      # collapse a path to its route template
      - source_labels: [path]
        regex: /api/v1/users/[^/]+
        target_label: path
        replacement: /api/v1/users/:id

Prometheus anchors relabel regexes (^(?:...)$), so the path rule matches only paths of exactly that shape; other unbounded paths need their own rules or a labeldrop.

Artefact 3: storage arithmetic. 200,000 series × 4 samples/min = 800,000 samples/min. Over 15d: 800,000 × 60 × 24 × 15 = 1.728×10¹⁰ samples. At 16 bytes raw that is ~276 GB before compression. Cardinality drives storage and query cost directly.

Limits and triggers. Real scrape-config options, all defaulting to 0 = unlimited: sample_limit, label_limit, label_name_length_limit, label_value_length_limit, target_limit. Set sample_limit above your normal scrape (e.g. 10,000), label_limit ~30, label_value_length_limit ~200. Isolate a tenant or drop labels when its series share exceeds ~20% of the total, or when churn exceeds ~10%/hour. A single Prometheus on 8 cores/32 GB is commonly cited as handling low single-digit millions of active series: treat that as a rule of thumb and measure your own ceiling with a load test before trusting it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Choose a trace-sampling strategy for a high-volume service.

Answer

The 90-second answer

I'd start by asking what the traces are for, because that decides the sampler. Three jobs pull in different directions: estimating latency and path mix across the fleet, catching rare failures, and keeping per-tenant and per-operation coverage. Then I'd pick a two-layer design: a cheap head sampler in the SDK to cut volume at the source, and tail sampling in the collector for the outcomes you can only judge after the trace ends.

Head sampling is a coin flip on the trace ID. In OpenTelemetry that's parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.01 for 1%. It's free, it's consistent: every span in a trace gets the same decision because the parent's sampled flag propagates in the W3C traceparent header, and it gives you an unbiased sample you can extrapolate from. What it can't do is look at the outcome: a 1% head sample keeps 1% of your errors, so a bug firing 500 times an hour becomes 5 traces an hour.

Tail sampling fixes that. The collector buffers spans per trace ID, waits, then decides. In the OTel Collector that's the tail_sampling processor: decision_wait defaults to 30s and num_traces to 50000, and you attach policies. status_code for errors, latency for slow traces, probabilistic for the baseline, rate_limiting to cap a flood.

The arithmetic that decides the buffer

Say the service does 50k requests/sec and each request emits 20 spans: 1M spans/sec. At 100% ingest with a 30s decision wait the collector holds 30M spans. At a rough 1.5 KB per buffered span that's ~45 GB of RAM, which is why nobody tail-samples at full volume. Head-sample at 10% first: 100k spans/sec, 3M spans buffered, ~4.5 GB. That's a collector you can actually run, and you can still afford to keep every error because errors are a small fraction of the 10%.

The cost is that you only ever see 10% of errors. At 0.1% error rate and 50k rps, a 10% head sample gives you 5 errors/sec: plenty. At 0.001% you get 0.05/sec and you're blind. So the head rate is set by the rarest thing you need to see, not by your storage budget.

Head (SDK)Tail (collector)
Cost~free; cuts network and collector loadfull ingest cost at the collector tier
Knows the outcomenoyes
Consistencytrace-ID hash, no coordinationneeds every span of a trace on one collector
Typical usebaseline volume cuterrors, slow traces, tenant cohorts

Failure modes and how you see them

  • Late spans. decision_wait: 30s means a 45-second batch job's error span arrives after the decision, and the trace is kept or dropped without it. Watch otelcol_processor_tail_sampling_sampling_trace_dropped_too_early; if it climbs, raise decision_wait and pay the memory.
  • Split traces. Tail sampling only works if every span of a trace hits the same collector. Put the loadbalancing exporter with routing_key: traceID in front of the tail-sampling tier. Get it wrong and you see traces with no root span and a span-count distribution with a fat left tail.
  • OOM. When in-flight traces exceed num_traces, the processor evicts the oldest. Detection is the otelcol_processor_tail_sampling_sampling_traces_on_memory gauge pinned at the limit plus container restarts.
  • Biased rules. Sampling only on status_code = ERROR makes your trace-derived p99 meaningless. Check it against the Prometheus histogram p99 weekly; a gap means the rules changed, not the service.
  • Error floods. A retry storm turns "keep all errors" into a denial-of-service on your own backend. Cap it with a rate_limiting policy per tenant.

What I'd ship

A baseline probabilistic policy at 1-5% so the sample is unbiased and hash-consistent, plus status_code: ERROR, plus a latency policy above your p99 threshold, plus per-tenant rate_limiting. Stamp the applied rate on the span so the backend can weight counts back up. Keep audit and security events out of sampled tracing entirely: separate, unsampled pipeline.

Then load-test it: replay a peak hour, watch memory, dropped-too-early and decision latency, and compare trace-derived p99 against metrics before trusting either.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Protect sensitive information throughout telemetry lifecycle.

Answer

Assume a multi-tenant SaaS on OpenTelemetry, shipping traces, logs and metrics to one vendor backend, with GDPR and a signed BAA in scope. Four controls, in this order: minimize at the source, redact before the process boundary, authorize every read path, and make retention and deletion per-field rather than per-store.

Minimize first, because the cheapest sensitive field is the one you never emit. OTel caps a span at 128 attributes by default and leaves the attribute value length limit unset, so nothing stops a service from attaching a whole request body. Use an allowlist of attribute keys, not a denylist: a denylist only catches the fields you already thought of.

Redact at the producer when you can, at the collector when you can't. Never put credentials or PII in baggage: baggage propagates to every downstream span and to the exporter, so one service adding user.email leaks it across the entire trace. Then authorize reads, a redacted pipeline with a shared dashboard login is still a leak, and set retention per field, because a raw body and a status code do not deserve the same lifetime.

SignalLeak vectorControlDetection
Tracesdb.statement, http.request.header.authorization, url.querydelete or allowlist in the Collectorcanary secret in synthetic traffic
Baggageuser.email rides every downstream spanallowlist baggage keys in the SDKcount dropped baggage keys at the Collector
Logsexception messages, raw request bodiesstructured logging with a field allowlistregex scan on ingest plus canary
Metricsuser ID or email as a labelhash or drop high-cardinality labelsprometheus_tsdb_head_series growth

A Collector transform that does the trace and baggage work:

YAML
processors:
  transform/sanitize:
    error_mode: ignore
    trace_statements:
      - context: span
        statements:
          - delete_key(attributes, "http.request.header.authorization")
          - delete_key(attributes, "db.statement")
          - delete_key(attributes, "url.query")
          - set(attributes["enduser.id"], SHA256(attributes["enduser.id"])) where attributes["enduser.id"] != nil
      - context: resource
        statements:
          - delete_key(attributes, "host.name")

Trace one span through it. It arrives with http.method=GET, http.route=/users/{id}, http.request.header.authorization=Bearer eyJ..., db.statement=SELECT * FROM users WHERE email='a@b.com', enduser.id=a@b.com. After the span statements, the authorization header, the SQL text and any query string are gone; enduser.id is replaced by its SHA-256 digest (64 hex characters); http.method and http.route survive. The resource statement drops host.name. An unlisted key such as user.email passes straight through, which is exactly why allowlist mode beats a denylist.

Retention arithmetic, illustrative: 5 TB/day of logs, 30 days hot on S3 Standard at $0.023/GB-month. Average stored volume is 5,000 GB/day × 30 ÷ 2 = 75,000 GB, about $1,725/month. Dropping the raw body field, say 40% of volume, saves roughly $690/month and removes the largest sensitive surface at the same time.

What actually breaks. A token base64'd into a query param, or an email URL-encoded as a%40b.com, slips past a regex written for plaintext: catch it with canary secrets injected into synthetic traffic and an alert if one lands in the backend index. Baggage added by one team leaks through every downstream span until the Collector drops the key. Deletion is the expensive one: S3 Glacier Flexible Retrieval standard restore takes 3–5 hours, and object-lock/WORM backups cannot be rewritten at all, so a GDPR erasure that must complete within one month can blow the window if the archive is immutable. Measure end-to-end deletion propagation rather than assuming it. A user ID as a Prometheus label creates one series per user and grows the head series count until the TSDB OOMs.

Where the alternatives sit. Redacting at the source keeps data inside the process but forces you to version the redaction library in every service; the Collector is one place to change but the raw data crosses the network and the Collector becomes a compliance boundary and a single point of failure. Sampling cuts volume and cost but the sampled traces still hold the secret, so it complements redaction rather than replacing it. A plain hash of an email is reversible by rainbow table because emails are low-entropy: use HMAC with a KMS-held key or a tokenization vault. A vendor BAA shifts contractual liability but the data still leaves your VPC; self-hosting keeps it inside and makes you own the audit. And if you genuinely cannot enumerate the sensitive fields, an allowlist breaks legitimate debugging: keep a separate, short-retention, access-controlled store for raw payloads instead of weakening the main pipeline.

With one week, I would ship the attribute allowlist and the canary test first. Those two catch everything the rest of the list is guessing at.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Secure trace context and baggage across trust boundaries.

Answer

Core answer (first 90 seconds). Treat traceparent, tracestate and baggage as untrusted network input. At each trust boundary, parse them strictly against the W3C formats, enforce count and size limits, and make an explicit decision: continue the incoming trace, restart it, or continue with a link to the original context. Never derive identity, tenant or authorization from any of these fields: they are caller-controlled strings. Allowlist the baggage keys you actually need, strip the rest before egress to third parties, and keep credentials and PII out of propagated context entirely. Then bound the cost: cap spans and cardinality per caller so a forged trace-id can't blow up your backend.

Why each field is spoofable. traceparent is version-trace-id-parent-id-flags, and nothing in it is signed. The sampled flag is bit 0 of the flags byte: a caller setting 01 forces your backend to record a trace (cost amplification), 00 suppresses one (observability loss). The trace-id is 16 bytes the caller chose, so a caller can join a trace they don't own, trace injection, or collide with a victim's trace-id to pollute their view. tracestate is a comma-separated list of vendor key/value pairs; the spec says the most recently updated entry goes leftmost and a vendor must not modify another vendor's entries. Conflicts arise when two proxies both rewrite the same key, or when a caller sends a key that collides with your vendor key: never trust the caller's value for a key you own. baggage is a plain key/value channel; the classic failure is a service reading baggage: tenant=acme and treating it as authoritative, which is a cross-tenant authorization bypass.

Restart vs continue. Restarting at ingress gives a fresh trace-id and immunity to injection, but you lose the causal link to the caller's trace: you can no longer see the caller's span as your parent. Continuing preserves end-to-end correlation but lets the caller join your trace. The middle ground OpenTelemetry supports is to start a new root span and attach a Link to the remote context: you keep the reference without trusting it as a parent.

Limits to enforce.

FieldLimitSource
traceparent55 chars; version 00; ff invalid; trace-id and parent-id must not be all zerosW3C Trace Context
tracestate≤32 list-members; key ≤256 chars; value ≤256 chars; drop rightmost when overW3C Trace Context
baggage≤180 entries; ≤8192 bytes totalW3C Baggage; OTel defaults OTEL_BAGGAGE_MAX_ENTRIES=180, OTEL_BAGGAGE_MAX_SIZE=8192
HTTP headernginx large_client_header_buffers default 4×8 KB; Envoy max_request_headers_kb default 60vendor defaults

Strict parse, then decide.

Python
import re

TRACEPARENT = re.compile(
    r"^(?P<version>[0-9a-f]{2})-"
    r"(?P<trace_id>[0-9a-f]{32})-"
    r"(?P<parent_id>[0-9a-f]{16})-"
    r"(?P<flags>[0-9a-f]{2})$"
)

def parse_traceparent(value: str):
    m = TRACEPARENT.match(value)
    if not m:
        return None                       # malformed -> restart
    if m["version"] == "ff":
        return None                       # ff is invalid per spec
    if m["trace_id"] == "0" * 32 or m["parent_id"] == "0" * 16:
        return None                       # all-zero ids are invalid
    return m.groupdict()

Trace: parse_traceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") matches, version is not ff, ids are non-zero, so it returns {'version': '00', 'trace_id': '4bf92f3577b34da6a3ce929d0e0e4736', 'parent_id': '00f067aa0ba902b7', 'flags': '01'}. parse_traceparent("ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") returns None on the ff check. parse_traceparent("00-00000000000000000000000000000000-00f067aa0ba902b7-01") returns None on the all-zero trace-id. parse_traceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7") returns None because the regex requires the flags field.

Failure modes and detection. Trace injection: alert on a trace-id appearing from more than one ingress peer, or a parent span whose service name doesn't match the peer. Cardinality explosion: per-ingress unique-trace-id and unique-baggage-key metrics; OTel's OTEL_ATTRIBUTE_COUNT_LIMIT (default 128) and span event/link limits (default 128 each) bound per-span damage, not per-tenant volume. Baggage authz bypass: grep for baggage reads in authorization paths and treat any hit as a bug. PII egress: allowlist baggage keys at the egress proxy; anything off the list is dropped before the third-party call. tracestate overflow: >32 entries or oversized values cause 400s at a downstream proxy. Watch the ingress 4xx rate.

What would change the decision. An authenticated peer over mTLS makes continuing the trace safe and preferable for correlation. A public-internet boundary means restart or link. If you genuinely need tenant context downstream, carry it in a signed token, not in baggage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design multi-tenant access and isolation for observability data.

Answer

Clarify first. "Tenant" here is the billing and blast-radius unit: usually a customer org, sometimes a team inside one. Two questions decide the design: is the isolation requirement contractual (a customer who must not share a disk with another), and is the data plane shared or per-tenant? Everything else follows from those.

Assumptions I'd state up front: shared control plane, shared data plane by default, one tenant per workload identity, and the collector fleet is trusted infrastructure while the network in front of it is not.

The core rule: derive tenant at a trusted boundary, never from the payload. A collector that reads tenant out of a resource attribute is trusting the sender. The identity should come from something the sender can't forge: a Kubernetes ServiceAccount token projected via TokenRequest (expirationSeconds: 3600, minimum 600), exchanged through STS AssumeRoleWithWebIdentity or a SPIFFE SVID, then mapped to a tenant by a lookup the platform owns. The collector stamps that as the X-Scope-OrgID header that Loki, Mimir and Tempo already use for tenancy. Everything the client sent (service.name, k8s.namespace.name, W3C baggage, tracestate) is untrusted input and gets dropped or allowlisted by an attributesprocessor/filterprocessor before the tenant stamp is applied.

Why server-side filtering is the mechanism, not a nicety. A tenant label on a series is only a claim until the query path enforces it. In Loki and Mimir the query frontend injects the tenant matcher from the authenticated X-Scope-OrgID and rejects a request whose header disagrees with the caller's identity, so the storage layer never sees a query without it. Filter in Grafana instead, a datasource with jsonData.httpHeaderName1: X-Scope-OrgID set per org, and you've moved the boundary into a UI the user can edit. Same mistake in Elasticsearch if you rely on a client-side filter rather than document-level security or a filtered alias.

Trade-offs, when not to isolate. Three tiers; the deciding criterion is the consequence of a leak, not tenant size:

TierStorageWhen
Shared index, tenant labelone TSDB / object prefix, row policy or RLSdefault; cheap, one query path
Shared cluster, per-tenant encryptionsame store, per-tenant KMS CMK + encryption contextcontractual separation, audit needs
Per-tenant cluster or bucketseparate store and credentialsregulated data, a neighbour no quota can contain

Per-tenant KMS keys run about $1/key/month plus request charges, so a 5,000-tenant fleet is real money: that's the argument for tier 1 until a contract says otherwise. Per-tenant clusters multiply operational surface; I'd only pay that when a quota genuinely can't contain the neighbour.

Failure modes and detection. Cardinality is the classic one: series = metric × every label combination, so http_requests_total{service,method,status,path} at 40 services × 5 methods × 8 statuses × 200 paths is 320,000 series for a single tenant. Cap it with Mimir's max_global_series_per_user or Loki's max_streams_per_user (default 5000) and alert on the ingester's discarded-samples counter with its reason label. Second: cross-tenant trace IDs. A traceparent from tenant A queried by tenant B; detect by asserting tenant on the trace's resource at query time, not only at ingest. Third: alert routing. A shared Alertmanager route that fans out on a label can page the wrong team; test it with a forged label. Fourth: shared caches. A query cache keyed without tenant hands back another tenant's result; key it on tenant.

Retention and deletion are per-tenant: Loki's retention_period in limits_config, Mimir's compactor_blocks_retention_period, Tempo's block_retention. Break-glass support access is a separate identity with approval, a TTL and an audit record: never a shared admin token.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Manage telemetry schema and semantic-convention changes.

Answer

Core answer (first 90 seconds)

Assume an OpenTelemetry pipeline into a Prometheus-compatible backend, the 15-day default retention, and SDKs you don't fully control: some services will pin an old SDK for months. Under those constraints a semantic-convention change is a schema migration, not a rename: version it, dual-emit for a bounded window, translate centrally where the mapping is exact, and delete the old form only after you can prove nothing reads it.

For the OTel HTTP rename introduced in semconv 1.21.0 and marked stable in 1.23.0:

old (≤1.20)new (≥1.21)
http.methodhttp.request.method
http.status_codehttp.response.status_code
http.urlurl.full
net.peer.nameserver.address
net.peer.portserver.port

These are the same field under two names. http.status_code and rpc.grpc.status_code are not, and must never be merged.

Dual-emit, then translate

OTEL_SEMCONV_STABILITY_OPT_IN=http/dup makes the SDK emit both attribute sets; http emits only the new one. For services you can't upgrade, translate in the Collector:

YAML
processors:
  transform:
    error_mode: ignore
    trace_statements:
      - context: span
        statements:
          - set(attributes["http.response.status_code"], attributes["http.status_code"]) where attributes["http.status_code"] != nil

error_mode: ignore matters: the default is propagate, and one failing statement drops the whole batch.

What the dual window costs (worked example)

50k spans/s, 12 attributes, ~40 bytes per key+value. Duplicating five renamed attributes adds 5 × 40 = 200 B/span → 10 MB/s → ~864 GB/day. A 30-day window is ~26 TB of extra ingest. That number is what turns "bounded" into a decision.

Failure modes and how you see them

  • Cardinality. http.status_code → http.response.status_code is cardinality-neutral; promoting url.full or server.address to a metric dimension is not. Watch prometheus_tsdb_head_series: one unbounded label can move a series count from 10^5 to 10^7.
  • Duplicate paging. During dual-emit both old and new series satisfy the same rule, so one incident pages twice. Count firing alerts per rule, not per series.
  • Silent reinterpretation. Never backfill new semantics onto old data. Keep the SDK version resource attribute (telemetry.sdk.version) as a label and refuse to aggregate across it, so a p99 mixing two definitions can't be computed by accident.
  • Dropped telemetry. otelcol_processor_dropped_spans climbing means the transform is failing on real payloads.

Proving equivalence

Run promtool test rules twice against the same input series (once with old metric names, once with new) and require identical exp_alerts. Group by telemetry.sdk.version to see which services still emit old names.

When to remove the old form

All three must hold: the new form is present on ≥99% of series for two full retention cycles (30 days at the 15-day default); a repo-wide grep finds no dashboard, alert or recording rule referencing the old name; and the rollback window has elapsed. Until then, keep both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Test observability instrumentation before release.

Answer

What a strong candidate says first

Clarify what "test the instrumentation" means: you are asserting the telemetry the app emits, not the app's behaviour. Assume OpenTelemetry SDK (Java 1.4x, Python 1.2x), OTLP/gRPC to an otelcol collector, Prometheus and Tempo behind it. The assertion target is emitted spans, metrics and logs, and the cheapest place to assert is an in-memory exporter inside a unit test.

Three layers, chosen by blast radius:

  • Unit: SDK in-memory exporter. Assert span names, attributes, status, metric values. Runs in milliseconds, catches most mistakes.
  • Integration: a real collector in a container, real OTLP export. Catches batching, sampling, resource attributes and exporter config.
  • Shadow: run new instrumentation beside the old in production and diff the two streams. Costs double ingest, so reserve it for high-cardinality or high-risk services.

Why the layers differ

Unit tests bypass the batch and export path entirely. BatchSpanProcessor defaults are queue 2048, batch 512, schedule delay 5000 ms, export timeout 30000 ms. A span dropped because the queue is full never reaches the in-memory exporter, so only the integration layer can catch it. Detection: the SDK logs a queue-full warning, and the collector exposes otelcol_receiver_refused_spans. Alert on both.

Worked check: checkout

POST /checkout has three outcomes. Counter checkout.requests{outcome}:

outcomeHTTPcounterspan status
success200+1UNSET
rejected402+1UNSET
error500+1ERROR + exception

The trap: a business rejection is not an error. If 402 sets span status ERROR, your error rate is wrong and every SLO built on it is wrong. Assert status explicitly.

Histogram http.server.duration uses the default explicit buckets [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] ms. A 3 ms request lands in (0, 5]. Assert bucket counts, not just sum and count: a wrong boundary passes a sum check and fails a percentile.

Failure modes and how you catch them

  • Route normalization: /users/12345/orders/678 must emit http.route=/users/{id}/orders/{id}. Raw paths explode label cardinality; assert the template, not the path.
  • Clock skew: span end before start gives a negative duration. Assert duration >= 0 and compare against a monotonic clock.
  • Invalid context: a malformed traceparent must start a new root span, not throw. Assert the request still succeeds.
  • Baggage: assert tenant baggage does not cross a tenant boundary, and that no Authorization header or PII appears in attributes or log bodies.
  • Collector outage: stop the collector, confirm the app stays within SLO (export is async and non-blocking) and that drops are visible rather than silent.

Trade-offs

Unit-only is right for a library with no network, no sampling and no collector. Integration is the minimum for anything shipping OTLP. Shadow verification costs double ingest and is worth it only where cardinality or privacy risk is high. Don't run the full matrix on every PR: unit on PR, integration nightly, shadow on release candidates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Measure instrumentation coverage and quality.

Answer

Core answer. Coverage is a ratio, and the denominator is the argument. One number is not enough: you need three, because each catches a different failure: what the catalog says should exist, what the edge actually saw, and what the payload is required to contain. Quality is a separate axis: a signal can be present, fresh, and still worthless because its labels exploded or its unit is wrong. Say up front which backends are authoritative (Prometheus for metrics, the trace store for spans, the log pipeline for events), the scrape interval, and what "expected" means for a service that legitimately has no traffic.

Three denominators.

denominatorsourcecheckact when
inventoryservice catalog (catalog-info.yaml, app.kubernetes.io/name)catalogued services with a live scrape targetany tier-1 service dark for > 2 scrape intervals
trafficEnvoy/ingress access logs, LB request countersedge requests with no matching span or metric> 0.5% of requests unaccounted over 1h
schemathe instrumentation contract (semconv version, unit, required resource attrs)spans missing service.name, metrics with non-base unitsany occurrence on a tier-1 service

Arithmetic. 240 catalogued services, 231 with a live target: 96.3% raw. But 12 are tier-1 and one is dark, so risk-weighted coverage is 11/12 = 91.7%. The raw number hides the one that pages you. Weight by blast radius, not service count.

Freshness. An instant query looks back 5m by default (--query.lookback-delta), so a series that stops receiving samples keeps returning its last value for up to five minutes: a naive "missing metric" alert fires long after the damage. With a 15s scrape interval, up == 0 for 1m detects a dead target in ~75s. For a target that stays up but stops emitting, check per series:

PROMQL
# had samples in the last hour, none in the last 5m
count_over_time(http_requests_total[1h] offset 5m) > 0
  unless
count_over_time(http_requests_total[5m]) > 0

# top 10 metric names by active series — your cardinality budget
topk(10, count by (__name__) ({__name__=~".+"}))

absent_over_time looks tempting here but fires only when every series of the metric is gone, so it misses one dead label combination.

Sampling is where coverage dies quietly. The OTel SDK default sampler is ParentBased(AlwaysOn): 100%, not 1%. Drops happen later: the batch span processor queues 2048 spans with a 5s schedule delay and discards on overflow; a Collector tail_sampling processor waits 30s (decision_wait) before deciding. So watch the SDK's dropped-span counter, not the exporter's success count: a green exporter behind a full queue is losing data.

Quality defects are bugs, not coverage gaps. A user_id label on a request counter, a unit that silently changed from milliseconds to seconds, a span with broken parentage. Give each an owner and a ticket, same as a 500.

Failure modes. Orphan spans with no parent: a context-propagation break at an async boundary or a message queue. Routes in edge logs but not in metrics: an endpoint shipped without instrumentation. Fresh but wrong telemetry: clock skew landing a span before its parent.

What changes the decision. If the edge logs are sampled or terminated at the CDN, the traffic denominator is unusable; fall back to synthetic canaries on the critical journeys. If the catalog is stale, fix it first: every coverage number derived from it is fiction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Make telemetry export failure-safe for the application.

Answer

Assumptions: OTel SDK in-process, OTLP export to a collector that can be down, slow, or rejecting. The thing you are protecting is the application's request path, not the telemetry pipeline.

Core answer. The invariant is: telemetry export must never block, slow, or OOM the request path, and loss must be visible rather than silent. You get that by making export asynchronous and bounded, and by making the drop path explicit. Retries, backoff and priority are tuning on top of that invariant, not the invariant itself.

Why bounded queues protect the request path. The batch processor's enqueue is O(1) and non-blocking: the request path hands a finished span to an in-memory queue and returns. A background thread drains the queue and does the network I/O. When the queue is full, the SDK drops the span and increments a counter: it does not block the caller. That is the mechanism. The request path's cost is independent of collector health.

Memory math. OTel's BatchSpanProcessor defaults are maxQueueSize 2048, maxExportBatchSize 512, scheduleDelay 5000 ms, exportTimeout 30000 ms. A span is roughly 1 KB in memory, so the queue is ~2 MB per process. If you "avoid drops" by setting maxQueueSize to 100,000, you have turned a 2 MB buffer into ~100 MB per process, and a slow collector now OOMs the app. The default is small on purpose.

Python
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

provider.add_span_processor(BatchSpanProcessor(
    OTLPSpanExporter(endpoint="http://collector:4317", timeout=10),
    max_queue_size=2048,          # default
    max_export_batch_size=512,    # default
    schedule_delay_millis=5000,   # default
    export_timeout_millis=30000,  # default
))

How retry storms form. If the exporter retries without backoff, every app instance hammers a down collector, the drain thread stays stuck in retries, and the queue fills faster. The OTLP exporter spec's defaults are 5 s initial backoff, 30 s max backoff, 300 s max elapsed time: after 300 s the batch is dropped, not retried forever. Jitter matters because N instances retrying on the same schedule synchronize into a thundering herd.

KnobDefaultWhat it bounds
maxQueueSize2048memory per process
maxExportBatchSize512per-request payload
scheduleDelay5000 msexport latency floor
exportTimeout30000 mstime a drain thread can block
retry max elapsed300 stotal retry lifetime

Failure modes and detection.

  • Collector down: queue fills, drop counter increments, request path unaffected. Detect via dropped-spans counter and queue depth.
  • Slow network: exportTimeout fires, batch retried, queue drains slower. Detect via export latency p99.
  • DNS failure: exporter fails fast, retries with backoff. Detect via export error rate.
  • Collector full disk: collector returns error, exporter retries, eventually drops. Detect via collector-side rejection metric.
  • Shutdown: flush with a bounded timeout; never block shutdown indefinitely.

Expose queue depth, drops by reason, export latency and error rate on a health path that does not depend on the collector.

What would change the decision. If a regulatory requirement says audit events must not be lost, do not elevate all telemetry: route those events to a separate durable channel (local WAL or disk-backed queue). Best-effort telemetry and durable audit are different requirements, so they get different mechanisms.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Monitor an observability pipeline end to end.

Answer

Core answer (say this first)

Assume a standard pipeline: SDKs → OTel Collector (receiver → processors → exporter) → backend (Prometheus/Tempo/Loki or a vendor) → query and alerting. I'd monitor four questions in order, because each one localises the next: is telemetry being produced, is it arriving, is it fresh, and can I still query and alert on it.

Per stage, the signals that actually decide something:

  • Producer: instrumentation coverage and SDK version per service. If a deploy ships with the SDK disabled, coverage drops before anything else moves.
  • Collector: otelcol_receiver_accepted_spans vs otelcol_receiver_refused_spans (refused means the collector is overloaded and is pushing backpressure to the SDK), and otelcol_exporter_sent_spans vs otelcol_exporter_send_failed_spans.
  • Queue: otelcol_exporter_queue_size against otelcol_exporter_queue_capacity (default 1000 for the OTLP exporter), plus queue age.
  • Backend: up and scrape_duration_seconds per target, prometheus_tsdb_head_series for cardinality, write/read errors, compaction, retention (Prometheus default 15d).
  • Query and alert: p99 query latency, alert evaluation failures, notification delivery.

Why queue age, not depth

Depth alone lies. With the default 1000-slot queue, a slow backend can hold depth at 900 indefinitely while every record sits 20 minutes before export: you are not dropping, you are just late, and late telemetry breaks alerting. Age is the signal that catches it: alert when the oldest queued item exceeds your freshness SLO, say 60s.

Reconciliation localises loss

Counts at each hop should match. Producer emits 1,000,000 spans/min; receiver accepted 998,000; exporter sent 997,500; backend ingested 997,400. The gaps tell you where: 2,000 refused = collector CPU or memory limit; 500 send_failed = backend rejecting (auth, 429); 100 ingested short = backend write path. Without the chain you only know "numbers are down".

Trade-off: self-monitoring vs external probe

A collector scraping itself, and Prometheus scraping itself, both go blind when the backend is down: exactly when you need them. External probes (a separate Prometheus, or a blackbox exporter hitting a canary endpoint) survive that, at the cost of a second stack to run and pay for. Decide by blast radius: pay for external on the alert-delivery path, accept self-monitoring elsewhere.

Failure modes and how you'd see them

  • Credential expiry: send_failed climbs with 401/403; a canary span stops arriving. Detect with a synthetic span every minute and an alert on its absence.
  • High cardinality: prometheus_tsdb_head_series grows without a matching traffic increase; memory and query latency follow.
  • Log flood: collector CPU saturates, queue age rises, refused climbs.
  • Silent gap: reconciliation shows producer > backend with no error counter moving. Usually a dropped pipeline in config.

SLOs and fault testing

Set an ingest SLO (99.9% of spans queryable within 60s) and capacity limits per collector. Fault-test by killing a collector, expiring a credential, and replaying a backfill: checking that recovery produces no duplicate alerts and no silent gap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design a resilient telemetry collection and export architecture: how do you deploy and scale collectors, buffer and apply backpressure when a backend is slow, fail over between backends or regions, and bound memory and disk while limiting data loss?

Answer

Two tiers, and only the second one is durable. A node-agent tier (DaemonSet, one Collector per node) does the cheap node-local work: OTLP receive, k8sattributes and resource detection, batching, a short in-memory queue. A gateway tier (Deployment behind a Service, 3+ replicas) does the expensive and stateful work: tail sampling, credential injection, persistent queue, fan-out to backends. The agent never holds a backend credential and never buffers to disk: node disks are ephemeral, and a lost node is an accepted loss window. Durability lives on the gateway, on a PVC.

Agents route to gateways with the loadbalancing exporter, routing_key: traceID, so every span of a trace lands on the same gateway. Without that, tail sampling sees partial traces and makes wrong keep/drop calls.

Backpressure is a chain, not a setting. Backend slows → gateway exporter queue fills → exporterhelper blocks the pipeline → the OTLP receiver's Consume call blocks, so the agent's request hangs to timeout → the agent's exporter queue fills → the SDK's BatchSpanProcessor queue fills and starts dropping spans. Every link is bounded, so the system degrades by dropping newest data instead of OOMing. memory_limiter is the hard stop: it refuses data at limit_mib rather than letting the process get OOM-killed.

yaml

OpenTelemetry Collector v0.100+ (contrib)

processors: memory_limiter: check_interval: 1s limit_mib: 1600 # container limit 2Gi, leave headroom spike_limit_mib: 400 exporters: otlp/gateway: endpoint: otel-gateway.obs.svc:4317 sending_queue: enabled: true num_consumers: 10 queue_size: 5000 storage: file_storage # gateway tier only retry_on_failure: enabled: true initial_interval: 5s max_interval: 30s max_elapsed_time: 0 # retry until the queue drains or fills extensions: file_storage: directory: /var/lib/otelcol/queue compaction: { on_start: true, on_rebound: true }

Sizing is arithmetic. 200 nodes at 50k spans/s, ~500 B/span, is 25 MB/s. A one-hour backend outage needs 90 GB of buffer; across 3 gateways, 30 GB each. If that is more disk than you will pay for, you have chosen your loss window: make it a sampling decision (drop debug spans first) rather than an accident.

Failover: the failover connector sends to a primary region and switches to a secondary on error, by priority level. Do not fan out to both by default; that doubles ingest cost and leaves you with two partial datasets. Retry semantics bite harder than people expect: retry_on_failure.max_elapsed_time defaults to 5 minutes, so a 20-minute outage silently drops everything queued unless you set it to 0 and let the persistent queue be the bound.

Failure modes and detection: memory_limiter refusals show as otelcol_processor_refused_spans; queue saturation as otelcol_exporter_queue_size pinned at queue_size; gateway PVC exhaustion as write errors plus disk alerts. Scale the gateway on queue-size ratio, not CPU: CPU stays flat while the queue grows, so a CPU HPA will not fire during the incident you built it for.

When not to: under ~20 nodes in one region with a highly available backend, one gateway tier (or sidecar collectors) is enough; the second tier buys tail sampling and credential isolation you may not need yet.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Capacity-test an observability backend.

Answer

Assumptions and the direct answer

Assume a Prometheus-compatible metrics TSDB scraped every 15s, a Loki-style log store, a Tempo-style trace store, multi-tenant, 15-day retention, and an SLO of p99 instant query under 2s and p99 6-hour range query under 5s. Capacity testing is finding the ingest rate, active-series count and query concurrency at which those SLOs still hold with headroom, and proving that past that point the system sheds load visibly instead of silently dropping data.

Do the arithmetic first. 1M active series at a 15s scrape is 66,700 samples/s. Prometheus TSDB compresses to roughly 1–2 bytes per sample, so that is ~11.5 GB/day and ~170 GB for 15 days before index overhead. That number sets the disk and the retention decision; the test is about what breaks it.

Load stages (figures hypothetical, scaled to your fleet):

stageingestactive seriesquery loadwhat it proves
baseline66k samples/s1M5 qpsSLOs hold, headroom measured
2x133k samples/s2M20 qpswhere head-block memory and compaction lag appear
churn attack66k samples/s+500k new/min5 qpsindex memory growth from unique labels
incident burst66k samples/s1M200 qps, 6h rangesquery queueing and alert evaluation delay

Why churn is the real enemy. Every new label combination creates a series with its own in-memory entry: a few KB of heap each in the head block. 500k new series/min adds ~1–2 GB/min of heap that only drops when those series go stale (default 5 min). That is how a unique-label attack takes down a metrics backend: not ingest bytes, but series cardinality. Detect it with prometheus_tsdb_head_series and per-tenant series counts, and cap it with per-tenant series limits that reject at the distributor rather than OOM the ingester.

Sampling trade-off. Head-based sampling decides at trace start, so it cannot keep the slow or errored traces you actually want: it biases your tail-latency data. Tail-based sampling buffers every span until the trace completes, which costs memory proportional to spans-in-flight and needs all spans of a trace to reach the same collector. Under load, choose: head-based at a low rate plus always-sample-on-error, or tail-based with a bounded buffer and an explicit drop policy. State which, and test that the drop is counted.

Failure modes to force and detect:

  • Ingester OOM from cardinality → head_series climbing, scrape targets returning 429.
  • Compaction falling behind → growing block count, query latency rising on old data.
  • Alert evaluation delay → rule_evaluation_duration_seconds p99 crossing the evaluation interval, meaning alerts fire late.
  • Silent loss → compare a known synthetic series' sample count against expected; if the gap is not accounted for by a dropped-samples counter, loss is invisible, which is the worst outcome.

Deciding criteria. Block vs shed: block (429 at ingest) when the tenant is over quota and you can tell them; shed (drop low-priority series) only when you have already committed to a priority scheme and can expose the loss. Drop vs downsample for retention: downsample when you need the shape of old data for capacity trends; drop when the data is only for debugging and the cost is real.

Then verify recovery. Restore from a snapshot, backfill a gap, and confirm catch-up does not re-fire alerts: dedupe by alert fingerprint and check ALERTS does not flap. Repeat the whole run after any schema or backend change.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Control observability cost without destroying incident evidence.

Answer

First 90 seconds

Assumptions I would state out loud: hosted Prometheus (or Thanos/Mimir) for metrics, an OpenTelemetry Collector fleet, Loki or Elasticsearch for logs, Tempo or Jaeger for traces; 15-day metric retention, 30-day log retention; one hard SLO on the checkout path; security and audit logs carrying a one-year obligation. Before cutting anything I pull per-signal spend, because the split decides the plan. In most stacks metrics dominate, but that is a measurement, not a belief.

Core answer: attack label cardinality and duplicate instrumentation first, because that removes cost without removing a datum you would use in an incident. Tier retention second. Sample third, and only with a policy that keeps every failure. SLO metrics and audit logs are never in scope.

Why cardinality is the first lever

A Prometheus series count is the product of the distinct values of its labels. A request-latency histogram scraped per pod with 5 methods x 4 statuses x 20 routes writes 5 x 4 x 20 x (12 buckets + _sum + _count) = 5,600 series per target. Across 2,000 targets that is 11.2M active series, or 11.2M x 1,440 = 16.1 billion samples a day at a 1-minute scrape. The same latency, aggregated by a recording rule that drops instance and pod:

- record: service:http_request_duration_seconds_bucket:rate5m
  expr: sum by (service, route, status, le) (rate(http_request_duration_seconds_bucket[5m]))

is 5 x 4 x 20 x 14 = 5,600 series in total, a 2,000x reduction, 8.1M samples a day. Nothing you alert on disappears; per-pod detail stays in traces and in per-instance health metrics. At a hypothetical $0.001 per active series per month, that is $11,200/month versus $5.60 - plug your own contract number in.

Tail sampling, and what it costs

Head sampling at 1% throws away 99% of your errors. Tail sampling buffers the whole trace and decides at completion, so 100% of ERROR traces and anything slower than 2s can be kept while baseline traffic drops to 1%. The OTel Collector tail_sampling processor defaults to decision_wait: 30s and num_traces: 50000 held in memory.

processors:
  tail_sampling:
    decision_wait: 30s
    num_traces: 50000
    policies:
      - name: errors
        type: status_code
        status_code: {status_codes: [ERROR]}
      - name: slow
        type: latency
        latency: {threshold_ms: 2000}
      - name: baseline
        type: probabilistic
        probabilistic: {sampling_percentage: 1}

Every span of a trace must reach the same collector, or replicas decide independently and you get half-traces. Route with the load-balancing exporter on routing_key: traceID before the sampler.

Failure modes, with the signal that catches them

FailureDetectionWhat it costs you
A new or un-templated route shipsprometheus_tsdb_head_series up more than 10% hour over hour; scrape_samples_scraped above its 7-day p99Query timeouts during the incident you are debugging
Error paths return HTTP 200 with an error body, so the status_code policy never matcheskept-trace error ratio diverges more than 20% from http_requests_total{status=~'5..'}Errors invisible in traces while metrics still show them
Retention shorter than the failure's recurrencepostmortems record the age of the oldest artefact used; p95 approaching retention triggers an extensionYou cannot compare this outage to the last one
A retry loop at 100k lines/s fills the collector queueotelcol_exporter_queue_size per signal, plus an alert on a series gap no drop counter explainsMetrics dropped, SLO dashboard dark mid-incident

Degradation order, then proof

When the budget is breached, ahead of any hard limit: drop debug and trace-level logs at the collector; cut baseline trace sampling from 10% to 1%; stretch low-value scrapes from 15s to 60s; disable non-SLO recording rules. Never degrade burn-rate SLO metrics, audit logs, or error traces.

Then prove it still works. In a canary namespace, fail a dependency for 5 minutes and check three things: the burn-rate alert fired inside 2 minutes, the failing span is retrievable at the new sampling rate, and the downstream error line is queryable from cold storage. Compare the measured time-to-detect against your last real incident. If it got worse, roll back.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Migrate observability vendors without losing operational capability.

Answer

Assume a two-week dual-run that contains at least one real incident or game day, budget for roughly +10% ingest, and no cross-vendor query federation: you compare with scripts and spreadsheets, not one UI. This is two migrations: instrumentation and pipeline, which are yours and portable, and query semantics, storage and alert delivery, which are not. Mix them and you have changed vendors without gaining a way to leave the next one.

The order that survives contact: move to OpenTelemetry SDKs plus a collector tier you own; dual-export from the collector; port dashboards, SLOs and alert rules and prove them against replayed windows; cut over per service and per signal; keep read access to the old backend until the longest investigation window closes.

Step one buys the option to fail. With OTLP into an OpenTelemetry Collector, swapping backends is editing one exporter (otlp/old, otlp/new, gRPC on 4317 or HTTP on 4318) and vendor behaviour becomes configuration you can read instead of agent code you cannot.

Sizing the dual run, hypothetically: a service at 900 req/s with 14 spans per request emits 12,600 spans/s; at roughly 400 bytes per OTLP span that is 5 MB/s, or 435 GB/day. A tail-sampling tier that keeps 10% with random sampling plus always-keep on errors and on latency above 500 ms sends the new backend about 45 GB/day, so the dual run costs roughly +10% ingest, not +100%.

YAML
tail_sampling:
  decision_wait: 30s    # 12,600 spans/s buffered for 30 s is ~380k spans resident
  num_traces: 50000
  policies:
    - name: errors
      type: status_code
      status_code: {status_codes: [ERROR]}
    - name: slow
      type: latency
      latency: {threshold_ms: 500}
    - name: sample
      type: probabilistic
      probabilistic: {sampling_percentage: 10}

Every span of a trace must reach the same collector process or decisions split, so put the loadbalancing exporter with routing_key: traceID in front rather than round-robin, and watch collector memory. Tail sampling holds the whole trace until decision_wait expires.

Then prove parity per signal, one comparator each:

signalcomparatorpass when
tracesdiff the waterfall for 20 trace IDs present in both backendsidentical span count and parent-child topology
metricssame 1 h window, same servicep99 in the same bucket; counter rate within 1%
logstop 20 fields, field by fieldsame parsed-to-unparsed ratio
alertsreplay the incident windowrule fires within one evaluation interval, on the same route

Failure modes that actually cost capability, and how they show up. Spans vanishing silently: the exporter's sending_queue fills, otelcol_exporter_queue_size pins at its limit (queue_size defaults to 1000) and otelcol_exporter_send_failed_spans climbs, while the application never notices. Alert on the gap between otelcol_receiver_accepted_spans and otelcol_exporter_sent_spans. Dashboards going blank after an SDK upgrade: semantic conventions v1.20.0 renamed http.status_code to http.response.status_code and http.method to http.request.method, so charts and rules keyed on the old names silently return nothing; add a no-data alert per dashboard before cutover. Metric math shifting: a backend that stores pre-computed quantiles cannot re-aggregate p99 across services, and different histogram bucket boundaries change histogram_quantile and the SLO burn-rate arithmetic, so compare bucket boundaries, not chart shapes. Alert delivery is capability too: Alertmanager group_wait, group_interval, repeat_interval, inhibition and silences must be recreated, and one rule that fires only in the old tool is the thing you lost.

At the edge, do not trust an inbound traceparent from the public internet: a client that picks your trace IDs picks your cardinality. Generate a new trace ID there and restart the trace on malformed input, per the OTel specification.

Cut over one service at a time, then one signal at a time, gated on flat error rate and no un-replayed rule. Keep the old backend readable for one full investigation window (30 to 90 days, matching your postmortem and audit practice) because traces get pulled into postmortems long after the last span was written.

Curated: · Written: · Reviewed:

Difficulty: Hard