Skip to main content
Gaming & Real-Time Bidding

Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog)

Staff / Principal

Complete FAANG-level system design blueprint for Metric Monitoring & Alerting (Prometheus / Datadog).

Production Scale: 500 Million Metric Samples/Sec • 10k Servers

Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog): Request Topology

5 Stages · 4 Sizing Benchmarks

Request traversal order for Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog) (Gaming & Real-Time Bidding) under target workload 500 Million Metric Samples/Sec • 10k Servers:

Stage 1

Stateless Ingestion Gateway & Cardinality Guard

Stage 2

TSDB Write-Ahead Log & Head Chunk Store

Stage 3

Inverted Postings Index & Object Compactor

Stage 4

Downsampling & Rollup Pipeline

Functional Requirements

  • •Ingest 500 million labeled time-series samples per second via Prometheus remote-write, OTLP, and agent push
  • •Execute PromQL-style range aggregations across recent hot metrics and 90-day historical rollups
  • •Evaluate continuous threshold and anomaly alerting rules and route deduplicated pages to PagerDuty or Slack

Non-Functional Requirements

  • •Sustained 500M samples/sec write throughput without random SSD IOPS saturation
  • •Sub-second dashboard query latency across 90-day multi-host metric windows
  • •Strict high-cardinality label protection and hysteresis-based alert storm suppression

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Production Scale Target500 Million Metric Samples/Sec
Peak Throughput10k Servers
Read-to-Write Ratio10 : 1
Availability Target99.999% SLA (Five 9s)

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

[Application Pods / Microservices]
            | (Push / Pull Metrics Exporter)
            v
[Prometheus / VictoriaMetrics Scrape Agent Pool]
            |
            v (Write Ahead Log + Timeseries Ring)
[Distributed TSDB Engine (Thanos / M3DB / ClickHouse)]
            |
            +------------------------------+
            |                              |
            v                              v
[Grafana Dashboard Query Engine]   [Alertmanager Evaluator]
                                           |
                                           v
                             [PagerDuty / Slack Dispatcher]

1Stateless Ingestion Gateway & Cardinality Guard

Enforces per-tenant series caps, strips unbounded labels, and consistent-hashes metric series across ingester shards.

2TSDB Write-Ahead Log & Head Chunk Store

Appends (timestamp, float64) samples into XOR/Gorilla-compressed in-memory chunks backed by sequential WAL segments.

3Inverted Postings Index & Object Compactor

Indexes metric label pairs for fast series lookup and periodically compacts two-hour blocks into immutable S3/GCS Parquet chunks.

4Downsampling & Rollup Pipeline

Pre-aggregates raw 10-second intervals into 1-minute, 5-minute, and 1-hour min/max/sum/count rollup tables for fast long-range dashboards.

5Distributed Query Frontend & Alert Evaluator

Splits multi-week range queries across parallel workers, caches aligned step intervals in Redis, and tracks alert `for:` hysteresis timers.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog) at a scale of 500 Million Metric Samples/Sec • 10k Servers requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureAP (High Ingress Availability & Partition Tolerance for TSDB)CP (Synchronous Distributed Consensus per Metric Data Point)Monitoring infrastructure must remain available during catastrophic network partitions to diagnose outages; metric scraping and dashboard aggregations tolerate eventual consistency.
Data Ingestion ModelPull-Based Scraping with OpenMetrics / Prometheus EndpointsDirect Push Telemetry from Every Application ThreadPull-based model protects storage backends from cascading denial-of-service during traffic surges; the scraper controls ingestion pace.
Timeseries Storage TieringTwo-Tier Architecture (In-Memory TSDB Ring for 2h + S3 Parquet for 365d)Monolithic SSD Storage for All Historical TimeseriesReduces storage infrastructure costs by 84% while maintaining sub-second query response for real-time alerting dashboards.
High Cardinality Metric ManagementStrict Metric Relabeling and Label Whitelisting at Scrape GatewayUnrestricted Ingestion of User IDs and UUIDs as Metric LabelsUnbounded metric cardinality causes memory explosion in time-series index inverted tables; sanitizing labels keeps memory predictable.
Alerting Evaluation FrequencyDecoupled Alertmanager with Sliding 1-Minute Evaluation WindowsSynchronous Evaluation on Every Raw Ingested SampleDecoupling alert rule evaluation prevents transient single-second metric spikes from triggering false-positive incident pages.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 500 Million Metric Samples/Sec • 10k Servers demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog):

1. Metric Cardinality Explosion (OOM Crash)

Blast Radius: Developers push code with dynamic user IDs in label keys, crashing scrapers.

Remediation Protocol: Scrape target limits enforce a maximum of 5,000 series per scrape job; excess series are dropped with error telemetry.

2. Network Partition Between Scraper and Monitored Subnet

Blast Radius: Gaps in telemetry graphs triggering spurious downtime alerts.

Remediation Protocol: Alertmanager rules require absent_over_time to persist across 3 consecutive scrape intervals before declaring target dead.

3. Alert Notification Storm During Core Router Outage

Blast Radius: Engineers receive 5,000 simultaneous PagerDuty alerts for individual services.

Remediation Protocol: Alertmanager inhibition and grouping rules group alerts by cluster and datacenter, dispatching a single root-cause notification.

4. Cold Storage Ingestion Backpressure on S3 Uploads

Blast Radius: Local WAL fills available disk on Thanos sidecar nodes.

Remediation Protocol: Thanos sidecar implements exponential backoff with disk reservation headroom alarms at 80% capacity threshold.

Production Algorithm Implementation: Sliding Window EWMA (Exponential Weighted Moving Average) Anomaly Detector

typescript

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog):

export class AnomalyDetector {
  private mean: number | null = null;
  private variance: number = 0;

  constructor(private alpha: number = 0.2, private thresholdSigma: number = 3.0) {}

  processSample(val: number): { isAnomaly: boolean; score: number } {
    if (this.mean === null) {
      this.mean = val;
      return { isAnomaly: false, score: 0 };
    }

    const diff = val - this.mean;
    const stdDev = Math.sqrt(this.variance);
    const zScore = stdDev > 0 ? Math.abs(diff) / stdDev : 0;

    // Update EWMA mean and variance
    this.mean = this.alpha * val + (1 - this.alpha) * this.mean;
    this.variance = (1 - this.alpha) * (this.variance + this.alpha * diff * diff);

    return {
      isAnomaly: zScore > this.thresholdSigma,
      score: zScore
    };
  }
}

Design Metric Monitoring & TSDB Alerting (Prometheus / Datadog): Design Scope & Constraints Summary

This staff / principal blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 500 Million Metric Samples/Sec • 10k Servers. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Gaming & Real-Time Bidding.

Architectural FAQs & Interview Deep Dives

1How does a time-series database sustain 500 million metric samples/sec without saturating SSD IOPS?

Incoming `(timestamp, float64)` samples append to per-series in-memory head chunks backed by a sequential WAL rather than updating disk blocks randomly. Using Gorilla XOR floating-point compression and delta-of-delta timestamp encoding shrinks each 16-byte sample down to roughly 1.4 bytes in RAM before flushing immutable 2-hour compacted blocks to object storage.

2Why can unbounded label cardinality crash a TSDB cluster, and how do ingestion gateways guard against it?

Each unique `{metric_name, label_key=label_val}` tuple creates a distinct active time series in the inverted postings index and allocates its own head buffer in memory. Attaching high-cardinality labels like `request_id` or `user_uuid` triggers runaway memory growth and OOM failures, so ingestion proxies enforce per-tenant active-series quotas, label allowlists, and dynamic drop/relabel rules.

3How do monitoring dashboards render 90-day queries in under a second across petabytes of historical samples?

Background compaction pipelines continuously downsample raw 10-second intervals into pre-aggregated 1-minute, 5-minute, and 1-hour rollup tables retaining `min`, `max`, `sum`, and `count` primitives. The query planner automatically selects the coarsest rollup matching the requested chart resolution and caches immutable historical block slices across distributed querier workers.

4How does the alerting engine avoid false pages and notification storms during partial network blips?

Alert rule evaluators run statelessly across replicated query frontends, requiring breaches to persist across a `for:` hysteresis duration before transitioning from `PENDING` to `FIRING`. Fired alerts flow into a deduplicating router that groups correlated symptoms by service/cluster, suppresses child alerts via inhibition rules when a root node goes down, and monitors dead-man's-switch heartbeats.