Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Storage and transactions · Lesson 3 of 11

Time-series databases

How a database for metrics and sensor data takes millions of samples a second: chunks compressed with delta-of-delta and XOR (built and measured in C#), a label index of postings lists, and rollups that can be re-aggregated.

ConceptCore27 min readUpdated

  • 5 code samples
  • 5 interviewer follow-ups
  • 5 self-checks

Read first: Storage engines and indexes

By the end you will be able to
  • Say what makes a time-series workload different and the storage layout that follows from it.
  • Implement delta-of-delta timestamp and XOR value compression, and say what makes a series cheap or expensive to store.
  • Find series by labels with postings lists, and say why the cost follows the shortest list and why a unique label is costly.
  • Roll data up without losing what you will need, by storing aggregates that can be re-aggregated.

5 code samples (369 lines), collapsed so the explanation stays in focus.

A thousand servers each report a hundred numbers every ten seconds. That is a million samples a second, and nobody ever updates one. The samples arrive in time order, are read back as recent windows and aggregates, and are deleted by age. A general database can hold them, and at this volume it does so badly: a row per sample spends dozens of bytes on an eight-byte number, and the index on series and time grows as heavy as the data. A time-series database (TSDB) is a storage engine specialised for this one shape. Prometheus's storage, InfluxDB, VictoriaMetrics, Facebook's Gorilla and Google's Monarch are built on it, and the same ideas appear in market data, IoT and any system that records measurements. This lesson builds the two parts that matter, a compressor for samples and an index for finding series, and then covers what to do with old data.

HLD

What is different about time series

  • Writes are appended, steady and nearly in time order for each series. Nothing is updated, and there are far more writes than reads.
  • Reads ask for a recent window, or a long range at a coarse step, aggregated across many series. The same dashboard query repeats every few seconds.
  • Deletes are by age, never by key.
  • The data is smooth. The next timestamp is usually the last one plus an interval, and the next value is usually near the last one.
  • A series is a metric name plus a set of label pairs (requests{service="checkout", region="eu"}). The number of distinct series, the cardinality, is the main scaling dimension besides the sample rate.

Three consequences shape every time-series store. Compress each series on its own, using the similarity of neighbouring samples. Keep "which series?" (an inverted index over labels) apart from "what are its samples?" (compressed chunks). And store immutable blocks per time window, so that retention is deleting a file and old data can be merged and downsampled without touching live data.

A row per sample in a relational tableA time-series store
Space per sampleDozens of bytes: row header, series id, timestamp, value and index entries (it varies by engine)0.3 to 8 bytes after compression, measured below
Write pathUpdate indexes in place, random writesAppend to a log and an in-memory chunk, flush immutable blocks
RetentionDelete rows, then reclaim spaceDrop whole blocks
Finding seriesA secondary index on the tagsA postings list for every label pair
FitsTransactions on changing rowsAppend-only numeric measurements read as ranges and aggregates

HLD

The layout: head, log and blocks

The write path is the one from the storage engines lesson, specialised. A sample is appended to a write-ahead log (flushed in batches, so many samples share one fsync) and added to the head: one open, compressed chunk per series, in memory, for roughly the last two hours. If the process crashes, the log is replayed to rebuild the head. When the head covers a full window it is cut into an immutable block holding the chunks, the label index and some metadata. A background compactor merges small blocks into larger ones, removes duplicates and can downsample. Retention deletes whole blocks. A query picks the blocks that overlap its time range, finds the matching series through each block's index and decodes their chunks. Prometheus's TSDB has exactly this layout, with two-hour blocks.

It resembles an LSM tree, with one simplification: blocks cover disjoint time windows, so merging never has to reconcile two versions of the same key. Only out-of-order data brings that problem back.

  sample (series, time, value)
        |
        v
  WAL: append, fsync in batches ------> replayed after a crash
        |
        v
  head: one open chunk per series, in memory, about the last 2 hours
        |  every 2 hours: cut
        v
  block: chunks + label index + metadata, immutable, time-bounded
        |  compaction: merge, deduplicate, downsample
        v
  bigger blocks ---> retention deletes whole blocks, no row deletes

  query: choose blocks by time range, find series by labels (postings),
         decode their chunks, aggregate
Fig. A time-series store: the write path and the read path

LLD

Compressing a series

A sample is a timestamp and a value, 16 bytes raw (8 + 8), or 128 bits. The scheme from Facebook's Gorilla paper shrinks both parts by encoding what changed.

Timestamps: the delta of deltas. Scrapes come at a fixed interval, so the difference between consecutive timestamps (the delta) is nearly constant, and the difference between consecutive deltas is nearly always zero. Store that second difference with a variable-length code: one bit (0) when it is zero, a short prefix and 7, 9 or 12 bits for small changes, and a prefix and 32 bits otherwise.

Values: XOR with the previous value. The bit patterns of two nearby floating-point numbers share their sign, exponent and top mantissa bits, so their XOR is mostly zeros. A repeated value XORs to zero and costs one bit. Otherwise store the window of bits that changed: how many leading zeros, how long the meaningful part is, and those bits. If the new changed bits fall inside the previous window, a control bit says so and only the bits are stored.

This codec is streaming: each sample is encoded as it arrives, so the open chunk in memory is already compressed, which a general-purpose compressor applied to a finished block cannot offer. The price is that a chunk must be decoded from its start, since each sample depends on the one before, so chunks are kept short (about 120 samples in Prometheus) and an out-of-order sample cannot be inserted into the middle of one. The types below are a complete codec.

C# · Writes bits, most significant first, into a growing byte array.150 lines
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.CompilerServices;

// Writes bits, most significant first, into a growing byte array.
public sealed class BitWriter
{
    private readonly List<byte> bytes = new List<byte>();
    private int used;                                      // bits used in the last byte; 0 means the next bit starts a new byte
    public long Bits { get; private set; }

    public void Write(ulong value, int count)             // the low `count` bits of value
    {
        for (int i = count - 1; i >= 0; i--)
        {
            if (used == 0) bytes.Add(0);
            if (((value >> i) & 1) == 1) bytes[bytes.Count - 1] |= (byte)(0x80 >> used);
            used = (used + 1) % 8;
            Bits++;
        }
    }

    public byte[] ToArray() => bytes.ToArray();
}

public sealed class BitReader
{
    private readonly byte[] data;
    private long position;

    public BitReader(byte[] data) { this.data = data; }

    public ulong Read(int count)
    {
        ulong value = 0;
        for (int i = 0; i < count; i++)
        {
            int bit = (data[position >> 3] >> (7 - (int)(position & 7))) & 1;
            value = (value << 1) | (uint)bit;
            position++;
        }
        return value;
    }
}

// A chunk of one series in the style of Facebook's Gorilla: timestamps as the delta of deltas, values as the XOR with the last value.
public sealed class Chunk
{
    private readonly BitWriter bits = new BitWriter();
    private int count;
    private long lastTime, lastDelta;
    private ulong lastValue;
    private int leading = -1, trailing;                    // the window of meaningful bits of the last XOR; -1 until there is one

    public int Count => count;
    public long Bits => bits.Bits;
    public byte[] Bytes => bits.ToArray();

    public void Append(long time, double value)
    {
        ulong raw = BitConverter.DoubleToUInt64Bits(value);
        if (count == 0)
        {
            bits.Write((ulong)time, 64);                   // the first sample is stored whole
            bits.Write(raw, 64);
        }
        else
        {
            WriteTime(time);
            WriteValue(raw);
        }
        lastTime = time;
        lastValue = raw;
        count++;
    }

    private void WriteTime(long time)
    {
        long delta = time - lastTime;
        long dod = delta - lastDelta;                      // zero for a perfectly regular series
        lastDelta = delta;
        if (dod == 0) bits.Write(0, 1);
        else if (dod >= -63 && dod <= 64) { bits.Write(0b10, 2); bits.Write((ulong)(dod + 63), 7); }
        else if (dod >= -255 && dod <= 256) { bits.Write(0b110, 3); bits.Write((ulong)(dod + 255), 9); }
        else if (dod >= -2047 && dod <= 2048) { bits.Write(0b1110, 4); bits.Write((ulong)(dod + 2047), 12); }
        else { bits.Write(0b1111, 4); bits.Write((ulong)(uint)checked((int)dod), 32); }
    }

    private void WriteValue(ulong raw)
    {
        ulong xor = raw ^ lastValue;
        if (xor == 0) { bits.Write(0, 1); return; }        // the same value again costs one bit
        bits.Write(1, 1);
        int lead = Math.Min(BitOperations.LeadingZeroCount(xor), 31);
        int trail = BitOperations.TrailingZeroCount(xor);
        if (leading >= 0 && lead >= leading && trail >= trailing)
        {
            bits.Write(0, 1);                              // the changed bits fall inside the previous window: reuse it
            bits.Write(xor >> trailing, 64 - leading - trailing);
        }
        else
        {
            bits.Write(1, 1);                              // a new window: 5 bits of leading zeros, 6 of length, then the bits
            int length = 64 - lead - trail;
            bits.Write((ulong)lead, 5);
            bits.Write((ulong)(length & 63), 6);           // a length of 64 is stored as 0
            bits.Write(xor >> trail, length);
            leading = lead;
            trailing = trail;
        }
    }

    private static double AsDouble(ulong bits) => Unsafe.As<ulong, double>(ref bits);          // reinterpret the 64 bits as a double

    public static List<(long Time, double Value)> Decode(byte[] data, int count)
    {
        var reader = new BitReader(data);
        var points = new List<(long, double)>(count);
        long time = (long)reader.Read(64);
        ulong raw = reader.Read(64);
        points.Add((time, AsDouble(raw)));
        long delta = 0;
        int leading = 0, trailing = 0;
        for (int i = 1; i < count; i++)
        {
            long dod;
            if (reader.Read(1) == 0) dod = 0;
            else if (reader.Read(1) == 0) dod = (long)reader.Read(7) - 63;
            else if (reader.Read(1) == 0) dod = (long)reader.Read(9) - 255;
            else if (reader.Read(1) == 0) dod = (long)reader.Read(12) - 2047;
            else dod = (int)(uint)reader.Read(32);
            delta += dod;
            time += delta;
            if (reader.Read(1) == 1)
            {
                if (reader.Read(1) == 1)
                {
                    leading = (int)reader.Read(5);
                    int length = (int)reader.Read(6);
                    if (length == 0) length = 64;
                    trailing = 64 - leading - length;
                }
                raw ^= reader.Read(64 - leading - trailing) << trailing;
            }
            points.Add((time, AsDouble(raw)));
        }
        return points;
    }
}

The test compresses seven kinds of series, 1,000 samples each at a ten-second interval, decodes every one and checks that every timestamp and value returns bit for bit. It also round-trips awkward floats (NaN, negative zero, infinity, the extremes) and timestamps that use all four encodings.

C#83 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

const int Samples = 1_000;                                      // 10,000 seconds at a 10-second interval
double Gauss(Random random) => Math.Sqrt(-2 * Math.Log(1 - random.NextDouble())) * Math.Cos(2 * Math.PI * random.NextDouble());

double[] Constant() => Enumerable.Repeat(1.0, Samples).ToArray();                              // up: always 1

double[] IntegerGauge()                                         // open connections: a random walk in whole numbers
{
    var random = new Random(1);
    var values = new double[Samples];
    double x = 200;
    for (int i = 0; i < Samples; i++) { x = Math.Max(0, x + random.Next(-3, 4)); values[i] = x; }
    return values;
}

double[] Counter()                                              // requests_total: about 500 more every interval
{
    var random = new Random(2);
    var values = new double[Samples];
    double total = 1_000_000;
    for (int i = 0; i < Samples; i++) { total += Math.Round(500 + 40 * Gauss(random)); values[i] = total; }
    return values;
}

double[] CpuPercent()                                           // a float with two decimals, wandering around 40
{
    var random = new Random(3);
    var values = new double[Samples];
    double x = 40;
    for (int i = 0; i < Samples; i++) { x = Math.Clamp(x + Gauss(random), 0, 100); values[i] = Math.Round(x, 2); }
    return values;
}

double[] CpuHundredths() => CpuPercent().Select(x => Math.Round(x * 100)).ToArray();           // the same readings as whole numbers: 43.27 becomes 4327
double[] LatencyMillis() { var random = new Random(4); return Enumerable.Range(0, Samples).Select(_ => 80 * Math.Exp(0.7 * Gauss(random))).ToArray(); }

long[] Regular() => Enumerable.Range(0, Samples).Select(i => 1_700_000_000L + i * 10L).ToArray();
long[] Jittered() { var random = new Random(5); return Enumerable.Range(0, Samples).Select(i => 1_700_000_000L + i * 10L + random.Next(-1, 2)).ToArray(); }

// Compress, decode, check that every timestamp and value came back bit for bit, and return the bits per sample.
double BitsPerSample(long[] times, double[] values)
{
    var chunk = new Chunk();
    for (int i = 0; i < times.Length; i++) chunk.Append(times[i], values[i]);
    var back = Chunk.Decode(chunk.Bytes, chunk.Count);
    Debug.Assert(back.Count == times.Length);
    for (int i = 0; i < times.Length; i++)
        Debug.Assert(back[i].Time == times[i] && BitConverter.DoubleToInt64Bits(back[i].Value) == BitConverter.DoubleToInt64Bits(values[i]));
    return (double)chunk.Bits / times.Length;
}
bool Near(double actual, double expected) => Math.Abs(actual - expected) < 0.01;

var regular = Regular();
double constantBits = BitsPerSample(regular, Constant());
double gaugeBits = BitsPerSample(regular, IntegerGauge());
double counterBits = BitsPerSample(regular, Counter());
double cpuFloatBits = BitsPerSample(regular, CpuPercent());
double cpuIntegerBits = BitsPerSample(regular, CpuHundredths());
double latencyBits = BitsPerSample(regular, LatencyMillis());
Debug.Assert(Near(constantBits, 2.13));                         // one bit for the timestamp, one for the value, plus the 16-byte header
Debug.Assert(Near(gaugeBits, 10.01));
Debug.Assert(Near(counterBits, 23.66));
Debug.Assert(Near(cpuFloatBits, 57.67));                        // a float with a noisy mantissa is barely compressed
Debug.Assert(Near(cpuIntegerBits, 16.04));                      // the same readings as integers cost 3.6 times fewer bits
Debug.Assert(Near(latencyBits, 59.13));
Debug.Assert(Near(BitsPerSample(Jittered(), Constant()), 8.55));    // scrape times off by a second break the one-bit timestamp
Debug.Assert(Near(BitsPerSample(Jittered(), Counter()), 30.07));

// A fleet that is 30% constant series, 30% integer gauges, 30% counters and 10% noisy floats averages about two bytes a sample.
double mix = 0.3 * constantBits + 0.3 * gaugeBits + 0.3 * counterBits + 0.1 * cpuFloatBits;
Debug.Assert(Near(mix, 16.51));

// Awkward floats come back bit for bit, and timestamps that need the 7, 9, 12 and 32-bit encodings round-trip.
long[] deltas = { 0, 10, 10, 11, 100, 400, 3_000, 100_000, 5 };
long[] oddTimes = new long[deltas.Length];
oddTimes[0] = 1_700_000_000;
for (int i = 1; i < oddTimes.Length; i++) oddTimes[i] = oddTimes[i - 1] + deltas[i];
double[] awkward = { 0.0, -0.0, double.NaN, double.PositiveInfinity, double.MaxValue, double.Epsilon, -1.5, 1.5, 0.0 };
BitsPerSample(oddTimes, awkward);
Series (1,000 samples, 10 s apart)Bits per sampleAgainst 128 raw
A constant (up, always 1)2.160 times smaller
An integer gauge (open connections)10.013 times
A counter (about 500 more each interval)23.75.4 times
CPU percent as a float with two decimals57.72.2 times
The same CPU readings as whole hundredths16.08 times
Latency in ms as a raw float59.12.2 times
The constant, with scrape times off by up to a second8.615 times
The counter, with scrape times off by up to a second30.14.3 times

What the numbers say:

  • Regular timestamps are nearly free, one bit each. A scrape that is a second early or late forces most samples into the 9-bit form (a 2-bit prefix and 7 bits) instead of one bit, which is why collectors align their timestamps to the schedule.
  • A value costs the bits that change. A constant costs one bit. A counter's increments differ a little each time, so it needs about 20 more. A float whose mantissa is full of noise changes almost every bit and compresses barely at all.
  • Report integers when you can. A float such as 43.27 has a full 52-bit mantissa, but 4327 stored as a double has most of its mantissa bits zero, and the same CPU readings cost 16 bits instead of 58. Counters in bytes, milliseconds or hundredths are cheaper than the same quantity as a fraction.
  • Plan with your own mix. The Gorilla paper reports an average of 1.37 bytes per sample on Facebook's production data, down from 16. The mix above averages about 2 bytes, and the metrics system case study uses that figure. A fleet of noisy floats would be four times worse, which is why the estimate must come from a measurement.

LLD

Finding series: the label index

A query names a metric and some label conditions, requests{service="checkout", region="eu-west", env="prod"}, and needs the ids of the matching series. Scanning every series is hopeless at ten million. The answer is the structure from the search lesson: an inverted index. For each label=value pair keep a sorted list of the ids of the series that carry it, a postings list. A query intersects the lists of its matchers. Starting from the shortest list and looking each id up in the others by binary search makes the cost follow the most selective matcher and not the number of series.

C# · An inverted index over series: for every label=value pair, the sorted ids of the series…72 lines
using System;
using System.Collections.Generic;
using System.Linq;

// An inverted index over series: for every label=value pair, the sorted ids of the series that carry it.
public sealed class SeriesIndex
{
    private readonly List<Dictionary<string, string>> series = new List<Dictionary<string, string>>();
    private readonly Dictionary<string, List<int>> postings = new Dictionary<string, List<int>>();
    public long Probes;                                           // work counter: comparisons made by the last query

    public int Count => series.Count;
    public int PostingLists => postings.Count;
    public long PostingEntries => postings.Values.Sum(p => (long)p.Count);

    public void Add(Dictionary<string, string> labels)
    {
        int id = series.Count;
        series.Add(labels);
        foreach (var pair in labels)
        {
            string key = pair.Key + "=" + pair.Value;
            if (!postings.TryGetValue(key, out var list)) postings[key] = list = new List<int>();
            list.Add(id);                                         // ids grow, so every list stays sorted
        }
    }

    // Series that match every label=value pair: start from the shortest list and look each id up in the others by binary search.
    public List<int> Select(params (string Label, string Value)[] matchers)
    {
        Probes = 0;
        var lists = matchers.Select(m => postings.TryGetValue(m.Label + "=" + m.Value, out var l) ? l : new List<int>()).OrderBy(l => l.Count).ToList();
        var result = lists[0];
        foreach (var other in lists.Skip(1))
        {
            var next = new List<int>();
            foreach (int id in result)
            {
                int low = 0, high = other.Count - 1;
                bool found = false;
                while (low <= high)
                {
                    Probes++;
                    int mid = (low + high) / 2;
                    if (other[mid] == id) { found = true; break; }
                    if (other[mid] < id) low = mid + 1; else high = mid - 1;
                }
                if (found) next.Add(id);
            }
            result = next;
        }
        return result;
    }

    // The alternative: look at every series.
    public List<int> Scan(params (string Label, string Value)[] matchers)
    {
        Probes = 0;
        var result = new List<int>();
        for (int id = 0; id < series.Count; id++)
        {
            bool all = true;
            foreach (var m in matchers)
            {
                Probes++;
                if (!series[id].TryGetValue(m.Label, out var v) || v != m.Value) { all = false; break; }
            }
            if (all) result.Add(id);
        }
        return result;
    }
}

The test builds one index of 100,000 series and one of 400,000, with 500 series per service, six regions, two environments and a different instance label on every series, and runs the same query on both.

C#35 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

SeriesIndex BuildIndex(int services)
{
    var random = new Random(4);
    string[] regions = { "us-east", "us-west", "eu-west", "eu-central", "ap-south", "ap-east" };
    var index = new SeriesIndex();
    for (int i = 0; i < services * 500; i++)                  // every service has 500 series
        index.Add(new Dictionary<string, string>
        {
            ["__name__"] = "http_requests_total",
            ["service"] = "svc" + (i % services),
            ["region"] = regions[random.Next(regions.Length)],
            ["env"] = random.NextDouble() < 0.7 ? "prod" : "staging",
            ["instance"] = "host-" + i,                       // a different value for every series
        });
    return index;
}
var smallIndex = BuildIndex(200);                             // 100,000 series
var largeIndex = BuildIndex(800);                             // 400,000 series
var query = new[] { ("service", "svc7"), ("region", "eu-west"), ("env", "prod") };

var smallViaIndex = smallIndex.Select(query); long smallIndexProbes = smallIndex.Probes;
var smallViaScan = smallIndex.Scan(query); long smallScanProbes = smallIndex.Probes;
var largeViaIndex = largeIndex.Select(query); long largeIndexProbes = largeIndex.Probes;
var largeViaScan = largeIndex.Scan(query); long largeScanProbes = largeIndex.Probes;

Debug.Assert(smallViaIndex.SequenceEqual(smallViaScan) && largeViaIndex.SequenceEqual(largeViaScan));   // same answers
Debug.Assert(smallViaIndex.Count == 43 && largeViaIndex.Count == 57);
Debug.Assert(smallIndexProbes == 7_918 && smallScanProbes == 100_563);                    // 13 times less work
Debug.Assert(largeIndexProbes == 9_321 && largeScanProbes == 400_579);                    // 43 times less: four times the series, 18% more work
Debug.Assert(smallIndex.PostingLists == 100_209 && smallIndex.PostingEntries == 500_000);    // 100,000 lists belong to the instance label

With four times the series, the scan did four times the work and the index did 18% more (the binary searches got a little deeper). That is the property to remember: lookup cost follows selectivity, not size. The other half of the output is the cost: the index holds one entry per series per label (500,000), and the unique instance label alone created 100,000 posting lists of length one. A label whose value is different on every series gets no benefit from the index and costs a list per series. That is the mechanism behind the cardinality warnings in the observability lesson. Three details complete the picture:

  • Other matchers. env!="prod" is "all series minus the postings of env=prod", so the index needs an all-series list. A regular expression (region=~"eu-.*") is checked against the distinct values of the label and the postings of the matches are merged, so its cost follows the number of values, and a regex over instance is expensive.
  • One index per block. Each block indexes only its own series. When pods are replaced the old series fade out with their blocks, so churn costs index space only for the blocks it touched.
  • Memory is the limit. Ten million series with six labels each is 60 million entries, hundreds of megabytes of ids and a dictionary of label strings. Multiplying the series by 100 multiplies that by 100.

HLD

Rollups and retention

Keeping every ten-second sample for years is neither affordable nor useful: a chart over 30 days needs a few hundred points, not 260,000. A rollup (downsampling) replaces the samples in each window (five minutes, one hour) with aggregates, and a query over a long range reads the coarse series. The rule that matters is to store aggregates that can be re-aggregated:

  • Sum and count, not the average. Two stored averages cannot be combined without their counts. With the sum and the count of each window, any coarser average is exact.
  • Min and max. They keep the peaks that an average erases.
  • Counters as increases, with resets handled. A counter that restarts drops back to zero, so "last minus first" is wrong. The increase adds each step, and counts the new value after a reset as growth from zero.
  • Histograms as bucket counts, which add exactly. A percentile is never stored and never averaged.
C# · A five-minute window of CPU samples every 10 seconds: a steady 20%, with a 30-second…29 lines
using System;
using System.Diagnostics;
using System.Linq;

// A five-minute window of CPU samples every 10 seconds: a steady 20%, with a 30-second spike to 100%.
double[] cpuWindow = Enumerable.Repeat(20.0, 30).ToArray();
cpuWindow[10] = cpuWindow[11] = cpuWindow[12] = 100;
Debug.Assert(cpuWindow.Average() == 28 && cpuWindow.Max() == 100);                 // the average hides the spike, the maximum keeps it

// Rollups kept as (count, sum, min, max) combine exactly. Stored averages do not.
(int Count, double Sum, double Min, double Max) Rollup(double[] samples) => (samples.Length, samples.Sum(), samples.Min(), samples.Max());
(int Count, double Sum, double Min, double Max) Merge((int Count, double Sum, double Min, double Max) a, (int Count, double Sum, double Min, double Max) b) =>
    (a.Count + b.Count, a.Sum + b.Sum, Math.Min(a.Min, b.Min), Math.Max(a.Max, b.Max));
double[] firstWindow = { 10, 20, 30 };
double[] secondWindow = { 40, 50, 60, 70, 80, 90 };
var merged = Merge(Rollup(firstWindow), Rollup(secondWindow));
Debug.Assert(merged.Sum / merged.Count == 50);                                       // the exact average of all nine samples
Debug.Assert((firstWindow.Average() + secondWindow.Average()) / 2 == 42.5);          // an average of averages is wrong

// A counter that restarts: the increase has to treat a drop as a reset.
double Increase(double[] counter)
{
    double total = 0;
    for (int i = 1; i < counter.Length; i++) total += counter[i] >= counter[i - 1] ? counter[i] - counter[i - 1] : counter[i];
    return total;
}
double[] requestsTotal = { 100, 150, 200, 20, 70 };                                  // the process restarted between 200 and 20
Debug.Assert(Increase(requestsTotal) == 170);
Debug.Assert(requestsTotal[^1] - requestsTotal[0] == -30);                           // last minus first is negative

A 30-second spike to 100% disappears in a five-minute average of 28%, which is why rollups keep the maximum, and the average of two averages, 42.5, is wrong where the exact answer from sums and counts is 50. Rollups cost space too: with four aggregates every five minutes the series keeps 4/30, about 13%, of its raw samples, so a rollup tier is a trade between detail and age and not a free archive. Keep raw data as long as alerting and debugging need it (days to weeks), and rollups for trends (months to years).

HLD

Late, duplicate and out-of-order samples

A chunk can only be appended to, and the delta-of-delta and XOR states assume the next sample follows the last. Real feeds break that: agents retry after a timeout (duplicates), buffer through an outage and send old data (late), and clocks disagree (out of order, or timestamps far in the future).

  • Retries must be harmless. A sample for the same series and time with the same value is accepted silently, and a different value for the same time is rejected as a conflict. Then at-least-once delivery, the only kind a network offers, cannot corrupt the store.
  • Out of order. Reject it (cheap, and what many systems do by default), or buffer a small window in a separate structure and merge it when blocks are cut. Whichever you choose, count the rejections.
  • Too old. Once a block has been cut, older samples belong to a sealed block. Reject them, or accept them into a side buffer that is merged later.
  • The future. Reject timestamps beyond a small skew, or one bad clock poisons the head.
  • Staleness. When a target disappears its series should end, or a chart keeps drawing the last value. Systems write a marker, or treat a series as stale after a lookback.

The head in the metrics system case study implements these rules and tests that a retried batch changes nothing.

HLD

Failure modes and edge cases

Failure or edgeWhat goes wrongDefence
Cardinality explosionIndex and head memory grow with series, and ingestion slows or the process runs out of memoryLimits on series per tenant and per metric, a top-series report, dropping or aggregating the label
Counter resetsIncrease and rate are wrong or negative across a restartDetect a drop and treat it as a reset, in queries and in rollups
Averaging rollupsAverages of averages, spikes erasedStore sum, count, min and max; combine those
Slow restartReplaying a long write-ahead log keeps the node downTruncate the log after each cut, checkpoint, keep the head window short
Jittered timestampsThe compressor loses its one-bit timestamps and storage grows several timesSnap timestamps to the schedule
Corrupt chunkDecoding is sequential, so one bad bit ruins the rest of the chunkChecksums per chunk, replicas, and short chunks to bound the damage
Compaction lagMany small blocks make every query open more filesAlert on block count, throttle ingestion before compaction falls behind
Wrong toolHigh-cardinality events (a row per request with user and URL) forced into seriesUse a columnar event store for those, and series only for aggregates

Senior depth

What senior interviews ask about time-series storage

Interviewer follow-upL5Why not store metrics in an ordinary relational table?How to answer

A row per sample costs dozens of bytes for an eight-byte value (header, ids, timestamp and index entries), the indexes are updated in place under a write rate of millions a second, and retention needs expensive deletes. A time-series store compresses each series to a few bytes a sample, appends to a log and an in-memory chunk, flushes immutable blocks, and drops whole blocks for retention. A relational table is fine for small volumes, and TimescaleDB-style extensions bring time partitioning and compression to it.

Interviewer follow-upL5How do you compress a time series?How to answer

Timestamps as the delta of deltas, which is zero for a regular series and so costs one bit, and values as the XOR with the previous value, which is zero for a repeated value and otherwise leaves a short window of changed bits to store. In the test a constant series cost 2.1 bits a sample, a counter 24, and a noisy float 58, against 128 raw. Facebook reported 1.37 bytes a sample on average. Jittered timestamps and noisy floats are what ruin it.

Interviewer follow-upL6What is cardinality, and why does it hurt?How to answer

It is the number of distinct series, the product of the values of each label that occurs. Every series needs an index entry per label, an open chunk in memory and its labels stored, so memory and index size grow with series and not with samples. In the test 100,000 series with a unique instance label created 100,000 posting lists of length one, and a query's cost follows the shortest list so the unique label never helps. Bound label values, drop per-instance labels before long-term storage and put identifiers in logs or traces.

Interviewer follow-upL6A query over the last 30 days is slow. What do you change?How to answer

Read a coarser series: roll up to five-minute and one-hour aggregates (sum, count, min, max) and pick the resolution from the query's range and step, so a 30-day chart reads about 720 points a series and not 260,000. Pre-compute expensive aggregations across many series as recording rules, split the query by time and cache the parts, prune blocks by time range, and put limits on series and samples per query so one dashboard cannot take down the store.

Interviewer follow-upL7How would you handle late and out-of-order data?How to answer

Decide what the product needs. For monitoring, reject out-of-order samples and count them, because freshness matters more than completeness. Where backfill matters (IoT devices that buffer offline), accept samples within a bounded window into a separate structure, merge it when blocks are cut or compacted, and make every append idempotent so retries are safe. Late data into sealed blocks needs a rewrite or an overlay block that compaction merges, and rollups of that period must be recomputed. State the cost of each choice.

HLD

Putting it into an answer

Name the workload first: append-only samples, recent range reads, deletes by age, millions of series. Then give the layout (write-ahead log, an in-memory head with compressed chunks, immutable blocks, compaction, retention by dropping blocks), the two key structures (delta-of-delta and XOR compression for samples, postings lists for series), rollups of sums, counts, minima and maxima for old data, and the first limit you will hit: cardinality.

Summary

Time-series data is appended in time order, read as recent windows and aggregates, deleted by age, and made of smooth series. A TSDB keeps a write-ahead log and an in-memory head of compressed chunks, cuts immutable time-bounded blocks, compacts them and retires them whole. Samples are compressed as delta-of-delta timestamps and XORed values: in the test a constant series cost 2.1 bits a sample, an integer gauge 10, a counter 24 and a noisy float 58 (against 128 raw), a second of timestamp jitter made a constant series four times larger, integers beat floats by 3.6 times, and a typical mix averages about two bytes. Series are found through postings lists per label pair, whose intersection cost follows the shortest list (13 and 43 times less work than a scan at 100,000 and 400,000 series) while the index size follows cardinality. Rollups store sums, counts, minima and maxima, counters as increases with resets handled, and histograms as bucket counts, never averages of averages. Duplicates must be harmless, out-of-order and late data need an explicit policy, and cardinality is the limit to guard.

Check yourself

Try answering out loud before you reveal each answer.

QuestionA series has samples every 10 seconds and a constant value. About how many bits does each sample cost with delta-of-delta and XOR encoding, and why?Reveal answer

About two. The delta of deltas is zero, which costs one bit, and the XOR with the previous value is zero, which costs one more. Only the first sample of a chunk is stored whole (128 bits). In the test the cost was 2.1 bits a sample over 1,000 samples, 60 times less than raw.

QuestionScrape timestamps drift by up to a second either way. What happens to storage, and what do you do?Reveal answer

The delta of deltas stops being zero, so most samples use the 9-bit form (a 2-bit prefix and 7 bits) and a constant series costs 8.6 bits a sample instead of 2.1, and a counter 30 instead of 24. Align the timestamps to the schedule when they are within a small tolerance, or store the scheduled time.

QuestionWhy does an index lookup for three label matchers cost about the same on 100,000 and on 400,000 series, while a scan costs four times more?Reveal answer

The lookup starts from the shortest postings list and checks each of its ids in the others by binary search, so the work follows the size of that list (500 ids here) and the logarithm of the others, not the number of series. A scan reads every series. In the test the index did 18% more work for four times the series and the scan did four times more.

QuestionWhy store sum and count in a rollup instead of the average?Reveal answer

Averages can be combined only when their counts are known. The average of 10, 20 and 30 and the average of six larger values, averaged together, gave 42.5, where the true average of all nine was 50. With sums and counts the merge is exact, and the minimum and maximum keep the peaks that an average hides.

QuestionA counter reads 100, 150, 200, 20, 70. What is its increase, and what goes wrong with last minus first?Reveal answer

170: 50 and 50, then the drop to 20 is a restart so it counts as 20 of growth, then 50 more. Last minus first is 70 − 100 = −30, a negative number of requests, because it ignores the reset.

Sources and further reading

Lesson 3 of 11

Nice. Lock it in, then keep going.

Up next · Lesson 4Transactions and isolation levelsWhat ACID really promises, the anomalies that appear when transactions overlap, how locking and MVCC implement each isolation level, and the patterns (atomic updates, locks, constraints, retries) that keep concurrent code correct.

Send a message

It goes straight to my inbox. I usually reply within a few days.