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 disaster-recovery plan for the telemetry platform itself, so that a full region outage doesn't cause total loss of visibility. What's your cross-region replication strategy, what RTO/RPO would you target, how would you preserve the most recent telemetry (say, the last 30 days), and how would you actually test DR readiness without disrupting production monitoring?
Sample Answer
Direct answer
Run the telemetry platform itself as an active/passive pair across regions: continuous asynchronous replication of the last 30 days of data into a standby region, a health-check-driven failover controller that can promote the standby to serve reads first (cheap and fast) and writes second (slower, more disruptive), and a DR test plan that exercises the whole path against synthetic data in the standby region without ever touching production traffic. RTO and RPO targets should be derived from an explicit component budget, not picked as round numbers.
Replication strategy for the last 30 days
- Hot tier (0-7 days): continuous change-data-capture (CDC) style async replication into the standby region's own hot store, so recent writes show up there within a bounded lag.
- Warm tier (7-30 days): replicated as compacted/downsampled batches, since this data changes less and can tolerate a coarser replication cadence.
- Anything older than 30 days is out of scope for real-time DR replication; it's expected to come from the same archive/cold tier described in the storage-lifecycle design, which typically already lives in geo-redundant object storage independent of this DR plan.
Deriving RPO from replication throughput
RPO is bounded by whether the replication pipeline can keep up with ingest. If ingest rate I exceeds replication throughput capacity C, the backlog grows without bound; the pipeline is only stable if utilization ρ=I/C<1.
Assume ingest I=500 GB/day =0.347 GB/min, and a CDC replication pipeline provisioned for C=2 GB/min:
ρ=CI=20.347=0.174Comfortably under 1, so lag doesn't grow; it stays close to the pipeline's own configured commit interval. If the checkpoint/commit interval is set to 60 seconds and cross-region network propagation is budgeted at 30 seconds, the achievable RPO floor is:
RPOmin=tcommit+tpropagate=60+30=90 sThe target SLO should sit above this floor with margin for jitter, for example a 5-minute RPO target for critical metrics, which comfortably covers the derived 90-second minimum plus room for transient replication slowdowns.
Deriving RTO from a component budget
RTO is the sum of the configured steps a failover actually has to execute, not a guess:
tdetecttdecidetpromote_readtwarm=3×20s (health checks, 20s interval, 3 needed to confirm)=60s=30s (automated runbook trigger, no human in the loop)=120s (promote standby read replica, weighted DNS shift)=180s (query engine cache warm-up in standby before full load) RTOread=60+30+120+180=390s=6.5 minutesPromoting the full write path (repointing every collector's ingest endpoint, promoting the CDC consumer to primary writer) is a bigger, fleet-wide operation budgeted at an additional 600 seconds:
RTOwrite=RTOread+600=390+600=990s=16.5 minutesSetting targets with margin over the derived minimums: RTO ≤10 minutes for read-only dashboard failover, RTO ≤20 minutes for full write-path failover, RPO ≤5 minutes for critical metrics. Each of these numbers should be tied back to a specific, tunable configuration value (health-check interval, DNS TTL, promotion runbook step budgets), so when the target is missed in practice you know exactly which knob to turn.
flowchart LR
Primary[Primary Region: Ingest + TSDB] --> CDC[CDC / Async Replication]
CDC --> DRReplica[DR Region Read Replica]
Primary --> Health[Health Check Monitor]
Health -->|3x fail| FailoverCtrl[Failover Controller]
FailoverCtrl --> DNS[Weighted DNS / Traffic Shift]
DNS --> DRReplica
FailoverCtrl --> PromoteWrite[Promote DR to Primary Writer]
PromoteWrite --> Collectors[Collector Fleet Repoint]
Testing DR readiness without disrupting production monitoring
- Synthetic canary in the standby region: continuously push tagged synthetic telemetry ("dr-test" namespace) through the full standby ingest-to-query path, so ordinary dashboards prove the standby is healthy at all times, without ever reading real production data from it.
- Scheduled drills: periodically shift a small, non-critical slice of real read traffic (a subset of low-priority dashboards) to the standby via the same weighted-DNS mechanism used for real failover, so the failover mechanism itself gets exercised under real conditions, not just the replication pipeline.
- Full failover game day: in a maintenance window, actually promote the standby for both read and write for a bounded period, with a pre-agreed rollback trigger and runbook, rather than relying on tabletop exercises alone; tabletop-only DR plans are a common source of surprises on the day it's needed for real.
- Continuous verification: monitor replication lag, CDC backlog depth, and sequence-continuity checks (are there gaps in the replicated stream) as first-class metrics on the primary's own dashboards, so a DR pipeline failure is itself an alertable condition, not something discovered during an actual regional outage.
Trade-offs and pitfalls
- Async replication is cheaper and simpler than active-active, but it structurally accepts the derived RPO floor as data loss on failover; if the business needs zero data loss, that requires synchronous replication or active-active, at meaningfully higher cost and complexity.
- Read-path failover is fast and low-risk to test; write-path failover is slower and riskier (duplicate writes, split-brain if both regions think they're primary), so the plan deliberately treats them as two separate RTOs with two separate promotion procedures rather than one all-or-nothing cutover.
- Testing with synthetic canary traffic proves the pipeline works but not that the promoted region can handle real production query load; a periodic full game-day is what actually validates capacity, and skipping it is the most common way DR plans fail silently until the real outage.
- Multi-region key management (KMS keys, IAM) is often the forgotten dependency in DR plans for encrypted telemetry; if the standby region can't decrypt replicated data because keys weren't also made cross-region available, the whole DR plan is theater.
Design a set of guardrails, at the instrumentation, ingestion, and query layers, that prevent cardinality explosions before they happen rather than reacting to one after the fact. How would you automatically detect a metric that's about to blow up cardinality, and decide whether to throttle it, reject it, or aggregate it away?
Sample Answer
Guardrails have to exist at all three layers because each one catches a different failure mode. Instrumentation-layer guardrails prevent bad label design from ever shipping; ingestion-layer guardrails catch what slips through in real time before it damages the shared backend; query-layer guardrails contain the blast radius of whatever cardinality already exists.
The three layers
flowchart LR
A[Instrumentation: SDK label schema] --> B[Ingestion: cardinality meter]
B --> C{Growth above threshold?}
C -->|no| D[Accept]
C -->|yes| E{Decision}
E -->|reduce signal value| F[Aggregate away]
E -->|protect budget, keep signal| G[Throttle]
E -->|hard limit exceeded| H[Reject]
D --> I[Query Layer]
F --> I
G --> I
- Instrumentation layer: require a metric schema/template before a new metric name can ship (declared label keys and, ideally, an expected cardinality bound per key); flag or reject at code-review/CI time any label key with an obviously unbounded domain (request IDs, raw user IDs, full URLs with path parameters unreplaced).
- Ingestion layer: maintain a live, low-memory estimate of distinct series per metric/tenant so growth can be detected within minutes, not after the backend already OOMs.
- Query layer: enforce query-time cost limits (max series a single query can touch, regex-predicate cost estimation) so that even cardinality that did get ingested can't be turned into a denial-of-service against shared query compute.
Detecting a metric about to blow up
The right tool is a HyperLogLog (HLL) sketch per metric name (or per metric x tenant), because it estimates distinct-count cardinality in fixed, small memory regardless of how many series actually exist. HLL's standard error and memory cost are both direct functions of its precision parameter $p$, where the sketch has $m = 2^p$ registers:
RSE=m1.04,memory≈86m bytes (6-bit registers)import math
for p in (10, 14):
m = 2 ** p
se = 1.04 / math.sqrt(m)
mem = m * 6 / 8
print(p, m, se, mem)
Result: p=10 gives 1,024 registers, 3.25% standard error, 0.77 KB memory; p=14 gives 16,384 registers, 0.81% standard error, 12.29 KB memory. Running one p=14 sketch per metric name across even 10,000 distinct metric names costs about 123 MB of memory total, cheap enough to keep live for every metric in the system, which is what makes real-time growth detection practical.
With a live baseline and a rolling-window estimate, growth-rate detection is a simple ratio check: if a metric's baseline series count is 5,000 and a 10-minute window shows 500,000, that's a 100x growth ratio against a chosen threshold of, say, 5x, which trips the guardrail well before the metric reaches an operationally dangerous size.
Deciding throttle vs. reject vs. aggregate
| Signal | Action | Why |
|---|---|---|
| Growth is gradual and the metric is below the hard tenant quota | Accept, but flag for the owning team | No immediate risk; early warning is enough |
Growth is caused by one specific label key going unbounded (e.g., request_id added to a previously-bounded metric) | Aggregate away: drop or bucket that one label key, keep the rest of the series | Preserves most of the signal's value; this is usually a mistake, not malice, and the metric is still useful without the offending label |
| Growth is broad-based and close to the tenant's hard quota, but the metric still has legitimate value | Throttle: apply sampling or rate-limit new series admission | Buys time and protects the shared backend without discarding an entire signal outright |
| Growth exceeds a hard ceiling with no clear single offending label | Reject: refuse new series for that metric until the owner fixes it | Protects everyone else sharing the backend; a soft response at this point is not enough |
A useful mechanism for the "which label is the culprit" question: if a metric normally has a bounded combinatorial cardinality (e.g., endpoint × status × pod = 50 × 6 × 500 = 150,000 possible series, computed by multiplying each label's distinct-value count) and observed cardinality is far above that bound, the excess growth is coming from a label outside that expected set, and the ingestion layer can pinpoint it by comparing per-label-key distinct-value growth rates rather than only the aggregate metric-level count.
Trade-offs and pitfalls
- A pure hard-reject policy at the ingestion layer is the easiest to build and the worst for reliability: it turns a labeling mistake in one service into a total metrics outage for that service (including its SLO-relevant metrics), which is why aggregate-away and throttle need to exist as intermediate responses.
- HLL is probabilistic; at low precision (small $p$) the standard error is large enough that near-threshold decisions can flap. Pick $p$ based on how close to the threshold you need confident decisions, not just "the default."
- Guardrails without an audit trail (which decision was applied, to which metric, when) make it impossible to tell a team why their metric got throttled, which erodes trust in the guardrail system and encourages people to route around it (e.g., renaming a metric to dodge a quota).
- The instrumentation-layer guardrail is the cheapest one to enforce and the one most often skipped; catching an unbounded label at CI time costs nothing compared to catching it after it has already damaged the shared backend.
Time-series databases lean on a handful of compression techniques: block-chunking, delta-of-delta timestamp encoding, XOR-based float compression (as in Facebook's Gorilla), and dictionary encoding for labels. Explain how each works and how it affects write throughput and query performance, and contrast a dense, monotonically-increasing counter against a sparse gauge: which techniques help most for each, and why?
Sample Answer
Time-series compression works because consecutive samples in a series are usually similar to each other: timestamps arrive at near-regular intervals, and values tend to change by small amounts (or not at all) between samples. Block-chunking, delta-of-delta timestamp encoding, XOR-based float compression, and label dictionary encoding each exploit a different piece of that similarity.
How each technique works
Block-chunking: samples are grouped into fixed time-window or fixed-count blocks (e.g., 2-hour windows), each with its own compressed byte stream and a small metadata header (start/end timestamp, min/max value). This lets a query engine skip whole blocks that fall outside a requested range without decompressing them, and it bounds how much has to be re-encoded when new data arrives (you only ever append to the current open block).
Delta-of-delta timestamp encoding: instead of storing each timestamp, store the delta from the previous timestamp, then the delta of that delta. For a series scraped at a fixed interval, the delta between consecutive timestamps is constant, so the delta-of-delta is exactly zero almost every time, which collapses to a single control bit per sample.
Di=(ti−ti−1)−(ti−1−ti−2)XOR-based float compression (Gorilla): XOR the current value's bit pattern against the previous value's bit pattern. If the value hasn't changed much, most of the leading bits (sign, exponent, high mantissa) and trailing bits (low mantissa) of the XOR result are zero, and only a short "meaningful" middle span needs to be stored explicitly.
meaningful_bits=64−leading_zeros(vi⊕vi−1)−trailing_zeros(vi⊕vi−1)Dictionary encoding for labels: label keys and values repeat across enormous numbers of series (env=prod appears on millions of series), so each distinct string is stored once in a dictionary and every series references it by a small integer ID instead of repeating the string.
Worked example: counter vs. sparse gauge
The following is executed Python (struct-level IEEE-754 bit manipulation, no external data) so the numbers are exactly reproducible:
import struct
def bits(f):
return struct.unpack('>Q', struct.pack('>d', f))[0]
def leading_zeros(x, width=64):
return width if x == 0 else width - x.bit_length()
def trailing_zeros(x, width=64):
if x == 0: return width
c = 0
while (x & 1) == 0:
x >>= 1; c += 1
return c
def xor_meaningful_bits(prev, cur):
x = bits(prev) ^ bits(cur)
if x == 0: return 0, 64, 0
lz, tz = leading_zeros(x), trailing_zeros(x)
return lz, tz, 64 - lz - tz
# dense monotonic counter: http_requests_total, +1 per 15s scrape
print(xor_meaningful_bits(184320.0, 184321.0))
# sparse gauge, small fluctuation: temperature idling
print(xor_meaningful_bits(21.4, 21.9))
# sparse gauge, large jump: temperature spikes
print(xor_meaningful_bits(21.9, 87.2))
Output:
(28, 35, 1) # counter +1 step: 1 meaningful bit
(16, 47, 1) # gauge, small change: also 1 meaningful bit
(9, 0, 55) # gauge, large jump: 55 meaningful bits (almost the full double)
And for delta-of-delta timestamps on a realistically jittered 15-second scrape, with the full input pinned so the result is exactly reproducible (10 explicit timestamps, which by the Di formula above yields 8 delta-of-delta values, since each output needs 3 consecutive timestamps):
timestamps = [
1720000000, 1720000015, 1720000030, 1720000045, 1720000060,
1720000075, 1720000089, 1720000105, 1720000120, 1720000134,
]
deltas = [timestamps[i] - timestamps[i - 1] for i in range(1, len(timestamps))]
delta_of_delta = [deltas[i] - deltas[i - 1] for i in range(1, len(deltas))]
print("deltas:", deltas)
print("delta-of-delta:", delta_of_delta)
Output:
deltas: [15, 15, 15, 15, 15, 14, 16, 15, 14]
delta-of-delta: [0, 0, 0, 0, -1, 2, -1, -1]
4/8 are exactly 0 (single control bit each): the first four scrape gaps land exactly on the 15-second interval, then jitter shows up as a 14s gap, a 16s gap, and two more gaps that miss the interval by one second, each producing a nonzero delta-of-delta.
Which techniques help most for which shape
| Series shape | Timestamp behavior | Value behavior | Best-fit techniques |
|---|---|---|---|
| Dense, monotonically-increasing counter (e.g., request count) | Very regular interval; delta-of-delta is 0 almost always | Small, steady XOR distance between consecutive floats even though the value keeps climbing, because the relative change per step is tiny | Delta-of-delta on timestamps (near 1 bit/sample), XOR compression on values (near 1 meaningful bit/sample as shown above); block-chunking with larger blocks since data is smooth and compresses uniformly well |
| Sparse gauge (e.g., a temperature or queue-depth sensor with irregular scrape gaps and occasional large jumps) | Irregular gaps mean delta-of-delta is frequently nonzero and needs the wider-value fallback encoding | Large jumps between samples XOR into far fewer leading/trailing zero bits (55 meaningful bits in the example above, near the 64-bit ceiling) | Smaller blocks so a poorly-compressing stretch doesn't drag down a whole block's average; per-block adaptive codec fallback (e.g., general-purpose compression like Snappy/LZ4 on top when Gorilla's assumptions don't hold); dictionary encoding still helps regardless since it targets labels, not values |
The counter case shows why Gorilla-style encoding is the default for metrics generally: even though the value itself is always changing (climbing), the bit pattern delta between consecutive floats stays small as long as the relative step size is small, which is true for almost all real counters. The gauge case shows the failure mode: a big jump changes the exponent bits, which wipes out both the leading-zero and trailing-zero runs simultaneously, so the encoding degrades toward storing the value nearly raw.
Trade-offs and pitfalls
- A common wrong turn is assuming XOR compression is "for gauges" and delta-encoding is "for counters" as a rule; the real determinant is how much the bit pattern changes step to step, which correlates with relative magnitude change, not with the metric type label.
- Partial decompression for range queries requires the block-level index (min/max timestamp, min/max value) to be cheap to read without decoding the compressed body; if you skip that index to save space, every range query degrades to a full block scan.
- Block size is a real tuning knob, not a footnote: too small and per-block metadata overhead dominates; too large and a single noisy stretch (like the sparse-gauge jump) drags down the compression ratio for the whole block and increases decompression latency for small range queries.
- Dictionary encoding for labels needs a compaction/garbage-collection story; a dictionary that only grows (never reclaims IDs for labels that stop being used) becomes its own unbounded-cardinality problem over long retention.
Build a cost model for a petabyte-scale observability platform. Identify the primary cost drivers (ingest and egress, storage class, query compute), and show which knobs actually move the number (sampling rate, retention tiers, downsampling, aggregation). How would you present the trade-offs to a product or finance stakeholder who isn't going to read your architecture diagram?
Sample Answer
Direct answer
Break the cost into four buckets tied to concrete volumes rather than one blended number: storage (split by hot/warm/cold tier), ingest compute, egress, and query compute. Once each bucket is a formula in terms of raw ingest volume, retention days, and downsample ratio, every proposed knob (sampling, retention, downsampling, precomputing queries) is just a parameter change you can re-run through the same formulas, which is what makes the model defensible to finance: they're not trusting your intuition, they're trusting arithmetic they can re-check.
Structured elaboration
The four cost buckets and what drives each:
| Bucket | Primary driver | Scales with |
|---|---|---|
| Storage | Bytes retained per tier x tier unit cost | Retention days, downsample ratio, raw ingest volume |
| Ingest compute | Bytes parsed/enriched | Raw ingest volume directly |
| Egress | Bytes leaving the platform to external consumers | Fraction of data exported, not total stored |
| Query compute | Bytes scanned per query x query frequency | Whether queries hit raw data or precomputed aggregates (see the query-engine design in this same topic area) |
Retention tiers as the main storage lever: hot (short window, full resolution, most expensive per byte), warm (downsampled, medium retention, mid-cost), cold (heavily downsampled, long retention, cheapest per byte, e.g. object storage archive class). Storage cost is the sum of the three tiers, each computed from its own retention window and downsample ratio, not one blended "storage cost per byte."
Which knobs move the number, and by how much: sampling rate reduces raw ingest volume directly, which cascades into every downstream bucket. Retention shortening only affects the tier whose window changed. Downsampling more aggressively in a tier only affects that tier and everything colder than it. Query precomputation (materialized views, discussed in depth as its own system-design question in this topic) reduces query compute without touching storage or ingest at all. These don't all move the same line item, which is exactly the point when explaining trade-offs to a non-architecture stakeholder: "cut retention" and "sample harder" save different money for different reasons.
Worked example
Baseline: 1 PB/month raw ingest (I=1,000 TB/month), three retention tiers.
Illustrative unit costs (chosen only to demonstrate how the model moves, not a vendor quote, since real pricing varies by provider, region, and contract):
- Hot storage: $0.023/GB-month. Warm: $0.010/GB-month. Cold archive: $0.0018/GB-month.
- Ingest compute: $2/TB processed. Egress: $0.05/GB. Query compute: $0.005/GB scanned.
Retention plan: hot 7 days (full resolution), warm 90 days (10x downsampled), cold 730 days (100x downsampled from raw).
hotStorageTB=I⋅307=1,000×307=233.33 TB warmStorageTB=10I⋅3090=100×3=300 TB coldStorageTB=100I⋅30730=10×24.33=243.3 TB storageCost=233,330×0.023+300,000×0.010+243,300×0.0018=$8,804.67/month ingestCost=1,000×$2=$2,000/monthAt 5% of raw volume egressing to external dashboards/consumers:
egressCost=(1,000×0.05)×1,000×$0.05=$2,500/monthAt 200,000 dashboard queries/day averaging 50MB scanned each (already benefiting from the materialized-view design, not a raw scan):
queryCost=200,000×0.05×30×$0.005=$1,500/month TOTAL=$8,804.67+$2,000+$2,500+$1,500=$14,804.67/monthStorage is 59.5% of the bill, egress 16.9%, ingest 13.5%, query 10.1%. Storage dominates, which tells the stakeholder conversation where to start.
Sensitivity: which knobs actually move the number.
| Knob | Change | New total/month | Δ vs. baseline |
|---|---|---|---|
| Baseline | (none) | $14,804.67 | (none) |
| Sample traces down to 10% (traces = 40% of raw volume) | I:1,000→640 TB | $10,014.99 | -32.4% |
| Shorten hot retention 7d → 3d | hot tier only | $11,738.00 | -20.7% |
| Harsher warm downsampling 10x → 20x | warm tier only | $13,304.67 | -10.1% |
(Trace sampling: assuming traces are 40% of the 1PB raw volume and are sampled down to keeping 10%, raw ingest drops to 1,000−0.4×1,000×0.9=640 TB, which scales storage, ingest, and egress together since all three are proportional to I; query cost is held fixed because it depends on materialized-view cardinality, not raw ingest volume.)
The trace-sampling knob moves the most money here because it's the only one that reduces the ingest-side volume driving three of the four buckets at once, not just one storage tier.
Trade-offs & pitfalls
Presenting this to a stakeholder who won't read the architecture diagram: lead with the four-bucket table and the "storage is 60% of the bill" headline, then show the sensitivity table as a menu: "shorten hot retention and you save about $3,067/month but lose the ability to debug anything past 3 days at full resolution; sample traces harder and you save more, about $4,790/month, but rare-event tracing gets less reliable." Frame every knob as a cost-versus-capability trade the business is choosing, not an engineering decision made in isolation.
Common wrong turns: reporting a single blended "$/GB" number across all tiers, which hides that hot storage is over 12x more expensive per byte than cold in this model and makes every optimization conversation vaguer than it needs to be; sizing the model off total data stored ever, rather than steady-state storage per tier (a tier's storage is bounded by its own retention window, not by cumulative ingest since the platform launched); and treating cross-cloud portability as free optionality when discussing a "buy versus build" version of this trade-off: egress pricing and archive-tier retrieval fees differ enough between providers that a cost model built on one provider's numbers doesn't transfer without re-deriving the tier costs.
Design the storage schema and partitioning strategy for a time-series database that has to handle high-cardinality metrics while still supporting efficient downsampling and range queries. Cover the data model (metric name, labels, timestamp, value), how you'd choose partition keys, your chunking strategy, compression, and index structures, and what that trades off in query latency versus storage overhead.
Sample Answer
The core design decision is a two-level key: shard by a hash of the series identity so writes and label lookups distribute evenly, and chunk by time within each series so both compression and range queries stay efficient. Everything else (indexing, downsampling, compression) hangs off that.
Data model
Each sample is (metric_name, labels, timestamp, value). In practice you don't store metric_name and labels as free strings per sample; you compute a SeriesID once per unique combination:
and every sample after that is just (SeriesID, timestamp, value). The label set is stored once in a separate series-metadata record, not repeated per sample.
Partitioning and chunking
flowchart LR
A[Sample Ingest] --> B[Hash by SeriesID]
B --> C[Shard 1]
B --> D[Shard 2]
B --> E[Shard N]
C --> F[Head Block: in-memory chunk]
F --> G[Flush to Durable Chunk]
G --> H[Inverted Label Index]
G --> I[Block Storage]
H --> J[Query: label lookup]
I --> J
- Partition key:
(time_window, shard_id)whereshard_id = hash(SeriesID) mod N. Time-first partitioning means old partitions become immutable and can be compacted/downsampled/expired independently; sharding by SeriesID hash inside each time window spreads a hot series's neighbors across nodes instead of colocating them. - Chunking: each series appends to an in-memory "head" chunk, flushed to a durable, compressed chunk when it hits either a time bound (e.g., 2 hours) or a size bound. Chunk metadata (SeriesID, start/end timestamp, min/max value) lets a query prune whole chunks without decompressing them.
- Compression: delta-of-delta for timestamps, XOR (Gorilla-style) for values within a chunk, general-purpose compression (LZ4/Snappy) over the chunk byte stream, dictionary-encoded label strings referenced by ID.
- Index structures: a primary LSM-style index maps
SeriesID -> chunk pointersfor fast range scans of one series; a secondary inverted index mapslabel_key=value -> [SeriesIDs], typically stored as compressed bitmaps (e.g., Roaring bitmaps) so a query like{job="checkout", env="prod"}becomes a bitmap intersection instead of a full scan.
Sizing the design against a concrete workload
Take 10,000,000 active series, an average of 6 label pairs per series (beyond the metric name), a 2-hour flush window at 15-second scrape interval, and a target of at most 2,000,000 active series per shard for balanced load:
active_series = 10_000_000
avg_labels_per_series = 6
bytes_per_posting_entry = 3 # Roaring-bitmap-compressed 32-bit series ID, moderately dense postings (assumption)
total_postings_entries = active_series * avg_labels_per_series
inverted_index_bytes = total_postings_entries * bytes_per_posting_entry
chunk_window_s = 2 * 3600
scrape_interval_s = 15
samples_per_series_per_chunk = chunk_window_s / scrape_interval_s
compressed_bytes_per_sample = 2 # consistent with the Gorilla-style bit math above, rounded up for a mixed workload (assumption)
head_bytes_per_series = samples_per_series_per_chunk * compressed_bytes_per_sample
head_total_bytes = active_series * head_bytes_per_series
target_series_per_shard = 2_000_000
min_shards = active_series / target_series_per_shard
Result: total_postings_entries = 60,000,000, inverted_index_bytes ≈ 180 MB, samples_per_series_per_chunk = 480, head_bytes_per_series = 960, head_total_bytes ≈ 9.6 GB, min_shards = 5.0 (round up to 8 for power-of-2 hash routing headroom).
That tells you two concrete things: the in-memory working set for the head block across all shards (~9.6 GB) comfortably fits on modern hardware split across 8 shards (about 1.2 GB/shard), and the inverted index itself (~180 MB) is small relative to the chunk data, meaning label-lookup cost is dominated by bitmap intersection speed, not index size. If active series grew 10x to 100M, head memory would grow to ~96 GB total, which is the point where you'd need to either shrink the chunk window (trading write amplification for lower per-shard memory) or add more shards.
Trade-offs
| Choice | What you gain | What it costs |
|---|---|---|
| Smaller chunk window (e.g., 30 min instead of 2h) | Lower head-block memory footprint, faster recovery on restart | More, smaller chunks on disk; more flush/compaction overhead; slightly worse compression ratio since fewer samples per block |
| More shards | Better write/query parallelism, smaller failure blast radius per shard | Cross-shard queries for a single label predicate now fan out to more nodes; more metadata to track |
| Time-first vs. hash-first partition key ordering | Time-first makes retention/expiry a cheap drop-partition operation | Hash-first can improve single-series read locality but makes retention expensive (has to scan and delete rather than drop) |
| Roaring-bitmap inverted index | Fast label-predicate intersection at low memory cost | Degrades if label values are extremely high-cardinality and postings lists become sparse and non-contiguous, hurting bitmap compression |
Pitfalls
- Choosing a partition key that's purely hash-based (no time component) makes retention expensive: you can't just drop a partition, you have to scan and delete, which is the mistake most designs make when they optimize only for write balance and forget that data has to expire.
- Sizing the head-block window without doing the arithmetic above (as many designs do) leads to either restart storms (window too large, recovery replays too much) or excessive flush overhead (window too small).
- An inverted index without a query-time cardinality guard turns a single broad label predicate (like an unbounded regex) into a full index scan across all shards; that needs a query-side cost limit independent of the storage design.
Unlock Full Question Bank
Get access to all 49 Observability and Monitoring Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.