Distributed Time-Series Metrics Database
Hard · System Design · Software Engineer · Onsite
Prompt
Architect a distributed time-series database engineered to ingest 5 million metric data points per second while serving aggregated range queries with sub-second latency. Each metric stream is identified and filtered through arbitrary key-value string tags—for instance, instance="worker-07", zone="eu-west".
Your system must satisfy the following functional and operational guarantees:
- Ingestion path: Accept metric points composed of a timestamp, a set of key-value tag strings, and a 64-bit floating-point measurement.
- Query path: Evaluate tag-filtered range aggregations, such as computing the mean
disk_io_utilacrosszone="eu-west"over the past 60 minutes. - Data lifecycle: Automatically purge measurements once they pass a 30-day retention horizon.
- Fault tolerance & durability: Survive the failure of any individual cluster node without losing acknowledged writes.
- Horizontal scale: Expand write throughput and query capacity smoothly by adding nodes as total metric volume grows.
- Consistency model: Asynchronous replication across the ingestion pipeline is fine, provided queries observe the latest committed measurements.
Scope & Expectations
- Storage engine & tag indexing: Detail how series metadata, label indexes, and timestamped floating-point values are laid out in memory and on disk to sustain heavy append traffic alongside fast range scans.
- High-level system architecture: Define the core ingestion, routing, query execution, durable storage, and background maintenance components and trace how writes and reads flow through them.
- Sharding, hotspots, and high cardinality: Explain how streams and time windows are partitioned across nodes to absorb bursts from noisy hosts while keeping index memory bounded when tag combinations explode.
- Compaction & multi-resolution rollups: Describe how high-frequency raw streams (for example, 10-second intervals) are compacted, downsampled into coarser summaries (for example, 1-hour buckets), and expired cleanly after 30 days.
Step-by-step walkthrough
Clarify requirements and assumptions
A time-series database (TSDB) stores measurements collected repeatedly over time—such as server CPU usage or network bytes every 10 seconds—and has a very specific workload shape: millions of tiny, append-only writes per second, almost zero updates to old values, and range queries that filter by tags and aggregate across thousands of streams at once.
Functional requirements
- Write path: Ingest metric samples
(labels, timestamp, value), wherelabelsis a set of key-value strings (such as{__name__="disk_io_util", instance="worker-07", zone="eu-west"}),timestampis Unix time in milliseconds, andvalueis a 64-bit floating-point number (float64). Treating the metric name as a reserved label__name__keeps the model uniform. - Read path: Evaluate sub-second range queries that filter series by labels (
=,!=, regex) and aggregate over time and across series—for example, "meandisk_io_utilacrosszone="eu-west"over the past 60 minutes at 1-minute steps." - Retention: Automatically expire and reclaim storage for data older than 30 days.
Non-functional requirements
- Throughput: Sustain 5 million samples/second on average, with headroom for 10 million/second bursts (for example, monitoring agents flushing buffered data after a brief network blip).
- Query latency: Sub-second (
p99 < 1 s) for typical dashboard and alerting range queries spanning thousands of series over hours, or days via pre-aggregated rollups. - High availability and durability: Tolerate the loss of any single node (or an entire availability zone) with zero loss of acknowledged writes and uninterrupted reads and writes.
- Consistency: Ingestion is asynchronous across the fleet, but once a write returns
200 OK, every subsequent query must include that sample (read-after-write consistency). - Horizontal scalability: Adding nodes must scale both write capacity and query capacity linearly without moving terabytes of historical data.
Assumptions to state out loud
- Monitoring agents scrape each metric every 10 seconds and send samples in compressed batches (500–2,000 samples per HTTP request).
- Multi-tenant deployment (
tenant_idcomes from the auth header; a single-tenant cluster simply uses one fixed tenant). - Samples normally arrive in chronological order per series, with a bounded window (for example, 1 hour) for slightly delayed samples.
- Write path: Ingest metric samples
Back-of-the-envelope numbers
Let's translate "5 million writes/s and 30-day retention" into concrete series counts, RAM, disk, and network numbers.
Series & sample volume Sustained ingest rate 5,000,000 samples/s (10,000,000/s peak burst) Active time series (at 10 s) 5,000,000 samples/s x 10 s = 50,000,000 active series Daily series churn (~20%/day) ~10M short-lived container/pod series/day -> ~350M series over 30 days Samples per day 5,000,000 x 86,400 s = 432,000,000,000 (432B samples/day) Storage math (30 days) Uncompressed (8B ts + 8B val) 16 B x 432B = 6.91 TB/day -> ~207 TB for 30 days Gorilla chunk compression ~1.5 B/sample -> ~648 GB/day -> ~19.4 TB for 30 days (1 compacted copy) Stateful ingester fleet (replication factor N = 3 across 3 availability zones) Cluster append rate 5M/s x 3 replicas = 15,000,000 appends/s Per-ingester capacity ~250,000 appends/s -> 15M / 250k = 60 ingester nodes Active series per ingester (50M x 3) / 60 = 2.5M series replicas per node RAM per active series ~4 KB (interned labels + index + open chunk) -> ~10 GB head RAM/node Sequential WAL disk bandwidth 250,000/s x 24 B (8B series_ref + 8B ts + 8B val) = 6 MB/s per node Query math 1-hour query, 200k series 200,000 x 360 samples (at 10s) = 72M raw samples (~108 MB compressed) 30-day query, 1,000 series 1,000 x 259,200 raw samples = 259.2M raw samples vs. 720k hourly bucketsFour conclusions drive our entire architecture: 1. A traditional SQL or row-per-sample NoSQL table cannot survive 5M inserts/s—index updates and per-row headers would turn 648 GB/day into tens of terabytes of random disk I/O. We need append-only, compressed per-series chunks. 2. 30 days of compressed samples is only ~19.4 TB—cheap enough for cloud object storage (S3/GCS), while the active working set (~600 GB across 60 nodes) fits comfortably in RAM. 3. 50M active series + 20% daily churn means the label-to-series index will explode if kept in one global structure; indexes must be scoped to fixed time blocks. 4. 30-day range queries touch hundreds of millions of raw points, so sub-second multi-day queries require downsampled rollups (5-minute and 1-hour resolutions).
API design
1) Batch write API (Protobuf compressed with Snappy or zstd) POST /api/v1/write X-Scope-OrgID: tenant_a Body: WriteRequest { series: [ { labels: [{name: "__name__", value: "disk_io_util"}, {name: "instance", value: "worker-07"}, {name: "zone", value: "eu-west"}], samples: [{ts_ms: 1764500000000, value: 0.42}, {ts_ms: 1764500010000, value: 0.44}] } ] } -> 200 OK fsynced to WAL on at least 2 of 3 ingester replicas (quorum W=2) -> 400 Bad Request invalid labels, timestamp too far in future/past, or conflicting duplicate -> 429 Too Many Requests tenant ingest rate or active-series cap exceeded -> 503 Unavailable safe to retry; identical (series, ts_ms, value) writes are idempotent 2) Range & metadata query API GET /api/v1/query_range?query=avg(disk_io_util{zone="eu-west"})&start=1764496400&end=1764500000&step=60s -> 200 OK { "result": [{ "labels": {}, "values": [[1764496400, 0.39], [1764496460, 0.41]] }], "stats": { "series_matched": 180000, "samples_scanned": 64800000, "resolution": "raw" } } GET /api/v1/labels list known label keys GET /api/v1/label/{name}/values autocomplete values for dashboards GET /api/v1/cardinality?limit=20 top metrics/labels by active series countMaking
(series, ts_ms, value)idempotent (re-sending the exact same timestamp and value is silently deduplicated) lets agents safely retry batches whenever a network timeout occurs.Data model: decouple the inverted index from sample chunks
Our single most important data-modeling rule is never store label strings alongside every sample, and never update an on-disk index on every sample. Labels (~200 bytes) are defined once when a series starts; samples (~1.5 bytes compressed) arrive every 10 seconds.
Each unique sorted label set gets a 64-bit routing fingerprint
series_hash = xxhash64(tenant_id + canonical_sorted_labels)and, inside a single node or storage block, a compact local integer ID calledref(1, 2, 3, ...).1. Series dictionary (written ONLY when a new series appears) ref 201 -> { __name__: "disk_io_util", instance: "worker-07", zone: "eu-west" } ref 202 -> { __name__: "disk_io_util", instance: "worker-08", zone: "eu-west" } ref 203 -> { __name__: "net_rx_bytes", instance: "worker-07", zone: "us-central" } 2. Inverted index / postings lists (maps each (label_key, label_val) -> sorted list of refs) (__name__, "disk_io_util") -> [201, 202] (zone, "eu-west") -> [201, 202] (instance, "worker-07") -> [201, 203] 3. Per-series sample chunks (append-only bitstreams, ~120 samples = 20 min per chunk) ref 201 -> [ chunk (t=00:00..00:20, 180 bytes) ] -> [ chunk (t=00:20..00:40, 176 bytes) ]An inverted index is the same data structure a book index uses: instead of scanning every series to check its labels, each
(label_name, label_value)pair points directly to a sorted array of matching seriesrefs, called a postings list.On-disk and object-storage layout. Every 2 hours, each ingester flushes its in-memory data into a self-contained, immutable directory called a block covering
[min_time, max_time):block_01JDX9.../ meta.json tenant_id, min_time, max_time, resolution (raw | 5m | 1h), source_blocks chunks/000001 contiguous compressed ~120-sample chunks grouped by series ref index interned string table + series table (ref -> label symbol IDs + chunk byte offsets) + compressed postings lists tombstones optional (ref, start_ts, end_ts) markers for targeted admin deletesBecause each block carries its own local index covering only series active during that block's window, short-lived container series from last week never bloat today's index, and 30-day retention becomes deleting whole block folders.
High-level architecture
Monitoring Agents (batch + Snappy compress + retry) | v +----------------------------------------------+ +--------------------------------------+ | Stateless Distributors |----->| Consistent Hash Ring (Gossip / etcd) | | auth, rate & cardinality limits, hash series | +--------------------------------------+ +----------------------+-----------------------+ | replicate each series to N=3 Ingesters across 3 AZs (ack at W=2) v +----------------------------------------------+ flush immutable 2h blocks | Stateful Ingesters (60 nodes across 3 AZs) |------------------------------------+ | NVMe WAL (group fsync) + in-memory Head | | +----------------------+-----------------------+ v ^ +------------------------------------+ | recent data (~last 13h, | Cloud Object Storage (S3 / GCS) | | quorum read R=2) | immutable blocks by tenant & time | +----------------------+-----------------------+ +---------+------------------+-------+ | Stateless Queriers | | ^ | intersect postings, fetch compressed chunks, |<-----------------------+ | | deduplicate replicas, compute aggregations | older data (>12h) | | +----------------------+-----------------------+ via Store Gateways v | ^ +-------------------+ +-----+-------+ +----------------------+-----------------------+ | Store Gateways | | Compactors | | Query Frontend |------------->| cache block index | | dedup N=3, | | split by day & shard, fair tenant queues, | completed | headers & chunks | | merge 24h, | | cache immutable windows | windows +-------------------+ | downsample, | +----------------------+-----------------------+ cache | 30d expire | ^ +-------------+ Dashboards & Alert RulesHow the two paths flow end-to-end: - Write path: A stateless Distributor authenticates the request, enforces per-tenant rate and series limits, computes
series_hashfor each series, and forwards samples in parallel to 3 Ingesters in 3 separate availability zones. Each Ingester writes to its local Write-Ahead Log (WAL) and appends to its in-memory Head; once 2 of 3 respond (W = 2), the Distributor returns200 OK. - Read path: The Query Frontend splits multi-hour or multi-day queries into parallel sub-queries, serves already-finished historical slices from the Results Cache, and dispatches the rest to stateless Queriers. Queriers read recent hours from Ingesters (R = 2quorum) and older blocks from Store Gateways (which keep lightweight block index headers cached over object storage), merge and deduplicate chunks, and compute the final aggregation.Deep dive 1: LSM-inspired storage engine and Gorilla compression
Each Ingester organizes storage like a Log-Structured Merge (LSM) tree—a write-optimized storage pattern that turns random writes into fast sequential disk appends by buffering recent writes in memory and periodically flushing immutable sorted files to disk:
Standard LSM concept Time-Series DB specialization --------------------- ------------------------------------------------------------------------- Write-Ahead Log (WAL) Sequential 128 MB disk segments; group-committed (fsync every ~10 ms) Memtable In-memory "Head": 1 open compressed chunk per active series + RAM postings Immutable SSTable 2-hour Block: per-series compressed chunks + self-contained inverted index Background Compaction Compactors merge 3 replica 2h blocks -> 1 deduplicated block -> 12h -> 24hWhy build a chunk-based time-series LSM instead of putting
(series_id, timestamp) -> valueas individual rows inside RocksDB? In a generic key-value LSM, every single sample repeats a 16-byte key and gets rewritten across 5–7 compaction levels. Packing 120 samples into one per-series Gorilla-compressed chunk shrinks each sample to ~1.5 bytes and copies already-compressed chunks without re-encoding during compaction!How Gorilla chunk compression gets 16 bytes down to ~1.5 bytes: 1. Delta-of-delta timestamps: Agents scrape on a steady 10-second timer. Instead of storing 64-bit timestamps
[1000, 1010, 1020, 1030], we store the first timestamp (1000), the first gap (+10), and then the change in gap (delta-of-delta):(1020 - 1010) - (1010 - 1000) = 10 - 10 = 0. Whenever the scrape arrives right on schedule, the delta-of-delta is0, encoded as a single'0'bit! 2. XOR floating-point values: Consecutive metric readings (like0.42followed by0.42, or0.42followed by0.44) share almost identical IEEE-754 bits. Computingcurrent_bits XOR previous_bitsyields0when unchanged (1 bit), or a small run of middle non-zero bits when slightly changed.def gorilla_timestamp_bits(timestamps_sec): """Count bits needed for delta-of-delta timestamps (Gorilla VLDB'15 bucket sizes).""" if not timestamps_sec: return 0 bits = 64 # full 64-bit starting timestamp in chunk header if len(timestamps_sec) > 1: bits += 14 # first delta stored in 14 bits for i in range(2, len(timestamps_sec)): delta = timestamps_sec[i] - timestamps_sec[i - 1] prev_delta = timestamps_sec[i - 1] - timestamps_sec[i - 2] dod = delta - prev_delta # 0 whenever scrape interval is steady! if dod == 0: bits += 1 # prefix '0' (1 bit total) elif -63 <= dod <= 64: bits += 2 + 7 # prefix '10' + 7-bit signed value elif -255 <= dod <= 256: bits += 3 + 9 # prefix '110' + 9-bit signed value elif -2047 <= dod <= 2048: bits += 4 + 12 # prefix '1110' + 12-bit signed value else: bits += 4 + 32 # prefix '1111' + 32-bit signed value return bitsFor 120 regular 10-second samples, timestamps take
64 + 14 + 118 x 1 = 196 bits(~25 bytes instead of 960 bytes—nearly 40x smaller!). Millisecond-precision engines (like Prometheus) use the exact same algorithm with slightly wider bit buckets (14, 17, 20bits) to absorb millisecond scrape jitter. Once a chunk hits 120 samples, the Ingester seals it and memory-maps it to local SSD so only one open chunk per active series stays on the heap.Deep dive 2: Inverted index and high label cardinality
Label cardinality is the total number of unique label-value combinations (unique time series). A label like
zonewith 6 values is low cardinality; accidentally attachingaccount_idorrequest_idwith 10 million values multiplies series count into a cardinality explosion that can exhaust ingester RAM and stall queries.How queries use postings lists fast. Suppose a user runs
avg(disk_io_util{zone="eu-west", env!="staging"}):Step 1: Fetch sorted postings(__name__="disk_io_util") -> [201, 202, 540, 910, ...] (2M refs) Step 2: Fetch sorted postings(zone="eu-west") -> [44, 201, 202, 800, ...] (15M refs) Step 3: Intersect sorted lists (binary/galloping search from shorter list) -> [201, 202, ...] Step 4: Subtract postings(env="staging") -> final matching series refs, then read ONLY their chunks!Four engineering techniques keep index size and memory bounded: - Time-partitioned per-block indexes: Each 2h or 24h block indexes only series that emitted samples during that window. Dead series from yesterday's Kubernetes rollout vanish from memory as soon as their 2-hour head window flushes. - String symbol interning: Long strings like
"eu-west-1-prod-cluster"are stored once per block in a symbol table; series definitions and postings store compact 32-bit integer IDs. - Delta-encoded postings / Roaring bitmaps: Sorted lists ofrefintegers compress tightly via variable-length deltas ([201, 202, 205]->[201, +1, +3]). - Hard per-tenant cardinality guardrails: Distributors and Ingesters enforcemax_active_series_per_tenant(e.g., 5M) andmax_series_per_metric(e.g., 500k). Crucially, hitting the cap rejects only brand-new series (429) while continuing to accept samples for already-active series, keeping existing production alerts alive!Deep dive 3: Partitioning, consistent hashing, and hotspots
Never partition by metric name (
__name__) alone: a ubiquitous metric likedisk_io_utilcan represent 20% of all cluster writes, creating an unfixable single-shard hotspot. Instead, we partition across both full series identity and time windows:- Consistent hashing on
xxhash64(tenant_id + sorted_labels). Every Ingester claims 128 virtual positions (tokens) around a 64-bit consistent hash ring (a circular keyspace where adding or removing a node reassigns only1/Nof keys instead of reshuffling the whole cluster). A series routes clockwise to the first 3 Ingesters in 3 distinct availability zones. Even ifinstance=worker-07goes rogue and emits 500,000 distinct metrics at once, each metric has different labels and hashes evenly across all Ingesters! - Shuffle sharding per tenant. In a 60-ingester cluster, assigning each tenant a deterministic virtual sub-ring of, say, 18 ingesters (6 per zone) isolates noisy neighbors—an overloaded tenant can affect at most its 18 nodes, and label-only queries (
{instance="worker-07"}, where__name__is unknown) only need to fan out to 18 nodes instead of all 60. - Time-range partitioning prevents data migration. Because Ingesters only hold the most recent ~2–3 hours before uploading immutable blocks to object storage, adding new Ingesters to the ring requires zero copying of historical data: new owners start accepting new samples immediately, while Store Gateways shard historical blocks by
hash(block_id)across days and hours so a 30-day query reads dozens of time slices in parallel. - Protecting against a single ultra-hot series. If one defective client writes to the exact same label set 50,000 times per second, label hashing cannot split a single series inside one time window; Distributors enforce a minimum sample interval per series (e.g., >= 100 ms) or pre-aggregate bursts at the agent.
- Consistent hashing on
Deep dive 4: Compaction, downsampling, retention, and consistency
Compaction and 30-day retention. Background Compactors (coordinated so only one worker processes a
(tenant, time_window)via lease) perform two cleanups: - Vertical compaction (replica deduplication): Merges the 3 replica 2-hour blocks uploaded by Ingesters into 1 deduplicated block in object storage (cutting S3 storage 3x, since object storage already replicates across disks and zones). - Horizontal compaction: Merges six2hblocks into12hand then24hblocks—copying compressed chunks directly without re-encoding while merging their symbol tables and postings so 12 separate index lookups become 1. - Zero-cost retention: Once a24hblock'smax_timeis older than 30 days, the Compactor deletes the whole block prefix in object storage—zero tombstones or random disk writes.Downsampling (
10s -> 5m -> 1h). For blocks older than 48 hours (after late data has settled), the downsampler writes parallel5mand1hrollup blocks storing five exact summary values per bucket:count,sum,min,max, andcounter_reset_adjusted_total. - Why never store just a pre-computedavg? Suppose Window 1 has 10 samples averaging100(sum = 1000, count = 10) and Window 2 had a network blip with only 2 samples averaging40(sum = 80, count = 2). Averaging the two averages gives(100 + 40) / 2 = 70(wrong!), whereas(1000 + 80) / (10 + 2) = 90gives the exact true average!Resolution Buckets/day/series Stored numbers/day 30-day scan across 1,000 series ---------- ------------------ ------------------ ------------------------------------------- Raw (10 s) 8,640 8,640 259,200,000 raw samples 5 minute 288 1,440 (5 aggs) 8,640,000 buckets (17.3M numbers for sum+count) 1 hour 24 120 (5 aggs) 720,000 buckets (1.44M numbers -> 180x less!)When a user queries a 30-day chart with
step >= 1h, the query planner automatically reads the1hrollup blocks and finishes in tens of milliseconds.Read-after-write consistency (
R + W > N) and failure recovery. - Every write replicates toN = 3Ingesters across 3 zones and commits only afterW = 2Ingesters group-fsync their WAL. - When querying recent hours across a tenant's 18-node shuffle shard, the Querier fans out to the shard (plus anyJOINING/LEAVINGnodes during ring resizing) and checks that for every hash-ring token range, at leastR = 2of its3replica owners responded (2 + 2 > 3), guaranteeing at least one responding node holds every committed write, then deduplicates by(series, ts_ms). - Single-node or full-zone crash: The surviving 2 zones still satisfyW = 2andR = 2with zero data loss; when a crashed Ingester restarts, it replays its local SSD WAL before rejoining the ring. - Query caching safety: The Query Frontend caches sub-query results only for windows older than the out-of-order horizon (e.g., > 70 minutes ago), so newly committed or slightly late samples in the active window are never hidden behind a stale cache.Summary of trade-offs
- Chunk-based time-series LSM + Gorilla compression vs. general-purpose DB: Shrinks storage ~10x (
~1.5 B/sample), turns 5M writes/s into sequential disk appends, and makes 30-day expiry a file delete, at the cost of making arbitrary historical point mutations expensive. - Decoupled per-block inverted index vs. inline labels or global index: Keeps hot sample writes tiny and automatically sheds churned container series every 2 hours, requiring queriers to intersect postings lists across touched blocks on reads.
- Sharding by
hash(tenant + all_labels)+ shuffle sharding vs. sharding by metric name: Eliminates hot-metric shards and isolates noisy tenants, trading off multi-ingester fan-out within the tenant's shuffle shard for label-filtered queries. - Quorum replication (
N = 3, W = 2, R = 2) on ingesters + 1 compacted copy in object storage: Guarantees zero acknowledged data loss and read-after-write consistency on live data while saving 3x long-term S3 storage cost once blocks are compacted. - Multi-tier downsampling (
count, sum, min, max) vs. raw-only: Cuts 30-day query work by ~180x while preserving exact weighted averages, adding background compaction CPU and ~20% extra rollup storage if raw 30-day blocks are also kept.
- Chunk-based time-series LSM + Gorilla compression vs. general-purpose DB: Shrinks storage ~10x (
Intuition & how it works
Imagine logging the temperature of 50 million rooms every 10 seconds. A naive database writes one full row per reading: (timestamp, "building=hq, floor=3, room=302, sensor=temp", 21.5). That repeats a 200-byte address label every 10 seconds for a 16-byte number and scrambles an on-disk B-tree index 5 million times per second! A time-series database flips the layout on its head like a binder of numbered clipboards: when a room sensor first reports in, we write its address once in a directory (an inverted index, which maps each tag like floor=3 to a sorted list of clipboard numbers called a postings list) and hand it clipboard #42. Every 10 seconds after that, we simply jot the latest number at the bottom of clipboard #42—and because readings arrive on a steady 10-second rhythm (+10s, +10s, +10s) and barely change (21.5, 21.5, 21.6), storing only differences (Gorilla compression) shrinks each reading from 16 bytes down to ~1.5 bytes!
Why obvious off-the-shelf designs fail here:
- A relational or row-per-sample NoSQL store drowns in random B-tree or per-key compaction I/O at 5 million writes/second and bloats 30 days of samples past 200 TB.
- Sharding by metric name (putting all disk_io_util on one server) melts that server because a single popular metric can carry 20% of all company traffic.
- Scanning raw 10-second points for 30-day dashboards reads hundreds of millions of samples per chart, blowing past our sub-second latency goal.
Walk through a concrete 4-sample trace for {__name__="disk_io_util", instance="worker-07", zone="eu-west"}:
1. Hash & replicate (W = 2 of N = 3): A stateless Distributor hashes the full sorted label set to hash = 0x8fa2..., picks 3 Ingesters in 3 availability zones on a consistent hash ring (a circular keyspace that spreads keys evenly across nodes), and sends the sample batch. Once 2 Ingesters group-flush their sequential Write-Ahead Log (WAL) on SSD, the write is acknowledged.
2. Compress in memory: On each Ingester, series ref = 201 receives four 10-second readings: (2000s, 0.42), (2010s, 0.42), (2020s, 0.42), (2030s, 0.42). Timestamp gaps are 10, 10, 10, so the changes in gap (delta-of-deltas) are 0, 0 (1 bit each!), and 0.42 XOR 0.42 = 0 (1 bit each!).
3. Flush & compact: Every 2 hours, Ingesters seal their in-memory Head into an immutable Block (chunks + local inverted index) in object storage (S3/GCS). Background Compactors deduplicate the 3 replica blocks into 1 copy, merge 2h -> 24h blocks, pre-compute 5m and 1h downsampled rollups (count, sum, min, max), and delete whole 24h blocks older than 30 days.
4. Sub-second range query: For avg(disk_io_util{zone="eu-west"}) over the past 60 minutes, a Querier intersects postings(__name__="disk_io_util") with postings(zone="eu-west") to get matching ref IDs, reads at least R = 2 of 3 Ingester replicas (R + W > 3 guarantees seeing every committed write), decodes their compact chunks in parallel, and returns in ~150 ms.
Key trade-offs
- Chunk-based time-series LSM vs. general-purpose row/KV database: Grouping ~120 consecutive samples per series into Gorilla-compressed chunks inside immutable time blocks cuts storage ~10x (
~19.4 TBvs.~207 TBfor 30 days), turns writes into sequential WAL appends, and makes 30-day expiration anO(1)block deletion. The trade-off is no in-place point updates: late arrivals and targeted deletes require separate out-of-order blocks and tombstones (deletion markers applied during compaction). - Separate per-block inverted index vs. inline labels or a single global index: Storing label strings once per series per block keeps per-sample writes tiny and lets dead container series age out of RAM every 2 hours instead of bloating a global index forever. In exchange, every range query pays a fast postings-list intersection per touched block before fetching sample chunks.
- Sharding by full label-set hash + shuffle sharding vs. sharding by metric name: Hashing
tenant_id + all_sorted_labelsspreads hot metrics (disk_io_util) and chatty hosts evenly across the fleet, while shuffle sharding (giving each tenant a fixed subset of, say, 18 of 60 ingesters) caps blast radius and bounds query fan-out when a query filters only oninstance="worker-07"without naming a metric. - Quorum ingest/read (
N = 3, W = 2, R = 2) + single-copy compacted object storage: Writing to 3 zones withW = 2and readingR = 2(2 + 2 > 3) guarantees zero loss of committed data when a node or zone fails and strict read-after-write visibility, at 3x ingester RAM/CPU cost; deduplicating to 1 copy during vertical compaction avoids paying 3x in S3, which already replicates data across disks and zones. - Downsampling (
count, sum, min, max) vs. raw samples only: Storing exact additive summaries at 5-minute and 1-hour tiers shrinks a 30-day 1,000-series average query from 259.2M raw samples to 720k hourly buckets (~180x fewer numbers read), trading background compaction compute and modest rollup storage for predictable sub-second multi-week queries.
Common mistakes
- Partitioning by metric name (
__name__): One high-volume metric likedisk_io_utilorhttp_requests_totaloverwhelms a single shard and limits parallelism to the number of distinct metric names. - Keeping one global label index across all 30 days: Container and pod restarts (
20%daily churn) create ~350M series over 30 days even when only 50M exist at once, exhausting memory unless indexes are scoped per time block. - Storing pre-computed averages during downsampling: Averaging two 1-hour averages produces wrong math whenever one hour had fewer samples than the other (and loses
min/max); always storecount, sum, min, max(plus counter-reset adjustments for monotonic counters) and computesum / countat query time. - Deleting expired samples row-by-row with background
DELETE WHERE ts < now - 30d: Row-level deletes flood storage engines with random write amplification, whereas dropping whole 24-hour immutable blocks is practically free. - Placing unbounded values (
account_id,request_id, full URLs) into metric labels: High-cardinality labels create millions of single-sample series that defeat chunk compression, blow up postings lists, and crash ingesters with out-of-memory errors. - Caching query windows that are still open to writes or late arrivals: Caching the last 60 minutes hides newly committed or out-of-order samples and violates read-after-write consistency; only cache finalized windows older than the late-arrival horizon.
Follow-up questions
- How should the storage engine ingest delayed samples whose timestamps precede the active write window while keeping background compaction safe? Handle lateness in two tiers while keeping every on-disk block strictly immutable. Samples arriving within a bounded out-of-order window (say, up to 1 hour behind a series' latest timestamp) are appended to a separate small out-of-order buffer in the Ingester's Head so active in-order Gorilla chunks stay untouched; when the Head flushes, those late samples write out as a small companion block overlapping the regular 2-hour block. Samples older than 1 hour (up to a 7-day backfill limit) go through an asynchronous backfill endpoint that writes new immutable blocks into object storage for the historical time window. Compaction is never corrupted because each Compactor job reads a fixed list of immutable source block IDs, writes a brand-new merged block (
meta.jsonuploaded last for atomic visibility), and only marks old blocks for delayed garbage collection afterward—any late block arriving mid-compaction is cleanly merged on the next compaction pass, triggers regeneration of affected5m/1hdownsampled blocks, and increments the tenant's query-cache generation key. - What safeguards at both ingestion and query execution prevent unbounded label keys such as
request_idoraccount_idfrom destabilizing the cluster? First stop the bleeding at ingest: enforce per-tenant (max_active_series) and per-metric (max_series_per_metric) caps that reject only new series creations (429) while letting existing series keep reporting, expose a/cardinalityendpoint ranking top offending metrics and label keys by postings-list length, and apply distributor relabeling rules (or pre-aggregation recording rules likesum without (request_id, account_id)) to strip unbounded labels before storage. Second, protect queriers with pre-execution cost estimation: check the lengths of matched postings lists before fetching any sample chunks and reject queries exceeding safe thresholds (for example, > 500k series or > 50M samples) or require at least one selective non-empty matcher. Combine strict per-query memory/byte budgets and context cancellation timeouts with per-tenant fair queuing and shuffle sharding so one runaway query cannot starve other tenants. - How would you manage cluster membership and shard ownership across nodes, and what are the trade-offs between strong-consensus protocols like Raft and epidemic protocols like Gossip? Node membership tracks which Ingesters and Store Gateways are alive and which hash-ring tokens they own. Raft (a leader-based consensus protocol used in
etcdandConsulwhere writes require a majority quorum) gives every Distributor and Querier a single strongly consistent view of the ring, making it ideal for low-rate coordination that strictly requires one owner—such as Compactor block leases so two workers never compact the same tenant window twice. Gossip (a decentralized peer-to-peer protocol like SWIM/memberlistwhere nodes exchange state with random peers every second, converging inO(log N)rounds) avoids any central leader bottleneck or externaletcdcluster outage on the 5M-writes/s hot path, though two Distributors can briefly see slightly different rings during a node join or leave. A hybrid works best at scale (and is used in production systems like Grafana Mimir and Cortex): use Gossip (with explicitJOINING -> ACTIVE -> LEAVINGtoken handoff states,N = 3replication, and shard-wide recent reads that absorb brief ring skew) for the high-throughput Ingester/Gateway hash rings, and a small Raft-backed store (or object-storage conditional Compare-And-Swap leases) for infrequent Compactor coordination and tenant limit configs.
Follow-up questions
- How should the storage engine ingest delayed samples whose timestamps precede the active write window while keeping background compaction safe?
- What safeguards at both ingestion and query execution prevent unbounded label keys such as `request_id` or `account_id` from destabilizing the cluster?
- How would you manage cluster membership and shard ownership across nodes, and what are the trade-offs between strong-consensus protocols like Raft and epidemic protocols like Gossip?
Similar questions
- Cross-Cloud Data Synchronization and Unified API Gateway
- Connected Land Regions in a Matrix
- Clockwise Spiral Order and Two-Sum Check
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform