Summary#
A time-series database (TSDB) stores measurements that arrive as (series, timestamp, value) points: the CPU of host-42 every 10 seconds, the price of a stock every tick, the temperature of a sensor every minute. It's built around five assumptions:
- writes are append-mostly and arrive roughly in time order;
- series are identified by a small set of indexed tags;
- adjacent values are similar;
- queries ask for time ranges and aggregates;
- old data matters less than new.
Exploiting those assumptions brings large gains. LSM-style ingestion, time partitioning, delta-of-delta and XOR compression (around 1–2 bytes per point instead of 16 or more), rollups and cheap retention make it 10–100× better than a general-purpose database for that workload. When the assumptions break, as with high-cardinality tags or cross-series analytics such as top-k over billions of ids, a TSDB becomes worse than a general-purpose database.
Why It Exists#
Imagine you're building the monitoring system for a cloud provider. There are 100,000 servers, each emitting 5 metrics (CPU, memory, disk I/O, network in and out) every 10 seconds:
- 100,000 × 5 / 10 s = 50,000 points per second sustained, with bursts several times higher during incidents, when everybody's dashboards and alerts light up;
- 50,000 × 86,400 = 4.3 billion points per day, or about 30 billion per week.
Users want dashboards that load in under a second, alerts that evaluate every 15–60 seconds, and the ability to debug last week's incident.
Try this in a plain relational table:
CREATE TABLE metrics (
ts TIMESTAMPTZ,
host TEXT,
metric_name TEXT,
value DOUBLE PRECISION
);
CREATE INDEX ON metrics (host, metric_name, ts);Several things go wrong at once:
- Storage bloat. Each row repeats the host name and metric name, and carries per-row overhead. In PostgreSQL, the tuple header alone is about 23 bytes, plus the index entries. A point that is really 16 bytes of information (an 8-byte timestamp and an 8-byte float) costs 50–100+ bytes. At 4.3 billion points per day, that's 200–400 GB per day before indexes.
- Write throughput. 50,000 inserts per second, each updating a B-tree, causes random I/O and WAL pressure. It's feasible with batching on a big machine, but with little headroom. Every extra index slows writes further.
- Reads. "Average CPU of host-42 over the last hour" uses the index, but then fetches rows scattered across pages. "Average CPU by region over 30 days" must touch billions of rows.
- Retention. "Keep 7 days" means
DELETE FROM metrics WHERE ts < now() - '7 days'across billions of rows. That creates heavy WAL, bloat and vacuum work, every day.
Every one of these problems comes from treating time-series data like general rows. Time-series data has structure the database could exploit:
- Time order. New points almost always have the newest timestamps. Data is append-mostly, and updates are rare or forbidden.
- Identity through tags. A point belongs to a series identified by a metric name plus a small set of labels (
host,region,env), and that identity repeats on every point. - Regularity. Timestamps come at fixed intervals, and consecutive values are usually close together.
- Query shape. Queries read a time range of one or a few series, or aggregate many series over a range. They rarely look up a single random point.
- Decaying value. Last hour at 10-second resolution matters, while last year is fine at 1-hour averages, and very old data can be deleted.
Time-series databases encode exactly these assumptions into their storage engines. Facebook's Gorilla paper (Tuomas Pelkonen and colleagues, "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015) showed that combining just a few ideas, chiefly delta-of-delta timestamps and XOR-compressed floats in an in-memory store, compresses points to about 1.37 bytes each, roughly 12× smaller than raw. That let Facebook keep 26 hours of monitoring data in memory for fast queries. Those ideas now sit inside Prometheus, VictoriaMetrics, InfluxDB, M3 and many others.
There's an important caveat up front: having time-stamped data doesn't mean you need a time-series database. Orders, clicks, chat messages and ride events all carry timestamps, but they're usually queried by entity id or aggregated in ways a TSDB handles badly. The classic trap is a top-k problem, such as the most-viewed videos in the last hour. A TSDB with one series per video id must deal with billions of series, and its topk() query becomes a scan across all of them, which is exactly what TSDBs are worst at (see the cardinality section below). Stretch general-purpose tools (PostgreSQL with partitioning, ClickHouse, DynamoDB) as far as they go, and reach for a TSDB when the workload truly matches its assumptions.
How It Works#
We'll first pin down the data model, then assemble a TSDB storage engine from simple building blocks. Each block is useful well beyond time series. Then we'll trace a query end to end.
The data model: series, tags and fields#
Every TSDB has the same core vocabulary, though the names differ:
- Metric or measurement: what is measured, such as
cpu_usageorhttp_requests_total. It's roughly a table. - Tags or labels: indexed key-value metadata identifying which thing was measured, such as
host="server-1",region="us-west"orenv="prod". - Fields or values: the measured numbers, such as
value=45.2. InfluxDB allows several fields per point (usage_user,usage_system). Prometheus has exactly one float per sample. - Timestamp: when the measurement was taken, at millisecond resolution (Prometheus) or nanosecond resolution (InfluxDB).
- Series: a unique combination of metric plus tag set. Each series is a sequence of (timestamp, value) pairs ordered by time, and it's the unit of storage, compression and indexing.
InfluxDB's line protocol makes the structure visible:
cpu_usage,host=server-1,region=us-west,env=prod value=45.2 1700000000000000000
└──── measurement + tag set (series key) ────┘ └ field ┘ └ timestamp (ns) ┘Prometheus writes the same idea as cpu_usage{host="server-1",region="us-west",env="prod"} 45.2, with the metric name itself treated as the label __name__.
The distinction between tags and fields is the single most important modelling decision:
- Tags are indexed. Queries filter and group by them quickly. But each distinct combination creates a new series, with memory and index cost.
- Fields aren't indexed. They're the payload. You can store anything there, but filtering by a field means scanning.
Put things you filter or group by and that have bounded values in tags: host, region, service, status code class. Put the measurements in fields. Getting this wrong leads to slow queries if a filter key is a field, or to cardinality explosion if an unbounded id is a tag.
Common characteristics of time-series data, and how a TSDB exploits each:
| Characteristic | Typical reality | Exploited by |
|---|---|---|
| Append-mostly, time-ordered | 99%+ of writes are "now"; updates rare | Append-only WAL + in-memory head; no in-place updates |
| Regular intervals | Scrape every 15 s, sensor every 60 s | Delta-of-delta timestamps (~1 bit each) |
| Slowly changing values | Gauges drift; counters increase steadily | XOR float compression, delta + varint for integers |
| Repeated identity | Same tag set on millions of points | Store tags once per series, not per point |
| Range + aggregate queries | "Last 6 h, per region, 1-min avg" | Series-contiguous chunks, streaming aggregation |
| Recent data is hot | Dashboards look at last hours | Head block in memory; older blocks on disk or object storage |
| Value decays with age | Nobody needs last year at 10 s resolution | Downsampling and rollups; partition-drop retention |
| High volume | 10^4–10^7 points/s per cluster | LSM ingestion, batching, sharding by series |
Building block 1: append-only storage#
The first idea is simple. Never update in place: always append. A traditional B-tree write must find the page, read it, modify it and write it back. That's random I/O, the most common cause of database slowness:
- spinning disks manage only about 100–200 random operations per second;
- SSDs, though far faster, still prefer sequential patterns, because of erase-block mechanics.
Appending to the end of a file needs no seeking and no read-before-write. Sequential throughput on an SSD reaches gigabytes per second, which absorbs hundreds of thousands of small writes per second when batched.
B-tree update: [seek 4752] → [read] → [modify] → [write] → [seek 9201] → ...
Append-only: [write at end] → [write at end] → [write at end] → ...Appending is also what makes the write-ahead log (WAL) cheap. Every TSDB writes incoming points to a WAL first, for durability, then into memory.
Building block 2: the LSM pattern#
Appending alone leaves data in arrival order, which is useless for "give me host-42's last hour". The log-structured merge (LSM) pattern, covered in depth in Storage Engines: B-Trees vs LSM Trees, fixes that:
- Buffer in memory, sorted. New points go to an in-memory structure, the memtable. TSDBs organise it by series, then by time: Prometheus's head block, or InfluxDB's cache. Writes touch only RAM, plus the WAL append.
- Flush immutable files. When the buffer is full, or a time window closes, it's written out as an immutable, sorted file. Because it's already sorted, the flush is one sequential write.
- Compact in the background. Over time, many small files accumulate. Background compaction merges them into larger ones, rewriting data in better order, dropping deleted data (tombstones), and re-compressing.
Writes never wait for reads or for reorganisation. The cost is read amplification (a query may consult several files) and write amplification (data is rewritten during compaction). TSDBs mitigate both with time partitioning, which keeps the set of files any query touches small, and with per-file indexes.
Building block 3: time-based partitioning#
TSDBs partition data by time window: Prometheus uses 2-hour blocks compacted into larger ones, TimescaleDB uses chunks of a configurable interval (7 days by default), and InfluxDB uses shard groups by duration. Partitions may live on one machine or many. Time partitioning gives three big wins:
- Writes are localised. Nearly every write goes to the current partition, which stays hot in memory and cache.
- Reads prune by time. "Last 2 hours" opens only the partitions that overlap the last 2 hours, and the other 364 days are never touched.
- Retention is free. "Keep 15 days" means deleting whole partition directories or files, which is an O(1) metadata operation. There's no row-by-row DELETE, no vacuum and no index rebalancing. This is the single biggest operational difference from a plain table. Data Lifecycle, Tiering and Retention covers retention design more broadly.
Within a time partition, data is laid out series-contiguous: all of host-42's points for the window are adjacent, in compressed chunks. That's like a columnar store per series, so a range scan for one series reads a few contiguous chunks.
Time partitioning alone concentrates write load on whichever node holds "now". Distributed TSDBs therefore combine time partitioning with sharding by series (a hash of the series key), so writes spread across nodes while each node's data stays time-partitioned. See Partitioning and Sharding.
Building block 4: compression that exploits regularity#
A raw point is a 64-bit timestamp plus a 64-bit float, which is 16 bytes. At 50,000 points per second that's 69 GB per day before indexes. Time-series compression routinely cuts this by 10–12x, because consecutive points in a series are extremely similar. The techniques below build on each other. Each works best on data sorted by series and then by time, which the LSM layout guarantees.
Delta encoding
Store the first value in full, then only the difference from the previous value:
Timestamps (s): 1700000000, 1700000015, 1700000030, 1700000045, 1700000060
Deltas: 1700000000, 15, 15, 15, 15Large numbers become small ones, but a small number in a fixed 64-bit slot still wastes 58 bits. Delta encoding therefore always pairs with a variable-length integer encoding.
Varint and zigzag
A varint (as in Protocol Buffers) uses 7 bits per byte for payload, and the 8th bit says "more bytes follow". Values below 128 take 1 byte, below 16,384 take 2 bytes, and so on. Deltas of 15 fit in one byte instead of eight.
Negative deltas, which come from a gauge going down, would look huge in two's complement. Zigzag encoding fixes that by mapping signed integers to unsigned ones: 0→0, −1→1, 1→2, −2→3, 2→4. Small magnitudes then stay small either way. Packing schemes such as Simple8b go further and pack many small integers into one 64-bit word, using a 4-bit selector that says how many bits each value takes. Run-length encoding (RLE) collapses a run of identical deltas into "value × count". InfluxDB's TSM engine, for example, picks RLE for timestamps when all deltas are equal and Simple8b otherwise.
Delta-of-delta (timestamps)
Metrics are usually scraped at fixed intervals, so the deltas are nearly constant, and the delta of the deltas is usually zero:
Timestamps: 1000, 1060, 1120, 1181, 1240, 1300
Deltas: 60, 60, 61, 59, 60
Delta-of-delta: 0, +1, -2, +1Zero can be stored in a single bit. Facebook's Gorilla paper ("Gorilla: A Fast, Scalable, In-Memory Time Series Database", Pelkonen et al., VLDB 2015) gives the canonical bucket scheme. After a block header, the first timestamp, and the first delta in 14 bits, each delta-of-delta D is written with a variable-length prefix:
In Facebook's production data, about 96% of timestamps compressed to the single '0' bit, because the collectors were very regular. The worked example above costs:
- 64 bits for the first timestamp, or less with a block-aligned header;
- 14 bits for the first delta (60);
- 1 bit for the 0;
- 9 bits each for +1, −2 and +1.
That's 106 bits for six timestamps, about 2.2 bytes each, against 8 bytes raw. With perfectly regular scrapes it falls towards 1 bit per timestamp. Jitter is the enemy: a scraper that wakes "every 15 s ± random milliseconds" stops most points from hitting the '0' bucket. That's one reason Prometheus aligns scrapes to fixed offsets within each interval.
XOR compression (floats)
Floats don't subtract nicely: a delta of two doubles is just another full double. Gorilla's insight is that consecutive values of a series usually share their sign, exponent and leading mantissa bits. XOR-ing a value with its predecessor therefore produces a number that is mostly zeros, with a short run of "meaningful" bits in the middle.
Take 12.0 followed by 24.0:
12.0 = 0x4028000000000000 = 0100 0000 0010 1000 0000 ... 0000
24.0 = 0x4038000000000000 = 0100 0000 0011 1000 0000 ... 0000
XOR = 0x0010000000000000 = 0000 0000 0001 0000 0000 ... 0000
11 leading zeros, 1 meaningful bit, 52 trailing zerosThe encoding rules:
- XOR = 0 (the value repeated): write
'0', which is 1 bit. Flat gauges, idle counters and "0 errors" compress to almost nothing. - XOR ≠ 0 and the meaningful bits fall inside the previous window (at least as many leading and trailing zeros as last time): write
'10'plus just the meaningful bits, reusing the previous window. - Otherwise: write
'11', then 5 bits for the leading-zero count, 6 bits for the meaningful-bit length, then the meaningful bits. For 12→24 that's 2 + 5 + 6 + 1 = 14 bits instead of 64.
The paper reports roughly half of values hitting the 1-bit case. Overall, timestamps and values together averaged about 1.37 bytes per point, against 16 bytes raw, which is about 12x smaller. That let Facebook keep 26 hours of data for its monitoring system in memory and serve queries at in-memory speed. The design was later open-sourced as Beringei. Prometheus's chunk encoding (XOR chunks) and many others descend directly from it.
Two caveats matter in design discussions:
- Compression ratio depends on the data. Noisy, high-precision floats such as sensor readings with 15 significant digits share few bits and compress poorly, often only 2–4x. Rounding to the precision you actually need can double the ratio. Integers stored as floats (counters) compress excellently.
- The encodings are sequential. You can't jump into the middle of a Gorilla chunk; you must decode from its start. This is why chunks are kept small (Prometheus targets about 120 samples, which is 30 minutes at 15 s scrapes) and why each chunk records its min and max time, so whole chunks can be skipped.
Columnar layout and general-purpose codecs
Column-oriented TSDBs (ClickHouse, TimescaleDB compression, InfluxDB 3 on Parquet, QuestDB) store each column contiguously and apply a per-column codec chain:
- timestamps get
DoubleDelta; - floats get
Gorilla; - small integers get
T64(which strips unused high bits) orDelta; - low-cardinality strings get dictionary encoding;
- then a general compressor (
LZ4for speed,ZSTDfor ratio) runs on top.
Sorting rows by series key and then time before compressing is what makes all of these effective. The same column from a random-order table compresses several times worse.
Building block 5: indexes that let queries skip data#
Compression makes data small, but queries must still find the right chunks quickly. TSDBs use three layered indexes.
1. The inverted tag index (postings). For every label=value pair, it keeps a sorted list of the series ids that carry it, exactly like a search engine's term-to-document postings (see Elasticsearch and Search Systems). For example:
__name__=cpu_usage → [1, 2, 3, 4, 7, 9]
region=us-west → [1, 2, 7]
env=prod → [1, 3, 7, 9]The query cpu_usage{region="us-west", env="prod"} intersects the sorted lists:
- [1,2,3,4,7,9] ∩ [1,2,7] ∩ [1,3,7,9] = [1, 7];
- that's a linear merge in O(total list length).
Regex matchers (host=~"web-.*") first expand against the sorted label-value dictionary, then union those postings lists. Prometheus stores this index per block. InfluxDB's TSI (time series index) is a disk-based LSM of exactly this mapping, introduced because the original in-memory index couldn't hold millions of series.
2. Block and chunk metadata (min/max). Every block records its time range, and every chunk records its minTime and maxTime. Columnar formats go further, with zone maps: the min and max of every column per granule or row group. A query for "last 2 hours" skips every block whose range doesn't overlap. A query with value > 90 can skip every row group whose max(value) < 90. This metadata is tiny, kilobytes per block, and is read before any data.
3. Bloom filters. A Bloom filter answers "is key K possibly in this file?" with no false negatives and a tunable false-positive rate. At about 10 bits per key with 7 hash functions, the false-positive rate is about 1%. A TSDB with many files per time range keeps a Bloom filter per file on series keys, and skips files that definitely don't contain the requested series. That turns "open 50 files to look for host-42" into "open the 1 file that has it, plus about 0.5 false positives". Bloom filters are covered in depth in Probabilistic Data Structures for Big Data. They matter most in engines where files aren't strictly partitioned by series (LSM SSTables, as in Cassandra-based TSDBs). Prometheus's per-block postings index makes them unnecessary there.
Building block 6: the on-disk file format#
Put the pieces together and a typical immutable TSDB file or block looks like this:
┌──────────────────────────────────────────────────────────────┐
│ Data section: compressed chunks, grouped by series, by time │
│ series 1: [chunk t0-t1][chunk t1-t2] ... │
│ series 2: [chunk t0-t1] ... │
├──────────────────────────────────────────────────────────────┤
│ Index section: series id → label set, chunk offsets + ranges │
│ Postings: label=value → sorted series ids │
│ Symbol table: every label name/value string stored once │
├──────────────────────────────────────────────────────────────┤
│ (optional) Bloom filter over series keys │
├──────────────────────────────────────────────────────────────┤
│ Footer: offsets of index/postings/bloom, block min/max time │
└──────────────────────────────────────────────────────────────┘Why the index sits at the end:
- The writer streams chunks out sequentially, without knowing their final offsets in advance.
- It writes the index once all offsets are known.
- The fixed-size footer points at the index.
A reader opens the file, reads the last few bytes, jumps to the index, and from there seeks directly to the chunks it needs. The same "data first, footer last" design appears in Parquet, ORC, SSTables and Prometheus blocks. Prometheus's block is a directory holding chunks/ segment files, an index file, meta.json (time range and compaction level) and tombstones. Blocks are immutable, so they can be memory-mapped and cached safely, and copied to object storage as-is.
Tracing a query end to end#
Here is a worked example. The query asks for the average CPU of prod servers in us-west over the last hour, in 5-minute buckets:
avg by (region) (avg_over_time(cpu_usage{region="us-west",env="prod"}[5m]))
-- or SQL-ish: SELECT time_bucket('5m', ts), avg(value) FROM cpu_usage
-- WHERE region='us-west' AND env='prod' AND ts > now()-1h GROUP BY 1Concretely, suppose the database holds 4 cpu_usage series:
| Series | host | region | env |
|---|---|---|---|
| 1 | web-1 | us-west | prod |
| 2 | web-2 | us-west | staging |
| 3 | web-3 | eu-west | prod |
| 7 | web-4 | us-west | prod |
The query runs in four steps:
- Time pruning. Of the 360 blocks held (30 days of 2-hour blocks), only the head block and the previous block overlap the last hour. The other 358 blocks are never opened.
- Postings intersection.
region=us-westgives [1,2,7] andenv=prodgives [1,3,7], so the result is [1,7]. Two series out of four. In a real system it's thousands out of millions, but the work is the same: merge-intersecting sorted integer lists. - Chunk selection. For series 1 and 7, the index lists chunk offsets with time ranges. Only chunks overlapping the last hour are read. At a 15 s scrape that's 240 samples per series, about 2 chunks each, roughly 4 chunks × ~250 bytes ≈ 1 KB from disk or page cache.
- Decode and aggregate. The chunks are decoded sequentially, which is fast at hundreds of millions of samples per second per core. Samples fall into 12 five-minute buckets, and each bucket averages its samples across both series. Say the first bucket has 20 samples from series 1 averaging 52.3 and 20 from series 7 averaging 55.9. That bucket's result is (52.3×20 + 55.9×20)/40 = 54.1.
Compare a Postgres table (ts, host, region, env, value) holding the same 30 days for 100k servers, which is about 130 billion rows:
- Without time partitioning, the B-tree on
(region, env, ts)still finds the rows, but each row is about 50–100 bytes with per-row headers, against about 1.4 bytes in Gorilla. - Rows aren't clustered by series, so the 480 matching rows may sit on 480 different heap pages.
- The table and its indexes are about 50x larger than the compressed TSDB blocks, so far less of it fits in RAM.
The TSDB answers in milliseconds from cache. The naive table often needs hundreds of random page reads, and hours of VACUUM after each retention DELETE. (TimescaleDB exists precisely to close this gap inside Postgres; we cover it below.)
Downsampling and rollups#
Raw 10-second data for a year is 3.15 million points per series. Nobody looks at a year-long chart at 10 s resolution: a 1,000-pixel-wide chart can show at most about 1,000 points. Downsampling precomputes coarser series:
The size arithmetic for 1 million series:
- raw 10 s data for 15 days = 130 billion points × 1.4 B ≈ 180 GB;
- the 1-min tier for 90 days = 130 billion points again, but with 4 aggregates each, so about 0.7 TB;
- the 1-hour tier for 2 years = 17.5 billion points × 4 ≈ 100 GB.
Without rollups, 2 years of raw data would be about 8.8 TB and every long-range dashboard query would scan it.
Key rules for rollups:
- Store mergeable aggregates, not just averages. Keep
sumandcount, so that average = sum/count can be re-aggregated across hosts or into coarser buckets. Keepminandmax. An average of averages is wrong whenever bucket counts differ. - Percentiles can't be averaged. The p99 of an hour isn't the average of sixty 1-minute p99s. Store mergeable sketches instead:
- t-digest (Dunning);
- HDR Histogram;
- DDSketch (Masson, Rim and Lee, VLDB 2019), which gives relative-error guarantees;
- or fixed histogram buckets, as Prometheus histograms do. Merge them at query time.
- Counters need care. Roll up counters by storing the increase per window, handling resets, rather than averaging the raw counter value.
- Roll up only closed windows, and allow a lateness margin. If late data arrives after a rollup ran, either re-run the rollup for that window or accept the inaccuracy. Continuous aggregates in TimescaleDB track invalidated ranges for exactly this reason.
Negotiate resolution in interviews. A strong move when requirements say "keep metrics for 2 years" is to ask at what resolution. "Ten-second data for 2 weeks, 1-minute data for 3 months, 1-hour data for 2 years" usually satisfies the real need and shrinks storage about 50x. Most of the hard scaling problem disappears once the interviewer agrees that old data can be coarse.
Retention and tiered storage#
Because data is partitioned by time, retention is dropping whole partitions, and tiering is moving whole partitions:
Object storage costs about $0.02 per GB-month against roughly $0.08–0.10 for SSD block storage, and it has no capacity planning. Modern TSDBs therefore increasingly treat it as the primary long-term store:
- Thanos, Cortex and Mimir upload Prometheus blocks;
- InfluxDB 3 writes Parquet;
- ClickHouse and TimescaleDB offer S3-backed tiers.
Local disk then becomes a cache. The trade-off is query latency on cold data: about 50–100 ms per object-store request, so it relies on parallel fetches and caching of index headers.
The cardinality problem#
Cardinality is the number of unique series: the number of distinct combinations of metric name and tag values. It's the one resource that every TSDB, from Prometheus to InfluxDB to Datadog's pricing model, is ultimately bounded by. Each series costs:
- an index entry and a postings membership per label;
- an open in-memory chunk, about 1–4 KB in the Prometheus head including labels and overhead;
- per-series bookkeeping in compaction.
Series count multiplies across tags:
cpu_usage tagged by host (1,000) × region (5) × env (3) → at most 15,000 series (fine)
+ container_id (20 per host, churns daily) → 300,000 live, millions over time
+ user_id (10 M users) → 150 BILLION potential series (fatal)Here's the canonical disaster. Someone adds user_id as a tag "to debug one customer". With 10 million users, 1,000 hosts, 5 regions and 10 endpoints, the potential series count is 500 billion. Even the 0.1% that actually occur in a day is 500 million series. At about 2 KB each, that's a terabyte of RAM for the head block. Ingestion stalls, the index balloons, queries over __name__ match millions of postings, and the TSDB falls over or the vendor bill explodes.
Note F3. Compression relies on many points per series. A series with one point has nothing to delta against, so high cardinality destroys the efficiency that justified the TSDB in the first place.
Mitigations, in rough order of preference:
- Don't put unbounded identifiers in tags. User ids, request ids, session ids, email addresses, full URLs with ids, and raw error messages belong in logs or traces, not metrics. A useful rule: if a tag's distinct values can't be listed on one screen, question it.
- Normalise values. Use the route template (
/users/:id) instead of the path (/users/48213), the status class (5xx) instead of 50 status codes when that's enough, and bucket latencies into histograms instead of tagging them. - Drop or relabel at ingest. Prometheus
metric_relabel_configscan drop a label or a whole series before storage. Collectors such as the OpenTelemetry Collector and Vector can strip attributes. Streaming aggregation tiers can pre-aggregate away a label, such as summing across pods to get per-deployment series. - Enforce limits. Set per-tenant or per-metric series limits (Mimir and Cortex
max_global_series_per_user, Prometheussample_limitper scrape target) so one bad deploy can't take down shared monitoring. Alert on series-count growth itself. - Watch churn, not just cardinality. In Kubernetes, every rollout creates pods with new names, and therefore new series, while the old ones linger in the index until their blocks age out. Ten deploys a day of 500 pods each adds 5,000 short-lived series per metric per day.
- Use a different tool for high-cardinality questions. "Which user saw the most errors?" is an analytics question. Put events in a columnar store (ClickHouse, Druid, Pinot, BigQuery), where
user_idis just a column andGROUP BY user_idis a fast scan, or send them to a tracing or observability backend designed for high-cardinality events. Columnar stores don't have a per-series cost, so cardinality only affects GROUP BY memory.
This is precisely why a TSDB is the wrong answer for "top-K most viewed videos" or "clicks per ad". Billions of videoId or adId series each receive a handful of points. A topk() over them is a full scan of every series, and the write path is built for appending to a bounded set of series, not for ranking a huge key space. See Design Top-K / Trending (Top Videos, Leaderboards) and Design an Ad Click Aggregator. Those designs use stream aggregation, sketches, and an OLAP store or Redis.
Query patterns#
TSDB query languages differ: PromQL, InfluxQL and Flux, SQL with time extensions (TimescaleDB, ClickHouse, QuestDB, InfluxDB 3), and MetricsQL in VictoriaMetrics. The query shapes they serve are the same handful:
| Pattern | Example | How the engine serves it |
|---|---|---|
| Range scan of one series | CPU of host-42, last 6 h | Postings lookup → 1 series → contiguous chunks |
| Filter + aggregate across series | p95 latency by region, last 1 h | Postings intersection → decode → group by label |
| Time bucketing | 1-min averages over a day | time_bucket / [1m] windows; or read a rollup |
| Rate of a counter | requests per second | rate(): per-second slope over a window, handles counter resets |
| Last value / latest | current temperature per sensor | Head block; "last point" cache in some engines |
| Top-N series | 10 hosts with highest CPU now | Aggregate per series then sort; costly over huge cardinality |
| Gap filling / interpolation | Fill missing minutes for a chart | fill(previous), interpolate(), time_bucket_gapfill |
| As-of / point-in-time join | Price at the time of each trade | ASOF JOIN (QuestDB, ClickHouse, kdb+) |
| Anomaly / threshold over window | Alert if 5xx > 1% for 5 min | Alerting rules evaluated periodically on recent data |
| Downsampled long range | 1-year trend | Planner picks the coarsest adequate rollup tier |
Here are a few patterns that trip people up.
Counters and rate(). Prometheus counters only increase, and reset to 0 when a process restarts. rate(http_requests_total[5m]) computes the per-second increase over a 5-minute window. It treats any decrease as a reset and adds the pre-reset value back, then extrapolates to the window edges. Never avg() a raw counter. Always rate() first, then aggregate: sum by (service) (rate(http_requests_total[5m])). Rate-then-sum works because a rate is additive across series. Sum-then-rate breaks when any single series resets.
Histograms and percentiles. Computing p99 across many servers needs mergeable data. Prometheus classic histograms store cumulative bucket counters (le="0.1", le="0.5", ...), and histogram_quantile(0.99, sum by (le) (rate(latency_bucket[5m]))) sums the buckets across servers and interpolates. The accuracy depends on how the buckets are chosen. Native histograms (Prometheus 2.40+, experimental at first) use exponential buckets with sparse storage, for much better resolution at lower cost. Summaries (client-computed quantiles) can't be aggregated across instances. Avoid them for fleet-wide percentiles.
Recording rules. An expensive query run by twenty dashboards should be computed once. A recording rule evaluates an expression on a schedule (job:http_requests:rate5m = sum by (job) (rate(http_requests_total[5m]))) and stores the result as a new, low-cardinality series. It's the TSDB equivalent of a materialized view, and the primary tool for keeping dashboards fast.
Alerting. Alert rules are queries evaluated every 15–60 s. They should target symptoms (error rate, latency SLO burn) rather than causes, and should use for: 5m to avoid flapping. Observability: Logs, Metrics and Traces covers SLOs, burn rates and alert design. Design a Metrics Monitoring and Alerting System builds the whole system around a TSDB.
The major tools#
Prometheus TSDB (and the systems built on it)
Prometheus (started at SoundCloud in 2012, and a CNCF graduated project) is a monitoring system with a TSDB embedded inside it. It pulls: it scrapes HTTP /metrics endpoints of discovered targets every 15–60 s.
How its storage engine (the "v3" TSDB designed by Fabian Reinartz, shipped in Prometheus 2.0 in 2017) works:
- Head block: the most recent ~2–3 hours live in memory, one open chunk per series, with a WAL on disk for crash recovery. Full chunks are memory-mapped to disk, which shortens WAL replay on restart.
- Chunks: XOR (Gorilla-style) encoding, about 120 samples per chunk, and about 1.3–2 bytes per sample in practice.
- Blocks: every 2 hours the head is cut into an immutable block directory (chunks, index with postings and a symbol table, meta.json, tombstones). Blocks are compacted into larger ranges, up to 10% of the retention period or 31 days.
- Retention:
--storage.tsdb.retention.time=15d(the default is 15 days) or a size limit. Expired blocks are deleted whole. - Out-of-order samples: historically rejected, since samples had to be appended in time order per series. An optional out-of-order window (
out_of_order_time_window, added in 2.39) now accepts late samples into a separate head structure that is merged at compaction. - Scale envelope: a single well-provisioned Prometheus handles a few million active series and hundreds of thousands of samples per second. Memory is the limit, at roughly a few KB per active series.
Prometheus is deliberately single-node and local: no clustering, no replication. High availability means running two identical Prometheus servers scraping the same targets. Long-term, global and multi-tenant storage comes from systems that take its blocks or remote_write stream:
- Thanos: a sidecar uploads 2 h blocks to object storage; a Store Gateway serves them; Querier fans out and deduplicates HA pairs; Compactor downsamples (5 m, 1 h).
- Cortex, and its successor Grafana Mimir: horizontally scalable, multi-tenant
remote_writereceivers. Distributors hash series to ingesters with replication factor 3. Ingesters build Prometheus blocks and ship them to object storage. Queriers and store-gateways read them back. - VictoriaMetrics: a separate engine with its own storage format (MergeTree-inspired) that speaks the Prometheus protocols. It's known for low memory per series and high compression, and comes in single-node and cluster versions.
InfluxDB
InfluxDB (InfluxData) is a purpose-built, push-based TSDB. Writes use the line protocol over HTTP, and Telegraf is its collection agent. Its storage engine has gone through generations:
- 1.x and 2.x, TSM:
- The Time-Structured Merge tree is an LSM variant: WAL plus in-memory cache, flushed to immutable, compressed TSM files.
- Per-type encodings: timestamps use delta plus Simple8b or RLE, floats use Gorilla XOR, integers use zigzag plus Simple8b, strings use Snappy, and booleans are bit-packed.
- Data is organised into shard groups by time, which makes retention a shard drop.
- The TSI disk-based series index replaced the in-memory index so that cardinality could reach tens of millions.
- Query languages: InfluxQL (SQL-like) and Flux (functional, in 2.x).
- 3.x, a rewrite in Rust (the "IOx" project) on the Apache Arrow ecosystem:
- an in-memory Arrow buffer;
- Parquet files on object storage;
- the DataFusion query engine with SQL support.
- The columnar design is a direct response to the cardinality limits of the series-per-key design: high-cardinality tags become just columns.
InfluxDB fits IoT and sensor telemetry, application metrics with push semantics, and teams wanting one turnkey time-series product with retention policies and downsampling tasks built in.
TimescaleDB
TimescaleDB (Timescale, now TigerData) is a PostgreSQL extension. You get full SQL, joins with relational tables, Postgres's ecosystem and tooling, and time-series storage mechanics underneath:
- Hypertables. You create a normal-looking table and convert it with
create_hypertable. Behind the scenes it's partitioned into chunks by time interval, and optionally by a space key. Each chunk is a real Postgres table with its own indexes, which stay small enough to fit in memory. Inserts go to the newest chunk. - Retention.
add_retention_policy(ordrop_chunks) drops whole chunks, avoiding row-level DELETE and the VACUUM that follows. - Columnar compression. Older chunks are converted to a compressed columnar form (the "hypercore" engine). Rows are grouped by
segmentbycolumns (for exampledevice_id) and ordered byorderby(for exampletime DESC). Each column is encoded with delta-of-delta, Gorilla, dictionary or LZ-style compression. Ratios of 10–20x are commonly reported, and compressed chunks still answer SQL queries. - Continuous aggregates. These are materialized views over
time_bucket()groupings that refresh incrementally as new data arrives, tracking invalidated ranges for late data. Real-time aggregates union the materialized part with not-yet-materialized raw rows. - Hyperfunctions:
time_bucket_gapfill,locf,interpolate, percentile approximations (t-digest, UDDSketch) and counter-aggregate helpers.
CREATE TABLE metrics (time TIMESTAMPTZ NOT NULL, device_id INT, temp DOUBLE PRECISION);
SELECT create_hypertable('metrics', 'time', chunk_time_interval => INTERVAL '1 day');
ALTER TABLE metrics SET (timescaledb.compress, timescaledb.compress_segmentby = 'device_id');
SELECT add_compression_policy('metrics', INTERVAL '7 days');
SELECT add_retention_policy('metrics', INTERVAL '90 days');
CREATE MATERIALIZED VIEW metrics_hourly WITH (timescaledb.continuous) AS
SELECT time_bucket('1 hour', time) AS bucket, device_id,
avg(temp) AS avg_temp, max(temp) AS max_temp, count(*) AS n
FROM metrics GROUP BY bucket, device_id;TimescaleDB fits when time-series data must be joined with relational data (devices, customers, orders), when the team already runs Postgres, or when it needs SQL and transactions. Its write throughput is high (hundreds of thousands of rows per second per node with batching) but bounded by single-node Postgres, unless you use multi-node setups or the managed service.
ClickHouse
ClickHouse (created at Yandex for Yandex.Metrica, open-sourced in 2016) isn't a TSDB per se but a columnar OLAP database. Its MergeTree engine makes it one of the best time-series stores for high-cardinality analytics:
- MergeTree:
- each insert writes an immutable sorted part;
- background merges combine parts, which is LSM-like at the level of whole column files;
- data is sorted by the table's
ORDER BYkey, for example(metric, host, timestamp).
- Sparse primary index: one index entry per granule of 8,192 rows by default, rather than per row. The index for billions of rows fits in RAM, and queries read only the granules whose key range matches.
- Codecs per column:
CODEC(DoubleDelta, ZSTD)for timestamps,CODEC(Gorilla)for floats,T64andDeltafor integers, andLowCardinality(String)for dictionary-encoded tags. - TTL:
TTL timestamp + INTERVAL 30 DAY DELETE, orTO VOLUME 'cold'to move old parts to S3-backed disks. - Pre-aggregation: materialized views into
AggregatingMergeTreetables storing aggregate states (avgState,quantileTDigestState,uniqState), merged later with-Mergecombinators. These are true mergeable rollups. - Partitioning:
PARTITION BY toYYYYMM(ts)or by day lets whole partitions be dropped instantly.
Because there's no per-series object, a user_id or ad_id column with a billion distinct values is fine for storage. GROUP BY over it costs memory proportional to the distinct values in the queried range, not to everything ever seen. Scans run at hundreds of millions to billions of rows per second per node. That's why ClickHouse (and Druid and Pinot) appear in ad-click, log analytics and observability backends: ClickHouse-based observability stacks such as SigNoz, and engines that store high-cardinality traces and logs. ClickHouse fits high-cardinality event analytics, ad-hoc SQL over time-stamped events, and logs and traces at scale. It's a less natural fit for PromQL-style per-series monitoring with alerting, unless you put a compatible layer on top.
Others worth knowing
| System | Model | Fits when |
|---|---|---|
| VictoriaMetrics | Prometheus-compatible, own storage | Cheaper, simpler long-term Prometheus storage; high compression |
| Grafana Mimir / Cortex / Thanos | Prometheus blocks on object storage | Global, multi-tenant, years of Prometheus metrics |
| M3 (built at Uber) | Distributed TSDB + aggregator | Very large-scale Prometheus-compatible metrics with streaming aggregation |
| QuestDB | Columnar, SQL, append-optimised | Fast ingest + SQL with ASOF/SAMPLE BY (finance, IoT) |
| Apache Druid / Apache Pinot | Real-time OLAP, segment-based | Sub-second slice-and-dice on event streams; user-facing analytics |
| Amazon Timestream | Managed serverless TSDB | AWS-native IoT/ops data without running servers |
| Azure Data Explorer (Kusto) | Columnar log/time analytics | Telemetry analytics in Azure |
| Google Monarch | Google's in-memory global TSDB (Adams et al., VLDB 2020) | Not available outside Google; landmark design reference |
| OpenTSDB | On HBase | Legacy Hadoop shops; mostly superseded |
| Graphite (Whisper/RRD) | Fixed-size round-robin files | Legacy; fixed retention per resolution baked into file |
| kdb+/q | In-memory columnar, vector language | Finance tick data; extreme speed, niche skills |
| Cassandra / ScyllaDB / Bigtable as TSDB | Wide rows keyed by series + time bucket | You already run them and need huge write throughput with simple reads |
The last row is a common interview design. Use Apache Cassandra in Practice with partition key (metric, series_id, day) and clustering key timestamp DESC. Writes are spread by partition, a day's data for one series is contiguous, and retention is a TTL plus TWCS (Time Window Compaction Strategy), which drops whole SSTables once every row in them has expired. You give up built-in compression schemes, rollups and a time-series query language, and must build those in the application layer.
Choosing among them#
When to Use It#
Reach for a time-series database when most of these are true:
- Writes are append-mostly and time-ordered. At least 95% of writes are new points near "now", and updates and deletes of individual points are rare.
- The volume is high. It runs at thousands to millions of points per second, or billions of points per day, where a row-per-point B-tree table becomes the bottleneck.
- Queries are time-range plus aggregate. "Last N hours/days, filtered by a few tags, bucketed by minute or hour, aggregated by avg, max, rate or percentile."
- Value decays with age. You want raw data for days, coarse data for months or years, and cheap automatic expiry.
- Series identity is bounded. Tag combinations number in the thousands to tens of millions, not billions.
- Typical domains:
- infrastructure and application metrics;
- IoT and sensor telemetry;
- industrial monitoring;
- fitness and wearable data (see Design a Fitness Tracking App (Strava));
- financial ticks;
- energy and smart meters;
- network telemetry.
Concrete signals that you've outgrown a general-purpose database for this workload:
- Storage is far larger than it should be. For example, 40 bytes or more per point, when a TSDB would use about 1.5.
- Retention DELETE jobs take hours and cause bloat or compaction storms.
- Dashboards over 7 or more days are slow because every query re-aggregates raw rows.
- Write throughput is capped by index maintenance on
(series, ts).
Pick something else instead when:
- Keys are high-cardinality analytics. Questions like top videos, clicks per ad, or per-user activity fit ClickHouse, Druid, Pinot, BigQuery, or stream aggregation into Redis, not a per-series TSDB.
- The data is transactional. Orders, balances and inventory need a relational database (Data Modeling).
- You need full-text search over log lines. Use Elasticsearch, OpenSearch or Loki.
- You need traces with request-level detail. Use Jaeger, Tempo, or a ClickHouse-based tracing backend.
When NOT to Use It#
- Small scale. A few thousand series at 1-minute resolution is about 4 million rows a day. Postgres with a
(series_id, ts)index and monthly partitions handles it fine, and you avoid another system to operate. - Frequent updates or deletes of individual points. TSDBs make these expensive (tombstones, rewrites). If points are routinely corrected, the data isn't really append-only.
- Rich relational queries. Many joins, constraints and transactions across entities either don't work in Prometheus or InfluxDB, or work poorly.
- Exact per-event records you must keep forever, such as a billing ledger. TSDB downsampling and retention discard detail by design. Keep the source of truth elsewhere and feed the TSDB from it.
- Unbounded tag values. If the dimension you care about most is
user_id, a series-oriented TSDB is structurally the wrong shape.
How to Implement It#
Here is a practical sequence for adding time-series storage to a system.
- Define the metrics and their identity.
- List the measurements, their types (counter, gauge or histogram), the units and the resolution.
- Choose tags deliberately: bounded, useful for filtering or grouping.
- Estimate cardinality as the product of each tag's distinct values, plus churn.
- Size it.
- points per second = series ÷ interval. For example, 2M series ÷ 15 s = 133k points per second.
- bytes per day = points per second × 86,400 × about 1.5 bytes = 17 GB per day raw compressed, or 260 GB for 15 days.
- Head memory is about series × 2–4 KB, so 4–8 GB here.
- Decide resolution tiers and retention. For example: raw 15 s for 15 days, 1 min for 90 days, 1 h for 2 years. Write down which queries use which tier.
- Pick the engine using the flowchart above. Decide pull or push: Prometheus scrape versus agents pushing via OTLP or line protocol.
- Build the ingestion path.
- Agents, or the OpenTelemetry Collector, batch and compress the data.
- For high volume or multiple consumers, put Kafka in front (Apache Kafka in Practice) to absorb spikes and fan out to the TSDB, alerting and archives.
- Apply relabelling and dropping at the edge.
- Shard and replicate for scale. Hash the series key across ingesters with replication factor 3, or use the engine's clustering. Keep time partitioning inside each node.
- Add rollups and recording rules for every dashboard panel that spans days, and for every alert expression that's expensive.
- Set guardrails.
- per-tenant series limits;
- per-scrape sample limits;
- query timeouts and maximum series per query;
- alerts on cardinality growth and ingestion lag.
- Tier to object storage for long-term data, and test cold-query latency.
A toy in-memory TSDB core shows the essential shape: per-series append-only arrays, a tag index, and time-range plus tag queries.
type Labels = Record<string, string>;
type Sample = { t: number; v: number };
class TinyTSDB {
private series = new Map<string, Sample[]>(); // seriesKey → time-ordered samples
private postings = new Map<string, Set<string>>(); // "k=v" → seriesKeys
private key(name: string, l: Labels) {
return name + "{" + Object.keys(l).sort().map(k => `${k}=${l[k]}`).join(",") + "}";
}
append(name: string, labels: Labels, t: number, v: number) {
const k = this.key(name, labels);
if (!this.series.has(k)) { // new series: index its labels once
this.series.set(k, []);
for (const [lk, lv] of Object.entries({ __name__: name, ...labels })) {
const p = `${lk}=${lv}`;
if (!this.postings.has(p)) this.postings.set(p, new Set());
this.postings.get(p)!.add(k);
}
}
const s = this.series.get(k)!;
if (s.length && t <= s[s.length - 1].t) throw new Error("out of order"); // append-only
s.push({ t, v });
}
avg(name: string, match: Labels, from: number, to: number): number {
let ids = [...(this.postings.get(`__name__=${name}`) ?? [])];
for (const [k, v] of Object.entries(match)) // intersect postings
ids = ids.filter(id => this.postings.get(`${k}=${v}`)?.has(id));
let sum = 0, n = 0;
for (const id of ids)
for (const p of this.series.get(id)!) // real engines: binary-search chunks by minT/maxT
if (p.t >= from && p.t < to) { sum += p.v; n++; }
return n ? sum / n : NaN;
}
}A real engine adds:
- a WAL;
- compressed chunks of about 120 samples with min and max times;
- block cutting and compaction;
- sorted postings lists merged by intersection, instead of set filtering;
- retention by dropping blocks.
| Technology | Fits when |
|---|---|
| Prometheus | Kubernetes/infra/app monitoring with pull scraping and PromQL alerting; single cluster scale |
| Grafana Mimir / Cortex / Thanos | Long-term, global, HA, multi-tenant Prometheus metrics on object storage |
| VictoriaMetrics | Prometheus-compatible with lower RAM/disk per series; simpler ops than Mimir |
| InfluxDB | Push-based IoT/sensor/app telemetry; turnkey retention and tasks; 3.x for high cardinality on Parquet |
| TimescaleDB | Time series that must join relational data; SQL and Postgres tooling; moderate-to-high ingest |
| ClickHouse | High-cardinality event analytics, logs/traces, ad-hoc SQL at billions of rows |
| Druid / Pinot | Sub-second user-facing analytics on real-time event streams |
| QuestDB / kdb+ | Financial and tick data; ASOF joins; extreme ingest |
| Amazon Timestream / Azure Data Explorer | Fully managed in their cloud; no cluster to run |
| Cassandra / ScyllaDB / Bigtable | Massive write rates with simple per-series range reads; you build rollups yourself |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Plain relational table (Postgres/MySQL) | No new system; SQL; joins; transactions | 30–100 B/point; slow retention DELETE; long-range queries scan rows; write ceiling | Under ~10k points/s and modest retention |
| Prometheus (local TSDB) | Simple; PromQL; pull model; excellent compression; alerting built in | Single node; no replication; cardinality limited by RAM; short retention | Monitoring one cluster or environment |
| Prometheus + Mimir/Thanos/VictoriaMetrics | Global view; years of data on object storage; HA; multi-tenant | Many components to operate; cold query latency | Organisation-wide metrics platform |
| InfluxDB | Turnkey; push ingest; retention and downsampling tasks; SQL in 3.x | Version churn (1.x/2.x/3.x differ); OSS clustering limits historically | IoT and telemetry products |
| TimescaleDB | Full Postgres; joins; SQL; continuous aggregates; columnar compression | Single-primary write ceiling; Postgres tuning still needed | Time series beside relational data |
| ClickHouse | Massive scan speed; high cardinality fine; SQL; codecs; TTL | Not built for point updates; merges need tuning; no native PromQL alerting | Event analytics, logs, traces, ads |
| Wide-column (Cassandra/Bigtable) | Linear write scaling; multi-DC; TTL + TWCS | No rollups, compression schemes or TS query language: build them yourself | Already operated; huge writes, simple reads |
| Managed (Timestream, cloud monitoring) | No ops; elastic | Cost at scale; vendor lock-in; limited query features | Small teams, cloud-native workloads |
The deeper trade-offs behind the table:
- Write speed vs query flexibility. Series-oriented layouts make "one series over time" blazing fast and "all series grouped by an arbitrary new dimension" slow. Columnar layouts do the opposite, at a higher per-point ingest cost.
- Resolution vs cost. Every 2x in scrape frequency doubles storage and ingest. Every rollup tier trades detail for 60x or more savings.
- Cardinality vs observability detail. More labels make debugging easier, at a multiplicative cost. Metrics for bounded aggregates plus traces and logs for high-cardinality detail is the usual split.
- Freshness vs efficiency. Larger batches and longer head windows compress better and write fewer files, but delay durability on object storage, and lengthen WAL replay after crashes.
- Pull vs push. Pull (Prometheus) gives target health for free ("up" is 0 if a scrape fails) and central control of rate. Push suits short-lived jobs, devices behind NAT, and very high fan-in. Prometheus's Pushgateway exists for batch jobs only.
Common Pitfalls#
- Unbounded tags: user ids, request ids, full URLs or error strings as labels. This is the number-one cause of TSDB outages and surprise bills.
- Averaging percentiles, or using client-side summaries, then trying to aggregate fleet-wide p99. Use histograms or mergeable sketches.
- Averaging raw counters, or
rate()aftersum(). Always rate first, per series. - Rollups that store only averages. Keep sum, count, min and max (and sketches) so that tiers can be re-aggregated correctly.
- Ignoring series churn from pod names, container ids and ephemeral hosts. The index grows with every deploy.
- Retention by DELETE in a general-purpose DB instead of partition drops. That leads to bloat, vacuum storms and replication lag.
- Treating a TSDB as a source of truth for billing or compliance. Downsampling and retention will delete data by design.
- Using a TSDB for top-K over a huge key space (videos, ads, products). topk() has to scan every series. Use streaming counters, sketches and an OLAP store.
- Out-of-order and late data silently rejected. Configure an out-of-order window, or buffer and sort at ingest, especially for mobile and IoT devices that sync late.
- Clock skew: devices with wrong clocks write the future or the past. Validate timestamps at ingest and reject or clamp them.
- Dashboards querying raw data over 30 days. Add recording rules or continuous aggregates.
Real-World Examples#
- Facebook Gorilla. Facebook built Gorilla as an in-memory write-through cache in front of its HBase-backed monitoring store. Delta-of-delta and XOR compression shrank points to about 1.37 bytes, which allowed 26 hours of data in memory for fast queries. The paper (Pelkonen et al., VLDB 2015) is the reference design for TSDB compression. Facebook later open-sourced the implementation as Beringei.
- Google Borgmon and Monarch. Google's internal Borgmon monitoring inspired Prometheus's design: label-based series, a pull model, and a rule language. Its successor, Monarch ("Monarch: Google's Planet-Scale In-Memory Time Series Database", Adams et al., VLDB 2020), is a globally distributed, in-memory, regionally partitioned TSDB with a push model and a hierarchical query engine.
- SoundCloud and Prometheus. Prometheus started at SoundCloud in 2012, joined the CNCF in 2016 as its second project after Kubernetes, and is now the default metrics system of the Kubernetes ecosystem.
- Uber M3. Uber built M3, a distributed TSDB plus streaming aggregator, to handle its metrics volume, and open-sourced it in 2018.
- Netflix Atlas. Netflix built and open-sourced Atlas, an in-memory dimensional time-series system for operational insight.
- Cloudflare and ClickHouse. Cloudflare has written publicly about using ClickHouse for its HTTP analytics at very large scale. It's a high-cardinality, time-stamped event workload where a columnar store beats a series-oriented TSDB.
Case studies that use this pattern#
- Design a Metrics Monitoring and Alerting System: the canonical TSDB design, covering collection, Kafka ingest, storage, downsampling, alerting and cardinality.
- Design a Fitness Tracking App (Strava): GPS and heart-rate samples per activity are time series, but stored per activity rather than as monitoring series.
- Design a Price Tracker (CamelCamelCamel): price history per product is a classic low-frequency time series.
- Design a Stock Trading Platform (Robinhood / Exchange): market data ticks, candles at 1 m, 5 m and 1 d, and ASOF joins.
- Design an Ad Click Aggregator and Design Top-K / Trending (Top Videos, Leaderboards): useful counter-examples where a TSDB is the wrong store, because of cardinality.
In the Interview#
Questions interviewers commonly probe, with strong answers:
-
"Why not just Postgres?"
- Thirty to 100 bytes per row against about 1.5 bytes per point.
- Random I/O on index maintenance.
- Retention DELETE causes bloat.
- Long-range scans re-aggregate raw rows.
Postgres is fine at small scale. TimescaleDB keeps Postgres but adds time partitioning, compression and continuous aggregates.
-
"How do you store a year of data?" Downsample into tiers, with mergeable aggregates, and keep the long tiers on object storage. Have the query planner pick the tier by range.
-
"What happens if someone adds a user_id label?" Cardinality explodes. Explain the memory per series, add per-tenant limits, drop the label at ingest, and move the question to logs, traces or an OLAP store.
-
"How do you get global p99 latency?" Use histograms or sketches merged across instances, never averages of p99s.
-
"How do you scale writes beyond one node?"
- Hash series across ingesters with replication factor 3.
- Put Kafka in front to absorb bursts.
- Keep time partitioning per node.
- Build blocks and upload them to object storage.
- Have queriers fan out and merge.
-
"Late or out-of-order data?" Use an out-of-order window or ingest buffer, re-compute rollups for invalidated windows, and clamp timestamps from bad clocks.
Deep Dive: Inside Gorilla-style compression and its successorsShow
Why XOR works, in terms of the bits. An IEEE 754 double has 1 sign bit, 11 exponent bits and 52 mantissa bits. Consider two values of a slowly moving series, say 71.25 and 71.50:
- They share the sign.
- They share the exponent, since both lie between 64 and 128.
- They share the high mantissa bits that encode "71".
They differ only in a few low-order bits, so their XOR has a long run of leading zeros. When the values are "round", as with integers or halves stored as floats, the low mantissa bits are all zero too, which gives long trailing zeros. The meaningful window is therefore short. The "reuse previous window" control code ('10') exists because a stable series tends to keep the same leading and trailing structure from point to point. Paying 11 bits of header every time would waste most of the gain.
The numbers from the paper. For values, about 51% were identical to the previous value (1 bit), about 30% fit in the previous window (the '10' case), and about 19% needed a new window (the '11' case, averaging roughly 37 bits). For timestamps, about 96% had a delta-of-delta of 0. Averaged over production data, that gave the 1.37 bytes per point.
Why the chunk size matters.
- Longer chunks compress slightly better, because the fixed header (the first timestamp and value in full) is amortised over more points.
- Longer chunks cost more for random access. To read the last 5 minutes you must decode from the chunk's start.
Gorilla used 2-hour blocks. Prometheus settled on about 120 samples, which is 30 minutes at a 15 s scrape. Its v3 storage design notes argued that compression gains flatten beyond roughly that size, while query cost keeps rising. Decoding is cheap per sample: a few nanoseconds of bit-twiddling. A query touching 10,000 series × 240 samples decodes 2.4M samples in a few milliseconds per core.
Where it fails.
- Noisy, high-entropy values. Sensor readings with full 52-bit mantissa noise produce a new window almost every point, at 30–60 bits per value. The remedy is lossy pre-rounding to meaningful precision. Storing temperature to 0.01 °C can halve storage.
- Irregular timestamps. Event-driven series (one point per user action) have random deltas, so delta-of-delta buys little. Columnar stores with generic delta plus ZSTD codecs do comparably well here.
- Integers. Counters stored as doubles compress well via XOR. A native integer path (delta, zigzag, Simple8b) is often better still. InfluxDB stores integers and floats as distinct types for this reason.
Successors.
-
Chimp ("Chimp: Efficient Lossless Floating Point Compression for Time Series Databases", Liakos, Papakonstantinopoulou and Kotidis, VLDB 2022):
- refines the XOR scheme by observing that trailing zeros are usually few in real data;
- spends its bits on leading zeros instead, with a 3-bit rounded leading-zero code;
- Chimp128 XORs against the best of the previous 128 values, not just the last one.
It reports clearly better ratios than Gorilla at similar speed.
-
ALP ("ALP: Adaptive Lossless floating-Point Compression", Afroozeh, Kuffó and Boncz, SIGMOD 2024):
- observes that most real doubles are decimals in disguise, such as 71.25;
- multiplies by a power of 10, stores the resulting integers with bit-packed frame-of-reference encoding, and handles exceptions separately;
- is designed for vectorised, columnar decoding (DuckDB adopted it).
The lesson for system designers is that compression ratio is a property of data + encoding, not a constant. Measure on your own data before sizing a cluster, and treat "1.37 bytes per point" as Facebook's number, not a law.
A quick sizing heuristic.
- Prometheus deployments commonly report about 1–2 bytes per sample on disk.
- Columnar stores with codec chains land at about 1–4 bytes per value for metrics, depending on noise.
- Generic row stores take 30–100 bytes.
Use 1.5 bytes per sample for monitoring estimates and 3–4 for noisy IoT data, then add 10–20% for indexes.
Deep Dive: Architecture of a horizontally scalable TSDBShow
A single Prometheus tops out at a few million active series. Organisations with hundreds of millions of series (large SaaS vendors, cloud providers, Monarch inside Google) use a distributed design. Mimir and Cortex make a concrete, open template.
Write path.
- Distributors are stateless. They authenticate the tenant and apply rate and series limits. Then they hash each series, not each sample, onto a consistent-hash ring (Consistent Hashing).
- Every sample of a series goes to the same 3 ingesters. Writes succeed at a quorum of 2, as in Quorums and Leaderless Replication.
- Ingesters are where the Prometheus TSDB actually runs. Each has a WAL, a head block per tenant, and a 2 h block cut.
- Blocks go to object storage. Because 3 replicas each upload a block for the same range, the compactor later vertically merges them, deduplicating identical samples, to restore a single copy.
Why shard by series rather than by time. Sharding by time would send all current writes to one node. Sharding by series spreads them evenly. Each series' chunk lives on one ingester, so compression still works. The cost is that any query matching many series must fan out to every ingester holding recent data.
Query path.
- A query frontend splits long-range queries by day ("query splitting"), caches results per split, and optionally shards one query by series hash ("query sharding") so that several queriers each aggregate a slice.
- Queriers merge partial results. They read recent data from the ingesters, and older data from store-gateways, which hold block index headers in memory and fetch chunks from object storage on demand.
- Duplicate samples from HA Prometheus pairs are removed either at ingest, using an HA tracker that accepts only one replica's writes per tenant, or at query time.
Consistency and failure.
- Losing one ingester of 3 loses nothing: the quorum write succeeded on 2.
- WAL replay restores the head on restart, though replaying millions of series can take minutes, which is why chunks are memory-mapped.
- Queries read with a quorum of ingesters and merge, so a sample acknowledged by 2 replicas is visible.
- Out-of-order data within the configured window is accepted.
- Alerting rules run in a separate ruler component against the same query path. Its reliability determines whether you get paged.
Monarch's different choices. Monarch shows how a planet-scale system rethinks this design:
- It is in-memory for its main serving path.
- Data is partitioned by region, with "leaves" storing series grouped by a target key such as job or task. That keeps related series together for efficient aggregation.
- It pushes data from collectors.
- It evaluates queries hierarchically: global root mixers, then zone mixers, then leaves, pushing aggregation down close to the data.
- Its availability was prioritised over strict consistency for monitoring data. That's a sensible choice: a dashboard that is briefly incomplete beats a monitoring system that is down during the outage it's supposed to show.
The design principle. Monitoring must be more available than the systems it monitors, and must not share their failure domains. Run it in separate clusters or cells, keep a minimal "meta-monitoring" path (a small Prometheus watching the big system), and make sure alerting works when the long-term store is degraded.
Deep Dive: Correct aggregation: rates, histograms, sketches and late dataShow
Counter math. For a counter series over a window, rate() does three things:
- It finds the samples in the window.
- It sums the positive increases, treating any drop as a reset to zero, so an increase across the reset is (the value after the reset) + (the value before the reset − the previous sample).
- It extrapolates to the window boundaries, but not beyond half an average scrape interval past the first and last samples, then divides by the window length.
Two consequences:
increase()over short windows yields non-integers for integer counters, because of the extrapolation.- A window must contain at least 2 samples, so
rate(x[1m])with a 30 s scrape is fragile. The rule of thumb is a window of at least 4× the scrape interval.
Histogram quantile error. With classic buckets of 0.1, 0.25, 0.5 and 1 s, histogram_quantile assumes observations are spread uniformly within a bucket and interpolates linearly. Suppose the true p99 is 0.27 s but falls into the 0.25–0.5 bucket. The estimate could land anywhere from 0.25 to 0.5, depending on how many observations sit near the bucket's edge. An SLO threshold should therefore coincide with a bucket boundary. "99% of requests under 300 ms" needs a 0.3 bucket. Native (exponential) histograms pick bucket boundaries as powers of 2^(2^−schema), so they have bounded relative error everywhere, and they store only non-empty buckets sparsely.
Mergeable sketches. For rollups and fleet-wide percentiles, store a sketch per window and per series group:
- DDSketch. It maps a value x to bucket ⌈log_γ(x)⌉ with γ = (1+α)/(1−α), and keeps counts per bucket. Any quantile it returns is within relative error α of the true value: with α = 1%, a true p99 of 200 ms is reported between 198 and 202 ms. Values from 1 µs to 1 hour (a range of 3.6×10^9) need about log(3.6×10^9)/log(γ) ≈ 1,100 buckets at α = 1%, and fewer once you store them sparsely. Merging is just adding bucket counts, so it's exact and associative. That's exactly what rollups need.
- t-digest (Dunning and Ertl). It clusters values into centroids that are small near the tails and large near the median. That gives very accurate extreme quantiles in a few KB. It's mergeable, though merging is approximate.
- HDR Histogram. It uses fixed relative precision via log-linear buckets, and is popular in latency measurement (Gil Tene).
Store these as binary blobs per (series group, window). ClickHouse's quantileTDigestState and TimescaleDB's percentile_agg / UDDSketch support exactly this pattern. Probabilistic Data Structures for Big Data covers the sketch family more broadly. HyperLogLog is relevant here as well: it counts distinct series cheaply, which is how you monitor cardinality itself.
Late data and rollup invalidation. Mobile and IoT devices batch and upload hours late, and network partitions delay agents. A rollup over [10:00, 10:05) computed at 10:06 misses data that arrives at 11:30. There are three strategies:
- Watermark plus lateness bound. Roll up a window only after "now − allowed lateness", and drop or side-output anything later. It's simple, and suits monitoring.
- Invalidation log. Record which windows received late writes, then periodically recompute those windows from raw data. This is what TimescaleDB continuous aggregates do. It's correct as long as raw data still exists.
- Mergeable, incremental aggregates. Store aggregate states (sum, count, sketch) and merge the late data's partial state into the existing window. That's possible when every aggregate is mergeable. ClickHouse's AggregatingMergeTree does it naturally: late inserts create new parts that merge into the same key.
This is the same event-time versus processing-time reasoning that stream processors formalise with watermarks. See Apache Flink and Stream Processing and Batch vs Stream Processing. In a TSDB, the choice determines whether your 1-hour tier is eventually exact or approximately final, and you should state which in a design.
Key Takeaways#
- Time-series workloads are append-mostly, time-ordered, range-and-aggregate queried, and decay in value with age. A TSDB is a storage engine shaped around exactly these properties.
- Series = metric + tag set is the unit of storage and indexing. Tags are indexed and must be bounded. Fields hold the values.
- The engine:
- a WAL plus an in-memory head;
- immutable time-partitioned blocks (LSM-style flush and compaction);
- series-contiguous compressed chunks;
- an inverted tag index, with min/max metadata and Bloom filters to skip data;
- a footer-indexed file format.
- Compression: delta-of-delta timestamps (about 96% in 1 bit) and Gorilla XOR floats give about 1.37 bytes per point against 16 raw (Facebook, VLDB 2015). Real ratios depend on data noise and regularity.
- Retention means dropping partitions, and downsampling into tiers with mergeable aggregates (sum, count, min, max, sketches) makes long ranges cheap. Always ask what resolution old data needs.
- Cardinality is the binding constraint. Unbounded ids in tags are the classic outage. Put that detail in logs, traces or columnar OLAP instead.
- Tools:
- Prometheus, plus Mimir, Thanos or VictoriaMetrics, for monitoring;
- InfluxDB for push and IoT telemetry;
- TimescaleDB when you need Postgres, SQL and joins;
- ClickHouse, Druid or Pinot for high-cardinality event analytics.
- Aggregate correctly:
rate()beforesum();- histograms or sketches for percentiles, never averaged p99s;
- a deliberate policy for late data.