9 min read

Taming the Firehose: High-Cardinality Metrics, Downsampling, and the Physics of Time-Series at Scale

Mastering High-Cardinality Time-Series at Scale

It’s 4:15 PM on a Friday. Your team just pushed a "minor" update to the checkout service. Suddenly, the P99 latency dashboard doesn’t just spike—it stops rendering entirely. Your Prometheus instance is OOM-looping (Out of Memory), and the alerting pipeline is deafeningly silent because the telemetry layer has collapsed under its own weight.

The culprit? A developer added a user_id tag to a request-duration metric, thinking it would be "useful for debugging." In a system with five million active users, you didn’t just add a label; you unleashed a cardinality explosion that turned your time-series database (TSDB) into a very expensive space heater.

In the world of modern observability, we are no longer just monitoring servers; we are monitoring ephemeral microservices, serverless functions, and per-customer experience metrics. This shift has pushed traditional TSDBs to their breaking point. To survive, we have to master the three pillars of time-series engineering: managing high-cardinality, strategic downsampling, and intelligent retention policies.

This isn't just about "storing data." It’s about the physics of data movement, the economics of NVMe storage, and the brutal reality of query-time compute.


The Anatomy of the Cardinality Crisis

In time-series parlance, cardinality is the number of unique combinations of label (or tag) values for a given metric.

If you have a metric http_requests_total with two labels:

  • method (GET, POST, PUT) - Cardinality 3
  • status (200, 404, 500) - Cardinality 3

The total cardinality is $3 \times 3 = 9$ unique series. This is trivial. However, when you add user_id or request_id, the cardinality becomes $3 \times 3 \times 1,000,000$. Now you have 9 million series.

Why Cardinality Kills Performance

Every unique series in a TSDB requires:

  1. Index Space: An entry in an inverted index (usually a B-Tree or an LSM-tree variant) to map labels to a unique Series ID.
  2. Memory overhead: Modern TSDBs like Prometheus or InfluxDB keep a "Head" block in RAM for recent data to ensure sub-millisecond writes.
  3. Metadata bloat: Even if a series only receives one data point per hour, the database must track its existence.

When cardinality explodes, the inverted index becomes too large to fit in memory. Queries that used to take 50ms now take 30s because the engine is performing massive random I/O hits to the disk just to figure out which series it needs to read.

The Shift to "Columnar Observability"

Recent hype has surrounded the "death of the inverted index." Systems like ClickHouse, VictoriaMetrics, and InfluxDB IOx are moving away from complex mapping structures in favor of high-performance columnar storage and brute-force scanning powered by SIMD (Single Instruction, Multiple Data) instructions.

By storing data in compressed Parquet or Arrow formats, these databases can scan millions of rows per second. Instead of spending CPU cycles maintaining a massive index, they spend them scanning narrowed-down data partitions. This is the technical substance behind the "Log-structured" vs. "Columnar" debate: we are trading index complexity for raw compute throughput.


Downsampling: The Art of Losing Information Gracefully

Storage is cheap; compute is expensive. But even cheap storage adds up when you're hitting 10 million samples per second. Downsampling is the process of reducing the resolution of historical data while preserving its statistical significance.

The Mathematics of Aggregation

You cannot simply "delete" every second data point. If you do, you lose the "spikes"—the very things you monitor for. Effective downsampling requires choosing the right aggregation function based on the metric type:

  • Counters (e.g., total_bytes): Use Sum.
  • Gauges (e.g., cpu_utilization): Use Min, Max, and Avg.
  • Histograms/Summaries: This is where it gets tricky. You need to store the P99, P95, and Mean as separate series after downsampling.

Implementation: The Materialized View Pattern

In a high-scale architecture, downsampling should happen asynchronously. Using a tool like Thanos or Cortex, raw data is uploaded to object storage (S3/GCS). A background "Compactor" process then reads this data and produces 5-minute and 1-hour resolution blocks.

-- Example: ClickHouse Materialized View for Downsampling
CREATE MATERIALIZED VIEW metrics_5min_mv
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (metric_name, tags, timestamp)
AS SELECT
    metric_name,
    tags,
    toStartOfFiveMinute(timestamp) AS timestamp,
    avgState(value) AS avg_val,
    maxState(value) AS max_val,
    countState(value) AS count_val
FROM raw_metrics
GROUP BY metric_name, tags, timestamp;

By querying the metrics_5min_mv table for a 30-day dashboard, you reduce the data volume by a factor of 300 (assuming 1-second raw scrapes), resulting in instantaneous dashboard loads.


Retention Policies: Tiered Storage Architectures

A common mistake in infrastructure design is treating all time-series data as equal. The value of a data point decays exponentially over time.

  1. The Operational Window (0–2 hours): High-precision (1s), held in RAM or NVMe. Used for alerting and real-time debugging.
  2. The Analysis Window (2 hours – 14 days): Medium-precision (10s–1m), held on SSD. Used for incident post-mortems.
  3. The Compliance/Trend Window (14 days – 2 years): Low-precision (1h), held on Object Storage (S3). Used for capacity planning and "Year-over-Year" reporting.

The "Hot-Warm-Cold" Infrastructure

To implement this at scale, we utilize Tiered Storage.

  • Hot Tier: TSDB instances (like Prometheus or VictoriaMetrics) with local NVMe. They handle the write-heavy ingest.
  • Warm Tier: A clustered storage layer (like Thanos Store or InfluxDB nodes) that manages compressed blocks on local disk or high-performance network storage.
  • Cold Tier: Object storage. The data is immutable and highly compressed using Gorilla (XOR) compression.

Gorilla Compression Explained: Developed by Facebook, Gorilla compression is the gold standard for TSDBs. It exploits the fact that timestamps and values in a series don't change much between samples.

  • Timestamps: Stored as "Delta-of-Deltas." If samples arrive every 15s, the delta is 0. This can often be compressed to a single bit.
  • Values: Stored using XOR. If a value is the same as the previous one, it's just a 0.

This compression allows us to keep years of data in S3 for pennies, provided we've downsampled it correctly.


Query Patterns: Solving the "Heavy Hitter" Problem

Even with great storage, a poorly formed query can bring a TSDB to its knees. When dealing with high cardinality, we see two primary query patterns that require different optimization strategies.

1. The "Needle in a Haystack" (Point Query)

  • Query: requests_total{user_id="12345", version="2.1.0"}
  • Optimization: This requires a highly efficient Bloom Filter or a precise index. If your TSDB has to scan a whole partition to find one user, your architecture is broken.

2. The "Global Aggregation" (Heavy Read)

  • Query: sum(rate(requests_total[5m])) by (region)
  • Optimization: This is where Parallel Query Execution and Data Locality matter.

Modern query engines solve this by "Pushing Down" the computation. Instead of the query node pulling 10GB of data over the network to calculate a sum, it sends the "Sum" instruction to the storage nodes. The storage nodes calculate local sums and return only a few kilobytes to the requester.

The "Top-K" Pitfall

In high-cardinality environments, users often run: topk(10, http_requests_total). Calculating the top 10 series out of 10 million requires the database to track the state of all 10 million in memory during the query. To scale this, we use Sketching Algorithms like HyperLogLog (HLL) or T-Digest. These provide "good enough" estimates with a fraction of the memory overhead.


Engineering for the Future: Is SQL the Answer?

For years, the industry moved away from SQL for time-series, favoring DSLs (Domain Specific Languages) like PromQL or Flux. However, we are seeing a massive SQL Renaissance.

The reasoning is simple: Optimization. Decades of research have gone into SQL query optimizers. By treating time-series as a specialized case of relational data (as seen in TimescaleDB or ClickHouse), we can leverage:

  • Join capabilities: Correlating metrics with deployment metadata in a Postgres table.
  • Standardized drivers: Using any BI tool to visualize infrastructure health.
  • Window functions: Performing complex trend analysis that is nightmarish in PromQL.

Example: Advanced SQL Windowing for Anomaly Detection

Instead of a simple threshold, we can use a moving Z-score to find anomalies in high-cardinality data without manual alerting rules for every series.

WITH stats AS (
    SELECT 
        timestamp,
        value,
        avg(value) OVER W AS rolling_avg,
        stddev(value) OVER W AS rolling_stddev
    FROM metrics
    WHERE metric_name = 'latency'
    WINDOW W AS (ORDER BY timestamp ROWS BETWEEN 60 PRECEDING AND CURRENT ROW)
)
SELECT * FROM stats 
WHERE value > (rolling_avg + 3 * rolling_stddev); -- Find values 3 sigma from the mean

The Operational Reality: A Checklist for Scale

If you are building or scaling a metrics platform today, "Deep-diving" into the code is only half the battle. You need an operational framework that prevents the cardinality firehose from drowning your team.

  1. Cardinality Limiting (The Circuit Breaker): Implement limits at the ingestor level. If a single scrape target provides more than 10,000 unique series, drop the data and fire an internal alert.
  2. Label Sanitization: Use relabeling configurations to drop high-entropy labels (like UUIDs, email addresses, or timestamps) before they reach the storage engine.
  3. Mandatory Downsampling: Never allow a dashboard to query raw data older than 48 hours. Force the use of downsampled tiers for long-term views.
  4. Cost Attribution: In a multi-tenant environment (like a large engineering org), track which team is responsible for the most series. Nothing fixes a cardinality explosion faster than showing a team the $5,000/month bill for their "useful" debugging tags.

Beyond the Horizon

We are entering an era of "Observability 2.0," where the lines between metrics, logs, and traces are blurring. High-cardinality is no longer a bug; it's a requirement. The next generation of TSDBs will likely move toward a unified "Event Store" model, where every metric is an event, and the database uses machine learning to automatically decide what to downsample, what to index, and what to discard.

Until then, the burden remains on us—the engineers—to understand the underlying mechanics of our storage engines. We must respect the physics of time-series data: the constant tension between the resolution we want and the compute power we can afford.

Master the index, control the cardinality, and for the love of your on-call rotation: keep user_id out of your Prometheus labels.


More to explore

Keep diving in