FullStack AI Hub
Studio
System Design · 03. Data & Storage
10 min
10 steps
Intermediate

Time-Series Databases

Ingest millions of telemetry points per second using time partitioning, Gorilla compression, and downsampling rollups.

System Design03. Data & StorageLesson 11 of 11
10 minIntermediate10 steps

Time-Series Databases

Ingest millions of telemetry points per second using time partitioning, Gorilla compression, and downsampling rollups.

INGEST TARGET
100k pts/s
B-TREE IOPS
97% pegged
30D CLEANUP
4h VACUUM
RAW FOOTPRINT
16 B / point
100k pts/sthrashing B-Tree100k pts/sMetricWriter86%random B-TreeUnpartitioned SQL96%VACUUM storm!
metric append
dashboard query
rollup / fast read
B-Tree thrash / high-card
TSDB OOM / lag
In This LessonStep 1 of 10
What You Will Master
  • ✓Replace random B-Tree index thrashing and expensive `DELETE` vacuums with time-partitioned immutable chunks
  • ✓Shrink telemetry disk footprint 12× using Delta-of-Delta timestamps and XOR float compression
  • ✓Prevent TSDB memory explosions by keeping tag labels strictly bounded in the inverted series index
  • ✓Serve 1-year Grafana dashboards in milliseconds using continuous downsampling rollups and hot/cold object tiering

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Time-Partitioned Chunks (2h–1d)Append-only telemetry ingestion and O(1) instant retention expiry via whole-file chunk dropsOut-of-order late backfill writes touching old closed chunks are more expensive
Gorilla Compression (Delta-of-Delta + XOR)Compressing regular 10s metric streams from 16 bytes/point down to ~1.37 bytes/point (12× smaller)Compressed bit-packed blocks are sequential to scan rather than random-row editable
Continuous Downsampling RollupsPre-aggregating raw 10s points into 1m and 1h min/max/avg/p99 summaries for instant 1-year chartsRaw per-second granularity is discarded after the short hot window (e.g., 14 days)
Low-Cardinality Tag HygieneKeeping TSDB in-memory series indexes lean (`service`, `region`, `status`) instead of unbounded `user_id`High-cardinality entity IDs must be stored in structured logs or wide-column stores instead

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Time-Series Databases.

STEP 01 · PROBLEMJump to step →

Why raw PostgreSQL B-Trees choke on 100k metrics/sec

10,000 microservices and IoT sensors emit CPU, latency, and temperature every 10 seconds—**100,000 immutable rows/sec** (`8.6 billion rows/day`).

Inserting them into a normal SQL table causes composite indexes `(metric_id, timestamp)` to outgrow RAM—turning writes into random SSD thrashing. Worse, deleting 30-day-old rows with `DELETE WHERE ts < now() - 30d` triggers catastrophic `VACUUM` I/O storms!

watch:Telemetry workloads are 99% append-only recent writes and time-range aggregations—fighting them with row-level B-Trees and row-by-row `DELETE` breaks every normal SQL DB.

Append-Heavy TelemetryIndex RAM SpillRow-Delete Vacuum Storm
STEP 02 · SOLUTIONJump to step →

Time Partitioning: hot 2-hour chunks & instant O(1) drops

A **Time-Series Database** (Prometheus, TimescaleDB, InfluxDB, ClickHouse) automatically slices data into fixed **Time Chunks** (e.g., 2-hour or 1-day immutable files).

All live writes hit **only the tiny active current chunk**—which fits 100% in RAM! And expiring 30-day-old data drops **one whole chunk file (`unlink()`) in 1 millisecond** with **zero `VACUUM` overhead**.

idea:Time partitioning solves both halves of the TSDB problem at once: hot working-set writes stay 100% in RAM, and retention cleanup becomes an instant O(1) file delete.

Time Chunks / HypertablesHot Working SetO(1) Chunk Drop
STEP 03 · TECHNIQUEJump to step →

12× Smaller on Disk: Gorilla Delta-of-Delta & XOR Compression

Each raw `(int64 timestamp, float64 value)` point takes **16 bytes** uncompressed. Meta’s **Gorilla compression** (used inside Prometheus, M3, VictoriaMetrics) exploits two facts of real telemetry:

**(1) Timestamps** arrive on steady ticks (`10:00:00, 10:00:10, 10:00:20`)—so the **delta-of-delta is `0`**, stored in just **1 single bit!** **(2) Float values** barely change (`72.1 → 72.1`)—so **XOR** yields `0`, also stored in **1 bit**, shrinking 16 bytes down to **1.37 bytes/point (12× compression)**!

idea:Columnar Gorilla encoding turns 12 TB of raw monitoring metrics into 1 TB on disk—so 12× more history fits directly in SSD and RAM page cache.

Delta-of-Delta EncodingXOR Float CompressionColumnar Chunks
STEP 04 · PROBLEMJump to step →

The #1 TSDB Killer: High-Cardinality Tag Explosion

TSDBs keep an **in-memory Inverted Index** mapping every unique tag combination (`{service="pay", region="us", status="200"}`) to a **Series ID**. 50 services × 3 regions × 5 statuses = just **750 active series** (2 MB RAM).

Now someone accidentally adds `user_id="u_981234"` as a metric label! Suddenly 750 series explodes to **75,000,000 active series**, exhausting TSDB RAM and OOM-crashing your entire monitoring stack.

watch:Cardinal rule of TSDB labels: every label MUST come from a small bounded enum (`service`, `region`, `method`, `status_class`). Never put `user_id`, `order_id`, or raw URLs in metric tags!

Series CardinalityBounded Label EnumsTSDB OOM Protection
STEP 05 · SOLUTIONJump to step →

1-Year Dashboards in 25 ms: Continuous Downsampling Rollups

An executive opens a **1-year CPU trend chart**. Reading raw 10-second data across 1,000 servers means scanning **3.1 billion raw points**—crashing the browser and timing out the TSDB!

Run **Continuous Downsampling Rollups**: keep raw `10s` points for **14 days**, auto-aggregate into `1m` rollups (`min, max, avg, count, sum`) for **90 days**, and `1h` rollups for **5 years**. A 1-year chart now reads just **8,760 rollup points** in **22 ms**!

idea:Never store only `avg` in rollups—store `(sum, count, min, max, histogram buckets)` so you can accurately combine rollups and preserve spike visibility.

Downsampling RollupsMulti-Resolution TiersMergeable Aggregates
STEP 06 · TRADE-OFFJump to step →

Edge case: handling late & out-of-order IoT sensor data

A delivery truck drives through a mountain dead zone for 2 hours, then uploads 700 buffered GPS/temperature points with **2-hour-old timestamps**.

If your TSDB rejects old timestamps, you lose telemetry. Modern TSDBs configure an **Out-of-Order (OOO) Acceptance Window** (e.g., 2 hours) that buffers late samples in a small OOO write buffer and merges them cleanly during background block compaction.

idea:Keep the out-of-order window bounded (e.g., 1–3 hours) so late IoT packets survive dead zones without forcing rewrites of months-old compressed cold chunks.

Out-of-Order IngestionLate-Arrival WindowBlock Compaction
STEP 07 · SOLUTIONJump to step →

Infinite Cheap History: Hot SSD + S3 Object Storage (Thanos/Mimir)

Keeping 3 years of metrics on replicated NVMe SSDs costs a fortune. Modern cloud-native TSDBs (Thanos, Grafana Mimir, VictoriaMetrics) keep only the **last 24–48 hours on local SSD** and ship sealed 2-hour Gorilla blocks directly to **S3 Object Storage**.

A stateless **Query Frontend** splits 6-month dashboard queries in parallel across cached hot blocks and S3 cold blocks—cutting multi-year monitoring costs by **75%** while gaining 11-nines durability!

idea:Decoupling stateless TSDB ingestors/queriers from S3 object storage lets you keep years of metrics at $0.02/GB without resizing disk clusters.

Stateless TSDB TieringS3 Block StoreQuery Range Splitting
STEP 08 · SOLUTIONJump to step →

Scaling Past Millions of Points/Sec: Consistent-Hash Ingestors

At **2 million data points/sec**, a single Prometheus server caps out. Place a stateless **Distributor** in front of an aligned ring of **Ingestor Nodes**.

The Distributor hashes each metric’s `(metric_name + labels)` so every point for the same series routes to the **exact same Ingestor** (replicated `RF=3`)—maximizing Gorilla compression while scaling write throughput linearly!

idea:Hashing by series fingerprint keeps consecutive points of the same metric together on one ingestor, preserving 12× Gorilla delta-of-delta compression at horizontal scale.

Series-Hash RoutingHorizontal IngestorsReplicated Head Chunks
STEP 09 · TECHNIQUEJump to step →

Pre-Computing Alert Queries: Recording Rules

Suppose 200 engineers open the main SRE overview dashboard at once, each running an expensive PromQL `histogram_quantile(0.99, sum(rate(...)))` across 5,000 pods.

**Recording Rules** evaluate that heavy expression **once every 30 seconds** in the background and save the result as a brand-new single lightweight series—turning 200 heavy scans into **200 instant 2 ms lookups**!

idea:Recording Rules are materialized views for time-series data: compute heavy fleet-wide SLO aggregations once, read them cheaply thousands of times.

Recording RulesMaterialized SeriesAlert Evaluation Isolation
STEP 10 · RECAPJump to step →

Recap: designing a million-points/sec Time-Series stack

Time-Series Databases achieve orders-of-magnitude gains over general SQL by specializing strictly around **append-only time chunks**, **12× Gorilla bit-packing**, **O(1) chunk-drop retention**, and **continuous multi-resolution rollups**.

Always guard against **high-cardinality labels**, tier sealed chunks into **S3 Object Storage**, and pre-compute hot SLO views with **Recording Rules**.

idea:Interview cheat code: mention four pillars — Time Chunks (O(1) drops), Gorilla 12× compression, Low-Cardinality tags, and Downsampling Rollups + S3 tiering.

Time ChunksGorilla 12×Low CardinalityRollups + S3

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.