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_id or request_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

  1. 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.
    • 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 a 3-minute window 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_id or request_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,000 active series per region (5,000,000 globally), and 5,000,000 data points/s globally (500,000 points/s per region — an average of 1 sample per series per second).
    • Alert latency: Under 30 seconds from 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 seconds for a 24-hour dashboard panel.
    • Retention policy (assumed): 15 days at raw 1-second resolution, 90 days at 5-minute resolution, and 2 years at 1-hour resolution.
  2. 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:

    1. Data point volume (10 MB/s per region) is modest; cardinality is the killer. Every active time series costs ~4 KB of in-memory state per replica. One developer adding user_id multiplies active series 20x and blows up RAM, so cardinality guardrails must sit at the front door.
    2. Hierarchical rollups cut WAN traffic 250x (100 MB/s down to 400 KB/s) while keeping each region self-sufficient during WAN cuts.
    3. Why ingest lag and watermark delay overlap: Because the alert engine deliberately evaluates timestamp now - 5 s, the <= 2 s pipeline 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 inside 30 seconds.
  3. 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 (400 with reason), never silent drops: If a team accidentally emits a forbidden user_id label, 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.

  4. 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},..."). Across 5,000,000 series, the birthday-paradox collision probability (N * N) / (2 * 2^64) is roughly 6.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) wastes 100+ bytes per point and scans millions of rows to filter labels. Instead, a TSDB separates label lookup (an inverted index, which maps each label=value tag to a sorted list of matching series_id integers, 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 from 16 bytes to ~1.5 bytes per 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 one series_id accumulating 7,200 compressed samples over 2 hours, you get millions of 1-sample series_ids, bloating the symbol table and postings lists until the index is larger than the metric values themselves.

  5. 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 /metrics on localhost (giving free "is the process alive?" up signals), strips disallowed labels, and batches samples to the Regional Ingest Gateway, which appends them to Regional Kafka. 2. Three TSDB Ingester replicas (sharded by series_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 within 1-2 seconds. Every 2 hours, immutable blocks flush to regional object storage, where background Compactors merge blocks and build the 5m and 1h downsampled 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 single instance).

    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!) every 5 seconds as of now - 5 s. 2. Whenever an alert transitions to firing or resolved, both replicas push it to all 3 cross-region Notifier nodes. The Notifiers deduplicate by alert fingerprint, group sibling alerts for 5 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-7c4 had counter 1,000 and restarted to 0 before climbing to 15, summing raw counters across instances would falsely dip by -985! Instead, the Aggregator tracks the previous raw value per input series_id, converts (1000 -> 15) into a reset-aware delta +15, and sums those deltas across all instances of (service, endpoint, status_class) over each 10-second window.

  6. Deep dive 1: Stateful alerting rules and late-arriving data

    Consider a rule that pages when billing's 5xx failure ratio stays above 5% continuously across a 3-minute window. Two subtleties immediately bite naive implementations: 1. Low-traffic noise: At 3 AM, 1 failed request out of 2 total requests is a 50% 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: If billing crashes completely and emits zero metrics, 0 / 0 is undefined (None), not 0% 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 None
    

    Surviving evaluator restarts: Every rule group runs on two active replicas that checkpoint (fingerprint, phase, pending_since, firing_since, clear_since) every 5 seconds. If both pods roll during a deployment, the replacement loads any checkpoint < 60 s old so a 3-minute timer is not reset to zero mid-incident.

    Handling late-arriving data in three tiers: 1. 1-5 seconds late (normal network jitter): Handled automatically by evaluating now - 5 s. Without this 5-second watermark, 5xx errors might flush 1 second before total requests, causing fake ratio spikes. 2. 5 seconds to 1 hour late (temporary host network partition): The host Collector buffers up to 2 hours on local disk and replays on reconnect. The TSDB Ingester accepts out-of-order samples up to 1 hour old 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 > 60 raises a "telemetry delayed" warning so gaps are never silent. 3. > 1 hour late: Written to isolated backfill blocks in object storage and merged asynchronously by the Compactor.

  7. 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,000 series! We stop explosions in four progressively deeper layers:

    1. 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 sample trace_id stored alongside the bucket count so an engineer clicking a latency spike jumps straight to an example trace in the tracing system!
    2. Layer 2 — Host Collector series budget: Each host agent tracks an exact hash set of active series per metric (~500 series/host is only kilobytes). If a metric breaches its per-host cap (e.g., 2,000 series), the agent keeps emitting already-known series (so existing production dashboards stay live!), drops only newly unseen series, and increments collector_series_dropped_total{metric, service}.
    3. Layer 3 — Regional Gateway tenant quotas & HyperLogLog detection: The gateway enforces max_series per service (e.g., 20,000 per 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 tiny 12 KB probabilistic register array per (metric, label_name) that estimates distinct label values within ~0.8% error and merges across ingesters in milliseconds, powering GET /v1/cardinality.
    4. Layer 4 — Block-level Bloom filters in storage: As noted in the data model, each 2-hour TSDB block includes a Bloom filter (~10 bits per series_id, ~1.2 MB per 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!
  8. Deep dive 3: Stopping alert storms during a regional outage

    Imagine eu-west's shared database or core network fails: 1,000 service instances across 50 services all cross 5% error rates simultaneously, triggering 2,000+ alert instances. Paging engineers 2,000 times 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-second for window, firing RegionDegraded at t + 35 s — more than two minutes before the 2,000 service-level 3-minute rules reach FIRING at t + 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_log of sent (group_key, alert_set_hash) entries. Node 0 sends immediately after group_wait = 5 s and gossips the receipt; Node 1 waits +5 s and stays silent when it sees Node 0's receipt; Node 2 waits +10 s. If Node 0's entire region dies, Node 1 automatically pages 5 seconds later (~23.5 s total, 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.

  9. 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/s at write time 400 KB/s (250x smaller 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 every 5 s for expensive expressions used on busy dashboards). - Ingester crash: Surviving 2 of 3 replicas serve queries immediately; the replacement node replays missed samples from the 24-hour Regional 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 s in the Global Alert Engine (which marks R as unknown, never 0, so global ratios don't miscalculate), and R's external dead-man's-switch heartbeat going silent — raising RegionDegraded{region="R"} within ~1 minute.

  10. Summary of architectural trade-offs

    • Regional raw TSDB + 10-second global rollups vs. centralized raw storage: Saves 250x WAN 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 s latency 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 s failover.
    • 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.

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:

  1. Cardinality-safe collection (t = 0 s to 1.5 s): Billing instance pod-7c4 serves /v2/invoices/90412/pay with a 500 error. The HTTP framework templates the path to /v2/invoices/{id}/pay, and the local host Collector scrapes /metrics, verifies labels against an allowlist (blocking stray user_id or request_id tags), and sends a compressed batch to the eu-west gateway -> 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, shrinking 16 bytes to ~1.5 bytes).
  2. Regional rollup to global (every 10 s): A regional Aggregator consumes from Kafka, drops the instance label, sums reset-aware counter increases (cumulative totals that only rise until a restart) across all billing instances into one 10-second summary point, and ships ~40 KB/s to the Global Rollup Store (250x less WAN traffic!).
  3. Stateful alert evaluation (t = 180 s to 190 s): After billing's 5xx failure ratio stays above 5% (with total traffic > 1 req/s) for 3 consecutive minutes, two redundant eu-west Alert Engine replicas — evaluating now - 5 s on a dedicated RAM query path — flip the alert's state machine from PENDING to FIRING and push the alert to all 3 cross-region Notifier nodes.
  4. Deduplication & storm suppression (t = 190 s to 198 s): The Notifiers merge duplicate alerts from the two evaluators by fingerprint (a hash of rule_id + labels), wait group_wait = 5 s to bundle sibling billing alerts into one notification, check inhibition rules (which mute symptom pages if external probes already fired RegionDegraded{region="eu-west"}), and page the on-call engineer at ~18.5 seconds — comfortably inside the 30-second SLA.

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 bandwidth 250x (100 MB/s down to 400 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 s lets normal 1-2 s batch jitter settle so errors and requests series align accurately, while overlapping ingest lag inside those 5 seconds keeps total alert latency < 30 s. Late data arriving up to 1 hour later (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 s even when a whole region dies (+5 s backup timer). The trade-off is 2x rule-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. Waiting 60 seconds to batch alerts would blow the 30-second notification budget. Instead, we keep group_wait at 5 seconds and rely on inhibition driven by fast 30-second external probe rules (RegionDegraded) to suppress thousands of 3-minute service 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_id attached to a latency histogram bucket instead of putting request_id in 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 into 5-minute (60x fewer points) and 1-hour (720x fewer 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) as 0% errors, or omitting a minimum traffic guard. If a crashed service emits zero metrics, treating 0 / 0 as 0 resolves active alerts during a total outage; conversely, without requests_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 a 2-minute clear hold, an error rate oscillating between 4.9% and 5.1% pages and resolves repeatedly ("flapping"); without checkpointing pending_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 (the label=value -> series_id lookup 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 (a 12 KB distinct-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 p99 values is mathematically not the 1-hour p99 (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 429 backpressure 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-second raw blocks for 15 days, 5-minute rollups for 90 days, and 1-hour rollups for 2 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 the reset-aware cumulative counter at window end (and downsample latency histograms by preserving each bucket's cumulative counter so accurate p95/p99 quantiles remain computable months later). For major postmortems, support an "incident pin" flag that exempts affected services' raw 1-second blocks 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, and RESOLVED transitions. Second, replay proposed changes through /v1/rules:backtest across 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 dispatches resolved events 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 within 30 seconds.

Follow-up questions

Similar questions

More Zscaler interview questions

All 3 Zscaler questions →