How to Implement Time-Series Downsampling
Downsample time-series data: bucket by interval, roll up aggregates incrementally, and keep raw data for a shorter window than rollups.
On this page
Introduction
Time-series data grows fast: a metric every second across many hosts is millions of rows a day. Querying years of raw points for a chart is wasteful, because the chart shows a few hundred pixels. Downsampling rolls raw points into coarser buckets over time so long-range queries read a small, precomputed set while recent queries can still use raw detail.
This tutorial implements downsampling: choose a bucket and the aggregates to keep, compute them from raw rows, store them incrementally with an upsert keyed on the bucket, and retire raw data faster than rollups. The examples use PostgreSQL, whose date_trunc makes bucketing simple and whose on-conflict makes bucketed upserts idempotent.
Choose the bucket and the rollup columns
Pick a bucket interval from the queries you serve. A dashboard showing a week can use hour buckets; a year view can use day buckets. Keep several resolutions if the same data is viewed at different zoom levels, each as its own table or with a resolution column. The bucket must divide the query ranges evenly, or the last partial bucket needs a label such as ‘in progress’.
Store aggregates that combine correctly across buckets. Count, sum, min, and max combine by summing or taking the extreme. Average does not: you must store the sum and the count so a coarser query computes sum over count. Keep a count column even when it looks redundant, because it is what makes averages and weighted combinations correct at any zoom.
CREATE TABLE metrics_1h (
bucket timestamptz NOT NULL,
host text NOT NULL,
metric text NOT NULL,
sum_value double precision NOT NULL,
count_value bigint NOT NULL,
min_value double precision NOT NULL,
max_value double precision NOT NULL,
PRIMARY KEY (host, metric, bucket)
);
Bucket the raw rows in one pass
Bucket with date_trunc to the chosen interval, or with integer division of the epoch for a custom interval that date_trunc does not offer, such as five minutes. Group by the bucket and the series key, and aggregate in one pass over the raw rows in the time range. This produces one row per series per bucket, which is what the rollup table stores.
Filter the raw scan to the range you are rolling up, and index the raw table on the time column so the scan reads only that range. For an append-only time series, a BRIN index on the time column is compact and effective because the values are naturally clustered in insertion order, which is exactly when BRIN beats a b-tree.
SELECT date_trunc('hour', recorded_at) AS bucket,
host, metric,
sum(value) AS sum_value,
count(*) AS count_value,
min(value) AS min_value,
max(value) AS max_value
FROM raw_metrics
WHERE recorded_at >= $1 AND recorded_at < $2
GROUP BY bucket, host, metric;
Upsert the rollup so buckets do not duplicate
A raw row can arrive after its bucket was already rolled up. If the rollup appends, the same bucket gets duplicate rows and every query double-counts. Instead, upsert on the bucket key and replace the aggregates, recomputing the bucket from all its raw rows. On conflict do update so the bucket reflects the latest input, keeping one row per series per bucket.
This makes the rollup job idempotent. Running it twice for the same range produces the same rows. A retry after a crash converges rather than duplicating. Combine the upsert with the bucket primary key so the database enforces one row per bucket, and the job cannot accidentally create two.
INSERT INTO metrics_1h (bucket, host, metric, sum_value, count_value, min_value, max_value)
SELECT date_trunc('hour', recorded_at), host, metric,
sum(value), count(*), min(value), max(value)
FROM raw_metrics
WHERE recorded_at >= $1 AND recorded_at < $2
GROUP BY 1, host, metric
ON CONFLICT (host, metric, bucket) DO UPDATE
SET sum_value = EXCLUDED.sum_value,
count_value = EXCLUDED.count_value,
min_value = EXCLUDED.min_value,
max_value = EXCLUDED.max_value;
Retain raw briefly and rollups long
Raw data is valuable for recent detail and expensive to keep forever. Retain raw for a short window, such as a few days, and rollups for the long term. A query for the last hour reads raw for detail; a query for last year reads the rollup. This keeps the raw table small and fast and pushes the long tail into a much smaller pre-aggregated table.
Roll up at multiple resolutions for different retention windows: raw for days, hourly for months, daily for years. Each level is computed from the level below it or from raw, and each has its own retention. Dropping the oldest level is cheap if the tables are partitioned by time, so the retention and partitioning decisions reinforce each other.
-- daily rollup computed from the hourly rollup combines correctly
SELECT date_trunc('day', bucket) AS day, host, metric,
sum(sum_value) AS sum_value,
sum(count_value) AS count_value,
min(min_value) AS min_value,
max(max_value) AS max_value
FROM metrics_1h
WHERE bucket >= $1 AND bucket < $2
GROUP BY 1, host, metric;
Test boundaries and late arrivals
Test that a raw row at the exact bucket boundary lands in the expected bucket, since the inclusive or exclusive choice of the range is a common off-by-one. Test that a late-arriving row updates its existing bucket rather than creating a second. Test that summing the hourly rollups for a day equals the daily rollup for that day, proving the aggregates combine. Test that the average computed as sum over count matches the raw average for a bucket.
psql -d app <<'SQL'
-- late arrival in an already-rolled bucket
INSERT INTO raw_metrics (recorded_at, host, metric, value) VALUES ('2026-03-01 00:30:00+00','h1','cpu', 10);
SELECT count_value FROM metrics_1h WHERE host='h1' AND bucket='2026-03-01 00:00:00+00'; -- updated, not duplicated
SELECT count(*) FROM metrics_1h WHERE host='h1' AND bucket='2026-03-01 00:00:00+00'; -- expect 1
SQL
Common pitfalls
Storing only an average so it cannot be combined, appending rollups without upserting so late rows duplicate a bucket, an off-by-one at the bucket boundary, a raw scan without a time index, and keeping raw data at full resolution forever are the recurring mistakes. Store sum and count, upsert on the bucket key, index the time column, define boundaries explicitly, and retain raw briefly.
Conclusion
Downsampling keeps long-range queries fast by reading a small precomputed table. Choose a bucket and store combinable aggregates (sum, count, min, max), bucket the raw rows in one pass over an indexed time range, upsert on the bucket key so late rows do not duplicate, and retain raw briefly while keeping rollups long. Self-check by asserting a late row updates its bucket and that hourly rollups sum to the daily rollup. Then history stays small and correct.
Sources: PostgreSQL: date_trunc and time functions, PostgreSQL: Aggregate functions, PostgreSQL: BRIN indexes for time-series.
FAQ
- Can averages be averaged?
- No. The average of averages is wrong when the buckets have different counts. Store the sum and the count per bucket and compute the average as sum divided by count at query time, so a coarser rollup combines correctly.
- How do I handle late-arriving data?
- Make the rollup an upsert keyed on the bucket so a late row updates its bucket. If a bucket may still receive data, either recompute it on write or accept eventual correction when the next rollup job runs. Do not append a second row for the same bucket.
Report a problem with this articleOpens a pre-filled issue on GitHub.