Time Series Databases
A time-series system stores measurements keyed by time and one or more dimensions.
What, why, when and how
What is it?
Time-series storage organizes timestamped measurements for range queries, retention, compression and aggregation.
Why is it needed?
Monitoring and telemetry workloads append many samples and repeatedly query time windows rather than isolated business records.
When should I use it?
Use it when time-range access, downsampling and retention dominate the workload.
When should I choose something else?
Do not create an unbounded label combination for every user or request. Ordinary relational storage may suffice for small volumes and transactional entities.
How do I use it?
Define series identity and timestamp semantics, budget active cardinality, choose retention tiers and preserve valid aggregate statistics.
Can you show a concrete example?
A dashboard rolls one-minute samples into hourly data. Store count and sum when later averages are needed; averaging the minute averages directly gives the wrong result when their sample counts differ.
Read the diagram
Minute A: sum 20, count 2; B: sum 90, count 3; Combined sum 110, count 5: average 22; Mean of minute averages is 20: wrong here
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
A time-series system stores measurements keyed by time and one or more dimensions. Design around bounded time-range queries, ingestion rate, cardinality, retention, and correction needs. “Millions of points per second” is not enough to pick a store: an unbounded set of unique label combinations can exhaust memory even when byte volume looks manageable.
Prune blocks before decoding samples
A series key combines a metric and bounded label set. Suppose tag region=east maps to series {1,2}, and service=api maps to {2,3}; intersection selects series 2. Three blocks cover 11:00–12:00, 12:00–13:00 and 13:00–14:00. A query for 12:10–12:20 skips the first and third by time metadata and reads relevant chunks from the middle block. A Bloom filter may reject a definitely absent series; a positive answer still needs verification.
tag candidates: {1,2} intersect {2,3} -> {2}
time candidates: block B only
decode samples: series 2, times [12:10,12:20]Read the diagram
tag candidates: {1,2} intersect {2,3} -> {2}; time candidates: block B only; decode samples: series 2, times [12:10,12:20]
Append-oriented storage, memory buffers and sorted immutable runs favor time-ordered ingestion. Delta-of-time/value encodings compress regular sequences; compression quality depends on the actual measurements. Time partitions make retention deletion cheaper, while tags and block statistics prune reads. Out-of-order ingestion and changing series cardinality complicate both compression and indexing.
Rollups retain counts, sums and suitable extrema/histograms rather than only an average. Bucket X has sum 20,count 2 and Y sum 90,count 3; combined mean is 110/5=22, not (10+30)/2=20. Missing data remains missing. Counter resets and late samples need explicit correction semantics and result versions.
Show answer and explanation
Answer: A user_id label can create one series per user and overwhelm metadata even when sample bytes seem manageable. Bound allowed labels, retention and query fanout, then measure ingest lag and block/compaction work.
Step-by-step reasoning
1. 1 · Frame
Clarify sample shape, timestamp source, write rate, query windows, resolution, retention, and late corrections. Separate operational dashboards from forensic or billing records. Define whether a chart may be approximate and how quickly a new sample must appear. Estimate both bytes and active series: series cardinality often drives index and metadata costs.
2. 2 · Model
Use a logical key of measurement plus bounded dimensions, with timestamped values. Reject or normalize unbounded labels such as raw user IDs unless a query need justifies them. Assign event time and ingest time separately. Partition by time and a stable shard key; keep series metadata distinct from compressed sample blocks.
3. 3 · Scale
Append samples into time-ordered chunks, compress them, and use time and label indexes to prune scans. Retention can delete whole old blocks efficiently. Downsampling produces coarser rollups for long ranges, while raw data remains available for the promised interval. Avoid downsampling across reset or counter-wrap boundaries without reset-aware logic.
4. 4 · Recover
Late data may target a sealed block; choose a bounded correction horizon and a repair path. A compaction job should be idempotent and publish a new block version before deleting old inputs. Protect query paths from expensive high-cardinality selections and monitor active series, ingestion lag, dropped samples, and storage growth.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
Series(key, dimensions, unit, schema_version)
Sample(series_id, event_time, ingest_time, value)
Chunk(series_id, time_range, encoding, checksum)
Rollup(series_id, interval, start_time, aggregate, revision)
Query = dimensions + bounded time range + resolutionWorked example
A dashboard asks for one-minute CPU averages over 30 days. Retain minute-level sum/count aggregates for at least 30 days and read that tier; daily aggregate values cannot reconstruct minute-level changes. Daily files may partition minute records without reducing their resolution, but that is different from a daily rollup. For example, histories [0, 100] and [50, 50] both average 50 across two minutes but have different minute peaks. If only a daily aggregate survives, return an explicitly coarser result or reject the requested resolution. When combining buckets, divide total sum by total count: buckets (sum=20,count=2) and (sum=90,count=3) combine to 110/5=22, not the unweighted mean 20 of their averages 10 and 30. An incident investigator can read raw samples from yesterday only while the raw-retention policy still preserves them. Bound both tenant scope and time range.
Failure walkthrough
A client attaches a unique request ID as a metric label, creating a new series per request. Ingestion still succeeds initially, but series indexes and memory grow much faster than sample bytes. Enforce label budgets, drop or route unsuitable dimensions to logs/traces, and make rejected-label behavior observable. Never silently merge semantically distinct metrics.
Read the diagram
Samples append into open chunk → Chunk is sealed by time → Rollup is computed with revision → Late sample revises bounded range → Old raw chunk expires by policy
Decisions and trade-offs
| Choice | Good fit | Cost |
|---|---|---|
| Time partitioned chunks | Append-heavy bounded range reads | Late corrections and compaction |
| Rollups | Long-range charts | Fine detail is irrecoverable after raw expiry |
| High-cardinality labels | Only when queries require them | Index and memory growth |
| Separate event archive | Audits and rebuilds | More storage and delayed queries |
Check your understanding
Design metrics retention for raw samples, hourly charts, and one late correction that arrives after a block was compacted.
Show answer and explanation
Answer: Keep raw data for a shorter explicit interval and hourly rollups for the longer chart horizon. Track event and ingest time; late corrections within a bounded horizon revise the relevant rollup version. Corrections outside that horizon require a replay/archive path or are rejected by contract. Publish compaction output atomically and retain source blocks until verification.
Primary documentation
Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.
Continue the connection
Study Metrics Monitoring and explain which guarantee from this lesson carries into that topic.
Budget series cardinality and retention
A time series is identified by a metric and label set, then contains timestamped values. Millions of unique label combinations can cost more than a high sample rate for a small stable set. User IDs, request IDs and free-form URLs are dangerous labels when they grow without bound.
Time partitioning supports retention and range scans; compression benefits from regular timestamps and related values. Downsampling lowers long-term cost but changes available questions. An hourly average cannot reconstruct a one-minute spike, and averaging percentiles from separate instances does not generally produce the combined percentile. Preserve suitable histogram buckets or raw observations for the required analysis.
Separate ingestion freshness, query latency and alert delay. Late or out-of-order samples need a policy. Missing data is distinct from zero. Delete or compact whole expired blocks where possible rather than generating billions of individual delete operations. Replication and remote archive paths must have clear replay and deduplication behavior.
Read the diagram
Choice / Good fit / Cost; Time partitioned chunks / Append-heavy bounded range reads / Late corrections and compaction; Rollups / Long-range charts / Fine detail is irrecoverable after raw expiry; High-cardinality labels / Only when queries require them / Index and memory growth; Separate event archive / Audits and rebuilds / More storage and delayed queries
Operational sketch
series = metric_name + normalized label set
sample = timestamp + numeric value
raw: 15-second resolution for 7 days
rollup: 5-minute buckets for 90 days
retention policy states which peaks are preservedA tempting mistake
Downsampling before defining alert requirements can erase the evidence for incidents. A cheap dashboard query is not enough if the data model cannot answer the operational question.
Transfer exercise
Why is endpoint=/orders/{id} a safer label than the full request URL?
Show answer and explanation
Answer: The normalized route has bounded cardinality. Full URLs create a distinct series for many IDs and query strings, increasing index and memory cost.