Prompt
How do I build a retention and rollup pipeline for time-series data?
Latest observation
A good retention + rollup pipeline usually has two jobs:
- Retention: delete or archive old raw data after a policy threshold.
- Rollup: aggregate raw data into coarser time buckets so long-term queries stay cheap.
Here’s a practical way to design it.
1) Start with the data model
For each time-series row, you typically want:
series_id/ tags / dimensionststimestampvalueor metric fields- optional metadata like tenant, source, quality flags
Example schema:
raw_metrics(
tenant_id,
series_id,
ts,
value,
tags...
)
Rollups often use the same logical shape, but with a bucketed timestamp and aggregate fields:
rollup_1m(
tenant_id,
series_id,
bucket_start,
count,
sum,
min,
max,
avg,
...
)
2) Define your retention tiers
A common pattern is:
- Raw data: keep 7–30 days
- 1-minute rollups: keep 30–180 days
- 1-hour rollups: keep 1–3 years
- 1-day rollups: keep indefinitely, if needed
Choose tiers based on:
- query patterns
- storage cost
- compliance requirements
- how much precision users need over time
A useful rule:
older data should be cheaper and less granular.
3) Use time partitioning
Partition data by time so you can:
- roll up one partition at a time
- delete old partitions quickly
- avoid scanning the whole table
Examples:
- PostgreSQL: monthly/daily partitions
- ClickHouse: partition by day/month
- BigQuery: partitioned tables
- S3/lakehouse: directory layout by date
Good partitioning makes retention a metadata operation rather than a huge delete.
4) Build rollups as incremental aggregates
For each rollup interval, compute aggregates from the next-finer tier.
Example:
- raw → 1m
- 1m → 1h
- 1h → 1d
Do not recompute everything if you can avoid it. Instead, process only new time ranges.
Typical aggregates
Depending on metric type, store:
countsumminmaxavgderived fromsum / countp50/p95/p99if you have sketches/histogramslast,firstif needed
For averages, store sum and count, not just avg.
For percentiles, store a mergeable structure like:
- HDR histogram
- t-digest
- DDSketch
5) Process in windows
Use a scheduled job or streaming job that processes closed time windows.
Example:
- every 5 minutes, roll up the previous 10-minute or 1-hour window
- always leave a delay buffer to avoid late-arriving events
A common pattern:
- Watermark delay: 5–15 minutes for late data
- Roll up only data older than watermark
- Reprocess recent windows to correct for late arrivals if needed
6) Choose batch vs streaming
Batch pipeline
Best if:
- data volume is moderate
- freshness can be minutes/hours
- infrastructure should stay simple
Implementation:
- cron/job scheduler
- query new raw rows by time range
- aggregate into rollup table
- mark processed ranges
Streaming pipeline
Best if:
- high ingestion rate
- low-latency rollups needed
- you already use Kafka/Flink/Spark Streaming
Implementation:
- consume events
- maintain sliding/tumbling windows
- write rollups continuously
- still do periodic backfills/reconciliation
Many systems do both:
- streaming for freshness
- batch for correction and backfill
7) Make rollups idempotent
Your job should be safe to run twice.
Ways to do that:
- write rollups into a staging table and merge
- use upserts keyed by
(tenant_id, series_id, bucket_start) - delete/rebuild the affected buckets before inserting
- use transactional replace per partition
This matters because retries and late data happen.
8) Handle late and out-of-order data
You have three main options:
-
Ignore after watermark
Simpler, but may lose some late data. -
Allow reprocessing recent buckets
Recompute the last N buckets every run. Common and practical. -
Use mutable rollup state Update aggregate state as late events arrive. More complex.
For most systems, the best tradeoff is:
- finalise a bucket only after a delay
- keep a correction window, e.g. last 24 hours
- recompute those buckets periodically
9) Retention strategy: delete or archive
You need a policy for old raw data.
Option A: hard delete
Delete partitions older than retention.
- simple
- cheap
- irreversible
Option B: archive then delete
Move to cheaper storage before deletion.
- good for compliance/replay
- more operational work
Option C: tiered storage
Move raw to cold storage and keep rollups in hot DB.
- often best if you need auditability
If you partition by time, retention becomes:
- drop old partitions
- or detach/move partitions
10) Recommended pipeline architecture
A simple, robust architecture:
Ingestion
- write raw events to a raw table or log
- partition by time
Rollup job
- runs every few minutes
- reads raw data for closed windows
- aggregates into 1m rollup
- optionally from 1m to 1h, 1h to 1d
Retention job
- runs daily
- deletes or archives partitions older than threshold
- ensures rollup tiers remain available
Query layer
- chooses the right table based on time range
- recent queries: raw
- medium-term: 1m/1h rollup
- long-term: 1d rollup
11) Query routing rule
A common strategy:
- if range <= 24h: query raw
- if range <= 30d: query 1m rollups
- if range <= 1y: query 1h rollups
- else: query 1d rollups
You can also let the app choose based on desired resolution.
12) Example SQL rollup
Example for 1-minute buckets:
INSERT INTO rollup_1m (tenant_id, series_id, bucket_start, count, sum, min, max)
SELECT
tenant_id,
series_id,
date_trunc('minute', ts) AS bucket_start,
COUNT(*) AS count,
SUM(value) AS sum,
MIN(value) AS min,
MAX(value) AS max
FROM raw_metrics
WHERE ts >= :start_ts AND ts < :end_ts
GROUP BY tenant_id, series_id, date_trunc('minute', ts);
To make it idempotent, use a merge/upsert or replace the target buckets.
13) Operational concerns
Backfill
When you add a new rollup tier, you’ll need to backfill historical data.
Schema evolution
If metric schema changes, version your rollup tables or transformation logic.
Monitoring
Track:
- ingestion lag
- rollup lag
- rows processed
- error rate
- late-arriving event rate
- partition count
- storage growth
Correctness checks
Periodically compare:
- raw aggregates vs rollup aggregates
- spot-check sampled buckets
- verify counts and sums
14) A simple implementation plan
If you want the shortest path to production:
- Partition raw data by day.
- Add a
rollup_1mtable. - Run a scheduled job every 5 minutes:
- process data older than a watermark
- aggregate into 1m buckets
- upsert results
- Keep raw data for 7 days.
- Add a daily retention job to drop old raw partitions.
- Add
rollup_1hfromrollup_1m. - Route queries to the smallest sufficient granularity.
15) If you want a concrete stack
Here are common combos:
- PostgreSQL: partitioned tables + cron/worker + upsert
- ClickHouse: materialized views + TTL + MergeTree rollups
- Kafka + Flink: streaming rollups + sinks to OLAP store
- S3 + Spark/dbt: batch rollups in a lakehouse
- TimescaleDB: continuous aggregates + retention policies
If you want, I can also give you:
- a reference architecture diagram,
- a PostgreSQL/TimescaleDB implementation, or
- a Kafka + Flink streaming design.