Why you are doing this at all
The obvious way to store a metric reading is as a row: a name, some labels, a time and a value. In Postgres, each row costs at least 52 bytes before any index. The row header takes 23 bytes, padded to 24. The pointer to the row takes 4. A series ID, a timestamp and a double take 24 more.
In 2015, Facebook's monitoring system took in about 12 million readings a second, over 1 trillion a day. Stored as plain 16-byte pairs of timestamp and value, one day was 16 TB. Facebook's in-memory database for this data, Gorilla, stored each reading in 1.37 bytes on average.
One reading, a timestamp and a value, is a sample. A series is the stream of samples for one metric with one exact set of labels, such as http_requests_total{route="/checkout", status="500"}.
A sample costs a time-series database about a byte and a half; how many series you create sets its memory and its index, and a query costs the series it matches times the points in its range.
A series costs you in four places.
- Memory. Each live series keeps an open chunk of recent samples and an entry in an index in memory.
- The index. Every block of time on disk lists every series that had a sample in it.
- Compression. The tricks that make a sample this cheap work along one series, so a short-lived series spreads its fixed costs over few samples.
- Queries. A query reads every series that matches it, in every block its time range covers.
When you don't need a time-series database
If you take in a few thousand samples a second and your queries join them with business tables, Postgres partitioned by time does the job. Choosing a database names TimescaleDB, a Postgres extension, as the cheap step from there.
If each event matters on its own, such as one request with its customer ID, you have rows, not series. A column store such as ClickHouse keeps one row per event, and a new customer ID costs nothing extra. Observability: metrics, logs and traces covers which signal belongs where. This page covers how series are stored and queried.
How a time-series database stores data
The mechanics below are those of Prometheus's storage engine unless a section says otherwise, because it's open, documented, and the model that Thanos and Grafana Mimir build on. A time-series database is called a TSDB from here on.
A series is a metric name and a set of labels
Prometheus names a series by its metric name plus its labels, and its docs say that changing any label value creates a new series. The storage engine gives each series an ID and stores its samples under that ID. Labels are not columns on a row. They're part of the series' name.
So the number of series in a metric is at most the product of the number of values of each label. Not every combination occurs, so the product is a ceiling, and it's the number to work out first.
The question is which labels one request counter can afford. The service runs 200 pods, and the counter is labelled by pod, method, route and status. pod 200 method 4 route 50 status 5 series, at most 200 × 4 × 50 × 5 = 200,000 Without the pod label series, at most 4 × 50 × 5 = 1,000 Two deploys a day replace every pod, and each new pod name starts new series new series a day 2 × 200,000 = 400,000 in a 30-day query 30 × 400,000 = 12M ───────────────────────────────────────────────────── The pod label multiplies the counter by 200, and it's the only label whose values keep changing. Keep it on the few metrics that are read per pod.
Series that stop and are replaced by new ones are called churn. Fabian Reinartz, who designed Prometheus 2's storage engine, pointed out that churn makes the total number of series grow in a straight line even when the fleet stays the same size. A rolling deploy or an autoscaler replaces pods, and every new pod name starts a new set of series. Choosing a database draws that growth for a cluster that replaces its pods once a day.
Prometheus's instrumentation guide gives numbers. Keep the cardinality of a metric, its number of series, below 10, and investigate anything that could grow past 100. It works through node_exporter on 10,000 machines: tens of series per machine for filesystem space comes to about 100,000, which is fine. Add a label for quota per user with 10,000 users and you reach tens of millions, which it calls too much.
The write path: one sample for every series
Prometheus collects data by scraping: every 15 seconds or so, it asks each target, such as a pod, for the current value of all its series. So one scrape writes one sample to each of hundreds or thousands of series at once. A query does the opposite. It asks for a few series across a span of time.
A database keyed by (series, time) handles those writes badly. Each scrape lands on as many places in the index as it has series. InfluxDB's developers hit this when they ran on a B+tree: appends to many series at once, they wrote, look more like random inserts than appends. If you key by time first instead, the writes are sequential, but reading one series means reading every series in the range. LSM trees vs B-trees prices what scattered page writes cost.
A TSDB buffers by series in memory. Prometheus calls this in-memory part the head. Each series in the head has one open chunk, a compressed run of its recent samples, and each new sample is appended to that chunk. The same sample also goes into a write-ahead log (WAL) on disk, so the head can be rebuilt after a restart. Write-ahead logs covers why the log, not the memory, is the copy that has to be right.
A chunk is full at 120 samples, which is 30 minutes at a 15-second interval. Since version 2.19, Prometheus then writes it to disk and maps the file into memory, so the operating system loads it only when a query reads it. Once the head spans 3 hours, its oldest 2 hours are written out as a block, and the WAL before that point is truncated.
So every live series costs memory whether anyone reads it or not. In 2019, Brian Brazil estimated it from a profile of Prometheus 2.9.2 and worst-case assumptions, scraping every 15 seconds with no churn. He put it at about 2 GiB per million series for the series themselves: their labels, index entries and bookkeeping. Samples added about 2.5 GiB per million, because the head held up to 3 hours of them. That version predates the memory-mapped chunks, so treat about 4.5 GiB per million live series as a first estimate.
A series that stops doesn't leave at once. It stays in the head until the next cut removes the time range it was in, up to about 3 hours later. It takes no new samples, and a deploy doesn't change how many samples arrive, so it adds about the 2 GiB per million share, not the full 4.5.
A TSDB's log is usually less strict than a database's. Prometheus writes each batch of samples to its WAL file, but calls fsync, which forces the bytes onto the disk, only when a segment of the log is closed, at 128 MB or at the truncation every 2 hours. So the log survives a crash of the Prometheus process, because the operating system still holds the bytes, but not a power cut.
Others went further. Gorilla buffered up to 64 KB, a second or two of samples, before writing its log at all, and kept a second copy in another region instead. Google's Monarch, its in-memory TSDB, writes its recovery logs without waiting for them to be acknowledged. All three chose to keep accepting writes over making each sample durable.
The head also expects time to move forward. In a Prometheus or Mimir head, a sample must be newer than the last sample of its series, or it's rejected as out of order. And a sample more than about an hour older than the newest data in the head is rejected as out of bounds. Worked example 4 deals with data that arrives late.
Compressing timestamps: the delta of deltas
Most series are sampled at a fixed interval, so their timestamps are predictable. A Prometheus chunk stores its first timestamp in full and the gap to the second one. After that it stores only how much each gap differs from the one before: the delta of deltas. Prometheus uses a variant of the encoding in Facebook's Gorilla paper.
For a scrape every 15 seconds, the gaps might be 15, 15, 15, 16 and 14, so the deltas of deltas are 0, 0, +1 and −2. The Gorilla paper counts in seconds and gives each range its own size of code.
- 0 is stored as a single
0bit. - Between −63 and 64 is
10followed by 7 bits. - Wider ranges get
110and 9 bits,1110and 12 bits, or1111and 32 bits.
Facebook found that about 96 percent of its timestamps compressed to one bit. Prometheus counts in milliseconds, so its codes after the single bit are wider: 14, 17 and 20 bits, then 64.
Compressing values: XOR with the previous value
A value is a 64-bit floating-point number. Neighbouring values in a series are usually close, and close values share their sign, their exponent and the top of their mantissa, the bits that hold the number's digits. So Gorilla stores the XOR of each value with the one before it, and the XOR is mostly zeros. The bits between its leading zeros and its trailing zeros are its window.
- The same value as before is stored as one
0bit. That was 51 percent of Facebook's values. - A change that fits inside the last change's window is
10followed by the bits in that window. That was 30 percent, at 26.6 bits on average. - Any other change is
11, then 5 bits for the count of leading zeros, 6 bits for the length, then the bits. That was 19 percent, at 36.9 bits on average.
Across its whole data set, Gorilla averaged 1.37 bytes per sample, timestamp and value together. Chunks longer than 2 hours compressed only slightly better, so 2 hours became its block length.
Prometheus's docs say it stores 1 to 2 bytes per sample. InfluxDB uses Gorilla's encoding for its floats, and TimescaleDB uses the delta of deltas and XOR inside its columnar batches.
The question is whether a row per sample is a real
option at this volume. Facebook's 2015 load: about
1 trillion samples a day.
Per sample
Postgres row header 24 + pointer 4
+ series ID, time, value 24 52 B
plain pair 64-bit time + 64-bit value 16 B
Gorilla average across its data 1.37 B
Per day
Postgres rows 1T × 52 B, before any index = 52 TB
plain pairs 1T × 16 B = 16 TB
Gorilla 1T × 1.37 B ≈ 1.4 TB
─────────────────────────────────────────────────────
A row costs 38 times the compressed sample. At 1.4 TB
a day, the recent samples fit in memory; as rows,
they would not.Both encodings compare a sample with the one before it in the same series. So the layout has to keep each series' samples together, and short series pay the full cost of their first sample. Prometheus's docs make the same point when they say that cutting the number of series saves more than scraping less often.
Blocks: one small database per two hours
Prometheus cuts time into blocks of 2 hours. Each block is a directory with its own chunk files and its own index, and once written it never changes. Reinartz described each block as a fully independent database for its time window.
A query reads only the blocks that overlap its time range, and merges their answers. Merging many blocks costs time, so a background job compacts neighbouring blocks into longer ones. Blocks grow to at most 10 percent of the retention period, or 31 days, whichever is smaller.
Retention is the cheap part of this design. A block that lies wholly behind the retention line is deleted as a directory, with no rows to find and no tombstones. A block that straddles the line waits until all of it has expired, and the 10 percent cap bounds how much extra that keeps. LSM trees vs B-trees explains why deletes one at a time are expensive in any engine.
The index over labels
A query names series by their labels, such as {route="/checkout", status="500"}. Each block's index answers that with an inverted index: for every label pair, a sorted list of the IDs of the series that carry it, called a postings list. The query intersects the lists for its matchers, just as a search engine intersects the lists for its words. Inverted indexes covers how that intersection runs.
The rest of the index serves the next step. It stores each label string once and refers to it by number. Each series entry lists its labels and its chunks, and each chunk carries its first and last timestamps. So a query can skip chunks outside its range without opening them.
The lists are few and long. Reinartz's test data had about 4.4 million series with about 12 labels each, and fewer than 5,000 distinct label pairs among them. A label like job="api" points at a large share of everything.
Every block lists every series that was live in it. So churn costs twice: once in the head, and again in the index of every block a series passed through. A query over 30 days for job="api" matches every API series that existed in those 30 days, including those of pods long gone.
Downsampling and rollups
Downsampling rewrites a series at a coarser resolution, such as one point per 5 minutes instead of one per 15 seconds. Thanos, which runs Prometheus blocks on object storage, downsamples to 5 minutes once a block is 40 hours old, and to 1 hour once it's 10 days old.
A downsampled point can't be one number. For each window, Thanos keeps the count, the sum, the minimum, the maximum and a counter value for computing rates. The reason is that averages don't combine. If one window holds 1,000 requests averaging 10 ms and the next holds 10 averaging 500 ms, the average of the two averages is 255 ms, and the true average is about 14.9 ms.
Percentiles have the same problem in a worse form. You can't build an hour's 99th percentile from twelve 5-minute ones. You need the bucket counts of a histogram, which add up across windows and across series.
The point of downsampling is reading speed, not disk. Thanos's docs say so: downsampling adds two more blocks for each raw block, at similar size, so keeping every resolution can make storage about 3 times bigger. What it buys is long queries that read far fewer points.
The question is which resolution a year-long panel can read. The panel shows 500 series scraped every 15 s and is about 1,000 pixels wide. Points per series in a year raw 365 × 86,400 / 15 ≈ 2.1M 5 minutes 365 × 288 = 105,120 1 hour 365 × 24 = 8,760 Points for the panel raw 500 × 2.1M ≈ 1.05B 5 minutes 500 × 105,120 ≈ 52.6M 1 hour 500 × 8,760 ≈ 4.4M the screen 500 × 1,000 = 500,000 ───────────────────────────────────────────────────── Raw is about 2,100 points per pixel. Even hourly points are about 9 per pixel, so a year-long panel reads the hourly rollup and nothing finer.
Downsampling shrinks a series along time. It does nothing to the number of series, which is the expensive part. The rollup that changes the bill works across series: it sums 200 pods into one series per service, for example. Prometheus does this with recording rules, queries that run on a schedule and store their results as new series. TimescaleDB does it with continuous aggregates, which can be built on top of each other. Monarch does it at ingestion, before anything is stored, as worked example 2 shows.
Tiering to object storage
Most reads are of recent data. Facebook found that at least 85 percent of its monitoring queries asked for the last 26 hours, so Gorilla kept 26 hours in memory and left the rest to HBase. Reinartz wrote that about 99 percent of Prometheus data is never queried again after 24 hours.
Prometheus keeps its blocks on one machine's disk, and its docs say that local storage isn't clustered or replicated. Thanos and Mimir move blocks to object storage, such as S3. A finished block is immutable, which suits object storage, where an object can't be appended to, as object and blob storage explains.
In Mimir's classic architecture, each series is written to three ingesters, the servers that hold the head. From Mimir 3.0, the preferred architecture is ingest storage, which puts Kafka between the write path and the ingesters.
Each ingester uploads its own 2-hour blocks to the bucket. A compactor merges the three copies into one and removes the duplicate samples, then merges neighbouring blocks into longer ones. Thanos's compactor also writes the downsampled blocks.
Store-gateways serve the blocks in the bucket. Each loads a small header of the index of every block it serves, and fetches only the parts of the index and the chunks that a query needs. A querier asks the ingesters for recent samples and the store-gateways for everything older.
Queries: fan-out and pushdown
A query has to reach every shard that holds a series it matches, in every block its range covers. Mimir places each series by a hash of its labels. So one service's series are spread over many ingesters, and a query that sums them has to ask all of those. Partitioning and sharding shows why a request that waits for every shard waits for the slowest one.
Where the work happens decides what crosses the network. Prometheus's remote read sends raw samples back, and all evaluation runs in the Prometheus that asked. Its docs warn that this limits how far remote reads scale.
Monarch makes two moves.
- Keep related series together. It shards by target, the thing being monitored, so all of one target's series sit on one leaf, the server that holds them in memory. A query about one target goes to one place.
- Push the aggregation down. Each leaf sums its own series by the query's groups and sends one series per group. Monarch's fleet is split into regional zones. Up to 95 percent of its standing queries, the ones that run on a schedule to keep rollups and drive alerts, complete inside one zone.
The question is what crosses the network when 4 shards hold the 200,000 series from the first worksheet. One hour at 15 s is 240 samples per series. Pull every matching series to one querier samples 200,000 × 240 = 48M as compressed chunks, about 2 B each ≈ 96 MB Sum by route on each shard first each shard returns 50 routes × 240 = 12,000 for all shards 4 × 12,000 = 48,000 as plain 16 B points ≈ 0.8 MB ───────────────────────────────────────────────────── Pushdown sends 1,000 times fewer points, so the querier adds 48,000 points instead of decoding 48 million.
Three layouts: Prometheus, TimescaleDB and wide rows
The same samples can sit in three different shapes on disk.
| Prometheus-style TSDB | TimescaleDB | wide rows (Cassandra, Bigtable) | |
|---|---|---|---|
| unit on disk | a chunk of about 120 samples of one series | rows in a time chunk, later batches of up to 1,000 values per column | a partition per series per time bucket, one cell per sample |
| compression | delta of deltas and XOR inside each chunk | delta of deltas and XOR, among others, inside each batch | general block compression over the file |
| finding series by label | an inverted index in every block | Postgres indexes, plus the column it groups rows by | none: you build the row key, or keep another table |
| expiry | delete whole blocks | drop whole chunks | time-window compaction, or a TTL |
| late samples | rejected unless an out-of-order window is set | accepted as ordinary rows | accepted, and they mix time windows |
| what you get for it | label queries over millions of series | SQL and joins with business tables | writes that scale out across nodes |
TimescaleDB keeps Postgres and partitions a table by time into chunks. Its docs advise making the chunks short enough that the indexes being written stay in memory. That's the same move as the hourly partitions in LSM trees vs B-trees. Samples arrive in batches, one insert per scrape or per upload, so the sample rate is not the commit rate.
Older chunks are rewritten as columnar batches of up to 1,000 rows, grouped by a column you choose, such as device_id. Its docs say that grouping by a column with fewer distinct values compresses better, which is the series argument again.
Wide rows put one series and one bucket of time, such as a day, in one partition, sorted by time inside the partition. Bigtable's docs call this the time-bucket pattern, and OpenTSDB on HBase used one row per series per hour. The row key is the only index. A query for one series builds its key, and a query by label alone scans every row under a key prefix, or needs a second table.
The method
1. Count the series. For each metric, multiply the values of its labels, and add the histogram buckets. Then add the churn: how many series a day the deploys and the autoscaler start.
2. Price the memory. Size the head for the worst moment: live series at about 4.5 GiB per million, plus the series that deploys stopped in the last 3 hours at about 2 GiB per million. These are 2019 estimates for Prometheus 2.9.2, so measure your own.
3. Price the samples. Series × samples a day × 1 to 2 bytes × days kept. Back-of-envelope estimation explains why a storage figure means nothing without the days kept. This is usually the small number.
4. Find the longest query. Multiply the series it matches by the points in its range. If that's far more points than the screen has pixels, it needs a rollup.
5. Choose what to roll up across series before the raw data ages out. A rollup can't be built later from data that's gone.
6. Place the aggregation. Work out which shards the busiest query reaches, and make each shard reduce its own series before sending anything.
7. Decide how late a sample may be. Measure how late data arrives, and pick an engine or an out-of-order window that covers it.
Worked examples, start to finish
Each of these four examples breaks a different obvious answer.
One Prometheus server, where memory runs out before disk
A Kubernetes cluster runs 4,000 pods, and each exposes about 1,500 series. Prometheus scrapes every 15 seconds and keeps 15 days, its default, on a machine with 48 GiB of memory. The obvious sizing starts from samples a second and disk.
The question is which resource runs out first: disk, ingestion or memory. Memory uses Brazil's 2019 estimates: about 4.5 GiB per million live series, and about 2 GiB per million stopped series still in the head. Steady state series 4,000 × 1,500 = 6M samples/s 6M / 15 = 400,000 disk a day 400,000 × 86,400 × 2 B ≈ 69 GB 15 days 69 GB × 15 ≈ 1.0 TB memory 6 × 4.5 GiB ≈ 27 GiB A rolling deploy replaces every pod. The old 6M series stop, but stay in the head for up to 3 hours memory 6 × 4.5 + 6 × 2 GiB ≈ 39 GiB A second deploy inside those 3 hours memory 6 × 4.5 + 12 × 2 GiB ≈ 51 GiB ───────────────────────────────────────────────────── On a 48 GiB machine, disk is fine and 400,000 samples a second is fine. The second deploy runs it out of memory.
The sample rate was never the risk. Reinartz reported that a single Prometheus 1.x server could ingest up to 1 million samples a second, and this cluster sends 400,000. Disk was never the risk either.
The decision is to size by series at the worst moment and split the work. Run two Prometheus servers, each scraping half the namespaces. Each then peaks at about 26 GiB during two close deploys: 3 × 4.5 GiB for its live series, plus 6 × 2 GiB for the stopped ones. Then list the series each pod exposes that no dashboard or alert reads, and drop them at scrape time. Every series dropped saves memory on every server and in every block.
A customer label, where one metric outgrows the cluster
An API runs on 200 pods and counts requests by route and status. Product wants error rates per customer on a dashboard and an alert when one customer's errors spike. There are 5,000 customers. The average one calls 10 routes, sees 2 statuses, and is spread over every pod by the load balancer.
The question is what the label costs, with the pod label still on every series. Memory at about 4.5 GiB per million live series, disk at 2 B a sample and 5,760 samples a day. Today: pod × route × status, at most series 200 × 50 × 5 = 50,000 With the customer label series 5,000 × 10 × 2 × 200 = 20M memory 20 × 4.5 GiB ≈ 90 GiB disk a day 20M × 5,760 × 2 B ≈ 230 GB each deploy starts all 20M again Summed across pods before storage series 5,000 × 10 × 2 = 100,000 memory 0.1 × 4.5 GiB ≈ 0.45 GiB ───────────────────────────────────────────────────── The customer label costs 400 times today's series. Summed across pods, it adds 100,000 series, twice today's, and deploys stop creating new ones.
So where should the numbers per customer live?
Add customer_id as a label, and give Prometheus more memory
It's one line of code in the service, and every dashboard and alert already uses PromQL, Prometheus's query language. For 50 customers it would be fine.
At 5,000 customers it's 20 million series and about 90 GiB of head for one counter. Every deploy replaces all 200 pods, so each deploy starts 20 million more. Every block lists all of them, and every query that sums the counter reads them.
Keep customers out of the metrics, and put them in a column store
The counter keeps route and status, 50,000 series. Each request also writes a log line with its customer ID, and the lines go to a column store such as ClickHouse. An error rate per customer is a query that groups recent rows by customer, and a row costs the same whatever the number of customers.
This is the standard answer, and it's right for investigation. The cost is that an alert per customer becomes a scheduled query over the column store, which runs every minute or so and scans recent rows. That's slower and dearer than a threshold on a series. The next tier asks whether series per customer were ever the problem.
Sum across pods before storing, so the customer label is affordable
The premise to question is that every series is stored as each pod emits it. Nobody reads a customer's errors per pod. So sum the 200 pods into one series per customer, route and status before anything is stored. That's 100,000 series, about half a gigabyte of head, and deploys no longer change them, because no pod name is left in the labels.
Monarch built this as collection aggregation. Disk I/O per user across millions of disk servers would have been tens of billions of series. So leaves sum the deltas in 1- to 60-second buckets and store only the total. On average it sums 36 input series into one.
What you give up: pods must report deltas, the change since their last report. Monarch requires them because adding cumulative counters that started at different times gives a meaningless total. The aggregator is a new stateful step on the write path. It has to close each bucket after a short window, and Monarch rejects deltas that arrive later than that. The per-pod view of this metric is gone, so keep a separate counter per pod without the customer label for debugging pods.
A year of dashboards, where reading costs more than keeping
A platform team runs Thanos over its Prometheus servers, 10 million active series at a 15-second interval. Leadership wants capacity dashboards that look back a year. The obvious plan keeps the raw data longer and downsamples it to make it smaller.
The question is what a year costs to keep. 2 B a
sample, 5,760 samples a day per series, S3 Standard at
$0.023 a GB a month for the first 50 TB and $0.022
above it.
Keep raw
a day 10M × 5,760 × 2 B ≈ 115 GB
a year 115 GB × 365 ≈ 42 TB
per month 42,000 GB × $0.023 ≈ $970
Keep raw, 5-minute and hourly
about 3 times, per Thanos ≈ 126 TB
per month 50 TB × $0.023
+ 76 TB × $0.022 ≈ $2,800
─────────────────────────────────────────────────────
Keeping a year of raw data costs less than $1,000 a
month. The cost is in reading it, as the panel
worksheet above showed.So what should old data look like, and where should it live?
Keep a year of raw data on the servers that scrape it
Nothing new to run: raise the retention flag and add disk. Prometheus's docs say local storage can hold years of data with the right setup.
But one machine's disk holds the whole year, so losing that disk loses the year. And every year-long panel reads about 2,100 raw points for each pixel it draws.
Ship blocks to object storage, and downsample for long queries
This is the Thanos design from the toolkit. Blocks go to S3 every 2 hours, a compactor merges them, and downsampled blocks at 5 minutes and 1 hour serve long ranges. The year-long panel reads 4.4 million hourly points instead of 1 billion.
This is the standard answer, and it works. The cost is that storage roughly triples rather than shrinks. And the old blocks still hold every series that ever lived, every pod from last March included, in every index a year-long query opens. The next tier asks whether the old data needs those series at all.
Decide what a year-old question asks, and keep only that
The premise to question is that old data needs the same series as new data. A capacity review asks how much a service used, not how much pod api-7f9c used last March. So write recording rules that roll pods up into series per service, with sums, counts and histogram buckets.
The rollups need their own stream of blocks. Thanos's compactor applies retention per resolution to every block it manages, not per series, so rollups written into the raw blocks would expire with them. Evaluate them in Thanos Ruler, which writes and uploads its own blocks, or in a separate Mimir tenant.
Then run one compactor per stream. The raw stream's compactor sets --retention.resolution-raw, -5m and -1h all to 30 days, because a flag left unset keeps that resolution forever. It could also skip downsampling altogether. The rollup stream's compactor keeps 13 months.
At an assumed 20,000 series at the service level, a year of 5-minute points is 20,000 × 105,120 × 2 B, about 4.2 GB. That's 500 times fewer series than the raw data, so every old block lists 500 times fewer series, and the year-long panel reads a few series per service instead of 500 per pod.
What you give up: nobody can zoom into a single pod older than 30 days. The rollups have to exist before the raw data ages out, and a rollup added in June can't be computed for March, because March's raw data is gone. Decide them with the teams who'll read them, and review them when the services change.
Device readings that arrive hours late
A fleet of 200,000 field devices sends a reading every minute with 8 values, so 1.6 million series. Devices lose signal, buffer readings, and upload them when they reconnect, up to 6 hours late. The obvious answer is a Prometheus-style TSDB, because this is time-series data.
A device that uploads its own backlog sends its samples in order, so they aren't out of order. They're out of bounds: more than about an hour older than the newest data in the head, which the other devices keep moving forward. Prometheus and Mimir reject those samples by default.
Both let you set an out-of-order window, such as 6 hours, which accepts any sample inside it. Mimir's docs name two costs. Cached query results for the last 6 hours can go stale, and recording rules that already ran over that window don't see the late samples.
TimescaleDB takes a late row like any other insert, into the chunk for its timestamp. If that chunk is already columnar, the row waits in row form until a background job compresses it again.
A continuous aggregate records that the time range has changed, and recomputes it at its next refresh, as long as the refresh window reaches back 6 hours. A wide-row table also takes the write, but LSM trees vs B-trees explains how a late write mixes time windows and holds up their expiry.
These readings are also read with the device registry: model, firmware and customer, all in Postgres tables. The decision is TimescaleDB, with 1-day chunks, chunks made columnar once they're 2 days old so late rows land in row form, and a refresh window that starts at least 6 hours back. The device ID is bounded, at 200,000, and never churns, so here a series per device is affordable.
Where it goes wrong
These are ordered by how often they come up.
1. A label with unbounded values
A user ID, request ID, customer ID or pod name multiplies every other label on its metric. One counter can reach 20 million series this way. Count the product before adding the label, and keep detail per item in a column store.
2. Sizing by samples a second
The sample rate and the disk are usually the small numbers. Memory scales with series in the head, and a deploy can double them for a few hours. Size for series at the worst moment.
3. Averaging averages, or percentiles
A rollup that stores an average can't be rolled up again correctly, and a 99th percentile can't be rebuilt from smaller windows. Store sums, counts and histogram buckets.
4. Rollups that expire with the raw data
In Thanos, rollups written into the raw blocks share their retention. In TimescaleDB, a continuous aggregate that refreshes over raw chunks that were dropped deletes its own rows for that range. Give rollups their own retention, and keep refresh windows inside the raw data.
5. Pulling raw series to one querier
If every matching series travels to one process, that process's memory sets the largest query you can run. Aggregate on each shard and send one series per group.
If you memorise nothing else
| fact | why it matters |
|---|---|
| A series is a metric name plus one exact set of labels | a new label value is a new series |
| Series in a metric ≤ the product of its label values | count it before adding a label |
| A compressed sample costs 1 to 2 bytes | Gorilla averaged 1.37 bytes; a Postgres row costs at least 52 |
| Delta of deltas: a steady interval costs one bit a timestamp | 96 percent of Gorilla's timestamps |
| XOR with the previous value: a repeat costs one bit | 51 percent of Gorilla's values |
| Each series in the head costs memory | estimated for Prometheus 2.9.2: about 4.5 GiB per million live, 2 per million stopped |
| Churn: replaced pods leave old series behind for hours | a deploy can double the head's series |
| Blocks of 2 hours, each with its own index | retention deletes whole blocks |
| Labels are found through postings lists | the query intersects them, then skips chunks by time |
| Downsampling keeps count, sum, min and max | long queries read hourly points, not raw ones |
| Roll up across series to cut the bill | downsampling cuts points, not series |
| Push aggregation to the shards | one series per group crosses the network |
| Prometheus's WAL is synced only when a segment closes | it survives a process crash, not a power cut |
What is expected at each level
Mid-level
Know the data model: a series is a metric name and a set of labels, and every new label value is a new series. Know that a TSDB buffers recent samples in memory with a write-ahead log, writes time blocks, and compresses timestamps with deltas and values with XOR. Know that retention deletes whole blocks.
You aren't expected to size the head or design rollups unprompted. If asked "why not put a user ID in a label?", a good mid-level answer is "each user becomes its own series, so the count grows with the users."
Senior
You lead this part of the discussion, and three things must come up without prompting.
The series count, as a product. Multiply the label values, include the churn from deploys, and say which label is the expensive one.
Memory as the limit. Size the head by series at the worst moment, live and stopped, not by samples a second or disk.
Rollups that combine correctly. Sums, counts and histogram buckets, with a resolution chosen for the longest query.
Two things are disqualifying: putting an unbounded ID in a metric label, and a design that answers a year-long query from raw samples.
Staff+
Producing a correct design is still the bar. A staff answer stands out by deciding which series exist at all, with numbers.
Aggregate across series before storage where nobody reads the individual series, and say what it costs: deltas, a new stateful step, and a late-data window.
Retain by question, not by age alone. Raw data for weeks, rollups per service for a year in their own stream, decided before the raw data ages out.
Shard so queries stay local, and push aggregation to the shards. Count the shards the busiest query reaches.
Choose the engine by the joins and the lateness, not by the words "time series". TimescaleDB when readings join business tables or arrive hours late, a Prometheus-style TSDB for label queries over millions of series.
And say what you would not build. Each of these can cost a team a quarter.
One is a bigger Prometheus box for a customer label, when summing across pods makes it add 100,000 series instead of 20 million. Another is a custom TSDB, when the problem is the number of series rather than the engine. And the last is a Cassandra wide-row schema for metrics that need label queries, then a second table to find series by label.
Sources
The engine figures below come from papers, docs and source code. The series, memory, storage and network arithmetic is worked out on this page from them.
- Gorilla: A Fast, Scalable, In-Memory Time Series Database, Pelkonen et al., VLDB 2015. Facebook's load, 16 against 1.37 bytes per sample, the delta-of-delta and XOR encodings with their bucket sizes and shares, 2-hour blocks, the 64 KB log buffer, 26 hours in memory and the 85 percent of queries behind it.
- Monarch: Google's Planet-Scale In-Memory Time Series Database, Adams et al., VLDB 2020. Sharding by target, query pushdown and standing queries, unacknowledged recovery logs, and collection aggregation with deltas, buckets, an admission window and 36 series into one.
- Fabian Reinartz, Writing a Time Series Database from Scratch, 2017, on the design of Prometheus 2's storage: churn, blocks as independent databases, the 10 percent cap on block size, postings intersection and the 4.4 million series test set.
- Prometheus docs on storage, the index and chunk formats, the out-of-order window, the data model, histograms and labels. The source of the WAL, for
fsyncat the segment switch, and of the XOR chunk, for the millisecond codes. Ganesh Vernekar's The Head Block for 120-sample chunks, the 3-hour head and memory-mapped chunks from 2.19, and Brian Brazil's How much RAM does Prometheus 2.x need for the memory per series. - Thanos docs on the compactor, for downsampling ages, the aggregates kept, retention per resolution and the note on storage, and on the ruler. Grafana Mimir's classic and ingest storage architectures, compactor, store-gateway, hash ring and out-of-order ingestion.
- TimescaleDB docs on chunk sizing, partitioning and the columnstore, continuous aggregates and retention.
- InfluxDB's storage engine page, for appends that behave like random inserts and Gorilla's floats. OpenTSDB's HBase schema, Bigtable's schema design for time series and Cassandra's compression for wide rows.
- PostgreSQL's page layout for the row header and pointer, and the AWS price list for S3 in us-east-1.