To design a time-series database (TSDB) is to build a store for readings that arrive continuously, each tagged with a time and a set of labels, that can answer "what happened between these two times" quickly and can throw old data away cheaply. A good answer explains how writes are made durable without being slow, how the data is laid out by time and compressed, how long-range queries use rollups, why the number of distinct label combinations is the number to watch, how old data is dropped, and what happens to readings that arrive late.
This lesson designs RainGauge, the storage behind 20,000 rain sensors spread over a city. Each sensor reports rain, temperature and battery level every 10 seconds, and engineers ask for totals by ward and district over days and months. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: the write path, compression, rollups, label cardinality, retention, and late data. All rates and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
Calling fsync after every point allowed 498 points a second, far short of 20,000. Group commit, one fsync every 10 ms, allowed 160,000 a second with an acknowledgement in 8,000 microseconds and no acknowledged point lost. Acknowledging first and syncing each second lost 10,036 acknowledged points per crash on average.
Delta-of-delta timestamps with bit-packed value deltas stored a point in 0.8 bytes for a rain counter (18.1 to 1) and 2.3 bytes for a noisy gauge (6.7 to 1), against 16.0 raw. Regular data compresses best.
Hourly rollups of sum, count and maximum answered a 30-day query by reading 720 rows instead of 215,305 and gave the exact average (469.8) and maximum (998). The average of the hourly averages gave 498.8, and a 95th percentile rebuilt from hourly values gave 722 instead of 804.
Sensor id, district, ward and model made 60,000 series. Adding a firmware version that changes with upgrades made 150,912. A unique reading id would have made 518,400,000 in one day.
Deleting expired rows needed 864,000 ms of work a day. Dropping a 1-day chunk needed 5 ms and kept an average of 1.66% extra data. 7-day chunks kept 11.66% extra.
A database that accepts only readings newer than the newest it has seen kept 17.1% of the data. A 60 s window kept 90.0%. A 900 s window kept 99.0% and needed 162 minutes of rollups to be recomputed.
1. Clarifying Requirements
Functional requirements
Write points: a series (a metric with labels), a time and a value.
Query a series, or all series matching label conditions, over a time range, with aggregates such as sum, average, maximum and percentile.
Downsample old data to coarser resolution.
Delete data automatically after a retention period.
Non-functional requirements
Sustained, high write rate with no acknowledged data lost.
Fast queries over recent data, and acceptable ones over months.
Small storage: time series compress well.
Tolerate readings that arrive late or out of order.
Say what you leave out: alerting rules, a query language, multi-region replication and per-tenant billing.
2. Back-of-the-Envelope Estimation
Writes: 20,000 sensors every 10 s is 2,000 points per second, or 172.8 million points a day.
Storage: at 16 bytes a point that is 2.8 GB a day and 83 GB for 30 days. At about 1.6 bytes after compression it is 276 MB a day and 8.3 GB.
Index: 3 metrics for 20,000 sensors is 60,000 series. At about 1 KB of index each, 60 MB in memory.
The write rate is modest. Cardinality and late data are the difficult parts.
3. Core APIs
POST /v1/writewith a batch such as[{"metric": "rain", "labels": {"sensor": "s-4411"}, "t": 1767225600000, "v": 12}]. The reply is204once the points are durable.GET /v1/query?metric=rain&district=7&from=...&to=...&step=1h&agg=sumreturns one value per step per matching series, or per group.GET /v1/series?match[]=rain{district="7"}lists series, which is how an editor finds label values.PUT /v1/retention/{metric}sets how long raw data and each rollup are kept.
4. High-Level Design
A point enters an ingest layer that makes it durable and puts it in memory. When enough has accumulated, a chunk is written to disk, sorted by series and time and compressed. Queries find the series from a label index, open only the chunks that overlap the time range and aggregate. Background jobs seal chunks, build rollups and drop expired data.
Memory first, then compressed time chunks, then rollups and expiry.
A write is acknowledged after the log is safe, not after the chunk is written.
A query starts from labels, not from time. The label index returns the series that match, the time range selects chunks, and a long range is answered from rollups.
Labels choose the series, time chooses the chunks.
Four layers with different jobs.
5. The Write Path
Sensors send a steady stream, so the write path must be cheap per point and still durable. A write-ahead log appends each point to a file before the point is kept in memory, so that after a crash the memory can be rebuilt by replaying the log. The expensive step is fsync, which makes the log really safe on disk. Calling it for every point does not scale. Group commit lets all the points that arrived in a short interval share one fsync.
The first program has 20 points arriving each millisecond (20,000 a second). An fsync costs 2 ms and appending a point to the log costs 5 microseconds. It tests four plans over 10,000 crashes at random moments, and counts the acknowledged points that were not yet safe.
Output
20,000 points a second. 10000 crashes at random moments per row.
write path points a wait for acknowledged acknowledged replay after
second it the ack points lost points lost a crash
can take (average) (average) (worst) (average)
fsync every point 498 2005 us 0 0 6 s
group commit, 10 ms 160000 8000 us 0 0 6 s
acknowledge first, fsync each 1 s 200000 5 us 10036 19980 6 s
no log, flush each 10 min 200000 5 us 6029912 11999900 none (data gone)
fsync every point: at most 498 points a second. It cannot keep up with 20,000, so the queue would grow without limit.
Group commit every 10 ms: up to 160,000 points a second, an average acknowledgement time of 8,000 microseconds (half the window, the fsync and the appends), and nothing acknowledged was lost.
Acknowledge first, fsync each second: almost no waiting (5 microseconds) and an average of 10,036 acknowledged points lost per crash (19,980 at worst).
No log, flush every 10 minutes: 6,029,912 points lost on average, 11,999,900 at worst, and nothing to replay.
Durability costs a few milliseconds if they are shared.
After a crash, the log since the last flushed chunk is replayed. With 20,000 points a second and a chunk flush every 10 minutes that is about 6 million points on average, which replays in about 6 s at a million points a second (an assumption). A shorter flush interval shortens the replay and produces more small files.
6. Compression
Time-series data is regular. A sensor reports every 10 s, so the difference between successive timestamps is almost always the same, and the delta of the deltas is almost always zero. Values often repeat or change by a little. So a point can be stored in a few bits. The second program stores 100,000 points of four series, where a quarter of the readings are 0 to 39 ms late, in three ways: raw (16 bytes), delta of time and value as variable-length numbers, and delta-of-delta of time with delta of value packed into bits (1 bit for zero, 9, 14 or 68 bits otherwise).
Output
100000 points per series, one every 10 s. Bytes per point:
series raw delta, bit-packed bit-packed against raw
varint
rain counter (0.1 mm) 16.0 4.0 0.8 18.1 to 1
temperature (0.1 C) 16.0 4.0 1.6 9.7 to 1
battery (0.1 %) 16.0 4.0 0.8 19.1 to 1
noisy raw gauge 16.0 4.8 2.3 6.7 to 1
Raw: 16.0 bytes for every series.
Delta with variable-length numbers: 4.0 bytes (4.8 for the noisy gauge). The 10,000 ms gap needs 3 bytes every time.
Bit-packed: 0.8 bytes for the rain counter (18.1 to 1) and the battery (19.1 to 1), 1.6 for temperature (9.7 to 1) and 2.3 for the noisy raw gauge (6.7 to 1).
The more regular the series, the fewer bits it needs.
The bit packing here is a simplified version of the idea in the Gorilla paper (which also compresses floating-point values by their XOR). The sizes depend on the data: a real series with noisy floats compresses less. Compression is also why chunks are written whole: a chunk is sealed, compressed once, and then only read.
7. Rollups and Downsampling
A query over a month of one sensor reads hundreds of thousands of points, and a dashboard may ask for many sensors. A rollup stores a summary for each interval (for example, per hour) so that long queries read only summaries. Old raw data can then be dropped while the rollups stay. The trap is to store something that cannot be combined. Sum, count, minimum and maximum can be combined exactly. An average can be rebuilt as sum divided by count, but not as the average of averages. A percentile cannot be rebuilt from percentiles at all.
The third program reads 30 days of one sensor: 259,200 readings, of which 215,305 arrived. In the heaviest fifth of the hours the sensor lost 60% of its readings (a flooded connector), so the hours do not have equal numbers of readings. It answers the same questions from raw readings, from 1-minute and 1-hour rollups of sum, count and maximum, and from hourly averages and hourly percentiles.
Output
259200 readings in 30 days from one sensor (215305 arrived). Values in 0.1 mm per hour.
data the query reads rows read average maximum 95th percentile
all readings 215305 469.8 998 804
1-minute rollups (sum, count, max) 42759 469.8 998 not possible
1-hour rollups (sum, count, max) 720 469.8 998 not possible
1-hour rollups, average of the hourly values 720 498.8 998 722
1-hour rollups, 95th percentile of hourly p95 720 - - 953
All readings: 215,305 rows, average 469.8, maximum 998, 95th percentile 804.
1-minute rollups (42,759 rows) and 1-hour rollups (720 rows): the same average (469.8) and maximum (998), exactly.
The average of the hourly averages was 498.8. The heavy hours have higher values and fewer readings, and each hour counted the same.
The average of the hourly 95th percentiles was 722 and the 95th percentile of the hourly values was 953. Neither is 804.
Store parts that can be combined. Keep raw data for percentiles, or use a sketch.
If you need percentiles over long ranges, store a mergeable summary (a histogram or a quantile sketch such as t-digest) in each rollup, which gives an approximate answer with a known error. Pick the rollup resolutions from the questions asked: for example raw for 7 days, 1-minute for 30 days, 1-hour for a year.
8. Cardinality
A series is one metric with one exact set of label values. The database keeps an index entry in memory for every series, so the number of distinct series, the cardinality, decides memory and speed, not the number of points. Labels that always go together do not add series (a ward belongs to one district). A label that changes over time, such as a firmware version, or that is unique, such as a reading id, multiplies them.
The fourth program has 20,000 sensors with 30 districts, 300 wards, 5 models and 8 firmware versions, and every sensor gets 0 to 3 upgrades in a year. It assumes 1 KB of index memory per series.
Output
20000 sensors, 3 metrics. One series needs about 1 KB of index memory.
labels on every point series index memory series read for rain
(MB) in district 7
sensor id 60000 60 667
sensor id, district, ward, model 60000 60 667
... and firmware version (1 year of upgrades) 150912 150 1652
ward, model, firmware (no sensor id) 29256 29 327
... sensor id and a unique reading id (1 day) 518400000 518400 5762880
Sensor id: 60,000 series (20,000 sensors times 3 metrics) and about 60 MB. Adding district, ward and model added no series.
Adding the firmware version: 150,912 series and 150 MB, because each upgrade starts a new series for that sensor.
Ward, model and firmware without the sensor id: 29,256 series, but no query for one sensor is possible.
A unique reading id on every point: 518,400,000 series in one day, about 518,400 MB of index. Nothing survives that.
Count the combinations before you add a label.
Put values that change or are unique in the point's value or in a separate lookup table, not in the labels. Limit the number of series per tenant, and alert when the number of new series per hour jumps, which is the usual sign of a bad label.
9. Chunks and Retention
Data is stored in time chunks, each a set of files for one time range. A query opens only the chunks that overlap its range. Retention becomes cheap: when every point of a chunk is older than the retention period, the files are deleted together. The alternative, deleting rows, needs to find and remove each row and later to compact the file.
The fifth program has 172.8 million points a day kept for 30 days. Deleting rows costs 1 s per 200,000 rows, dropping a chunk file 5 ms, and opening a chunk for a query 2 ms. A chunk can only be dropped when all of it has expired, so data stays on average half a chunk longer.
Output
172.8 million points a day, kept for 30 days.
storage layout chunks held retention work data kept beyond open chunks open chunks
each day 30 days (average) for 7 days for 30 days
one table, delete rows 1 864000.0 ms 0.0 h (0.00%) 2 ms 2 ms
1-hour chunks 720 120.0 ms 0.5 h (0.06%) 336 ms 1440 ms
1-day chunks 30 5.0 ms 12.0 h (1.66%) 14 ms 60 ms
7-day chunks 5 0.7 ms 84.0 h (11.66%) 4 ms 10 ms
One table, delete rows: 864,000 ms (14.4 minutes) of work every day, and compaction afterwards.
1-hour chunks: 120 ms a day to drop, only 0.5 hours of extra data (0.06%), but 720 chunks held and 1,440 ms to open the chunks of a 30-day query.
1-day chunks: 5 ms a day, 12.0 hours of extra data on average (1.66%), 14 ms to open 7 days and 60 ms for 30 days.
7-day chunks: 0.7 ms a day, 5 chunks held, 4 ms to open 7 days, and 84 hours of extra data on average (11.66%).
Drop files, not rows. Choose the chunk size from the queries.
The chunk size is a trade between the cost of opening many chunks and the extra data kept. A day is a common middle. Larger chunks also make late writes more costly, which is the next problem.
10. Late and Out-of-Order Data
Sensors lose their connection and send stored readings later. A database that seals a chunk as soon as time has passed cannot take them. There are three options: refuse them, accept those within a window, or accept everything and rewrite sealed chunks and the rollups built from them.
The sixth program has 100,000 readings made 100 ms apart. 90 in 100 arrive within 5 s, 9 in 100 are 1 to 10 minutes late and 1 in 100 are 1 to 7 hours late. The database keeps the last 5 minutes in memory and seals older data. It accepts a reading only if its time is within a window of the newest time it has seen.
Output
100000 readings. 90 in 100 arrive within 5 s, 9 in 100 are 1 to 10 minutes late, 1 in 100 is 1 to 7 hours late.
what the database accepts accepted dropped written into minutes of rollups
sealed chunks to recompute
only newer than the newest 17.1% 82834 0 0
60 s window 90.0% 9904 0 0
900 s window 99.0% 911 4836 162
accept every reading 100.0% 0 5747 162
Only newer than the newest: 17.1% accepted and 82,834 readings dropped. Even delays of a few seconds lose most of the data.
60 s window: 90.0% accepted, no sealed chunk touched.
900 s window: 99.0% accepted, 911 dropped, 4,836 writes into sealed chunks, which meant 162 minutes of rollups to recompute.
Accept every reading: 100.0%, 5,747 writes into sealed chunks and the same 162 minutes of rollups.
A window keeps the hot path simple; the rest goes through a backfill path.
The usual design is a small window for the normal path and a separate backfill path for the rest: the late points are collected, merged into the old chunk in the background, and the affected rollups are recomputed. Because a rollup can change, queries over recent hours should be marked as provisional, or the system should wait for the longest normal delay before it finalises a rollup.
11. Replication and Scale
A single node holds all of this easily at 2,000 points a second, so scale here means safety and growth. Replicate the write-ahead log to a second node before acknowledging when loss is not acceptable. To grow, split series across nodes by a hash of the series (so one node does not take all of the writes for one hot sensor), keep each series' chunks together, and send a query to the nodes that hold the matching series and merge the partial results. Combining partial results again requires mergeable aggregates (sum and count, not average of averages).
12. Choosing the Design
Start from the queries.
| Concern | Choice | Watch for |
|---|---|---|
| Durability and speed | Write-ahead log with group commit | The wait for the group |
| Space | Delta-of-delta timestamps, packed value deltas | Noisy values compress less |
| Long queries | Rollups of sum, count, min and max | Averages and percentiles of rollups |
| Memory | Few, stable labels | Version or id labels |
| Expiry | Time chunks dropped whole | Chunk size against extra data kept |
| Late data | A window plus a backfill path | Rollups that must be recomputed |
13. Trade-offs to Mention
Group commit raises throughput and adds a short wait.
Compression saves space and makes chunks immutable and more work to change.
Rollups make long queries cheap and fix the questions you can ask of old data.
More labels make queries flexible and multiply series.
Small chunks drop expired data tightly and cost more to open; large chunks do the reverse.
A wide late-data window saves readings and forces rewrites and recomputed rollups.
14. Common Mistakes
Calling fsync for every point.
Acknowledging a write before it is in the log.
Using a user id, request id or version number as a label.
Averaging averages, or percentiles of percentiles.
Deleting expired rows one by one.
Dropping late readings silently.
Keeping raw data for a year when a rollup would do.
15. Interview Questions
How do you make writes durable without making them slow? A write-ahead log with group commit: many points share one fsync.
Why do time series compress so well? Timestamps are regular and values change slowly, so deltas and delta-of-deltas are small or zero.
What is cardinality and why does it matter? The number of distinct label combinations. Each series costs index memory, so a label with many or changing values can exhaust it.
How do you answer a one-year query quickly? Read rollups of sum, count, min and max, rebuilt into averages by sum over count.
How do you expire old data? Store data in time chunks and drop whole chunks.
What do you do with data that arrives late? Accept it within a window, and send the rest through a backfill path that rewrites chunks and recomputes the rollups.
Summary
Log first with group commit, then memory, then compressed chunks.
Store regular data as deltas of deltas, packed into bits.
Roll up sum, count, min and max; never average averages.
Keep labels few and stable; watch the number of series.
Partition by time, and drop files for retention.
Handle late data with a window and a backfill path.
Conclusion
A time-series database looks like a table with a time column, and most of its design is about what that shape allows: cheap sequential writes, strong compression, summaries that can be combined and files that can be dropped whole. The corners are label cardinality, answers that cannot be rebuilt from summaries and readings that arrive late. In an interview, state the write rate, the number of series and the retention period, and show how each choice follows from them.
Previous topic: Design Message Queue. Next topic: Design a Distributed Locking Service.
References and further reading
Pelkonen et al., Gorilla: A Fast, Scalable, In-Memory Time Series Database (VLDB 2015), for delta-of-delta timestamps and XOR value compression.
Prometheus documentation on the storage format, blocks, the write-ahead log and label cardinality; the InfluxDB and TimescaleDB documentation on retention policies, continuous aggregates and chunking.
Dunning and Ertl, Computing Extremely Accurate Quantiles Using t-Digests (2019), for mergeable percentile summaries.
Design Key-Value Store and Design Message Queue on this site, for the log, compaction and replication ideas used here.