Multi-Region Telemetry Monitoring and Alerting
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a global metrics telemetry and real-time alerting platform for a fleet of thousands of microservice instances operating across 10+ geographic regions.
Your system must meet the following functional goals and scale constraints:
- Global metric collection: Reliably ingest time-series telemetry from distributed service hosts despite variable cross-network latencies.
- Dashboard & historical storage: Store metrics efficiently so operators can run fast live dashboard queries alongside multi-week or multi-month historical analysis.
- Stateful rule evaluation: Evaluate sustained threshold conditions (for instance, paging when a service's failure ratio stays above 5% continuously over a 3-minute window) and deliver notifications to on-call responders in under 30 seconds.
- Alert storm suppression: Coalesce and deduplicate related alerts so widespread regional incidents do not flood responders with thousands of redundant pages.
- High-cardinality guardrails: Prevent unbounded tag dimensions (such as per-user or per-request IDs like
user_idorrequest_id) from exhausting memory and index storage. - Target scale: Sustain 500,000 distinct metric time series per region and 5,000,000 ingested samples per second worldwide.
Scope & Expectations
- Pipeline components & data flow: Define the roles of collection agents, aggregation tiers, time-series storage, and alerting engines, tracing how a metric travels from a service host to both dashboards and on-call notifications.
- Cardinality & alert-storm controls: Detail concrete mechanisms for bounding label cardinality and deduplicating noisy outage alerts within the 30-second paging budget.
- Fault tolerance & late telemetry: Explain how the platform handles delayed or out-of-order samples and continues alerting when an entire region or cross-region link fails.
- Storage topology trade-offs: Compare centralized global metric storage against decentralized regional storage across bandwidth, query latency, and blast radius.
Step-by-step walkthrough
Clarify requirements and the core regional-first principle
Before drawing boxes, define the foundational terms and avoid the biggest trap in global monitoring. A time series is a stream of
(timestamp, value)data points identified by a metric name plus key-value tags called labels — for example,api_requests_total{service="billing", region="eu-west", status_class="5xx", instance="pod-7c4"}.The classic mistake is shipping every raw data point from all 10+ regions into one giant central database and running all alerts there. That design fails at the exact moment you need monitoring most: when a cross-region network link (WAN, wide-area network) is congested or severed, raw metrics cannot reach the center and on-call engineers get zero alerts. Our guiding principle is therefore: collect, store, and evaluate alerts locally inside each region, and ship only small pre-aggregated summaries ("rollups") across the WAN.
Functional requirements
- Ingestion: Collect three metric types from thousands of microservice instances across 10+ regions:
- Counters: cumulative totals that only increase until a process restarts (e.g.,
api_requests_total). - Gauges: point-in-time measurements that go up and down (e.g.,
memory_used_bytes). - Histograms: cumulative counters per latency bucket (e.g., requests finishing in
<= 10 ms,<= 50 ms,<= 250 ms) so percentiles like p99 can be aggregated across hosts.
- Counters: cumulative totals that only increase until a process restarts (e.g.,
- Storage & dashboards: Serve recent metrics at full 1-second resolution and historical trends from downsampled (coarser-grained) tiers.
- Stateful alerting: Evaluate sustained conditions such as paging when a service's 5xx failure ratio stays above
5%across a3-minutewindow per service/region, plus global rules (e.g., global error budgets or full-region health). - Alert deduplication & storm control: Coalesce related alerts using grouping, deduplication, silences, and root-cause suppression so a regional incident sends one actionable page instead of thousands.
- Cardinality protection: Block or cap high-cardinality labels like
user_idorrequest_id(cardinality means the total count of unique label combinations, i.e., distinct time series) before they exhaust memory and disk.
Non-functional requirements & assumptions
- Scale: 10 regions (designed to add more linearly),
500,000active series per region (5,000,000globally), and5,000,000data points/s globally (500,000points/s per region — an average of 1 sample per series per second). - Alert latency: Under
30 secondsfrom the moment a rule's condition has held for its full duration (e.g., the 3-minute mark) to the moment the paging provider accepts the notification. - Availability & partition tolerance: Regional ingestion and regional alerting must continue working even if the WAN or another region is completely unreachable.
- Dashboard query latency:
p95 < 2 secondsfor a 24-hour dashboard panel. - Retention policy (assumed):
15 daysat raw 1-second resolution,90 daysat 5-minute resolution, and2 yearsat 1-hour resolution.
- Ingestion: Collect three metric types from thousands of microservice instances across 10+ regions:
Back-of-the-envelope capacity and latency math
Turn the problem's numbers into concrete bandwidth, RAM, storage, and latency budgets:
1. Fleet & Ingestion Bandwidth (10 regions) Active series 500,000 / region (5,000,000 globally) Samples per second 500,000 / s / region (5,000,000 / s globally) Wire size (batched + Snappy/zstd) ~20 bytes / sample (amortized labels + timestamp + float) Regional ingress 500,000 x 20 B = 10 MB/s per region (~80 Mbps) Global raw ingress 100 MB/s = 8.64 TB/day (expensive & fragile over WAN!) 2. Time-Series Storage (Gorilla compression: ~1.5 bytes/sample on disk) Raw samples per day (global) 5,000,000 x 86,400 s = 432 billion samples/day Compressed raw storage 432B x 1.5 B = 648 GB/day globally (~64.8 GB/day per region) 15-day raw tier per region 64.8 GB x 15 = ~1.0 TB in regional object storage 3. Ingester RAM — Why Cardinality Is the Real Bottleneck Active head state in RAM ~4 KB / series (label set, index pointers, active 2h chunk) Healthy region (RF = 3 replicas) 500,000 x 3 x 4 KB = 6 GB RAM across the region (easy!) Accidental `user_id` bug on ONE metric (1M users x 10 endpoints): 10,000,000 extra series x 3 x 4 KB = 120 GB RAM instantly -> OOM crash without limits! 4. Regional-to-Global Rollups (drop `instance` label, aggregate to 10-second windows) Series per region after rollup ~20,000 (service x endpoint x status_class) Rollup samples/s per region 20,000 series / 10 s = 2,000 samples/s (20,000/s globally) Cross-region WAN bandwidth 2,000 x 20 B = 40 KB/s per region (400 KB/s globally -> 250x smaller!) Global rollup storage 20,000/s x 86,400 s x 1.5 B = ~2.6 GB/day (< 1 TB/year) 5. End-to-End 30-Second Alert Notification Budget (after 3-minute breach completes at t = 180s) Scrape + gateway + log + ingester <= 2.0 s (overlaps inside the 5.0 s straggler watermark below) Straggler watermark delay 5.0 s (engine evaluates `now - 5 s` so batches align) Rule tick wait + RAM query <= 5.5 s (5.0 s tick interval + 0.5 s query & alert push) Notifier `group_wait` window 5.0 s (coalesce sibling alerts from the same outage) Backup notifier handoff 0.0 s (+5.0 s if primary notifier node is dead; +10.0 s if 2 dead) Paging provider API call 1.0 - 3.0 s ------------------------------------------------------------------------------------------- Worst-case total ~18.5 s normal | ~23.5 s (1 node down) | ~28.5 s (2 nodes down)Three design conclusions jump right out of this math:
- Data point volume (
10 MB/sper region) is modest; cardinality is the killer. Every active time series costs~4 KBof in-memory state per replica. One developer addinguser_idmultiplies active series20xand blows up RAM, so cardinality guardrails must sit at the front door. - Hierarchical rollups cut WAN traffic
250x(100 MB/sdown to400 KB/s) while keeping each region self-sufficient during WAN cuts. - Why ingest lag and watermark delay overlap: Because the alert engine deliberately evaluates timestamp
now - 5 s, the<= 2 spipeline lag from host scrape to ingester memory finishes during that 5-second wait rather than adding on top of it, keeping even double-failover alerts inside30 seconds.
- Data point volume (
API design
We expose three clean internal interfaces: a regional write endpoint for host collectors, a Prometheus-style query API for dashboards, and a versioned rules/alerts API.
1. Regional Ingest API (Host Collector -> Regional Gateway; never crosses WAN) POST /v1/write (Content-Type: application/x-protobuf; Content-Encoding: snappy) { "series": [ { "labels": {"__name__": "api_requests_total", "service": "billing", "endpoint": "/v2/invoices/{id}", "status_class": "5xx", "instance": "pod-7c4"}, "samples": [[1764421200000, 2410.0], [1764421201000, 2413.0]] } ] } -> 204 No Content (all accepted) -> 400 Bad Request {"rejected": [{"metric": "api_requests_total", "reason": "disallowed_label:user_id"}]} // partial reject! -> 429 Too Many Requests {"retry_after_ms": 2000, "reason": "service_series_cap_exceeded"} 2. Dashboard & Ad-Hoc Query API GET /v1/query_range?expr=sum by (service)(rate(api_requests_total{status_class="5xx"}[1m])) &start=1764334800&end=1764421200&step=15s&tier=auto // `tier=auto` selects raw (<= 48h), 5m rollups (<= 30d), or 1h rollups (> 30d) GET /v1/cardinality?service=billing // returns top metrics and label names ranked by estimated distinct series count 3. Alert Rules, Backtesting & Silences API PUT /v1/rules/{rule_id} { "version": 17, "scope": "region", "expr": "sum by (service, region)(rate(api_requests_total{status_class='5xx'}[1m])) / sum by (service, region)(rate(api_requests_total[1m])) > 0.05", "min_volume_expr": "sum by (service, region)(rate(api_requests_total[1m])) > 1", "for": "3m", "keep_firing_for": "2m", "labels": {"severity": "page", "team": "revenue"} } POST /v1/rules:backtest {"rule": {...}, "from": ..., "to": ...} -> historical firing windows POST /v1/silences {"matchers": [{"region": "eu-west"}], "ends_at": ..., "comment": "..."}Two API choices save hours of operational pain: - Explicit partial rejects (
400withreason), never silent drops: If a team accidentally emits a forbiddenuser_idlabel, valid metrics in the same batch still succeed while the collector logs and counts the exact rejection reason immediately. - First-class/v1/rules:backtest: Letting engineers replay a proposed rule change over the last 30 days of stored metrics catches noisy thresholds before anyone gets paged at 3 AM.Data model and specialized time-series indexing
Series identity. Every unique combination of metric name + sorted labels hashes to a deterministic 64-bit integer
series_id = hash64("__name__=api_requests_total,endpoint=/v2/invoices/{id},..."). Across5,000,000series, the birthday-paradox collision probability(N * N) / (2 * 2^64)is roughly6.8 * 10^-7(less than 1 in a million), and storing the full label dictionary in the block index allows exact verification so even a hash collision never corrupts data.How the Time-Series Database (TSDB) stores samples and resolves label queries fast:
A standard relational row
(timestamp, metric, labels_json, value)wastes100+ bytesper point and scans millions of rows to filter labels. Instead, a TSDB separates label lookup (an inverted index, which maps eachlabel=valuetag to a sorted list of matchingseries_idintegers, just like a book index maps words to page numbers) from sample compression (Gorilla compression, which stores differences-of-differences for regular 1-second timestamps and XORs consecutive floating-point values so an unchanging or smoothly changing metric shrinks from16 bytesto~1.5 bytesper sample):1. Specialized Metric Inverted Index (inside each 2-hour immutable TSDB block) Postings list for service="billing" -> [114, 208, 519, 840, 845] (sorted series_ids) Postings list for status_class="5xx" -> [062, 208, 703, 840] (sorted series_ids) | | Sorted list intersection (linear scan) --------> [208, 840] <---+ 2. Block Layout in Regional Object Storage (flushed from Ingester RAM every 2 hours) block_01J9.../ index symbol table + sorted postings lists `(label, value) -> [series_id, ...]` bloom Bloom filter of `series_id`s (~10 bits/series -> 1% false positives, 0 false negatives) so queries for specific series skip irrelevant historical blocks without opening `index` chunks/ Gorilla-compressed ~120-sample chunks grouped sequentially by `series_id` meta.json min_time, max_time, resolution_tier (`raw` | `5m` | `1h`), region 3. Stateful Alert & Notification Records alert_instance fingerprint = hash64(rule_id + sorted_group_labels), phase (`inactive`|`pending`|`firing`), pending_since, firing_since, clear_since, rule_version (checkpointed every 5 s) notify_log (group_key, receiver, alert_set_hash, sent_at) (gossiped across notifiers)Notice why high cardinality (
request_id="req-99812") breaks this index: instead of oneseries_idaccumulating7,200compressed samples over 2 hours, you get millions of 1-sampleseries_ids, bloating the symbol table and postings lists until the index is larger than the metric values themselves.High-level architecture and end-to-end data flow
Here is how the four core components (Collector, Aggregator, Storage, and Alert Engine) fit together across each region and the global tier:
====================== Region R (1 of 10+ independent regions) ====================== [Service Instances (~1,000)] | 1s local pull (/metrics) or local push v [1. Collector: Per-Host Agent] - URL templating, label allowlist, per-metric series cap, 2h local disk buffer | Snappy-compressed Protobuf batches (in-region only) v [Regional Ingest Gateway] ---> enforces per-service quotas, returns 400 / 429 | v [Regional Kafka Log (24h retention, RF=3)] <--- decouples spikes & node restarts | | | Consumer Group A | Consumer Group B v v [3a. Storage: Regional TSDB Ingesters] [2. Aggregator: Regional Rollup Workers] - RF=3 by `series_id` hash - drops `instance`, computes 10s reset-aware - local WAL + 2h in-memory head counter increases, gauge min/max/sum/count, | | and merged histogram buckets | flush 2h blocks | dedicated low-latency | v | alert query path | async WAN push (~40 KB/s) [Regional Object Store] v | shipped to 2 global regions raw (15d), 5m (90d), [4a. Regional Alert Engine (x2)] | 1h (2y) <- [Compactor] - evaluates 5s ticks | - checkpoints timer state | =============================================================|======================= | firing/resolved alerts v | (both replicas send) [3b. Global Rollup Store (x2)] | - 200k rollup series (10s res) | | | [4b. Global Alert Engine (x2)] | - global SLOs & `RegionDegraded` v | [4c. Notifier Cluster (3 nodes across 3 regions)] <---+ - fingerprint dedup, 5s grouping, inhibition, silences - gossip-replicated notification log | v [PagerDuty / Slack / SMS Providers]Data flow 1 — Service instance to dashboard (
~1-2 s): 1. Every second, the per-host Collector scrapes/metricson localhost (giving free"is the process alive?"upsignals), strips disallowed labels, and batches samples to the Regional Ingest Gateway, which appends them to Regional Kafka. 2. Three TSDB Ingester replicas (sharded byseries_id) consume from Kafka, append to a local write-ahead log (WAL) (an append-only disk file used to recover memory after a crash), and insert into the 2-hour in-memory head — making data queryable within1-2 seconds. Every 2 hours, immutable blocks flush to regional object storage, where background Compactors merge blocks and build the5mand1hdownsampled tiers. 3. Dashboard queries hit a Query Frontend that splits time ranges by day, caches completed historical days, routes recent hours to Ingesters and older days to object-store blocks (tier=auto), and reads cross-region overview panels from the Global Rollup Store (fanning out to regions only when an engineer drills into a singleinstance).Data flow 2 — Service instance to on-call notification (
< 30 s): 1. Two active-active Regional Alert Engine replicas query the Ingesters over a dedicated priority port (isolated from dashboard traffic!) every5 secondsas ofnow - 5 s. 2. Whenever an alert transitions tofiringorresolved, both replicas push it to all 3 cross-region Notifier nodes. The Notifiers deduplicate by alert fingerprint, group sibling alerts for5 seconds, suppress symptom alerts if a whole-region outage is active, and page on-call.How the Regional Aggregator handles counter resets: If instance
pod-7c4had counter1,000and restarted to0before climbing to15, summing raw counters across instances would falsely dip by-985! Instead, the Aggregator tracks the previous raw value per inputseries_id, converts(1000 -> 15)into a reset-aware delta+15, and sums those deltas across all instances of(service, endpoint, status_class)over each10-secondwindow.Deep dive 1: Stateful alerting rules and late-arriving data
Consider a rule that pages when
billing's 5xx failure ratio stays above5%continuously across a3-minutewindow. Two subtleties immediately bite naive implementations: 1. Low-traffic noise: At 3 AM,1failed request out of2total requests is a50%error rate! Every ratio rule therefore pairs with a minimum traffic guard (e.g.,requests_per_s > 1.0). 2. Missing data vs. zero errors: Ifbillingcrashes completely and emits zero metrics,0 / 0is undefined (None), not0%errors. If missing data resolved firing alerts, your worst total outage would page"RESOLVED"!Here is the exact per-alert state machine and trace across 5-second ticks:
Timeline trace for (rule="ElevatedFailureRatio", service="billing", region="eu-west"): t = 0s error rate jumps to 9% -> phase: INACTIVE -> PENDING (pending_since = 0s) t = 5..175s error rate stays > 5% -> phase stays PENDING (duration < 180s) t = 180s 180s - 0s >= 180s! -> phase: PENDING -> FIRING (firing_since = 180s) -> EMIT "fire" t = 240s error rate dips to 4.9% -> phase stays FIRING, starts `clear_since = 240s` (anti-flap!) t = 245s error rate spikes 5.3% -> `clear_since` resets to None (no false resolve/re-page!) t = 300s error rate drops to 0.2% -> `clear_since = 300s`, holds healthy for 120s... t = 420s 420s - 300s >= 120s -> phase: FIRING -> INACTIVE -> EMIT "resolve"INACTIVE = "inactive" PENDING = "pending" FIRING = "firing" def compute_error_ratio(errors_per_s, requests_per_s, min_requests_per_s=1.0): """Return error ratio, or None if traffic is too low to judge.""" # Guard against 3 AM low-volume noise (e.g., 1 error in 2 requests = 50%). if requests_per_s is None or errors_per_s is None: return "no_data" if requests_per_s < min_requests_per_s: return "low_volume" return errors_per_s / requests_per_s def step_alert_state(alert, status_or_ratio, threshold, now_s, hold_s=180, clear_s=120): """Advance one stateful (rule_id, labels) alert instance by one 5-second tick.""" # Missing telemetry must NOT mark a firing outage as healthy; a separate # staleness rule alerts on missing data while preserving current timer state. if status_or_ratio == "no_data": return None breached = (status_or_ratio != "low_volume") and (status_or_ratio > threshold) if breached: # Any new breach cancels an in-progress recovery timer so oscillating metrics don't flap. alert["clear_since"] = None if alert["phase"] == INACTIVE: alert["phase"] = PENDING alert["pending_since"] = now_s if alert["phase"] == PENDING and (now_s - alert["pending_since"] >= hold_s): alert["phase"] = FIRING alert["firing_since"] = now_s return "fire" return None # Condition is currently healthy (or below minimum traffic volume). if alert["phase"] == PENDING: # A single healthy evaluation before 3 minutes resets the "for" clock completely. alert["phase"] = INACTIVE alert["pending_since"] = None return None if alert["phase"] == FIRING: # Require `clear_s` (e.g., 2m) of continuous health before resolving to prevent alert flapping. if alert["clear_since"] is None: alert["clear_since"] = now_s if now_s - alert["clear_since"] >= clear_s: alert["phase"] = INACTIVE alert["pending_since"] = None alert["firing_since"] = None alert["clear_since"] = None return "resolve" return NoneSurviving evaluator restarts: Every rule group runs on two active replicas that checkpoint
(fingerprint, phase, pending_since, firing_since, clear_since)every5 seconds. If both pods roll during a deployment, the replacement loads any checkpoint< 60 sold so a 3-minute timer is not reset to zero mid-incident.Handling late-arriving data in three tiers: 1.
1-5 secondslate (normal network jitter): Handled automatically by evaluatingnow - 5 s. Without this 5-second watermark,5xxerrors might flush 1 second before total requests, causing fake ratio spikes. 2.5 secondsto1 hourlate (temporary host network partition): The host Collector buffers up to2 hourson local disk and replays on reconnect. The TSDB Ingester accepts out-of-order samples up to1 hourold into its head block so dashboards and long-window SLO burn rules heal accurately, while short 3-minute rules do not retroactively page for transient blips that already ended 20 minutes ago. Meanwhile,collector_buffer_age_seconds > 60raises a"telemetry delayed"warning so gaps are never silent. 3.> 1 hourlate: Written to isolated backfill blocks in object storage and merged asynchronously by the Compactor.Deep dive 2: Four-layer defense against high cardinality
Why does cardinality explode? Because unique series multiply across labels:
50 endpoints * 5 status classes * 1,000,000 user_ids = 250,000,000series! We stop explosions in four progressively deeper layers:- Layer 1 — Source SDK & CI allowlists (cheapest): Every metric declares its allowed labels (
service,region,endpoint,method,status_class,instance). HTTP frameworks automatically template dynamic URL paths (/v2/invoices/90412/pay->/v2/invoices/{id}/pay) so raw IDs never become label values. To preserve per-request debugging without high cardinality, histogram buckets attach exemplars — a single sampletrace_idstored alongside the bucket count so an engineer clicking a latency spike jumps straight to an example trace in the tracing system! - Layer 2 — Host Collector series budget: Each host agent tracks an exact hash set of active series per metric (
~500series/host is only kilobytes). If a metric breaches its per-host cap (e.g.,2,000series), the agent keeps emitting already-known series (so existing production dashboards stay live!), drops only newly unseen series, and incrementscollector_series_dropped_total{metric, service}. - Layer 3 — Regional Gateway tenant quotas & HyperLogLog detection: The gateway enforces
max_seriesperservice(e.g.,20,000per region) so one team's bug can never starve another team's memory. To pinpoint which label caused an explosion across 1,000 hosts without keeping giant sets in RAM, ingesters maintain a HyperLogLog (HLL) sketch — a tiny12 KBprobabilistic register array per(metric, label_name)that estimates distinct label values within~0.8%error and merges across ingesters in milliseconds, poweringGET /v1/cardinality. - Layer 4 — Block-level Bloom filters in storage: As noted in the data model, each 2-hour TSDB block includes a Bloom filter (
~10 bitsperseries_id,~1.2 MBper million series) so queries skip historical blocks that do not contain the target series without reading disk indexes. Remember: Bloom filters speed up reads on large indexes; Layers 1-3 are what actually prevent write/RAM collapse!
- Layer 1 — Source SDK & CI allowlists (cheapest): Every metric declares its allowed labels (
Deep dive 3: Stopping alert storms during a regional outage
Imagine
eu-west's shared database or core network fails:1,000service instances across50services all cross5%error rates simultaneously, triggering2,000+alert instances. Paging engineers2,000times buries the root cause. Our 3-region Notifier cluster tames the storm through four stages:2,000 raw alert events (x2 evaluator replicas = 4,000 messages) | +--> [1. Fingerprint Dedup] merges identical `(rule_id, labels)` from the 2 replicas -> 2,000 alerts | +--> [2. Root-Cause Inhibition] `RegionDegraded{region="eu-west"}` (30s hold, detected from | external probes) suppresses downstream `severity="page"` alerts in `eu-west`! | (Suppressed alerts still appear on the incident dashboard + team Slack digests.) | +--> [3. Grouping + Timers] remaining alerts coalesce by `(alertname, region, service)`: | - `group_wait = 5s`: wait 5s after first alert to bundle siblings into ONE page | - `group_interval = 2m`: batch newly joining alerts into 2-minute summary updates | - `repeat_interval = 4h`: don't re-page unchanged firing alerts every 5 seconds | +--> [4. Silences & Routing] manual incident silences (with mandatory expiry) + severity routing -> Result: ONE actionable root-cause page to the incident commander!Critical timing insight for inhibition: Root-cause inhibition only prevents symptom pages if the root-cause alert fires before the symptom alerts finish their 3-minute hold! That is why cross-region synthetic health probes and regional heartbeat checks use a fast
30-secondforwindow, firingRegionDegradedatt + 35 s— more than two minutes before the2,000service-level3-minuterules reachFIRINGatt + 3.5 min.High-availability Notifier deduplication without a single point of failure: Both Regional Alert Engine replicas push every alert to all 3 Notifier nodes placed in 3 separate cloud regions. The 3 Notifiers gossip a small
notify_logof sent(group_key, alert_set_hash)entries. Node0sends immediately aftergroup_wait = 5 sand gossips the receipt; Node1waits+5 sand stays silent when it sees Node0's receipt; Node2waits+10 s. If Node0's entire region dies, Node1automatically pages5 secondslater (~23.5 stotal, still< 30 s). If a WAN split isolates the Notifiers from each other, an engineer receives at most a duplicate page — an intentional choice because a duplicate page is a minor annoyance, whereas a dropped page is a missed outage.Centralized vs. decentralized storage, scaling, and regional failures
Explicit storage trade-off comparison:
Dimension Centralized (ship all raw points to 1 global DB) Fully Decentralized (regional DBs only, zero global store) Hybrid Regional Raw + Global Rollups (our design) Cross-region WAN bandwidth 100 MB/s(8.64 TB/day)0 MB/sat write time400 KB/s(250xsmaller than centralized)Regional alerting during WAN cut Fails for isolated regions Works normally Works normally Global overview dashboards Fast single-cluster query Slow 10-region fan-out (bound by slowest region) Fast single query on Global Rollup Store Drill-down to one host's raw metrics Local to central DB Direct query to that region Federated query to that region (marks partial if region down) Failure blast radius Global outage if central DB fails Single region Single region (Global Rollup Store runs active-active in 2 regions) How each bottleneck scales and degrades gracefully under failure: - Scaling Ingesters & Query cost: Ingesters hash-partition by
series_id(RF=3), scaling horizontally by adding nodes. Dashboard queries scale via the Query Frontend's day-splitting cache and automatic resolution switching (raw->5m->1h), plus recording rules (pre-computed time series saved every5 sfor expensive expressions used on busy dashboards). - Ingester crash: Surviving 2 of 3 replicas serve queries immediately; the replacement node replays missed samples from the24-hourRegional Kafka log + local WAL with zero data loss. - Total loss of Region R: A dead region cannot send alerts about itself! Detection comes from outside Region R: cross-region synthetic probes failing, Region R's rollup watermark stalling> 60 sin the Global Alert Engine (which marks R as unknown, never0, so global ratios don't miscalculate), and R's external dead-man's-switch heartbeat going silent — raisingRegionDegraded{region="R"}within ~1 minute.Summary of architectural trade-offs
- Regional raw TSDB + 10-second global rollups vs. centralized raw storage: Saves
250xWAN bandwidth and keeps regional alerting immune to WAN partitions, at the cost of running regional stacks and using federated fan-out when drilling into raw host-level series across regions. - 5-second evaluation watermark + no retroactive paging vs. strict event-time waiting: Absorbs normal batch skew inside
< 30 slatency and keeps late host buffers (<= 1 h) healing dashboards without waking engineers over resolved blips. - Active-active dual rule evaluators + staggered 3-region Notifiers vs. single leader election: Doubles cheap rule-evaluation queries and occasionally sends duplicate pages during WAN splits, in exchange for zero leader-election downtime and guaranteed
< 30 sfailover. - Four-layer cardinality guardrails (dropping new series only) vs. unbounded dynamic labels: Requires teams to declare allowed labels and use trace exemplars for
request_id, ensuring one bad deploy never crashes shared ingester RAM or breaks existing dashboards.
- Regional raw TSDB + 10-second global rollups vs. centralized raw storage: Saves
Intuition & how it works
Think of a global metrics and alerting system like fire safety across a chain of 10 regional hospitals: every room has local smoke sensors (per-host collectors) wired to a fire panel inside that same building (the regional time-series database and regional alert engine) so alarms ring within seconds even if fiber cables to headquarters are severed by a storm. Meanwhile, each building sends a tiny 10-second summary report (hierarchical rollups) to headquarters (the global rollup store) so executives can watch company-wide health on one screen without streaming millions of raw sensor readings across the globe.
A naive design ships all 5,000,000 raw data points per second from every region over the wide-area network (WAN, the cross-region internet/backbone links) into one central database, and runs one central alert job against it. That fails in three ways: shipping 8.64 TB/day over the WAN is expensive and brittle, any WAN cut blinds alerting right during an outage, and a single developer accidentally tagging a metric with user_id (1,000,000 users) creates millions of unique time series (streams of (timestamp, value) points identified by a metric name and key-value tags called labels), exhausting central RAM in minutes.
Walk through 4 concrete events in eu-west to see how our regional-first pipeline works end to end:
- Cardinality-safe collection (
t = 0 sto1.5 s): Billing instancepod-7c4serves/v2/invoices/90412/paywith a500error. The HTTP framework templates the path to/v2/invoices/{id}/pay, and the local host Collector scrapes/metrics, verifies labels against an allowlist (blocking strayuser_idorrequest_idtags), and sends a compressed batch to theeu-westgateway -> Kafka -> three TSDB (time-series database) ingesters. Each ingester appends to a write-ahead log (WAL) (an append-only disk file for crash recovery) and stores the point in RAM using Gorilla compression (delta-of-delta timestamps + XOR floats, shrinking16 bytesto~1.5 bytes). - Regional rollup to global (
every 10 s): A regional Aggregator consumes from Kafka, drops theinstancelabel, sums reset-aware counter increases (cumulative totals that only rise until a restart) across all billing instances into one10-secondsummary point, and ships~40 KB/sto the Global Rollup Store (250xless WAN traffic!). - Stateful alert evaluation (
t = 180 sto190 s): After billing's 5xx failure ratio stays above5%(with total traffic> 1 req/s) for3 consecutive minutes, two redundanteu-westAlert Engine replicas — evaluatingnow - 5 son a dedicated RAM query path — flip the alert's state machine fromPENDINGtoFIRINGand push the alert to all 3 cross-region Notifier nodes. - Deduplication & storm suppression (
t = 190 sto198 s): The Notifiers merge duplicate alerts from the two evaluators by fingerprint (a hash ofrule_id+ labels), waitgroup_wait = 5 sto bundle sibling billing alerts into one notification, check inhibition rules (which mute symptom pages if external probes already firedRegionDegraded{region="eu-west"}), and page the on-call engineer at~18.5 seconds— comfortably inside the30-secondSLA.
Key trade-offs
- Regional raw storage + global 10-second rollups vs. centralized raw storage. Keeping raw 1-second data in each region and shipping only
instance-less 10-second rollups (pre-aggregated summaries) cuts WAN bandwidth250x(100 MB/sdown to400 KB/s) and keeps regional alerting alive during WAN cuts. The trade-off is running per-region storage stacks and using a slower federated fan-out query (which explicitly flags partial results if a region is down) when an engineer drills into raw host-level series across multiple regions. - 5-second straggler watermark + no retroactive paging vs. waiting for all late data. Evaluating rules at
now - 5 slets normal1-2 sbatch jitter settle soerrorsandrequestsseries align accurately, while overlapping ingest lag inside those 5 seconds keeps total alert latency< 30 s. Late data arriving up to1 hourlater (after a host network blip) heals dashboards and multi-hour SLO rules, but does not retroactively page humans for 3-minute blips that already ended. - Dual active-active evaluators + staggered 3-region Notifiers vs. leader election. Having two regional evaluators run every rule and push to 3 Notifiers that gossip a sent-notification log avoids distributed leader-election pauses and hits
< 30 seven when a whole region dies (+5 sbackup timer). The trade-off is2xrule-query CPU (cheap on in-memory data) and preferring an occasional duplicate page during a WAN split over a missed outage. - Short
group_wait(5 s) + root-cause inhibition vs. long batching windows. Waiting60 secondsto batch alerts would blow the30-secondnotification budget. Instead, we keepgroup_waitat5 secondsand rely on inhibition driven by fast30-secondexternal probe rules (RegionDegraded) to suppress thousands of3-minuteservice symptom pages during regional failures. - Strict 4-layer cardinality caps (dropping only new series) vs. schema-less labels. Requiring label allowlists, per-host series budgets, per-service tenant caps, and exemplars (a single sample
trace_idattached to a latency histogram bucket instead of puttingrequest_idin labels) adds governance overhead, but guarantees one team's cardinality bug never crashes shared ingester RAM or breaks their existing dashboards. - Multi-tier downsampling (
min, max, sum, count, reset-aware counter) vs. raw retention forever. Compacting raw data into5-minute(60xfewer points) and1-hour(720xfewer points) rollups preserves exact rates, averages, and extreme spikes for 2 years at tiny object-storage cost, with the trade-off that long-range percentiles require keeping histogram bucket series rather than averaging pre-computed percentiles.
Common mistakes
- Shipping all raw samples to a single global TSDB and alerting centrally. Any cross-region WAN congestion or outage then disables alerting for isolated regions right when incidents happen.
- Double-counting or ignoring pipeline stages in the 30-second alert budget. Forgetting collector batching, straggler watermarks, evaluation tick intervals,
group_wait, and paging API latency leads to designs that look real-time on paper yet take 2+ minutes in production. - Treating missing data (
no samples) as0%errors, or omitting a minimum traffic guard. If a crashed service emits zero metrics, treating0 / 0as0resolves active alerts during a total outage; conversely, withoutrequests_per_s > 1, a single failed request at 3 AM (1 / 2 = 50%) wakes on-call needlessly. - Forgetting a recovery hold timer (
keep_firing_for) and timer checkpointing. Without a2-minuteclear hold, an error rate oscillating between4.9%and5.1%pages and resolves repeatedly ("flapping"); without checkpointingpending_since, rolling evaluator restarts silently reset 3-minute timers back to zero. - Putting
user_id,request_id, or un-templated URLs (/v2/invoices/90412) into metric labels. High cardinality (millions of unique label sets) bloats the inverted index (thelabel=value -> series_idlookup lists) and ingester RAM; drop/template at the source and drop only new overflow series with explicit error metrics rather than silently dropping existing series. - Relying on Bloom filters alone to "solve" high cardinality. A Bloom filter (a compact bit array with zero false negatives used to skip historical disk blocks that lack a
series_id) speeds up reads on cold blocks, but does not save active ingester RAM — source allowlists, host caps, and HyperLogLog (a12 KBdistinct-value estimator) detect and block explosions before storage. - Averaging percentiles during downsampling, or sharing one query pool between dashboards and alerts. The average of twelve 5-minute
p99values is mathematically not the 1-hourp99(you must sum histogram buckets instead), and letting 300 engineers refreshing incident dashboards starve alert-engine queries delays pages during outages.
Follow-up questions
- How do you keep the observability and paging pipeline operational during a widespread failure of the production fleet it monitors? Isolate the observability stack onto dedicated compute clusters with static bootstrap configurations and zero runtime dependencies on production databases, identity services, or service meshes, preventing circular dependencies from pulling monitoring down mid-incident. Inside each region, host collectors prioritize alert-critical metrics ahead of verbose debug counters, ingest gateways shed overload via
429backpressure while Kafka buffers spikes, and alert evaluators query ingesters through a dedicated priority port isolated from dashboard stampedes. Finally, deploy the 3-node Notifier cluster across 3 distinct regions with fallback paging channels (e.g., PagerDuty plus backup SMS), and emit a continuous watchdog ("dead man's switch") heartbeat from every regional evaluator to an external observer that pages immediately if any region's telemetry pipeline goes quiet. - Under tiered storage retention, how should downsampling be designed so multi-month historical trends preserve peak spikes and accurate percentiles? Run asynchronous background Compactor workers over immutable object-storage blocks to build multi-resolution tiers: retain
1-secondraw blocks for15 days,5-minuterollups for90 days, and1-hourrollups for2 years, with the Query Frontend automatically selecting the finest tier covering the queried range. Rather than storing a bare mean — which erases brief CPU or latency spikes — store five summary fields per series per rollup window:min,max,sum,count, and thereset-aware cumulative counterat window end (and downsample latency histograms by preserving each bucket's cumulative counter so accuratep95/p99quantiles remain computable months later). For major postmortems, support an "incident pin" flag that exempts affected services' raw1-secondblocks from the 15-day TTL until review concludes. - What safeguards and testing workflows ensure the alerting engine behaves accurately whenever engineers modify or remove live alert rules? Manage alert rules as version-controlled code gated by a four-step verification workflow: first, deterministic CI unit tests feed synthetic time series (covering counter resets, missing-data gaps, and low-volume hours) into the rule state machine to assert exact
PENDING,FIRING, andRESOLVEDtransitions. Second, replay proposed changes through/v1/rules:backtestacross 30 days of historical TSDB data to show reviewers a concrete diff of past firing windows, followed by 24 hours of shadow evaluation (scoring live telemetry and logging transitions without paging). On rollout or deletion, stamp every emitted alert with(rule_id, rule_version): removing a rule or altering its grouping labels explicitly dispatchesresolvedevents for orphaned active fingerprints and records a tombstone so lagging replicas cannot revive deleted rules, while an hourly synthetic canary rule continuously validates live end-to-end paging within30 seconds.
Follow-up questions
- How do you keep the observability and paging pipeline operational during a widespread failure of the production fleet it monitors?
- Under tiered storage retention, how should downsampling be designed so multi-month historical trends preserve peak spikes and accurate percentiles?
- What safeguards and testing workflows ensure the alerting engine behaves accurately whenever engineers modify or remove live alert rules?
Similar questions
- Atomic Multi-Quota Job Rate Limiter
- Zero Trust Access Models and Segmented Video Security
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests