Systemsfor Aravinda
0 / 78 core
Week 3 · Storage

Time-series data

1.5 hours · core path

Read first: Partitioning and sharding, Choosing a database

In one sitting

Time-series data is appended, compressed, downsampled, and dropped on a retention clock. A bounded set of labels keeps one series per host and metric. Put a user id on the label and you create a series per user, which is how a metrics system runs out of memory.

A metrics system does not store your requests. It stores a number per series per interval, and it throws that number away on a schedule. The design question is how many series you just created, and which points you agreed to lose.

The write shape is append-mostly. New points land at the end. You rarely update an old point. That fits a log-structured layout better than a tree that rewrites a page for every tick. Indexes: B-trees and LSM trees is the comparison: an LSM tree takes a write in memory and a log, then flushes immutable files, and you pay write amplification for that. A B-tree is the better fit when you need point reads and range scans of data you update in place. A stream of samples is the LSM-shaped job. Choosing a database includes “this table is the wrong shape” as a real outcome. One row per point, with a secondary index on every label, is how a metrics workload makes an OLTP database miserable without ever exceeding a headline write rate.

Core concepts

Append, compress, downsample, drop

Append-mostly means a point is a new write at the tail of a series. The common case is in order: the next timestamp is later than the last one. A late point, from a host that was partitioned or a scraper that stalled, is the exception you design for. If you pretend every write is an update of an old row, you pay random writes for a workload that was sequential.

Compression works because successive points look alike. A scrape every ten seconds has timestamps whose first difference is ten, ten, ten. The difference of those differences is zero. You can store a run of zeros instead of a full timestamp on every point. Values that drift slowly have small deltas too, and small integers pack tighter than raw floats. A series of unrelated user ids would not look like that. The similarity is the assumption under the compression, which is why the data model tries to keep one smooth series rather than a bag of random keys. Jeff Dean’s teaching list puts compressing 1 KB with Zippy at about 3,000 ns, which is 3 microseconds. That is a CPU cost for a small block, not a compression ratio. Do not quote a ratio you have not measured. The interview point is the mechanism: deltas of regular timestamps, then drop the raw width.

Downsampling replaces a window of raw points with a coarser one. Ten-second samples become one point per minute. You keep an aggregate you chose: a sum, a count, a min, a max, an average. You do not keep the original points. A ten-second stall disappears inside a calm minute if you stored only the average. A max keeps the stall and loses the shape around it. Pick the aggregate the alert needs before you discard the raw window. After retention deletes the raw points, you cannot reconstruct them from the average.

Retention drops data past a horizon, by time. A log does the same job by time or by size for events many consumers reread. Queues and logs is that store. Metrics add downsampling on the way to the drop: you may keep a cheap coarse series long after the fine series is gone. “Keep everything” is how the disk fills. The horizon is a product decision. A graph of last week does not need ten-second points from last year. A capacity plan that needs a year does not need every scrape. Say the horizon out loud, because the default of forever is not a plan.

Tags, also called labels, are the indexed dimensions of a series: host, region, status code, metric name. The combination of tags is the series. Raw events are not tags. A log line can carry a user id because you are storing an event, not opening a new indexed series for that id. The moment the user id becomes a label on a metric, it is a dimension, and the store will try to keep it addressable.

High cardinality

High cardinality means too many distinct series. A unique label per user id is the usual way to get there. One request counter for the whole service is one series. The same counter labeled by user id is one series per user who appears. A million users is a million series for a single counter, each of which the database has to keep hot enough to accept the next point. Memory is what blows up. The byte cost of the points is the disk bill you can sketch. The failure the cardinality warning names is the index of series, and it arrives before the disk is the story you think you have.

Idle users do not save you if the series still exists. Skipping a write for a quiet series avoids some points and leaves the label indexed. Cardinality follows how many distinct label sets you created, not how many of them ticked in the last minute.

The fix is to keep labels bounded. Host, region, and status have cardinalities you can count on one page. User id, request id, and raw URL do not. Put those on a raw event, a log line or a trace, and sample them. Observability separates the three signals: metrics are aggregated numbers, logs are what one request did and are expensive at volume, traces are a tree of spans. RED for a service is rate, errors, and duration. USE for a resource is utilization, saturation, and errors. Those are a handful of names times a handful of hosts. A user id is not on that list. OpenTelemetry is the shared way to emit the spans, metrics, and logs. It does not make a bad label cheap.

A label you added “just for this one customer” and left in place is the same bug on a delay. Distinct users grow. The process limit does not. A bigger machine moves the wall. It does not change the slope.

What you must not average

A percentile is a point on a distribution. p99 means about 1 in 100 requests is slower than that line. The p99 of host A and the p99 of host B do not combine by averaging. They do not combine by taking the max. Each host saw a different number of requests, so each percentile is a point on a different distribution. The fleet p99 is a percentile of the merged requests. An average of per-host p99 values treats a tiny host and a huge host as the same vote, and it answers a question nobody asked.

Fanout makes this concrete for the user, not just for the scraper. If one page waits on many hosts, the user waits on the slowest call. Averaging the per-host p99 will look calmer than that page. The metric lied because of the combine step, not because the scrapes were late.

What you can add across hosts is a sum, a count, or a bucketed histogram. Adding buckets, then walking the totals until you have passed 99 percent of the counted requests, is a fleet percentile. That walk is the advanced note. Until you have it, compute the percentile where the requests already meet, or store a histogram on purpose. Do not average the p99 column and put it on a dashboard.

Where the writes land

Range partitioning by time keeps a recent scan local: one partition holds a time bucket, and a query for that hour touches one place. Retention can drop an old bucket instead of deleting point by point. The cost is hot ranges. Append-mostly writes all land in the latest bucket. The partition for “now” takes the ingest, and the older ones sit quiet. Partitioning and sharding is the general fact: range scans stay local, and hot ranges exist. Hashing by series spreads the writes and scatters a query for “the last five minutes of every host.” You often do both in spirit: a time bucket, and inside it a split by series, so the current bucket is not a single owner. Say which split you drew. “We partition by time” alone means every host’s newest point hits the same shard.

A late point that arrives after you downsampled its window finds the raw data already gone. You can drop it, or you can fold it into the coarse point and accept that the aggregate moved, or you can keep the raw window long enough for the lateness you actually see. You cannot have the original ten-second series back. That is the retention choice showing up as a correctness bug in a graph, not as a disk saving.

A worked example

You are taking metrics from a fleet of hosts. Every number below that is not a conversion of 86,400 is an assumption.

  • 1,000,000 hosts. An interview-sized fleet, not a company you can cite.
  • 20 metrics per host: CPU, memory, a few disks, a few application counters.
  • One sample every 10 seconds, even when the value did not move.
  • A stored point is an 8-byte timestamp and an 8-byte value. Labels live on the series, not copied onto every point. This width is a teaching assumption. Compression sits on top and is not included, because there is no ratio in evidence.
  • You keep raw 10-second points for 2 days, then 60-second points until 30 days, and you do not promise the raw series after that.
  • The bad label: one request counter also tagged with user id, for 1,000,000 distinct users. An assumption of how many users appear, not a measured product.

A day has 86,400 seconds. A 30-day month is 30 times that, 2,592,000 seconds, and the shortcut is about 2.6 million seconds. A year is about 30 million seconds.

series, healthy labels
  1,000,000 hosts * 20 metrics = 20,000,000 series

samples per series per day
  86,400 / 10 = 8,640
  shortcut day of 100,000 s: 100,000 / 10 = 10,000

points per day
  20,000,000 * 8,640 = 172,800,000,000

write rate
  172,800,000,000 / 86,400 = 2,000,000 points/s
  same rate from the interval: 1,000,000 / 10 * 20 = 2,000,000

width, 16 bytes, labels on the series
  172,800,000,000 * 16 = 2,764,800,000,000 bytes
  2,764.8 GB per day, counting 10^9 bytes as a GB

30 days at that width
  30 * 86,400 = 2,592,000 s
  2,000,000 * 2,592,000 = 5,184,000,000,000 points
  * 16 bytes = 82,944 GB uncompressed
  shortcut month of 2.6 million s is about 83,200 GB

downsample after 2 days, 10 s to 60 s, a factor of 6
  2 days raw = 5,529.6 GB
  28 days coarse = 28 * 2,764.8 GB / 6 = 12,902.4 GB
  18,432 GB instead of 82,944 GB

one metric labeled by 1,000,000 users
  series = 1,000,000 instead of 1
  points/day if each series ticks every 10 s
    1,000,000 * 8,640 = 8,640,000,000
  * 16 bytes = about 138 GB/day for that one counter
  write rate = 8,640,000,000 / 86,400 = 100,000 points/s
  one series, no user label: 8,640 * 16 = about 138 KB/day

The healthy fleet is 20,000,000 series and 2,000,000 points a second. At 16 bytes and no compression, that is 2,764.8 GB a day and 82,944 GB across a 30-day month. You would not store it that wide. The arithmetic is the bill before compression and before you throw anything away, so you can see what downsampling is worth.

Keeping two days raw and the rest of the month at one point per minute cuts the month by more than a factor of four in this sketch, to 18,432 GB at the same width, because 28 of the 30 days shrink by 6. A year of one-minute points, using about 30 million seconds, is about 500,000 samples per series. Times 20,000,000 series is 10 trillion points, times 16 bytes is 160,000 GB uncompressed. The same year at ten-second resolution is six times that, 960,000 GB, for detail you already decided you would not graph. Retention is the rest of the saving: past 30 days in this design, the fine data is gone, and past the horizon you chose for the coarse data, the series is gone too.

The user-id label is a different problem from the fleet’s disk bill. One counter becomes a million series. If each of those series is written every ten seconds, that single counter is 100,000 points a second and about 138 GB a day before compression. The healthy version of the same counter is one series and about 138 KB a day. The ratio is a million, which is the number of users you put in the label. The fleet’s 20 million series stop growing when you stop adding hosts. The user label grows when a new account appears, and a million indexed series is the memory blowup even when many of them are idle. Removing the label is the fix. A larger machine is a delay.

flowchart LR
  hosts[Many hosts]
  ingest[Ingest]
  raw[Recent raw window]
  coarse[Downsampled points]
  drop[Drop by retention]
  hosts --> ingest
  ingest --> raw
  raw --> coarse
  coarse --> drop

A user id label is not a box on this path. It is a multiplier on how many series enter ingest. The drop at the end cannot save you from a million series you are still updating today.

The merge you must not do sits beside this. Suppose each host reports a p99. Averaging a million of those numbers is not the fleet p99. A host with a handful of requests votes the same as a host with half the traffic. The page a user waits on is closer to a max across the hosts that page touched than to an average of percentiles. Store counts you can add. Read the percentile from the combined counts, or admit you only know the per-host figure.

Tradeoffs

Choice What you gain What you spend
10-second raw points for a short window Spikes that last a few scrapes stay visible 2,764.8 GB a day at the teaching width, before compression, for this fleet
Downsample to 60 seconds after two days The rest of the month shrinks by about 6 times You cannot see inside the minute, and a short stall needs a max or it vanishes
Retention that deletes the coarse series Disk has a horizon A graph past that horizon is a blank, not a slow query
Labels limited to host, region, and status Series count stays on the order of hosts times metrics You cannot ask this store which user was slow
User id as a label A per-user graph that feels convenient One series per user, so memory grows with accounts instead of with hosts
Raw events in a log for the user id High cardinality stays off the metrics index You sample, you retain for less time, and you do not get a cheap per-user graph
Partition the newest time bucket by series Ingest is not stuck on one hot range A “last five minutes of everyone” query scatters
One time partition for “now” Range scans of one hour stay local Every host’s newest point hits that partition

The log row is the one people try to skip by overloading metrics. A raw event can hold a user id because it is an event. It is expensive at volume, so you sample and you keep it for a short time. That is a different store from the 20 million series above. Putting the user id on the metric to avoid running a log gives you both bills and the memory failure.

Pitfalls

  • A user id, a request id, or a raw URL as a metric label. The symptom is memory growth that tracks distinct values, then a metrics process that dies or stops accepting scrapes while disk still looks fine.
  • Averaging per-host p99 values into a fleet p99. The symptom is a calm graph on a day when the busiest hosts were slow, or a terrifying graph driven by a host that served ten requests.
  • Downsampling to an average only. The symptom is an incident that lasted twenty seconds and does not appear in the minute rollup. The max would have kept it. You have to choose that before the raw window closes.
  • No retention. The symptom is disk that grows by the uncompressed daily bill every day, about 2,765 GB in this sketch before you even count replication, until the volume fills at a moment that is not an incident in the product.
  • Treating points as rows you update. The symptom is random writes and index maintenance for a workload that was an append, and a database that falls behind a scrape it should have absorbed.
  • Accepting a late point into a window you already replaced with a coarse aggregate, and pretending the aggregate is still exact. The symptom is a minute that does not match anyone’s memory of the outage, with the raw points already deleted so you cannot check.
  • Scraping every one second because the graph looks smoother, without changing retention. The symptom is six times the 10-second bill, immediately, for detail your downsample throws away two days later.
  • One partition for the current hour and nothing else. The symptom is a hot shard on the newest bucket while yesterday’s partitions sit idle. The writes were never spread out in time. They are always “now.”

In the interview

In the first five minutes, multiply hosts by metrics and say the series count. Multiply by samples per day and say the write rate. In this sketch that is 20 million series and 2 million points a second, and 2,764.8 GB a day before compression and retention. Name the bottleneck: the current time bucket if you partitioned only by time, or memory if a label is unbounded. The honest tradeoff is resolution against retention. You keep ten-second points for two days because that is the incident window, and you keep coarser points further out because a year of raw scrapes is the expensive way to draw a smooth line.

Skip codec internals. “Deltas of timestamps, then a real codec, and I will not invent the ratio” is enough. The question that usually follows is what happens if you add user id so support can see one customer. You refuse it on the metric. One million users is one million series, and if they all tick it is on the order of 100,000 points a second for a single counter. The customer lookup belongs on a sampled log or a trace. Design a metrics system is the full interview version of this page, with a query path and a rollup job. The cardinality decision is the one to walk in before you draw the rest.

Check yourself

A million hosts, twenty metrics each, one sample every ten seconds. What is the series count and the write rate?

Series are 1,000,000 times 20, which is 20,000,000. Each series produces 86,400 over 10, which is 8,640 points a day. Times 20,000,000 series is 172.8 billion points a day. Divided by 86,400 seconds, that is 2,000,000 points a second. You can also divide hosts by the 10-second interval and multiply by 20, which is the same 2,000,000. A shortcut day of about 100,000 seconds changes the daily total, not that interval rate.

What breaks if a user id is a label on one request counter used by a million users?

You create one series per user instead of one series for the counter. That is a million indexed series, which is the high-cardinality memory blowup, whether or not every series ticks. If each series is written every ten seconds, the counter alone is 100,000 points a second and about 138 GB a day at 16 bytes a point, against about 138 KB a day for the single unlabeled series. A bigger metrics box slows that down. It does not change the fact that the label set is unbounded.

Why is the average of each host p99 not the fleet p99?

Each p99 is a point on that host’s own distribution, and hosts do not serve the same number of requests. Averaging them gives a tiny host the same vote as a large one, and it is not the 99th percentile of the merged traffic. Sum counts, or sum histogram buckets and then walk the total. A page that fans out across hosts waits on the slowest call, which an average of percentiles will paint as calmer than the user experienced.

You downsample ten-second points to one point per minute and then drop the raw window. What did you throw away?

You threw away the points inside the minute. An average cannot show a ten-second stall. A max can show that something spiked and still cannot show when inside the minute, or how many scrapes were bad. After retention deletes the raw samples, no query brings them back. The factor of six in storage is the whole point, and it is paid for with that lost detail. Decide the aggregate while the raw window still exists.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Jeff Dean, Numbers Everyone Should Know.