Design a Time-Series Telemetry and Alerting Platform
Hard · System Design · Software Engineer · Technical Screen
Prompt
Design a multi-tenant time-series telemetry and alerting platform capable of collecting numeric health signals across a large fleet of microservices, storing years of historical trends cost-effectively, serving interactive dashboards, and paging on-call teams reliably when reliability targets slip.
Your system should address the following requirements:
- Telemetry collection: Ingest numeric
counter,gauge, andhistogramseries annotated with key-value dimensional labels across both pull (periodic target scraping) and push (agent/SDK streaming) workflows at high write throughput, applying graceful backpressure during overload. - Compressed, tiered time-series storage: Pack raw samples compactly in memory and on disk, and age data across hot and cold storage tiers using automated compaction and coarse-grained downsampling.
- Query engine & dashboards: Expose APIs and a time-series query language supporting label matchers, time-window downsampling, rate/percentile math, and cross-series aggregations for live dashboards.
- Threshold & SLO alerting: Continuously evaluate static threshold rules and Service Level Objective (SLO) burn-rate alerts with grouping, deduplication, maintenance silences, and multi-channel routing.
- Multi-tenancy & scale: Scale horizontally with high availability across failure zones, isolate tenants from noisy neighbors, cap active-series cardinality growth, and enforce per-tenant ingestion quotas.
Scope & Expectations
- Ingestion & query contracts: Compare pull vs. push collection boundaries, define write/query/alert APIs, and explain layered backpressure under traffic surges.
- Storage layout & indexing: Detail series identification, chunk compression, inverted label indexes, sharding, and hot-to-cold rollup compaction.
- Cardinality & tenant isolation: Show how per-tenant quotas, dynamic label controls, and shard placement prevent accidental label explosions from degrading shared infrastructure.
- Read/write paths, consistency & alerting: Walk through quorum durability, dashboard vs. alert consistency choices, node/zone failure recovery, and fault-tolerant alert deduplication.
Step-by-step walkthrough
Clarify requirements and scope
A metrics monitoring system collects numeric health signals from thousands of machines, stores them as time series (sequences of
(timestamp, value)points over time), serves fast dashboard charts, and pages engineers when something breaks. Three problems are much harder than the rest: keeping ingestion alive during traffic bursts and outages, stopping one team's accidental label explosion from crashing everyone else, and firing alerts without missing pages or sending floods of duplicates. Agree on the scope first so you can spend most of the interview on those three.Metric types and labels
Every metric has a name and a set of
key="value"labels (also called tags), such as{__name__="rpc_requests_total", service="payments", status="500", pod="payments-6b4d"}. Every unique combination of labels defines one distinct time series. We support three numeric metric types:- Counter: a cumulative number that only goes up (such as total requests served) and resets to
0only when the process restarts. - Gauge: a number that can go up or down freely (such as current memory usage or queue depth).
- Histogram: a distribution of measurements (such as request latency) recorded as cumulative counters per bucket (
le="0.05",le="0.1",le="0.25", ...,le="+Inf") plus_sumand_count. Unlike pre-computed per-pod percentiles, bucket counts can be summed accurately across thousands of pods.
Functional requirements
- Ingest metrics via both pull (agents periodically fetching
/metricsHTTP endpoints) and push (short-lived batch jobs, serverless functions, and OpenTelemetry SDKs sending metrics out). - Compress and store time series across hot, warm, and cold retention tiers, automatically downsampling older data into coarse summaries.
- Provide a time-series query language supporting label filtering, per-second rates, cross-series aggregations, and histogram percentiles for dashboards and APIs.
- Evaluate threshold and SLO (Service Level Objective — an agreed reliability target such as 99.9% successful requests) alert rules, with grouping, silencing, deduplication, and routing to pagers, chat, and webhooks.
- Isolate multiple tenants (teams or customers) and enforce per-tenant cardinality and rate quotas.
Non-functional requirements and scale assumptions
- Write availability first: ingestion must stay up during partial outages because incidents are the exact moment engineers need metrics most. Target
99.9%availability for writes, queries, and alerts. - Freshness and latency: newly scraped samples become queryable within
30 s; alert rules evaluate within1 min; 24-hour dashboard queries return in under2 satp99(99th percentile). - Scale (confirm with interviewer):
100Mactive series across500tenants (largest tenant:20Mseries), scraped every15 sin one region across3availability zones (AZs — physically separate data centers with independent power and networking). - Retention: raw
15 ssamples for15 days,5-minuterollups for13 months, and1-hourrollups for5 years.5,000live dashboards and100,000recording/alerting rules.
- Counter: a cumulative number that only goes up (such as total requests served) and resets to
Back-of-the-envelope numbers
Let us turn the scale assumptions into concrete throughput, memory, and storage targets so we know where the real bottlenecks sit.
Ingestion throughput samples per second 100M active series / 15 s interval = ~6.7M samples/s network into cluster ~50 B/sample compressed on the wire = ~335 MB/s (~2.7 Gbps) (labels travel with batches in remote-write) internal replication x3 replicas across 3 AZs = ~1.0 GB/s internal traffic Storage (using Gorilla time-series compression at ~1.5 bytes per raw sample) raw per day (1 copy) 6.7M samples/s x 86,400 s/day x 1.5 B = ~864 GB/day raw for 15 days 864 GB/day x 15 days = ~13 TB (after deduplicating 3 replicas) 5-min rollups 288 windows/day x 100M series x 10 B/point = ~288 GB/day -> ~114 TB for 13 months (5 summary numbers per window at ~2 B each) 1-hour rollups 24 windows/day x 100M series x 10 B/point = ~24 GB/day -> ~44 TB for 5 years total object storage 13 TB + 114 TB + 44 TB = ~171 TB (plus ~10-15% for indexes) Ingester memory (recent active data held in RAM) replicated series 100M series x 3 replicas = 300M in-memory series per ingester node ~2.5M series on a 32-64 GB RAM node (~8 KB/series for labels, index, chunk) ingester fleet 300M / 2.5M = 120 ingesters (40 per AZ, ~167k samples/s each) Query load live dashboards 5,000 dashboards x 10 panels / 30 s refresh = ~1,700 range queries/s rule evaluations 100,000 rules / 30 s evaluation interval = ~3,300 instant queries/sWhat the math tells us:
335 MB/sof network traffic and171 TBof cheap object storage (such as S3 or GCS) are very manageable. The dangerous number is cardinality — the count of distinct active series. Ingester RAM (120stateful nodes), inverted index size, and query scan cost all scale directly with the number of distinct label combinations, not with the number of bytes per sample.API and query language
Every request passes through an authentication gateway that extracts the
tenant_idfrom the caller's API token or mTLS certificate and injects an internalX-Scope-OrgIDheader. Clients never passtenant_idas a query parameter, so one tenant can never read or write another tenant's data.Write APIs (HTTP + Snappy-compressed Protobuf) POST /api/v1/push Prometheus remote-write from cluster agents POST /otlp/v1/metrics OpenTelemetry push from SDKs and short-lived jobs 200 OK Stored on a quorum (at least 2 of 3 ingesters) 202 Accepted Dropped intentionally (standby replica of an HA agent pair) 400 Bad Request Malformed labels or over hard series quota -> sender drops, no retry 429 Too Many Requests Tenant sample/s rate limit exceeded -> sender buffers and retries 503 Service Unavailable Server overloaded -> sender buffers and retries with backoff Read APIs GET /api/v1/query?query=<expr>&time=<ts> Instant evaluation (used by alerts) GET /api/v1/query_range?query=<expr>&start=&end=&step= Time-range series (used by dashboard graphs) GET /api/v1/series?match[]=<selector>&start=&end= Metadata lookup of matching series GET /api/v1/cardinality?limit=20 Top metric names and label keys by series count Alerting, silences, and admin APIs PUT /api/v1/rules/<namespace> Upload validated YAML alerting and recording rule groups GET /api/v1/alerts List pending and firing alerts POST /api/v2/silences Mute matching notifications for [starts_at, ends_at] with audit comment PUT /api/v1/tenants/<id>/limits Update per-tenant series and ingestion quotas (admin only)Notice why status codes distinguish
400from429/503: retrying invalid data or a label-explosion series only wastes bandwidth, whereas retrying during a brief rate spike preserves data in the agent's local buffer.PromQL-style query model
Queries follow four composable stages: select series by label matchers (
=,!=,=~regex,!~), slice a time window ([5m]), apply per-series math (ratedetects counter resets automatically when a sample drops below the previous one), and aggregate across series (sum by (service)):# 1. Per-service 5xx error ratio over 5 minutes sum by (service) (rate(rpc_requests_total{env="prod", status=~"5.."}[5m])) / sum by (service) (rate(rpc_requests_total{env="prod"}[5m])) # 2. Fleet-wide p99 latency from histogram buckets (sum buckets across pods first, never average p99s!) histogram_quantile(0.99, sum by (le, service) (rate(rpc_request_duration_seconds_bucket[5m]))) # 3. 30-day memory trend (automatically routed to 5-minute rollups by the query planner) avg_over_time(node_memory_used_bytes{cluster="us-east-1"}[1h])Data model: series, chunks, blocks, and inverted index
Series identity. A series is uniquely identified by
(tenant_id, sorted_labels). We hash this pair into a 64-bit integerseries_id. Across100M(10^8) series, the birthday-paradox chance of at least one 64-bit hash collision is roughly(10^8)^2 / (2 x 2^64) ≈ 0.00027(0.027%) — rare, not zero — so ingesters store the full sorted label set alongside eachseries_idand verify exact label equality on lookup (chaining on collision).Gorilla chunk compression. Raw samples
(timestamp_ms: int64, value: float64)would cost16 byteseach, or~9.2 TB/day. Instead, ingesters pack ~120 consecutive samples of one series (30 minutes at 15 s intervals) into a compressed chunk using Facebook's Gorilla encoding:- Timestamps use delta-of-delta encoding: because scrapes happen every
15,000 ms, the first difference (delta) between consecutive timestamps is almost always15,000, so the difference between consecutive deltas (delta_of_delta) is0and compresses to a single0bit! Small jitter (+1 ms,-2 ms) takes only a few bits. - Values use XOR encoding: each
float64is XOR-ed with the previous value. If a gauge stays unchanged, XOR is0(stored as1bit); if it changes slightly, only the changed mantissa bits are written. Together, real-world metrics average 1.3 to 1.6 bytes per sample (~10x smaller than raw).
def delta_of_delta(timestamps): """Compute second differences of scrape timestamps for Gorilla compression.""" # Regular 15,000 ms scrapes produce 0s, which compress to 1 bit each second_diffs = [] prev_delta = None for i in range(1, len(timestamps)): delta = timestamps[i] - timestamps[i - 1] if prev_delta is not None: second_diffs.append(delta - prev_delta) prev_delta = delta return second_diffs # Scrape jitter of +1 ms at 45s (delta=15001, then next delta=14999) gives tiny diffs: [0, 1, -2] assert delta_of_delta([0, 15000, 30000, 45001, 60000]) == [0, 1, -2]Immutable blocks and the inverted index (postings). Every
2 hours, each ingester seals its recent chunks into an immutable directory (a block) in object storage under<tenant_id>/<block_id>/. Inside each block is an inverted index — the same data structure search engines use to map words to document IDs, except here we map eachlabel="value"pair to a sorted list ofseries_ids (called a postings list):Block <tenant_id>/<block_id>/ (covers a fixed time range, e.g., 12:00 - 14:00) chunks/000001 ... Gorilla-compressed sample byte slices index symbol table Every unique string ("payments", "500", ...) stored once as an integer ID series table series_id -> full labels + [(min_t, max_t, chunk_file_offset), ...] postings lists (__name__="rpc_requests_total") -> [201, 208, 215, 340] (service="payments") -> [201, 208, 412] (status="500") -> [208, 340] (status="503") -> [215, 412] meta.json min_time, max_time, resolution (raw | 5m | 1h), compaction_level tombstones Ranges marked for deletion Evaluating rpc_requests_total{service="payments", status=~"5.."}: 1. Union status=~"5.." postings: [208, 340] U [215, 412] = [208, 215, 340, 412] 2. Intersect with __name__ list: [201, 208, 215, 340] ^ [...] = [208, 215, 340] 3. Intersect with service list: [208, 215, 340] ^ [201, 208, 412] = [208] -> Fetch chunk bytes ONLY for series 208!Relational metadata with low write volume — tenant configs, quota limits, rule definitions, dashboards, and silence audit logs — lives in PostgreSQL.
- Timestamps use delta-of-delta encoding: because scrapes happen every
High-level architecture
We split the system into three isolated compute paths (inspired by Prometheus Mimir / Cortex / Thanos): the write path, the dashboard read path, and the alert path. Separating their worker pools ensures a user running a slow 30-day dashboard query can never starve ingestion or delay an on-call page.
Monitored Pods / Services Batch Jobs, Lambdas, OTLP SDKs | GET /metrics every 15s (pull) | POST /otlp/v1/metrics (push) v | Cluster Agent (HA pair: replica a & b) | (service discovery, relabel, 2h disk WAL) | | Snappy Protobuf remote-write | v v [ Auth Gateway ] (extracts tenant_id from token/mTLS) ─────────────────────────────┐ | WRITE PATH READ PATH | v v [ Distributors ] (stateless) [ Query Frontend ] validate, drop rules, token-bucket rate limit, align steps, split by day, HA replica dedup, hash series -> ring (RF=3 across 3 AZs, W=2) cache past days, per-tenant queues | | v [ Queriers ] [ Ingesters ] (120 stateful nodes) <───────────────────────────────────────┼───────┐ append to SSD WAL + RAM head chunk, cut 2h blocks last 13h | | older than 12h | upload every 2h v v [ Store Gateways ] [ Object Storage (S3/GCS) ] <── [ Compactor ] cache block index headers, per-tenant block prefixes dedup 3 replicas -> 1 copy, byte-range fetch chunks merge 2h -> 24h, build 5m & 1h rollups | enforce 15d / 13m / 5y retention <───────────────┘ ALERT PATH (isolated pool): [ Rulers ] (sharded by rule group) ──> [ Dedicated Alert Queriers ] | firing / resolved alerts (sent to all 3 replicas) v [ Alertmanager ] (3 replicas, gossip sync) ──> PagerDuty, Slack, Email, Webhooks [ PostgreSQL ]: tenants, quotas, rules, dashboards [ Memcached ]: query results, postings, chunksDeep dive 1: write path, replication, and backpressure
Pull at the edge, push to the center. Inside each Kubernetes cluster or VPC, a lightweight collection agent discovers local pods, scrapes
/metricsevery15 s, and pushes batches to the central monitoring service:- Why pull locally? The agent controls the scrape rate (a buggy service cannot flood it), gets a built-in health signal (
up = 0immediately if a scrape fails, plus a staleness marker when a pod disappears so charts do not flatline on old values), and lets engineers inspect/metricsin a browser. - Why push centrally? The central platform exposes one authenticated write endpoint without needing firewall holes into hundreds of application VPCs. Short-lived batch jobs and serverless functions that exit in
2 seconds(before a15 sscrape could ever catch them) push directly via OpenTelemetry (OTLP). If an SDK pushes delta counters ("+5 since last push"), a stateless routing tier hashes the series to a stateful aggregator that converts deltas into cumulative counters before ingestion.
HA agents without double counting. One crashed agent must not blind a cluster, so each cluster runs two identical agents (
replica="a"andreplica="b") scraping the same pods. Distributors track one elected leader per(tenant, cluster)in a fast key-value store (etcd or Consul): samples from leaderaare stored (200 OK), while samples from standbybare acknowledged and discarded (202 Accepted— a success code sobdoes not retry or fill its buffer). Ifastops sending for30 s, distributors promotebautomatically.Quorum replication without Kafka in the hot path. Distributors hash
(tenant_id, series_id)onto a consistent-hash ring (a virtual circle where adding or removing one node moves only1/Nof keys) and send each sample in parallel toN = 3ingesters — one in each of the 3 AZs. A write succeeds as soon asW = 2ingesters append the sample to their local SSD write-ahead log (WAL) (an append-only disk file replayed after a crash) and in-memory chunk. Skipping a central Kafka cluster saves an extra stateful fleet and network hop because the edge agents' local2-hourWAL disks already act as our distributed burst buffer!Layered backpressure (protecting the core from overload):
- Edge agent buffer: if the central API returns
429or503, the agent buffers samples in its local2-hourSSD WAL and retries with jittered exponential backoff (up to5 min). If an outage lasts longer than2 hours, it drops the oldest buffered data first so fresh incident metrics arrive first. On400, it drops the invalid batch immediately and increments a self-monitoring counter. - Distributors: each distributor enforces
tenant_rate_limit / num_healthy_distributorslocally in memory using a token bucket (a counter that refills atRtokens/sec up to a burst cap, spending 1 token per sample with zero network calls) and sheds excess with429. Hard caps on in-flight bytes protect distributor RAM (503). - Ingesters: if an ingester runs out of memory (OOM), replaying gigabytes of WAL on restart takes several minutes — the worst possible failure during an outage. Above
85%RAM, an ingester refuses new series creation while still accepting appends to existing series, and rejects excess in-flight requests with503. When buffered data arrives minutes late after recovery, ingesters accept out-of-order samples up to a1-hourwindow.
- Why pull locally? The agent controls the scrape rate (a buggy service cannot flood it), gets a built-in health signal (
Deep dive 2: retention tiers, compaction, and downsampling
Hot, warm, and cold tiers balance query speed against storage cost:
Tier Age & Resolution Storage Medium Typical Query Latency Hot Last ~13 hours, raw15 sIngester RAM (last 2 hhead) + local SSD (memory-mapped chunks)Single-digit to tens of ms Warm Raw up to 15 days;5-minrollups up to90 daysStandard object storage + Store Gateway SSD/Memcached caches 50 - 500 msCold 5-minrollups90 d - 13 mo;1-hourrollups up to5 yearsInfrequent-access object storage (cheaper per GB stored, small per-GB read fee) 200 ms - 2 sWhy compaction is essential. Every
2 hours, all3replica ingesters upload blocks containing the same series. Background compactors process each tenant's blocks in object storage to do four jobs:- Deduplicate replicas (
3x -> 1xstorage): merge the 3 replica blocks by keeping one sample per unique timestamp, cutting39 TBof 15-day raw data down to13 TB. - Merge small blocks (
2 h -> 12 h -> 24 h): so a 15-day query opens15daily block indexes instead of180two-hour indexes. Stopping at24-hourblocks is equally important for pod churn: when daily deploys replace pod names, old pod series exist only in yesterday's block index rather than bloating one permanent global index forever! - Generate downsampled rollups for blocks older than
2 days(5-minuteand1-hourwindows). - Apply tombstones and retention expiry using two-phase delayed deletion (mark soft-deleted first, remove files hours later so in-flight queries never crash mid-read).
Downsampling without breaking math. Simply storing the 5-minute average would destroy latency spikes, counters, and histograms! Instead, each rollup point stores five summary values per window:
count,sum,min,max, andcounter_increase(the reset-adjusted counter gain inside that window, catching any drop to0across consecutive raw samples, including the boundary sample from the previous window). From those five numbers:avg_over_timeissum / count, andmax_over_timepreserves brief 15-second spikes inmax.rate()andincrease()over any multi-day span simply sumcounter_increaseacross windows and divide by time — even across separate 24-hour blocks!histogram_quantile()still works because each histogram bucket (_bucket{le="0.25"}) is itself a counter whosecounter_increaseis preserved.
A 30-day dashboard chart (~1,000 pixels wide, ~43-minute step) reads
8,640five-minute rollup points per series instead of172,800raw 15-second samples — 20x less data fetched and decoded.- Deduplicate replicas (
Deep dive 3: cardinality control and multi-tenant isolation
How a cardinality explosion happens. Suppose
rpc_requests_totalnormally has5methods ×10routes ×5status codes ×40pods =10,000series. A developer accidentally addsuser_id(5,000,000users) or un-normalized URL paths (/invoices/981723) as a label. Within minutes, one deploy creates millions of brand-new series, blowing up ingester RAM and inverted indexes.Defense Layer 1: quotas that fail safe. Each tenant gets configurable defaults (for example:
2Mactive series total,200kseries per metric name,30labels per series,200ksamples/s).- At ingesters (enforcing active-series caps): only ingesters know whether a
series_idis already in memory. If a tenant's series are spread across a shard ofS = 12ingesters with replication factorRF = 3, each ingester enforces a local cap with zero cross-node coordination:local_series_limit = global_limit x RF / S = 2,000,000 x 3 / 12 = 500,000 series. Crucially, when a tenant hits this cap, the ingester rejects only brand-new series (400with reasonmax_series_per_tenant) while continuing to accept samples for existing series. The offending team's existing dashboards and alerts stay live while they debug! - At distributors (instant mitigation without redeploying): tenants inspect
/api/v1/cardinality(which reports top metrics and labels with the most distinct values) and get automated alerts at80%of quota via internalactive_seriesmetrics. An admin or tenant can push a dynamic relabel rule (action: labeldrop, regex: "user_id") to distributors that strips the bad label in milliseconds without waiting for a code rollback.
Defense Layer 2: shuffle sharding (blast-radius isolation). If every tenant wrote to all
120ingesters, one runaway tenant triggering an OOM bug would degrade all120nodes and hurt all500customers. Instead, we assign each small/medium tenant a deterministic, pseudo-random subset of12ingesters (4out of40in each of the3AZs):AZ-1 (40 ingesters) AZ-2 (40 ingesters) AZ-3 (40 ingesters) Tenant A shard: [3,11,19,34] [2,15,27,38] [7,14,22,39] (12 nodes total) Tenant B shard: [5,11,24,39] [8,16,29,31] [1,12,25,33] (overlaps ONLY node 11 in AZ-1!) Probability a random series of Tenant B hits an overloaded Tenant A node in one AZ = 4 / 40 = 10%. With 1 replica per AZ and quorum 2-of-3, Tenant B loses a series ONLY if >= 2 of its 3 AZ replicas land on dead Tenant A nodes: 3 x (0.10)^2 x 0.90 + (0.10)^3 = 2.8% even if ALL 12 of A's nodes died!Shuffle sharding also cuts query fan-out by
10x: a query for Tenant A asks at most12ingesters, not120.- At ingesters (enforcing active-series caps): only ingesters know whether a
Deep dive 4: alerting, SLO burn rates, and deduplication
Fault-tolerant rule evaluation. Rules live in named groups hashed onto a Ruler ring. Every
30 s, the assigned ruler evaluates a group's recording rules (pre-computed expensive queries written back as new time series) and then its alert rules, using a dedicated alert-querier pool isolated from dashboard traffic.Each alert series follows a state machine:
inactive -> pending -> firing -> resolved. Afor: 10mclause keeps brief blips inpendinguntil the condition holds continuously for10 minutes. Rulers persistALERTS_FOR_STATEtimestamps back into the time-series store itself, so if a ruler crashes at minute9, the new ruler picks up at minute9instead of resetting the timer to0! Because missing metrics causeerror_rate > 0.05to return an empty set (silentlyfalse), critical services pair threshold alerts withabsent(up{service="payments"})rules.Multi-window, multi-burn-rate SLO alerts. Alerting on raw CPU or single-minute blips causes pager fatigue. Instead, if a service targets a
99.9%30-day availability SLO, its monthly error budget is0.1%of30 days(43.2 minutesof 100% outage). Burn rate measures how fast that budget is being consumed relative to a 30-day pace (burn_rate = current_error_ratio / 0.001):Severity | Long Window & Short Window | Error Ratio | Budget Burned | Why Both Windows? ---------+-------------------------------------+-------------+---------------+---------------------------------- Page | burn_rate > 14.4 over 1h AND 5m | > 1.44% | 2% in 1 hour | 1h proves real impact; 5m stops Page | burn_rate > 6.0 over 6h AND 30m | > 0.60% | 5% in 6 hours | paging within minutes of the fix! Ticket | burn_rate > 1.0 over 3d AND 6h | > 0.10% | 10% in 3 days | Slow leak -> daytime Jira ticketChecking both windows (
AND) prevents false pages on brief 2-minute spikes (fails the1hcheck) AND prevents the alert from staying firing for55 minutesafter engineers roll back the bad deploy (clears as soon as the5mwindow recovers!).Alertmanager: deduplication, grouping, silences, and HA. Every ruler sends firing alerts to all 3 Alertmanager replicas:
- Deduplication & grouping: alerts with identical labels share a fingerprint, deduplicating repeated 30-second evaluations. Grouping by
(cluster, service)waits30 son the first alert so100crashing pods trigger one consolidated page instead of100. - Inhibition & silences: if
ClusterDown{cluster="eu-1"}is firing, inhibition suppresses downstream warning alerts ineu-1. Maintenance windows create time-bounded silences (label matchers + expiry + author comment) that mute notifications without stopping rule evaluation. - No duplicate pages across 3 replicas: replicas gossip silences and a notification log of already-sent group keys. Replica
0sends immediately and gossips the log entry; Replica1waits15 sand stays quiet once it sees Replica0succeeded. During a network partition, two replicas may both page — at-least-once delivery is intentional because waking an engineer twice is far safer than missing an outage.
- Deduplication & grouping: alerts with identical labels share a fingerprint, deduplicating repeated 30-second evaluations. Grouping by
Scaling, failure modes, consistency, and trade-offs
Fast read path at scale. A querier fetches the last
13 hoursfrom ingesters and blocks older than12 hoursfrom Store Gateways (the1-houroverlap hides block-upload lag; duplicate timestamps merge idempotently). Store Gateways keep only compact block index headers (symbol tables and postings byte offsets) on local SSD and perform HTTP byte-range reads through Memcached for just the matching postings and chunks. Ahead of queriers, the Query Frontend aligns query timestamps tostepboundaries, splits multi-day queries into per-day sub-queries (caching completed historical days so a 30-second dashboard refresh only computes the trailing few minutes!), shards associative aggregations (sum,count,min,max) into16parallel series-hash slices, and enforces hard per-query limits (500kmax series,50Mmax samples) so a "query of death" returns a clear422error instead of crashing a querier.Consistency, failures, and meta-monitoring
- Quorum consistency (
N = 3, W = 2, R = 2): writes require2AZ replicas and reads merge answers from at least2replicas (R + W > N), guaranteeing every acknowledged sample appears in reads. If two replicas of a shard fail simultaneously, dashboards degrade gracefully by serving1replica with a"partial data"banner, whereas alert rulers fail the evaluation and retry in30 sso missing data never falsely resolves a firing alert! - Surviving major outages: losing an entire AZ leaves
2replicas in the remaining2AZs (both writes and reads stay100%healthy). If object storage has an outage, ingesters buffer sealed 2-hour blocks on local SSD (sized for24 hours), keeping fresh dashboards and all alerts running uninterrupted. - Who monitors the monitor? A tiny, independent monitoring stack in a separate failure domain scrapes this platform's health metrics. In addition, an always-firing
"Watchdog"alert routes through the full Alertmanager pipeline every minute to an external dead man's switch service, which pages on-call if the heartbeat stops arriving — catching total silent failure of the alerting pipeline itself.
Summary of key architectural trade-offs
- Pull at the edge + push to the center gives automatic target health (
up = 0) and scrape protection locally while keeping a single firewall-friendly central write API, at the cost of running lightweight cluster agents. - Direct 2-of-3 quorum ingesters + agent SSD WALs avoid operating a massive central Kafka cluster while surviving node and AZ failures with lower ingest latency.
- Gorilla chunks + 24-hour immutable object-storage blocks + 5-value rollups shrink storage ~10x, bound pod-churn index growth, and speed up 30-day queries
20x, trading sub-window granularity on old data for massive cost and speed wins. - Per-tenant new-series rejection + shuffle sharding contain label explosions to a
12-node shard while keeping existing dashboards and alerts alive.
- Quorum consistency (
Intuition & how it works
Think of a time-series telemetry platform like the central ward of a large hospital watching heart-rate monitors attached to thousands of patients. Every 15 seconds, each bedside monitor emits a tiny numeric reading tagged with labels (patient, ward, sensor_type); nurses need instant live screens for the last few hours, doctors need summarized charts across months of history without reading millions of raw heartbeats, and an alarm system must page the right doctor when a patient crashes — without ringing 100 separate bells when a single power strip unplugs.
The obvious naive approach — inserting every (metric_name, labels_json, timestamp, value) reading as a row in a traditional relational database like PostgreSQL — collapses immediately at scale. At 100 million series scraped every 15 seconds (6.7 million writes per second), B-tree indexes thrash disk I/O, uncompressed rows consume nearly 10 TB per day, and a single buggy deployment that puts a unique request_id into a label creates millions of distinct tag combinations that exhaust memory and freeze queries for every team sharing the database.
Here is how a single metric flows through our design on a tiny 3-scrape example:
- Scrape & push: A
paymentspod exposes a cumulative counterrpc_requests_total{service="payments", status="500"}with values20att = 0 s,23att = 15 s, and29att = 30 s. A local cluster agent scrapes/metrics, buffers to a local write-ahead log (WAL — an append-only disk file for crash recovery), and pushes compressed batches to stateless Distributors. - Shard & compress: The Distributor checks the tenant's quota, hashes the sorted label set to a
series_id(#208), and writes to3Ingesters across3availability zones (succeeding once2acknowledge). Each Ingester compresses timestamps using delta-of-delta ([15000 - 15000] = [0], taking 1 bit!) and values using XOR encoding, packing samples into ~1.5 bytes each in memory. - Index & tier: Every
2 hours, Ingesters upload an immutable block to object storage with an inverted index (mappingstatus="500" -> [208]). Background Compactors deduplicate the3replica blocks down to1copy and build5-minuteand1-hourrollups (count, sum, min, max, counter_increase) for fast multi-month graphs. - Query & alert: Every
30 seconds, a Ruler runsrate(rpc_requests_total{service="payments", status="500"}[5m])on an isolated query pool, intersects the inverted-index lists to read only series#208, detects sustained error budget burn, and sends the firing alert to a 3-replica Alertmanager, which groups related pod alerts into a single page.
Key trade-offs
- Pull at the edge vs. push everywhere. Pull scraping gives an automatic liveness metric (
up = 0when a target stops answering) and prevents runaway services from flooding the collector, whereas push works for short-lived batch jobs and serverless functions that finish between scrapes. Scraping via local cluster agents and pushing compressed batches to the central cluster captures both benefits, at the cost of deploying an agent per cluster. - Direct quorum writes (
W = 2of3) vs. a Kafka log in front of ingesters. Writing directly from distributors to 3 zone-separated ingesters keeps ingest latency low and avoids running a multi-gigabyte-per-second Kafka cluster. A central Kafka log would offer longer central replay windows, so we compensate by giving every edge agent a2-hourlocal SSD WAL buffer. - Availability over strict consistency for dashboard reads, reversed for alerts. Monitoring is needed most during outages, so dashboards accept partial answers (with a warning banner) if 2 of 3 replicas of a shard fail. Alert rule evaluation makes the opposite choice — it fails and retries on the next 30-second cycle rather than letting missing error counters falsely resolve a real firing page.
- Gorilla chunks and immutable object-storage blocks vs. mutable in-place tables. Compressing streams into immutable 2-hour blocks yields ~1.5 bytes per sample and cheap S3/GCS durability, and daily 24-hour blocks stop pod-restart churn from bloating a single global index forever. The trade-off is running background compactors and caching block index headers in Store Gateways so cold reads stay fast.
- 5-value rollups vs. long raw retention. Downsampling older blocks into
(count, sum, min, max, counter_increase)shrinks 30-day query scans by20xand makes 5-year history affordable (~44 TB), while preserving averages, peaks, counter rates, and histogram buckets. What you trade away is sub-window timing (you see that a spike hit98%inside a 5-minute bucket, not the exact second). - Rejecting only new series on quota breach + shuffle sharding. Dropping brand-new series when a tenant hits its active-series cap protects cluster memory while keeping that tenant's existing dashboards and alerts working during their own bad deploy. Shuffle sharding (assigning each tenant
12of120ingesters) bounds blast radius and cuts query fan-out10x, trading away perfectly uniform load balancing across all nodes. - At-least-once paging in Alertmanager. Three gossiping Alertmanager replicas suppress duplicate pages under normal operation, and intentionally allow a rare duplicate page during a split-brain network partition rather than risking a missed outage notification.
Common mistakes
- Sizing around bytes per second instead of active series (cardinality). Network bandwidth (
335 MB/s) is modest; what crashes monitoring systems is unbounded label values (user_id,request_id, raw URLs) multiplying in-memory series entries and inverted-index postings. - Averaging per-pod
p99latencies. The average of 1,000 pod 99th percentiles is mathematically meaningless when traffic is uneven across pods; pods must export cumulative histogram buckets (_bucket{le=...}) that are summed across pods first. - Ignoring counter resets. Treating a counter drop from
50,000to12after a pod restart as-49,988produces nonsensical negative spikes unlessrate()and rollup builders treat decreases as resets from0. - Sharing one query pool between user dashboards and alert rules. One engineer opening a heavy 90-day regex dashboard can queue behind all workers and delay critical paging alerts by minutes.
- Downsampling by storing only averages. Pure
avgrollups erase brief spikes (max), break counterrate()math, and ruin histogram bucket aggregation. - Storing all 3 replicated copies forever. Failing to deduplicate replica blocks during compaction triples long-term object storage costs for zero extra durability (object storage is already replicated internally).
- Forgetting meta-monitoring ("who watches the watcher?"). Without an external dead man's switch watching a continuous heartbeat alert, a broken Alertmanager outbound webhook fails completely silently.
Follow-up questions
- How do you compute an accurate fleet-wide p99 latency across 1,000 service pods? You cannot average per-pod percentiles because pods with 10 requests and pods with 100,000 requests would get equal weight and tail skew disappears. Instead, every pod exports a histogram (cumulative counters per latency bucket such as
le="0.1",le="0.25",le="0.5", or an exponential native histogram with automatic bucket boundaries). At query time,sum by (le) (rate(rpc_request_duration_seconds_bucket[5m]))merges all 1,000 pods into one fleet-wide latency distribution, andhistogram_quantile(0.99, ...)interpolates the 99th percentile; placing a bucket boundary right at your SLO target (say0.25 s) makes the SLO error ratio exact with zero interpolation error. - Suppose a buggy deployment attaches request_id as a metric label and creates 10 million new time series in 10 minutes—how does your platform contain the blast radius? Each ingester in that tenant's 12-node shuffle shard quickly hits its local active-series quota (
500,000series for a2Mtenant limit atRF = 3) and rejects samples for further new series with400 Bad Requestwhile continuing to ingest existing series so the tenant's normal dashboards and alerts keep working. Other tenants remain safe because shuffle sharding and the ingester85%RAM guard contain the load to those 12 nodes. The tenant receives an automated quota alert, spotsrequest_idvia/api/v1/cardinality, and applies a distributorlabeldroprule to striprequest_idimmediately without waiting for a rollback; note that the idle series created before the cap hit remain in the ingester's head until the next 2-hour block cut, so an admin may temporarily bump the tenant's series cap if legitimate new pod names deploy during that window. - How do you monitor the alerting and telemetry platform itself so a silent pipeline failure never goes unnoticed? A tiny, independent "meta-monitoring" instance running in a separate cluster or region (with zero shared storage or network dependencies) scrapes the main platform's distributors, ingesters, compactors, and rulers to alert on ingest error rates, WAL disk usage, compaction lag, and rule evaluation delays. In parallel, the main system runs an always-firing
"Watchdog"alert rule every minute through its real Alertmanager pipeline to an external dead man's switch, which pages on-call if the heartbeat stops arriving for 3 minutes. Finally, a synthetic canary service writes a known metric value every 15 seconds and queries it back to verify end-to-end ingest-to-query freshness.
Follow-up questions
- How do you compute an accurate fleet-wide p99 latency across 1,000 service pods?
- Suppose a buggy deployment attaches request_id as a metric label and creates 10 million new time series in 10 minutes—how does your platform contain the blast radius?
- How do you monitor the alerting and telemetry platform itself so a silent pipeline failure never goes unnoticed?
Similar questions
- End-to-End Project Execution, Risks, and Outcomes
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency