Prompt
How do I build a system that stores both raw and rolled-up metrics?
Latest observation
A good way to build this is to treat raw metrics and rolled-up metrics as two related layers in the same pipeline:
- Raw metrics: immutable, high-granularity events or time-series points
- Rolled-up metrics: pre-aggregated summaries over fixed windows like 1m, 5m, 1h, 1d
The key is to design for write once, query many.
1) Start with your access patterns
Before choosing technology, decide:
- How often do you ingest metrics?
- What is the expected cardinality of dimensions/tags?
- What queries do you need?
- recent live dashboards?
- long-range trend analysis?
- alerting?
- ad hoc analytics?
- How long must raw data be kept?
- How long must rollups be kept?
Typical pattern:
- Keep raw data for a short period, like 7–30 days
- Keep rollups for much longer, like 6–24 months
2) Use two storage tiers
Raw store
Store every metric point/event at full resolution.
Good options:
- Time-series database: TimescaleDB, InfluxDB, VictoriaMetrics
- Log/analytics store: ClickHouse, Apache Druid
- General-purpose DB if volume is modest: PostgreSQL + partitioning
Raw schema example:
metric_name
timestamp
value
dimensions/tags
source_id
Example row:
{
"metric_name": "cpu.utilization",
"timestamp": "2026-10-25T12:00:00Z",
"value": 67.4,
"host": "web-17",
"region": "us-east-1"
}
Rollup store
Store precomputed aggregates at predefined intervals.
Common rollups:
- min, max, avg, sum, count
- percentiles if needed
- rate per second
- error rate
- histogram buckets
Example rollup schema:
metric_name
window_start
window_size
dimensions/tags
count
sum
min
max
avg
Example rollup row:
{
"metric_name": "cpu.utilization",
"window_start": "2026-10-25T12:00:00Z",
"window_size": "5m",
"host": "web-17",
"region": "us-east-1",
"count": 300,
"sum": 19810.2,
"min": 42.1,
"max": 88.9,
"avg": 66.03
}
3) Build an ingestion pipeline that writes raw first
A common pattern:
- Metrics arrive from apps/agents
- Validate and normalize
- Write to raw storage
- Publish to a stream/queue for rollup processing
Recommended architecture:
- Ingest API
- Message bus: Kafka, Pulsar, Kinesis, Pub/Sub
- Raw writer
- Rollup processor
- Rollup writer
This decouples ingestion from aggregation and makes the system more reliable.
4) Compute rollups asynchronously
Do not calculate rollups in the request path unless traffic is very small.
Instead:
- Consume raw metric events from the stream
- Group by metric name + dimensions + time window
- Aggregate in batches
- Write rollup rows periodically
If you need near-real-time rollups:
- use streaming windows
- watermark late events
- allow slight delays, e.g. 30–120 seconds
5) Support multiple rollup levels
Usually you want more than one rollup granularity:
- 1-minute rollups for recent analysis
- 5-minute rollups for medium-range trends
- 1-hour rollups for long-term reporting
- 1-day rollups for very long retention
A common approach is hierarchical rollups:
- Raw → 1m
- 1m → 5m
- 5m → 1h
- 1h → 1d
This reduces compute cost, but be careful:
- Some aggregates can be derived safely from lower-level rollups
- Some cannot, especially percentiles unless you store sketches/histograms
For safe rollup types, store:
count,sum,min,max- histogram or sketch for percentile approximation
6) Decide how to handle late or duplicate data
You need clear rules:
Duplicates
Use an event id or dedup key:
(metric_name, timestamp, dimensions, source_id, sequence_number)
Late arrivals
Options:
- accept late data for a grace period
- recompute affected windows
- mark windows as mutable until they close
For example:
- windows are “open” for 2 minutes after end time
- after that, they are finalized
7) Partition data for scale
For raw metrics:
- partition by time
- optionally shard by metric name or tenant
For rollups:
- partition by window start date and metric
- cluster by dimensions used in queries
This helps with:
- retention deletion
- query pruning
- efficient batch writes
8) Query logic: choose the best resolution automatically
When a user asks for metrics, your query layer should choose:
- raw data for very short ranges or high detail
- 1m rollups for medium ranges
- 1h/1d rollups for long ranges
Example policy:
- last 15 minutes → raw
- last 24 hours → 1m or 5m rollups
- last 30 days → 1h rollups
- last 1 year → 1d rollups
This is often called downsampling selection.
9) Retention policy
A common retention setup:
- Raw: 14 days
- 1m rollups: 90 days
- 5m rollups: 6 months
- 1h rollups: 2 years
- 1d rollups: indefinite or very long
Automate cleanup with TTLs or partition drops.
10) Example system design
Simple version
- App emits metrics
- API writes to PostgreSQL
- Background job aggregates into rollup tables
- Query service reads from the best table
Scalable version
- App emits metrics
- Kafka ingests events
- Stream processor computes rollups
- Raw data stored in ClickHouse/S3
- Rollups stored in ClickHouse/TimescaleDB
- Query API routes requests based on time range
11) Important design choices
If you need exact aggregates
Store raw data long enough to recompute rollups.
If you need low storage
Keep raw briefly and rely on rollups.
If you need percentile queries
Use sketches/histograms, not just min/max/sum/count.
If you need multi-tenant isolation
Partition by tenant and enforce quotas.
12) Recommended implementation pattern
A practical starting point:
- Store raw metrics in a partitioned time-series table
- Create rollup jobs for 1m/5m/1h buckets
- Keep raw for 7–30 days
- Keep rollups for longer periods
- Build a query service that chooses the right source
If you want, I can also provide:
- a database schema for raw + rollup tables,
- a Kafka/streaming architecture, or
- an example in PostgreSQL, ClickHouse, or TimescaleDB.