Prompt
How do I build a query layer for aggregated metrics over time?
Latest observation
A good query layer for aggregated metrics over time usually has 5 pieces:
- A clear metric model
- A storage layout optimized for time-series aggregation
- An API/query interface
- Pre-aggregation and caching
- Correct handling of time, grouping, and filters
Here’s a practical way to build it.
1) Define the metrics you need
Before building the layer, decide:
- What is a metric?
Examples:page_views,orders,revenue,active_users - What dimensions can you group by?
Examples:time,country,device,plan,campaign - What aggregations are needed?
Examples:count,sum,avg,min,max,distinct count - What time windows matter?
Examples: per minute, hour, day, week, month - What latency is acceptable?
Real-time, near real-time, batch hourly, daily
This determines the shape of the data and the query layer.
2) Store raw events and/or rollups
There are two common approaches:
A. Event-based model
Store each event row with:
- timestamp
- entity id
- metric value
- dimension fields
Example:
events (
id,
event_time,
user_id,
country,
device,
revenue
)
Then aggregate on query.
Pros: flexible, simple to reason about
Cons: slow at scale for large time ranges
B. Pre-aggregated rollup model
Store summarized data at various granularities:
metric_rollups (
bucket_start,
bucket_size,
metric_name,
dimension_key,
dimension_value,
value_sum,
value_count,
value_min,
value_max
)
Example buckets:
- 1 minute
- 1 hour
- 1 day
Pros: fast queries
Cons: more complexity, eventual consistency, more storage
3) Design the query interface
Your query layer should accept parameters like:
metricstart_timeend_timegranularityfiltersgroup_byaggregation
Example API request:
{
"metric": "revenue",
"start": "2026-01-01T00:00:00Z",
"end": "2026-01-08T00:00:00Z",
"granularity": "day",
"group_by": ["country"],
"filters": {
"device": "mobile"
}
}
Example response:
{
"series": [
{
"bucket": "2026-01-01",
"groups": [
{ "country": "US", "value": 1200.5 },
{ "country": "CA", "value": 300.0 }
]
}
]
}
4) Handle time bucketing carefully
Time aggregation is often the hardest part.
Key rules:
- Always store timestamps in UTC
- Round using a consistent bucket function
- Support gaps in time series
- Be explicit about bucket boundaries
Example bucket logic:
- hour bucket:
2026-01-01T13:00:00Z - day bucket:
2026-01-01T00:00:00Z
If users want local time zones, convert only at query/render time unless your business logic requires local-day grouping.
5) Use the right aggregation strategy
For simple metrics
You can query directly from raw data:
SELECT
date_trunc('day', event_time) AS day,
country,
SUM(revenue) AS revenue
FROM events
WHERE event_time >= $1 AND event_time < $2
GROUP BY 1, 2
ORDER BY 1, 2;
For large datasets
Use rollups:
SELECT
bucket_start AS day,
country,
SUM(value_sum) AS revenue
FROM metric_rollups
WHERE metric_name = 'revenue'
AND bucket_size = '1 day'
AND bucket_start >= $1
AND bucket_start < $2
GROUP BY 1, 2
ORDER BY 1, 2;
For arbitrary date ranges
Combine rollups:
- use the largest pre-aggregated bucket that fits the query
- fall back to raw data for partial edge buckets if needed
This is often called a hybrid query plan.
6) Build a query planner
A good query layer usually picks the best source automatically.
Example logic
If query range is:
- 1 hour → use 1-minute rollups
- 7 days → use 1-hour rollups
- 1 year → use 1-day rollups
Pseudo-logic:
if query_range <= 2 hours:
use 1-minute rollup
elif query_range <= 30 days:
use 1-hour rollup
else:
use 1-day rollup
You can make this more accurate by considering:
- freshness requirements
- requested granularity
- cost of scanning raw data
- whether rollups exist for all dimensions
7) Index for your query patterns
If using SQL, index for:
event_timemetric_name- common dimensions
(metric_name, bucket_start)(bucket_start, dimension_value)
Example:
CREATE INDEX idx_rollups_metric_bucket
ON metric_rollups (metric_name, bucket_start);
CREATE INDEX idx_rollups_bucket_country
ON metric_rollups (bucket_start, country);
If you filter often by tenant/account, include that too.
8) Support nullable and sparse dimensions
Not every metric has every dimension.
Use one of these patterns:
- Wide table with nullable columns
- Key-value dimension table
- JSON/Map dimensions
- Normalized dimension IDs
For large-scale systems, a normalized or encoded dimension model is usually better for performance.
9) Deal with distinct counts and percentiles separately
Some metrics are harder than SUM().
Distinct counts
Exact COUNT(DISTINCT ...) can be expensive. Consider:
- HyperLogLog
- precomputed sketches
- approximate distinct counts
Percentiles
Use:
- t-digest
- HDR histogram
- quantile sketches
These require special storage and merging logic.
10) Make the layer resilient to changes
Metrics evolve. Design for:
- new dimensions
- new aggregation types
- schema versioning
- backfills
- late-arriving data
Best practice:
- keep raw events if possible
- rebuild rollups from raw when definitions change
11) Add caching
Cache common queries:
- dashboard defaults
- recent time windows
- popular dimension combinations
Cache keys should include:
- metric
- time range
- granularity
- filters
- group_by
- version of metric definition
12) Recommended architecture
A common architecture:
Ingestion
→ raw event store / stream
→ rollup builder
→ query API
→ cache
→ dashboard/client
Possible tech choices:
- Postgres for smaller scale
- ClickHouse for analytical queries
- BigQuery/Snowflake/Redshift for warehouse-style analytics
- Kafka + stream processor for near real-time rollups
- Redis for caching hot query results
13) Minimal example schema
CREATE TABLE metric_rollups (
metric_name TEXT NOT NULL,
bucket_start TIMESTAMPTZ NOT NULL,
bucket_size INTERVAL NOT NULL,
dimensions JSONB NOT NULL,
value_sum DOUBLE PRECISION,
value_count BIGINT,
value_min DOUBLE PRECISION,
value_max DOUBLE PRECISION
);
Query example:
SELECT
bucket_start,
dimensions->>'country' AS country,
SUM(value_sum) AS total
FROM metric_rollups
WHERE metric_name = 'revenue'
AND bucket_size = '1 day'
AND bucket_start >= '2026-01-01'
AND bucket_start < '2026-01-08'
GROUP BY 1, 2
ORDER BY 1, 2;
14) What to implement first
If you want a practical MVP, start with:
- Raw event table
- A daily rollup table
- A query API with:
- time range
- granularity
- group_by
- filters
- Basic caching
- Backfill job for rollups
Then add:
- hourly/minute rollups
- query planner
- approximate distinct counts
- percentile sketches
If you want, I can also give you:
- a Postgres-only implementation,
- a ClickHouse design, or
- a full API + schema example in code.