Observability and Monitoring Architecture Questions
Building visibility into infrastructure and services: metrics, logs, and traces, dashboards and alerting, SLIs/SLOs, and the design of an observability stack. Covers instrumenting systems for actionable signal, reducing alert noise, and diagnosing production issues from telemetry. Infrastructure-wide observability, distinct from network-specific monitoring.
Design a cross-signal correlation index that lets an engineer jump quickly from a metric anomaly to the relevant logs and traces for root-cause analysis. What identifiers would you require every signal to carry, how would you build and maintain that mapping, and how would you keep queries across systems fast at scale, including when an identifier is missing?
Sample Answer
Direct answer
Require every signal (metric, log line, trace span) to carry a small set of common identifiers, most importantly trace_id (or a request/correlation ID where full tracing isn't wired up yet), plus service_name and a timestamp. Build a lightweight mapping index, keyed by those identifiers, that points to where each related log or span physically lives (shard, offset, time range) rather than storing the events themselves twice. When an identifier is missing, fall back to narrowing by time window and service first, then use a scored, probabilistic match on top of that narrowed candidate set instead of searching the whole corpus.
Structured elaboration
Required identifiers per event:
trace_id/span_id: the strong identifier, present when full distributed tracing is instrumented.service_name,host_or_pod_id: contextual keys usable even when tracing isn't present.event_timestamp: needed for the time-window fallback and for ordering.metric_dimensions/anomaly_id: on the metrics side, the anomaly detector emits an anomaly document carrying whatever identifiers were present on the underlying series.
Index structure, not a duplicate copy: the mapping store is a pointer index (topic/partition/offset for logs, trace/span ID for traces), not a second copy of log or trace bodies. Logs and traces stay in their existing systems (search index, trace store); the correlation index only tells the query which shard and offset to fetch.
Query flow:
- Direct ID lookup, if the anomaly carries a
trace_id: O(1) pointer lookup into the mapping store. - Indexed search, if not: query the log/trace index filtered by
service_nameand a time window around the anomaly. - Probabilistic fallback, if identifiers are sparse: score candidates from step 2 by temporal proximity, shared host, and payload fingerprint, and return ranked results with a visible confidence, not a silent best guess.
flowchart LR
A[Metric anomaly] --> ID{trace_id present?}
ID -- yes --> M[(Mapping index: id -> pointer)]
M --> L1[Fetch log/trace by pointer]
ID -- no --> TW[Filter: service + time window]
TW --> SC[Score candidates: proximity, host, fingerprint]
SC --> L2[Ranked candidates + confidence]
Maintaining the mapping: on ingest, if a strong identifier is present, upsert a bounded (capped) pointer list into the mapping store for that ID and set a TTL matching the signal's own retention. A background job prunes expired entries so the index doesn't grow unbounded past what the underlying logs and traces themselves retain.
Worked example
Index sizing. Assume the cluster produces 50,000 events/sec across logs and trace spans combined:
eventsPerDay=50,000×86,400=4.32×109Each mapping entry (topic, partition, offset, timestamp, service ID) is about 40 bytes:
indexBytesPerDay=4.32×109×40 bytes=172.8 GB/dayAt a 7-day retention window matching typical hot log retention:
indexBytesRetention=172.8×7=1,209.6 GB≈1.21 TBThis is the number that justifies capped pointer lists and TTL-based pruning in the design above: an unbounded, uncapped index at this event rate would grow past a terabyte inside a week even though it stores no event bodies, only pointers.
Fallback candidate-set size when the identifier is missing. With 200 services sharing the 4.32×109 daily events roughly evenly:
eventsPerServicePerDay=2004.32×109=21,600,000Narrowing to a ±2.5s window (5s total) around the anomaly timestamp before service-level scoring:
timeReductionFactor=586,400=17,280 candidateSetSize=17,28021,600,000=1,250 eventsFiltering by service and a 5-second window before running any fuzzy scoring shrinks the search space from 21.6 million events/day for that service down to about 1,250 candidates, small enough for a scoring pass to run against on every anomaly without scanning the full day's log volume.
Trade-offs & pitfalls
| Fallback stage | Precision | Cost | When it's needed |
|---|---|---|---|
| Direct ID lookup | Exact | O(1) | trace_id present (the common case in fully-instrumented services) |
| Service + time window | Approximate, but bounded | O(candidates), here ~1,250 | trace_id missing, service known |
| Fuzzy scoring | Ranked, with confidence | O(candidates) scoring passes | trace_id missing and multiple plausible matches remain |
Common wrong turns: treating the mapping index as a full copy of the underlying signals instead of a pointer index (this doubles storage for no correlation benefit and creates a second source of truth to keep consistent); running the fuzzy-scoring pass over the entire day's events instead of narrowing by service and time window first, which turns an O(1,250) scoring problem into an O(21,600,000) one for no accuracy gain; and silently returning the single top-scored fuzzy match without surfacing its confidence, which looks like a correlation but is actually a guess an on-call engineer has no way to sanity-check.
Design the mechanics of tail-based sampling at real scale, say 100,000 traces per second: spans have to be buffered somewhere until the sampling decision can be made, slow or erroneous traces need their full span set captured, and everything else gets thinned. How do you coordinate that buffering and decision-making across many collector instances without unbounded memory growth?
Sample Answer
The key mechanic is consistent-hash routing by trace_id at the load balancer, so every span belonging to a given trace lands on the same collector instance and no cross-collector coordination is needed to assemble a trace before deciding whether to keep it. Memory is then bounded with a fixed decision window plus per-shard and per-trace caps, not by trying to hold every trace indefinitely.
Coordination architecture
flowchart LR
A[Application Spans] --> B[Load Balancer: hash by trace_id]
B --> C[Collector Shard 1: buffer]
B --> D[Collector Shard 2: buffer]
B --> E[Collector Shard N: buffer]
C --> F[Sampling Decision Engine]
D --> F
E --> F
F -->|keep| G[Export Full Trace]
F -->|drop| H[Discard]
F -->|timeout| I[Partial-Trace Fallback]
Because routing is consistent-hash on trace_id, adding or removing collectors only reshuffles a small fraction of trace-to-collector assignments (standard consistent-hashing property), so scaling the fleet doesn't require a coordinated rebalance of in-flight traces.
Sizing the buffer
Take the stated 100,000 traces/sec, an average of 20 spans/trace (a typical microservice call depth), an average compressed span size of 500 bytes (a labeled assumption), and a 10-second decision window (wait up to 10 seconds after a trace's apparent last span before deciding, which covers the large majority of trace completion times):
traces_per_sec = 100_000
avg_spans_per_trace = 20
avg_span_bytes = 500
decision_window_s = 10
num_collectors = 50
span_rate = traces_per_sec * avg_spans_per_trace # 2,000,000 spans/sec
spans_buffered_systemwide = span_rate * decision_window_s # 20,000,000 spans
bytes_buffered_systemwide = spans_buffered_systemwide * avg_span_bytes # 10 GB
spans_per_collector = spans_buffered_systemwide / num_collectors # 400,000 spans
bytes_per_collector = spans_per_collector * avg_span_bytes # 200 MB
At 50 collectors, each instance buffers about 400,000 spans (200 MB), a footprint that fits comfortably in a modest container (2-4 GB), while the system-wide live buffer is about 10 GB spread across the fleet. This is the concrete argument for sharding by trace_id: a single collector holding the full 10 GB buffer would need a memory profile most container platforms would flag as oversized, while 50 shards each holding 200 MB is unremarkable.
Bounding memory beyond the happy path
The 10-second window handles typical traces, but slow or stuck traces need explicit handling so they don't grow the buffer without bound:
- Per-trace TTL: destroy a trace's buffer if no new span arrives within some multiple of the decision window (e.g., 2x), forcing a decision (keep as partial, or drop) rather than waiting indefinitely.
- Per-shard memory cap with eviction: each collector enforces a hard memory ceiling; if exceeded, evict the lowest-priority buffered traces first (e.g., traces with no error/latency signal yet) rather than failing open.
- Global admission control: a lightweight control-plane process aggregates each collector's buffer occupancy and kept-rate on a slow control loop (seconds, not per-request) and adjusts the decision window or sampling probability fleet-wide if the system is trending toward the memory ceiling, rather than each collector reacting in isolation and potentially over-correcting.
Decision logic
- Cheap deterministic rules first (status code indicates an error, latency exceeds a fixed threshold): mark "must keep" immediately without waiting for the full window, since these are unambiguous.
- For everything else, wait out the decision window, then apply either a lightweight scoring model (feature-based, comparing this trace's shape against a recent rolling baseline) or a straightforward probabilistic sample at a rate tuned to the fleet-wide keep-rate budget.
- On TTL expiry before a full decision, export whatever spans were captured as a partial trace rather than silently dropping everything; a partial error trace is still more useful for incident response than nothing.
Trade-offs and pitfalls
- The most common design mistake is trying to coordinate the sampling decision across collectors (e.g., a central service that all collectors ask before deciding); at 2,000,000 spans/sec that coordination service becomes the bottleneck. Consistent-hash-by-
trace_idavoids this entirely by guaranteeing the decision can be made locally. - A fixed decision window is a trade-off, not a free parameter: too short and slow-but-successful traces (a legitimately slow but non-erroring downstream call) get truncated into partial traces; too long and the buffer grows for no benefit on traces that were always going to be dropped.
- Eviction policy under memory pressure needs to bias toward keeping traces that already show error/latency signal; a naive LRU eviction can evict exactly the traces you most want to keep just because they arrived earlier.
- Rebalancing collector count changes which shard owns which traces going forward, but in-flight traces already buffered on their original shard need to either finish there or be explicitly drained; a hash-ring change that silently orphans in-flight buffers loses those traces' decisions.
What does the OpenTelemetry Collector actually do inside a telemetry pipeline? Walk through what a receiver, a processor, and an exporter are each responsible for, and explain when you'd deploy the collector as a per-host agent versus a central gateway.
Sample Answer
Direct Answer
The OpenTelemetry Collector is a pipeline with three stages: a receiver takes telemetry in (from an app via OTLP, or by scraping an endpoint), a processor chain transforms it in flight (batching, filtering, enriching), and an exporter sends it out to one or more backends. Deploy it as a per-host agent when you want telemetry to leave the host already batched and lightly processed; deploy it as a central gateway when you want heavier processing (like sampling decisions that need to see traffic from many sources at once) done in one place instead of duplicated on every host.
Structured Elaboration
Pipeline diagram
flowchart LR
A["Instrumented App"] -->|"OTLP"| R["Receiver"]
R --> P["Processor Chain: batch, filter, enrich"]
P --> E["Exporter"]
E --> B1[("Backend A")]
E --> B2[("Backend B")]
Receiver
Accepts telemetry in a given format and protocol, most commonly the OTLP receiver (gRPC or HTTP) for data pushed from an instrumented application, or a Prometheus-style receiver that scrapes metrics endpoints on a schedule. A single collector can run multiple receivers at once.
Processor
Sits between receiver and exporter, transforming data without changing where it came from or where it's going. Common processors: batch (groups items to amortize per-request overhead, see the worked example), memory_limiter (sheds load before the process runs out of memory), attributes (adds, renames, or redacts fields), and sampling processors (drop a fraction of data by a configured rule).
Exporter
Sends processed telemetry to one or more backends in whatever protocol that backend expects (Prometheus remote-write, OTLP to a vendor, a file, and so on). A pipeline can fan out to multiple exporters from the same processed stream.
Agent versus gateway
An agent runs on or near every host (often as a DaemonSet), doing initial receipt and light processing close to the source. A gateway is a smaller number of centrally deployed instances that agents forward to, doing heavier fleet-wide processing (tail-based trace sampling needs to see many sources at once to decide, which an agent working alone cannot do) before the final export.
Worked Example
Consider sending spans without the batch processor, one OTLP request per span, versus with it, spans grouped into batches of 500 before a single request.
Assume each request carries a fixed protocol/framing overhead of roughly 1,024 bytes (headers, envelope) and each span payload is roughly 500 bytes (a stated design input, not a measured wire capture).
Without batching, one span per request:
overhead fraction=1,024+5001,024=1,5241,024≈67.2%Roughly two-thirds of every byte sent is framing overhead, not span data.
With batching, 500 spans per request:
payload=500×500 B=250,000 B,overhead fraction=1,024+250,0001,024≈0.41%The batch processor takes the overhead fraction from about 67% down to about 0.4%, which is the concrete reason batching sits in almost every collector pipeline by default rather than being an optional tuning step.
Trade-offs and Pitfalls
Running the collector as an agent everywhere is simple to reason about but limits what any single instance can see: it cannot make a decision (like tail-based trace sampling) that depends on data arriving at a different host. That kind of decision needs a gateway tier the agents forward to.
Too large a batch size trades throughput efficiency for latency: a batch that only flushes every few seconds under low traffic delays every piece of telemetry inside it by that long, even though the framing-overhead math above still favors big batches under high traffic. Most collector configurations flush on whichever comes first, a size threshold or a time threshold, exactly to avoid this under low load.
A processor chain's order matters and is easy to get wrong: a memory_limiter should run early (to shed load before spending CPU on later processors), and a batch processor should generally run late, right before the exporter, so it only batches data that already survived filtering or sampling decisions rather than wasting batch capacity on data about to be dropped.
Design the aggregation and partitioning strategy for a horizontally scalable time-series database that needs efficient single-metric queries at long retention. How would you choose sharding keys (metric name versus specific label sets), handle replication, and separate the read path from the write path, while avoiding hot shards?
Sample Answer
Direct answer
Shard primarily by metric name so a single-metric query only ever touches one shard, but split the shard's key space with a secondary hash over the label set so one enormously popular metric doesn't overload the shard that owns it. Separate the write path (append-heavy, needs low-latency durable ingestion) from the read path (needs efficient range scans and can tolerate a small replication lag) by giving reads their own replica tier, and detect hot shards from live load metrics rather than assuming the initial hash assignment will stay balanced as traffic shifts.
Structured elaboration
Primary sharding key: metric name. shard=hash(metric_name)modN. This keeps all time-series for one metric co-located, so "give me this metric's values" is a single-shard query instead of a scatter-gather across the whole cluster, which is the dominant query pattern this design optimizes for.
Secondary partitioning: label set, within a metric. Inside the shard(s) a metric owns, further split by hash(sorted_label_pairs) into K sub-partitions. This only matters for metrics whose write volume alone would overload a single shard; low-traffic metrics don't need it.
Replication: replication factor 3 across availability zones, quorum writes for durability (a write acknowledges once a majority of replicas confirm), asynchronous replication to read replicas that can serve slightly stale reads for range queries that don't require strict recency.
Read/write path separation: writes go to the shard leader's write-ahead log and in-memory segment; reads for recent data can be served from the leader or a follower depending on the caller's consistency requirement, and reads for long-range historical queries hit compacted, downsampled cold storage rather than the hot write path at all.
Rebalancing: use virtual nodes (many small virtual shards mapped onto fewer physical nodes) so that splitting a hot shard means moving a subset of its virtual nodes to other physical nodes, not re-hashing the whole ring.
flowchart LR
W[Writes] --> L[Shard leader: WAL + in-memory segment]
L -- quorum ack --> F1[Follower replica]
L -- quorum ack --> F2[Follower replica]
R[Range / historical reads] --> C[(Compacted cold storage)]
R2[Recent reads] --> F1
Q[Single-metric query] --> RT["Ring lookup: hash(metric_name)"]
RT --> L
Worked example
Assume 10,000,000 writes/sec cluster-wide across N=64 shards. If load were perfectly uniform, average shard load would be:
avgShardLoad=6410,000,000=156,250 writes/secSharding by metric name alone. Suppose one metric name (a widely-instrumented per-request counter) carries 8% of all cluster writes:
hotMetricWrites=0.08×10,000,000=800,000 writes/secBecause that entire metric maps to one shard under pure metric-name hashing, that shard's load is roughly the hot metric's full volume plus its normal share of other metrics:
hotShardLoad≈800,000+156,250=956,250 writes/sec avgShardLoadhotShardLoad=156,250956,250=6.12× the average shardThat shard is running over 6x hotter than every other shard in the cluster, purely from metric-name hashing.
Adding secondary label-hash partitioning (K=16 sub-partitions for this one metric):
perSubPartitionWrites=16800,000=50,000 writes/sec shardLoadAfterSplit≈50,000+156,250=206,250 writes/sec avgShardLoadshardLoadAfterSplit=156,250206,250=1.32×Splitting the hot metric's writes across 16 label-hashed sub-partitions brings its owning shards from 6.12x average load down to 1.32x, close enough to average that normal rebalancing headroom absorbs it. The insight worth stating explicitly: the number of sub-partitions K should scale with a metric's observed write share, not be a fixed constant applied uniformly, since a metric carrying 0.1% of traffic never needed splitting in the first place.
Trade-offs & pitfalls
| Sharding strategy | Single-metric query | Hot-metric protection | Rebalance cost |
|---|---|---|---|
| Metric name only | 1 shard, fast | None: any popular metric is a hot shard | Low, rare |
| Label set only | Scatter-gather across shards | Even by construction | Low |
| Metric name + secondary label split (this design) | 1 shard for low-traffic metrics, bounded fan-out for hot ones | Good, tunable per metric | Moderate: needs live monitoring to decide K |
Common wrong turns: applying secondary label-set splitting to every metric uniformly, which turns even low-traffic single-metric queries into unnecessary scatter-gathers across K sub-partitions for no load-balancing benefit; treating quorum-write durability and hot-shard mitigation as unrelated concerns when a hot shard under quorum writes also means its followers are under proportionally more replication load, compounding the imbalance; and rebalancing by re-hashing the whole ring on every detected hot shard instead of moving individual virtual nodes, which causes a much larger and slower data migration than the imbalance warranted.
Set a concrete retention and downsampling policy for metrics and traces that balances cost against query fidelity, for example raw metrics for 14 days, downsampled metrics for a year, full traces for 30 days then sampled. Walk through your rationale and what it means for the kinds of queries you can still answer after each window closes.
Sample Answer
Set the policy by working backward from what each query pattern actually needs, then verify the storage savings with the arithmetic rather than picking round numbers and hoping. A reasonable concrete policy: raw metrics at native resolution for 14 days, 5-minute rollups for 1 year, hourly rollups for years 2 through 5; full traces for 30 days, then 1% sampled for the following 11 months.
Rationale by window
flowchart LR
A[Raw ingest: native res] -->|14 days| B[Raw tier: hot]
B -->|downsample| C[5-min tier: 1 year]
C -->|downsample| D[Hourly tier: years 2-5]
D -->|expire| E[Deleted]
F[Trace ingest] -->|30 days full| G[Full trace tier]
G -->|sample 1%| H[Sampled trace tier: 11 months]
- 14 days raw: covers essentially all incident debugging, since almost every retro or root-cause investigation happens within two weeks of the event, and alerting needs full resolution on recent data to avoid missing short spikes.
- 1 year at 5-minute rollups: supports capacity planning and seasonal comparisons (week-over-week, month-over-month) without needing per-second precision; 5 minutes is short enough to still show diurnal patterns clearly.
- Years 2-5 at hourly rollups: supports long-term trend and year-over-year growth analysis; anything finer than hourly at this age is rarely queried and expensive to keep.
- 30 days full traces: matches the raw-metrics window for the same reason, full-fidelity root cause work happens fast, and traces are the most expensive telemetry type per unit.
- 1% sampled for 11 more months: preserves enough statistical signal for "did this class of error exist a few months ago" investigations without paying for full trace volume; always retain 100% of traces tied to errors or SLO breaches regardless of the sampling rate (a fixed-percentage sample can otherwise miss the rare traces investigators actually want).
Verifying the storage savings
For 1,000,000 active series, using the same 2-bytes/compressed-raw-sample and 8-bytes/downsampled-point (4 aggregates: min, max, sum, count, at roughly 2 bytes each) assumptions used elsewhere in TSDB capacity planning:
series = 1_000_000
compressed_bytes_per_raw_sample = 2
agg_bytes_per_downsampled_point = 8
def samples(days, interval_s):
return series * (days * 86400 / interval_s)
raw_bytes = samples(14, 15) * compressed_bytes_per_raw_sample
ds_bytes = samples(365, 300) * agg_bytes_per_downsampled_point
hourly_bytes = samples(1460, 3600) * agg_bytes_per_downsampled_point
total_tiered_bytes = raw_bytes + ds_bytes + hourly_bytes
allraw_bytes = samples(14 + 365 + 1460, 15) * compressed_bytes_per_raw_sample
Result: raw tier = 161.28 GB, 5-min tier = 840.96 GB, hourly tier = 280.32 GB, total tiered storage over the full 5-year window ≈ 1.283 TB, versus an all-raw-forever equivalent of ≈ 21.19 TB for the same window, a 16.5x reduction. The 5-minute tier dominates total storage (840 GB of the 1.28 TB) precisely because it covers the most time (1 year) at the finest surviving resolution; that's useful to know when deciding whether to push the raw window shorter or the 5-minute window's resolution coarser if the budget gets tighter.
For traces, at 10,000 traces/sec with an assumed 4 KB compressed size per trace: full 30-day retention stores about 103.68 TB, while the following 11 months at 1% sampling adds roughly 11.40 TB, so the sampled tail costs about 11% as much as the initial 30-day full window despite covering over 10x the time span.
What you can and can't still answer after each window closes
| Window | Still answerable | No longer answerable |
|---|---|---|
| After 14 days (raw metrics gone) | Was there a sustained regression this week vs. last month, at 5-minute granularity | Exact second-level spike shape of an incident 3 weeks ago |
| After 1 year (5-min rollups gone) | Year-over-year seasonal comparison at hourly granularity | Any sub-hour pattern from 13 months ago |
| After 30 days (full traces gone) | Error-tagged and SLO-breach traces remain at full fidelity indefinitely (by policy) | A specific successful request's full span tree from 6 weeks ago, unless it happened to fall in the 1% sample |
| After 11 months (sampled traces gone) | Aggregate error-rate and latency-percentile trends from metrics, which persist far longer than traces | Any trace-level detail at all from over a year ago |
Trade-offs and pitfalls
- Percentile aggregates (p95, p99) do not survive naive downsampling: averaging five 1-minute p99 values is not the same number as the true p99 across that 5-minute window. If percentile fidelity matters at the rollup tier, you need to store enough of a histogram or sketch (not just min/max/sum/count) to recompute percentiles, which raises the per-point byte cost above the 8-byte assumption used here.
- A fixed sampling percentage for traces (1% flat) will statistically under-represent rare-but-important request types unless it's stratified or combined with the always-keep-errors/SLO-breach rule; a pure random sample optimizes for "typical" traffic, which is exactly what you don't need for debugging.
- Retention policy that isn't enforced automatically (a manual cleanup job, or "we'll get to it") tends to silently become the accidental real retention policy; tie expiry to the storage engine's native TTL/compaction mechanism rather than a side script.
- Communicating the policy to teams matters as much as setting it: if engineers don't know that a 3-week-old spike is only visible at 5-minute resolution, they'll draw wrong conclusions from a smoothed-out graph without realizing detail was lost.
Unlock Full Question Bank
Get access to all 45 Observability and Monitoring Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.