Prompt
How do I query recent and historical windows fast in a time-series database?
Latest observation
To query recent and historical windows fast in a time-series database, you generally want to optimize for two different access patterns:
- Hot/recent data: last minutes/hours/days
- Cold/historical data: older, larger scans
The best approach is usually a combination of data layout, partitioning, indexing, pre-aggregation, and tiering.
Core strategies
1) Partition by time
Store data in time-based partitions (daily/hourly/monthly depending on volume).
Why it helps:
- Recent queries only touch a few partitions
- Historical queries can prune partitions quickly
- Makes retention and archival easier
Example:
sensor_readings_2026_11_01sensor_readings_2026_11_02
Or in systems that support it:
- partition key =
time_bucket
2) Cluster/sort by time within partitions
Within each partition, keep rows ordered by timestamp, often alongside a series key like device_id.
This helps:
- Fast range scans for
WHERE ts BETWEEN ... - Better compression
- Less disk I/O
Typical sort order:
(device_id, timestamp)or(timestamp, device_id)- Choose based on your most common query pattern
3) Use a hypertable / chunking design
Many TSDBs use chunks or shards automatically.
Good chunk sizing:
- Too small: too many files/partitions overhead
- Too large: queries scan too much data
Rule of thumb:
- Chunk so a typical query hits only a small number of chunks
- Common chunk interval: 1 day, 1 hour, or 1 week depending on ingest rate
4) Add indexes that match your filters
For time-series queries, common filters are:
- time range
- series/device tag
- tenant/customer ID
- metric name
Useful indexes:
timestamp- composite index like
(device_id, timestamp) - sometimes
(timestamp, device_id)if most queries are time-first
Avoid too many indexes on write-heavy tables.
5) Precompute rollups / materialized views
Historical queries often ask for aggregates:
- avg per minute
- max per hour
- percentiles per day
Instead of scanning raw data each time:
- maintain rollup tables
- use materialized views
- store downsampled data
Common pattern:
- raw data kept for 7–30 days
- 1-minute rollups for 6 months
- 1-hour rollups for years
This is one of the biggest performance wins for historical analytics.
6) Tier hot and cold data
Keep recent data in fast storage and historical data in cheaper/slower storage.
Hot tier:
- in-memory cache
- SSD
- recent chunks
Cold tier:
- object storage / columnar archive
- compressed older partitions
This way:
- recent windows are fast
- old windows stay queryable without bloating the hot path
7) Use compression suited to time-series
Time-series data compresses very well if:
- timestamps are ordered
- values are similar or slowly changing
- data is columnar
Common benefits:
- less disk I/O
- faster scans
- better cache efficiency
8) Query only what you need
For fast queries:
- select only needed columns
- avoid
SELECT * - use tight time predicates
- filter by series/tenant/device when possible
Bad:
SELECT * FROM metrics;
Better:
SELECT ts, value
FROM metrics
WHERE device_id = 'abc'
AND ts >= now() - interval '1 hour';
Query pattern recommendations
Recent window queries
For recent data, you want:
- small hot chunks
- memory cache
- narrow indexes
- maybe a write-optimized store
Example query:
SELECT *
FROM readings
WHERE device_id = 'sensor_12'
AND ts >= now() - interval '15 minutes'
ORDER BY ts DESC;
To make this fast:
- index
(device_id, ts DESC) - keep recent chunks small enough to stay hot
Historical window queries
For older data, you want:
- partition pruning
- rollups/materialized views
- columnar scans
- compression
Example:
SELECT date_trunc('hour', ts) AS hour, avg(value)
FROM readings
WHERE device_id = 'sensor_12'
AND ts >= '2025-01-01'
AND ts < '2025-02-01'
GROUP BY hour
ORDER BY hour;
This is much faster if the DB has hourly rollups instead of raw rows.
Practical architecture pattern
A common production setup:
- Raw recent data: last 7–30 days, chunked by time
- Rolled-up data: minute/hour/day aggregates
- Retention policy: raw data expires, rollups retained longer
- Query router: recent queries hit raw, old queries hit rollups
If you’re designing the schema
A good baseline schema:
CREATE TABLE readings (
device_id TEXT NOT NULL,
ts TIMESTAMP NOT NULL,
value DOUBLE PRECISION NOT NULL,
metric_name TEXT
);
Then:
- partition by time
- index by
(device_id, ts) - optionally add
(metric_name, ts) - create materialized views for common aggregations
Rule of thumb
To make recent and historical windows both fast:
- partition by time
- cluster by series + time
- index for your most common filters
- roll up historical aggregates
- compress and tier old data
- avoid scanning raw history when you can pre-aggregate
If you want, I can also give:
- a PostgreSQL/TimescaleDB design,
- a ClickHouse design,
- a general schema/indexing checklist, or
- example queries for last 1h / 24h / 30d windows.