Geospatial and Time-Series Data Questions
Specialized data shapes and their stores: geospatial data types, spatial indexing, and location queries; and time-series data with high-ingest, retention, downsampling, and cardinality management. Covers storage-engine tuning such as compression, chunking, and indexing for range queries, and when purpose-built extensions or databases beat general-purpose stores for these workloads. A niche but recurring topic for location- and telemetry-heavy systems.
Users report tail latency spikes on complex aggregation queries that scan thousands of series. Propose optimizations across schema, query rewriting, storage-engine (e.g., indices, partitions), and caching layers to improve tail latency while keeping storage cost reasonable.
Sample Answer
Direct answer
First measure where the tail latency comes from (index lookup, reading chunks, the compressed blocks of consecutive samples a time-series engine actually stores and reads off disk, decoding, aggregation, or one slow shard among many, a shard being one partition of the data and the node that serves it, so a query spanning many shards waits on whichever one is slowest), because the fix differs for each. The biggest wins for aggregations over thousands of series (a series is one metric name plus one exact set of labels, the key/value tags such as service="checkout" attached to it) are almost always: pre-aggregate (recording rules, continuous aggregates, a warehouse or TSDB feature that keeps a rollup automatically up to date as new raw rows arrive rather than a job you schedule yourself, or rollups so the query reads 50 series instead of 20,000), read coarser data for long ranges (5-minute or 1-hour rollups), split and cache query results by time, and cut fan-out stragglers (fan-out: sending one query out to many shards or series in parallel; a straggler is the one shard that answers much slower than the rest and so decides the whole query's latency) with hedged requests. Index and partition tuning come next. Each of these costs little storage compared with the raw data.
Tail latency means the slow end of the latency distribution, usually p99 (99th percentile: 1 in 100 queries is slower). A rollup (downsampled table) stores one aggregated point per series per interval (for example a 5-minute min, max, sum and count) instead of every raw sample. A recording rule is a query the TSDB (time-series database) runs on a schedule, storing its result as a new, much smaller series.
Step 1: diagnose before optimising
Break one slow query into stages using the engine's query statistics (Prometheus-compatible engines and ClickHouse both expose per-query stats such as series touched, samples or rows read, and bytes read):
| Symptom | Likely cause | Fix family |
|---|---|---|
| Many series matched, most discarded | Broad or regex label matchers | Schema and query rewriting |
| Huge sample count read | Long range at raw resolution | Rollups, step alignment |
| Most time in one shard | Straggler or hot shard | Hedging, rebalancing |
| Same query repeatedly slow | No result caching | Split plus results cache |
Why fan-out makes the tail worse: if each of n shards is independently slow 1% of the time (p = 0.01), the query waits for the slowest shard, so
P(query is slow)=1−(1−p)n 1−(1−0.01)50=1−0.605=0.395With 50 shards, about 39.5% of queries hit at least one shard's p99. With 10 shards it is 9.6%. A per-shard 1-in-100 event now hits roughly 2 in 5 queries.
Step 2: schema
- Cut cardinality (cardinality: the number of distinct series a metric produces, driven by how many distinct label-value combinations exist). Drop labels no dashboard groups by (pod UID, request ID, full URL path). Fewer series means fewer index entries and chunks to open.
- Pre-aggregate the hot query. If a dashboard always shows
sum by (service) (rate(http_requests_total[5m]))(read: for each service, the average per-second rate of thehttp_requests_totalcounter over the trailing 5 minutes, summed across every series for that service), store that as a recording rule or continuous aggregate. 20,000 series collapse to 50. - Keep rollups mergeable: store sum and count (and min and max), never only a pre-computed average, so you can combine rollups correctly across hosts and intervals.
Step 3: query rewriting
- Replace regex matchers (
path=~".*", a label matcher that pattern-matches against every value of thepathlabel instead of picking one exact value, so the engine has to check it against every series) with equality matchers on low-cardinality labels. - Aggregate as early as possible (
sum by (service)inside the subquery, not after joining). - Align the query step (in PromQL, the spacing between the evaluated points a query returns, for example one point every 30 seconds) to the rollup interval, and align start and end times to step boundaries, so identical dashboards produce identical, cacheable queries.
- Pick the resolution from the range: a 7-day panel does not need 15-second samples on an 800-pixel-wide chart.
Step 4: storage engine
- Time partitioning so the planner opens only the partitions in range.
- Inverted index from label value to series IDs (Prometheus-style postings lists: the per-label-value list of which series IDs carry that label, the same idea a search engine uses to find every document containing a given word), or a sort key starting with the grouping columns (ClickHouse
ORDER BY (metric, service, ts)) so matching rows are contiguous. - Tiered resolutions: raw for the last few days, 5-minute rollups for weeks, 1-hour rollups for a year. The query layer routes by range.
- Bigger, compacted blocks so a 7-day query opens a handful of files rather than hundreds.
Step 5: caching and fan-out control
- Split long queries by day and cache each day's result; only the current, still-changing day is recomputed on refresh.
- Chunk and index caches (memcached, a widely used in-memory key-value cache, or local SSD) in front of object storage.
- Hedged requests: if a shard has not answered by its p95 latency, send the same request to a replica and take whichever answers first. This targets exactly the straggler math above, at the cost of a few percent extra load.
- Per-query limits (max series, max samples) so one runaway query cannot starve everyone else's tail.
Worked example
A dashboard panel: sum by (service) (rate(http_requests_total[5m])) over 7 days, matching 20,000 series scraped every 15 s.
- Raw samples read: 20,000 × (7 × 86,400 / 15) = 806.4 million samples.
- From a 5-minute rollup: 20,000 × (7 × 86,400 / 300) = 40.32 million, a 20x reduction.
- From a recording rule producing 50 per-service series at 5-minute resolution: 50 × 2,016 = 100,800 points, 8,000 times fewer than raw.
Storage cost of the recording rule: 50 extra series, against the 20,000 it summarises, a 0.25% increase. That is why pre-aggregation is the first lever, not the last.
Trade-offs and pitfalls
- Rollups lose detail. A 5-minute average hides a 20-second spike; keep max in the rollup and keep raw data for recent incident debugging.
- Recording rules only help known queries. Ad-hoc exploration still hits raw data, so pair them with query limits.
- Caching the latest interval returns stale data; exclude the most recent few minutes from the cache or give it a short TTL (time-to-live).
- Hedging doubles load on an overloaded cluster if the slowness is global rather than one straggler; cap hedges as a small percentage of requests.
- Common wrong turn: adding more shards. That spreads storage but, by the formula above, can make the tail worse for fan-out queries.
Explain different write paths used by TSDBs: append-only with WAL, direct columnar writes, and write buffering with compaction. For each, describe impact on write latency, durability, recovery time after crash, and read performance.
Sample Answer
Direct answer
The three write paths differ in where a sample is safe the moment the client gets "OK". With append-only WAL (write-ahead log), the sample is appended to a sequential log and synced to disk, then placed in an in-memory buffer; writes are fast and durable, but a crash means replaying the log, so recovery time grows with how much is unflushed. With direct columnar writes, each insert is written straight into immutable column files; durability and recovery are simple, but each write is expensive, so it only works with large batches. With write buffering plus compaction, samples sit in memory and are flushed to files periodically, then merged in the background; this gives the lowest latency and best file layout, but anything in the buffer is lost on a crash unless something upstream can resend it. My default for a metrics TSDB is WAL plus in-memory buffer plus background compaction (the design Prometheus and InfluxDB use), because it is the only one of the three that is fast and durable per write at the same time.
Key terms
- WAL (write-ahead log): an append-only file where every change is recorded before it is applied elsewhere. After a crash, the system replays it to rebuild what was in memory.
- fsync: the call that forces the operating system to put buffered data physically on disk. Until then a power loss can lose it. Group commit means one fsync covers many writes.
- Columnar: storing each column (timestamps, values, labels) in its own compressed file, so a query reading only values reads only that file.
- Compaction: background merging of many small files into fewer large ones, with better compression and sorting.
- Write amplification: bytes physically written per byte ingested. WAL plus flush plus two compactions means each sample is written about four times.
- Head block / memtable: the in-memory structure holding recent, not yet flushed samples.
- Series and scrape: a series is one metric plus one set of labels; a scrape is Prometheus's term for pulling a fresh set of values from a target on a fixed interval (here, 15 seconds).
The three paths
1. Append-only WAL + in-memory buffer (Prometheus, InfluxDB TSM engine)
InfluxDB's documented path: points are compressed and written to a WAL segment, the file is fsynced, the data is added to the in-memory cache, and only then is success returned. The cache is later snapshotted into TSM (time-structured merge) files, which are compacted through several levels. Prometheus keeps the current 2-hour window in an in-memory head block protected by a WAL in 128 MB segments (the WAL is split into fixed-size files; older ones are deleted once no longer needed for replay), and replays the WAL on restart.
2. Direct columnar writes (ClickHouse MergeTree, ClickHouse's default storage engine family that stores rows sorted on disk and merges files in the background, with synchronous inserts)
Each INSERT is sorted and written as a new immutable part (a directory of column files) on disk; there is no separate log. Background merges combine parts. ClickHouse's documentation warns that many small synchronous inserts create many parts, which hurts query performance and causes errors, so clients must batch.
3. Write buffering + compaction (no per-write log)
Samples are collected in memory (in the client, an agent, or the server) and flushed as a file when the buffer is full or a timer fires, then compacted. ClickHouse asynchronous inserts are an example of server-side buffering: by default (wait_for_async_insert = 1) the server acknowledges only after the buffer is flushed to disk, which makes it durable but adds the flush delay (default timeout 200 ms, or 1,000 ms on ClickHouse Cloud) to write latency; with wait_for_async_insert = 0 it acknowledges on buffering, and ClickHouse's docs state there is then no guarantee the data is persisted.
Comparison
| WAL + buffer | Direct columnar | Buffer + compaction (ack before flush) | |
|---|---|---|---|
| Write latency per request | Low: sequential append plus a group-committed fsync | High per insert (sort, compress, write several files); acceptable only per large batch | Lowest: memory only |
| Durability at ack | Durable once the WAL fsync completes | Durable once the part is written | Not durable: buffer lost on crash unless an upstream source (Kafka, the device) can resend |
| Recovery after crash | Replay WAL since last checkpoint; time grows with unflushed data | Near zero: parts are already complete; incomplete parts are discarded | Near zero restart, but data loss or an upstream replay |
| Read performance | Recent data served from memory (fast); older from compacted files | Good once merged; poor with many small parts | Good after flush and compaction; unflushed data is invisible or served from memory |
| Main risk | Long replay and memory pressure with high series counts | "Too many parts" from small inserts | Silent data loss |
Worked example: 1 million series at a 15-second scrape
samples per secondsamples in a 2-hour head=1,000,000/15≈66,667=66,667×7,200≈480,000,000- WAL: Prometheus's own head holds up to 2 hours before being flushed to a block (as noted above), so a crash just before the flush means replaying up to about 480 million samples. Replay time is proportional to that count (and to the number of series, since each needs its in-memory structure rebuilt). Flushing and checkpointing (recording how far into the WAL has already been safely applied, so replay after a crash starts from that point instead of from the beginning) more often shortens recovery at the cost of more, smaller files and more compaction.
- Group commit: instead of every single write forcing its own fsync (a disk operation that typically costs single-digit milliseconds), writes are batched and one fsync covers a whole batch; each write inside a batch waits for that shared fsync, adding at most one batch's worth of delay. Fsyncing each 10,000-sample batch means about 6.7 fsyncs per second instead of 66,667, which is what keeps WAL write latency low: 66,667 individual fsyncs per second would make the disk the bottleneck long before the WAL itself did.
- Direct columnar: sending one insert per 100 samples would create about 667 new parts per second. Batching into 100,000-row inserts brings it to about 0.67 parts per second, which background merges can keep up with.
- Buffering with a 5-second flush: at any moment up to 66,667 x 5, about 333,000 samples are in memory only. Acceptable if the source is Kafka (a durable, replayable message queue that can resend data on request) and the consumer commits its offset only after the flush, meaning it only tells Kafka "I'm done with these messages" once they are safely on disk, so a crash before that point makes Kafka replay them; not acceptable if the source is a device that already discarded the data.
Trade-offs and pitfalls
- These are layers, not exclusive choices. An LSM-style (log-structured merge: writes land in memory first, are flushed as sorted immutable files, and are merged together in the background) TSDB is WAL + buffer + compaction together. The real design question is which component gives durability at acknowledgement time.
- An fsync per request turns the WAL into the bottleneck. Always group-commit.
- Buffering without an upstream replay source is how metrics silently disappear during a restart. If you buffer, make the acknowledgement to the upstream (Kafka offset commit) happen after the flush.
- Recovery time is an SLO (service-level objective) input. If the TSDB must be queryable within minutes of a crash, limit the head size or run replicas so a restart is not on the critical path.
- What would flip the default: for bulk loads of historical data, or an analytics store fed from Kafka in large batches, direct columnar writes are simpler and give better read layout from the start.
Design a retention and compaction policy for time-series sensor data with different SLAs: raw data retained for 30 days with high-resolution, summarized data kept for 3 years. Explain how to implement rollups, partition pruning, and how to support queries that need both raw and rolled-up data.
Sample Answer
Direct answer
Store raw readings in a table partitioned by day and keep 30 days of partitions; build hourly rollups from raw continuously and keep them 3 years; build daily rollups from the hourly table and keep them 3 years too, purely to make multi-year queries fast. Expire data by dropping whole partitions, never by DELETE. Every query carries a time predicate so the database reads only the partitions in range (partition pruning). A thin query layer (a view or a small service) routes each request: the part of the range within the last 30 days comes from raw, the older part from the rollup tier, stitched at a fixed boundary. At 10 million points per day this keeps the database around 16 GB instead of more than 500 GB for 3 years of raw data.
Key terms
- Retention: how long a tier keeps data. SLA (service-level agreement) here means the commitment: raw at full resolution for 30 days, summaries for 3 years.
- Rollup: a pre-computed summary per sensor per bucket (hour, day): min, max, sum, count.
- Compaction: replacing many small units of data with fewer, larger ones. Here it means turning raw rows into rollup rows and dropping the raw rows, and, for columnar storage, merging many small files into large ones.
- Partition: a physical slice of a table, here one per day for raw data. The database treats it as a separate table underneath, so dropping it is instant.
- Partition pruning: the planner (the part of Postgres that decides how to execute a query, including which partitions it actually needs to open) skips partitions whose time range cannot match the
WHEREclause. A query for "yesterday" opens 1 partition out of 30.
The tiering table
| Tier | Resolution | Retention | Partition size | Built from | Serves |
|---|---|---|---|---|---|
| Raw | as sent (about every 8.6 s per sensor) | 30 days | 1 day | ingestion | investigations, exports, anything under 30 days needing exact values |
| Hourly | 1 hour | 3 years | 1 month | raw, every 15 min | charts from 2 days to 1 year, anomaly review |
| Daily | 1 day | 3 years | 1 year | hourly, once a day | multi-year trends, reports |
Storage cost vs latency, the explicit trade-off. Each coarser tier costs storage and one more job, and buys query latency on long ranges. The hourly tier is mandatory (the 3-year SLA requires summaries to exist once raw is gone). The daily tier is optional: it costs about 4% of the hourly tier's storage (1/24) and cuts a 3-year chart from 26,280 rows per sensor to 1,095. That is cheap latency, so I keep it. A further tier (weekly, monthly) would save almost nothing more and is not worth the extra job.
Worked example at 10 million points per day
Assume 1,000 sensors, each sending one reading about every 8.64 seconds (86,400 / 10,000), so 10,000,000 points per day. Take 48 bytes per raw row in a row store (timestamp, sensor id, value, plus per-row overhead) and 64 bytes per rollup row; these are planning assumptions, not measurements.
raw, 30 dayshourly, 3 yearsdaily, 3 yearsraw kept 3 years instead=107×30=3×108 rows≈14.4 GB=1,000×24×1,095=26,280,000 rows≈1.68 GB=1,000×1,095=1,095,000 rows≈0.07 GB=107×1,095×48 B≈525.6 GBTotal about 16.2 GB against 525.6 GB. Columnar compression would shrink both sides, but the ratio is what matters.
Implementing the rollups
- Hourly job, every 15 minutes, recomputes the last 3 hours of buckets from raw with an upsert (
INSERT ... ON CONFLICT (sensor_id, hour) DO UPDATE). Recomputing a trailing window picks up readings that arrived late, for example from a sensor that reconnected. Upserts make the job idempotent: running it twice gives the same result, so retries after a crash are safe. - Daily job runs after midnight plus a margin (say 03:00) and aggregates the previous day's 24 hourly rows: min of mins, max of maxes, sum of sums, sum of counts. These combine exactly, which an average of averages would not.
- Watermark table: each job records the latest bucket it completed. The retention job reads it (next section).
Retention and compaction by partition
-- PostgreSQL declarative partitioning, one partition per day for raw
CREATE TABLE readings (
sensor_id int NOT NULL,
ts timestamptz NOT NULL,
value double precision NOT NULL
) PARTITION BY RANGE (ts);
CREATE TABLE readings_2026_09_28 PARTITION OF readings
FOR VALUES FROM ('2026-09-28') TO ('2026-09-29');
CREATE INDEX ON readings (sensor_id, ts); -- propagates to every partition
A scheduler (pg_partman, a PostgreSQL extension that creates and drops partitions on a schedule, or a cron job) creates partitions a few days ahead and drops old ones:
- Check the hourly watermark covers the whole partition's day, plus the 3-hour late-data window the hourly job recomputes (see "Implementing the rollups" above), so a drop never runs ahead of data the rollup job might still need.
ALTER TABLE readings DETACH PARTITION readings_2026_08_28;thenDROP TABLE readings_2026_08_28;- If the watermark is behind, do not drop: alert instead. A 31st day of raw data costs 0.48 GB; a lost day of summaries is unrecoverable.
Dropping a partition is a metadata operation (it just removes an entry from the table's list of partitions and unlinks a file; it never opens or touches a row inside it). DELETE FROM readings WHERE ts < now() - interval '30 days' would touch 10 million rows a day: each deleted row still has to be recorded in the write-ahead log (WAL, the append-only file Postgres writes every change to before applying it, so it can recover after a crash), and each becomes a dead row (an old row version Postgres keeps around rather than erasing in place) that VACUUM (Postgres's background cleanup process) later has to scan and reclaim.
Pruning only works if queries let it. WHERE ts >= '2026-09-01' AND ts < '2026-09-08' prunes to 7 partitions. WHERE date_trunc('day', ts) = '2026-09-01' wraps the column in a function and may force a scan of all 30.
Serving queries that need both raw and rolled-up data
flowchart LR
C[Client: sensor, range, resolution] --> R{Query router}
R -->|range within 30 days| RAW[(Raw partitions)]
R -->|older part of range| H[(Hourly)]
R -->|range over 1 year| D[(Daily)]
RAW --> M[Merge at boundary]
H --> M
D --> M
M --> C
- Rule 1: choose the output resolution first. A 90-day chart at hourly resolution is 2,160 points per sensor. Serve it entirely from the hourly table (which covers the last 30 days too), rather than stitching, so the line is consistent.
- Rule 2: stitch only when the caller needs raw detail for the recent part. Example: "last 60 days, raw where available". The router splits at the boundary
now() - 30 daysrounded down to a whole hour: raw rows after it, hourly rows before it, returned with aresolutionfield on each point so the client can draw them differently. - Rule 3: return the same shape from every tier (min, max, avg as
sum / count, count), so a raw point is presented as a bucket of count 1. - A SQL
UNION ALLview across raw and hourly with complementary time predicates works for simple cases; a service layer is better once you have several tiers and caching.
Trade-offs and pitfalls
- Dropping raw before the rollup covers it is the one failure that loses data permanently. Gate every drop on the watermark.
- Percentiles cannot be rebuilt from min, max, sum, count. If the 3-year SLA includes percentiles, store a fixed-bucket histogram per hour (a count of readings falling into fixed value ranges, like 0-10, 10-20, which can be summed across hours and used to estimate a percentile, unlike a single stored percentile number).
- Too-small partitions (hourly partitions for raw) mean 720 partitions to plan over for 30 days and slower planning; too-large ones (monthly) mean retention can only be exact to the month. Daily matches the 30-day SLA.
- What would change it: at 1 billion points per day instead of 10 million, raw storage moves to a columnar TSDB (a time-series database that stores each column of data compressed together, built for that scale) or Parquet files (a compressed, columnar file format) in object storage, but the tier table, watermark-gated drops and the router stay the same.
Write PostgreSQL/TimescaleDB SQL to:
- Create a hypertable for host metrics with schema: metric_id serial PK, host text, metric_name text, metric_value double precision, ts timestamptz NOT NULL.
- Create a 5-minute continuous aggregate (rollup) for CPU metric per host.
- Show a query that returns the 5-minute avg CPU per host for the last 24 hours, sorted by highest spike.
- Add a retention policy to drop raw chunks older than 7 days.
Provide correct TimescaleDB functions and explain any assumptions about chunk interval.
Sample Answer
Direct answer
Create a normal table, convert it to a hypertable with create_hypertable(..., by_range('ts', INTERVAL '1 day')), build a continuous aggregate with time_bucket('5 minutes', ts) filtered to metric_name = 'cpu', give it a refresh policy, query the aggregate for the last 24 hours ordered by each host's peak, and add add_retention_policy('host_metrics', drop_after => INTERVAL '7 days'). Two details trip people up: the primary key must include ts, and the aggregate's refresh window must stay inside the 7-day raw retention, or a refresh will erase aggregated history.
Terms used
- TimescaleDB: a PostgreSQL extension for time-series data.
- Hypertable: a table that looks like one table but is stored as many chunks, each chunk holding one time range (here, one day). Queries on recent time touch only recent chunks, and old data is removed by dropping whole chunks, which is much cheaper than
DELETE. - Continuous aggregate: a materialized view (a stored query result) that TimescaleDB refreshes incrementally, recomputing only the time buckets whose raw data changed.
time_bucket: rounds a timestamp down to the start of its bucket, so 10:03:27 becomes 10:00:00 for 5-minute buckets.- Retention policy: a background job that drops chunks older than a threshold.
Code
-- 1) Table and hypertable
CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE host_metrics (
metric_id bigserial,
host text NOT NULL,
metric_name text NOT NULL,
metric_value double precision,
ts timestamptz NOT NULL,
PRIMARY KEY (metric_id, ts) -- a unique key on a hypertable must include the time column
);
SELECT create_hypertable('host_metrics', by_range('ts', INTERVAL '1 day'));
-- lookups are "this metric, this host, recent time"
CREATE INDEX host_metrics_name_host_ts ON host_metrics (metric_name, host, ts DESC);
-- 2) 5-minute continuous aggregate for CPU per host
CREATE MATERIALIZED VIEW cpu_5m
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '5 minutes', ts) AS bucket,
host,
avg(metric_value) AS avg_cpu,
max(metric_value) AS max_cpu,
count(*) AS samples
FROM host_metrics
WHERE metric_name = 'cpu'
GROUP BY time_bucket(INTERVAL '5 minutes', ts), host
WITH NO DATA;
-- keep it refreshed: every 5 minutes, recompute the window from 3 days ago to 5 minutes ago
SELECT add_continuous_aggregate_policy('cpu_5m',
start_offset => INTERVAL '3 days',
end_offset => INTERVAL '5 minutes',
schedule_interval => INTERVAL '5 minutes');
-- optional: include the newest, not-yet-materialized data at query time
ALTER MATERIALIZED VIEW cpu_5m SET (timescaledb.materialized_only = false);
-- 3) Last 24 hours of 5-minute averages, hosts with the biggest spike first
SELECT host,
bucket,
round(avg_cpu::numeric, 1) AS avg_cpu_5m,
round(max(avg_cpu) OVER (PARTITION BY host)::numeric, 1) AS host_peak_5m
FROM cpu_5m
WHERE bucket >= now() - INTERVAL '24 hours'
ORDER BY host_peak_5m DESC, host, bucket;
-- 4) Drop raw chunks older than 7 days (the aggregate keeps its own rows)
SELECT add_retention_policy('host_metrics', drop_after => INTERVAL '7 days');
Key points
1. The primary key. The requested schema says metric_id serial PK. On a hypertable every unique index, including the primary key, must contain all partitioning columns, because uniqueness is enforced per chunk. PRIMARY KEY (metric_id) alone makes create_hypertable fail, so the key becomes (metric_id, ts). I also changed serial to bigserial, deliberately. serial is a 32-bit integer that stops at 2,147,483,647. At 2,000 hosts x 50 metrics x one sample every 10 s:
Many metrics tables drop the surrogate metric_id altogether, because nothing looks rows up by it.
2. Chunk interval assumption (1 day). TimescaleDB's default is 7 days. Its documented guideline is to size chunks so the indexes of the chunk currently being written fit in about 25% of RAM; its own example is that 10 GB of index growth per day on a 64 GB server calls for a 1-day interval. I chose 1 day for two reasons. At about 864M rows a day, a 7-day chunk's indexes would not stay in memory. And the retention policy drops only chunks that are fully older than 7 days, so with 1-day chunks raw data lives between 7 and 8 days, while 7-day chunks would keep up to 14 days.
3. The aggregate. WITH NO DATA creates the view instantly instead of scanning all history in one transaction; the policy (or a manual CALL refresh_continuous_aggregate(...)) fills it. Storing max_cpu and samples next to avg_cpu is cheap and means a later question like "worst single sample in that 5 minutes" needs no raw data. In current TimescaleDB versions materialized_only defaults to true, so the view returns only refreshed buckets; setting it to false adds the latest raw data at query time ("real-time aggregation") at some extra query cost.
4. The query. "Sorted by highest spike" is read as: hosts ordered by their worst 5-minute average in the window, each host's buckets in time order. The window function max(avg_cpu) OVER (PARTITION BY host) attaches each host's peak to every row without collapsing them. For only the single worst buckets across all hosts, use ORDER BY avg_cpu DESC LIMIT 20 instead.
5. Retention and the refresh window. Dropping raw chunks does not delete the aggregate's rows, as long as the aggregate is never refreshed over the dropped time range. If it were, TimescaleDB would see "raw data gone" and remove the aggregated buckets too. Here start_offset is 3 days and raw retention is 7 days, so refreshes never reach dropped data. To bound the aggregate as well, give it its own longer policy, for example add_retention_policy('cpu_5m', drop_after => INTERVAL '90 days').
Complexity
- Insert: one B-tree insert per index into the current chunk. The table stays fast only while those indexes fit in memory, which is what the chunk interval controls.
- Aggregate refresh: proportional to the rows in buckets that changed since the last refresh, not to the whole table.
- The 24-hour query reads 288 buckets per host from the aggregate (24 x 60 / 5), so 2,000 hosts means 576,000 small rows instead of about 864M raw rows.
- Retention: dropping a chunk is a metadata operation plus file removal, with no row-by-row
DELETEand no table bloat.
Edge cases
- Late-arriving samples older than
start_offset(3 days) are stored in raw data but never folded into the aggregate. Widen the offset or refresh that range manually. - Hosts that stop reporting simply have no buckets; the aggregate does not create zero rows. Use
time_bucket_gapfillon a query over the aggregate if a chart needs explicit gaps. - Time zones: 5-minute buckets are the same everywhere, but daily buckets default to UTC boundaries.
- Newer syntax: TimescaleDB 2.20 and later also accept
CREATE TABLE ... WITH (tsdb.hypertable, tsdb.partition_column = 'ts', tsdb.chunk_interval = '1 day'), which replaces the separatecreate_hypertablecall. The function form shown above still works.
You want to keep 7 days of raw metrics but maintain 2 years of aggregated metrics using continuous aggregates in TimescaleDB. Design an automated policy for (a) creating and refreshing continuous aggregates, (b) downsampling raw into the aggregates, and (c) removing raw chunks older than 7 days without breaking queries that request older aggregated data.
Sample Answer
Direct answer
Create an hourly continuous aggregate (a materialized view, meaning a table-like object that stores the precomputed result of a query, that TimescaleDB keeps up to date incrementally) over the raw hypertable, storing min, max, sum and count per bucket, plus a daily aggregate stacked on top of the hourly one. Attach a refresh policy whose window starts 3 days back, a retention policy that drops raw chunks after 7 days, and a retention policy that drops aggregate chunks after 2 years. The one rule that keeps this safe: the refresh policy's start_offset (3 days) must be smaller than the raw retention's drop_after (7 days). If a refresh ever covers a period whose raw chunks were already dropped, TimescaleDB recomputes the aggregate from the now-missing data and the aggregated history for that period is lost. Dashboards then query the aggregates for anything older than 7 days, and those rows stay put because the aggregates have their own, separate retention.
Key terms
- Hypertable: a TimescaleDB table that is automatically split into chunks, each covering a fixed time range (one day here). Dropping old data means dropping whole chunks, which is fast and leaves no bloat (leftover, no-longer-visible row versions that make a table bigger and slower until a cleanup process reclaims them), unlike
DELETE. - Continuous aggregate (cagg): a view defined with
time_bucket()and aggregates. TimescaleDB stores the results and only recomputes buckets whose raw data changed, rather than the whole view. - Refresh window: the time range a refresh recomputes, defined relative to "now" by
start_offset(how far back) andend_offset(how close to now). - Real-time aggregation: an option where querying the cagg also computes the not-yet-materialized recent buckets from raw data on the fly. In TimescaleDB 2.13 and later it is disabled by default for new caggs.
- Hierarchical continuous aggregate: a cagg built on another cagg (supported since TimescaleDB 2.9). The upper bucket must be a multiple of the lower one (1 day is 24 hours, so daily-on-hourly works).
The policy
flowchart LR
R[metrics hypertable<br/>raw, 1-day chunks<br/>kept 7 days] -->|refresh every 30 min<br/>window: now-3d to now-1h| H[metrics_hourly<br/>kept 2 years]
H -->|refresh every 6 h| D[metrics_daily<br/>kept 2 years]
Q[Dashboards] --> R
Q --> H
Q --> D
(a) Create and refresh the continuous aggregates
CREATE TABLE metrics (
time timestamptz NOT NULL, -- timestamptz: PostgreSQL's timestamp-with-time-zone type
device_id integer NOT NULL,
value double precision NOT NULL
);
SELECT create_hypertable('metrics', by_range('time', INTERVAL '1 day'));
CREATE MATERIALIZED VIEW metrics_hourly
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 hour', time) AS bucket,
device_id,
min(value) AS min_v, max(value) AS max_v,
sum(value) AS sum_v, count(*) AS n
FROM metrics
GROUP BY bucket, device_id
WITH NO DATA;
SELECT add_continuous_aggregate_policy('metrics_hourly',
start_offset => INTERVAL '3 days',
end_offset => INTERVAL '1 hour',
schedule_interval => INTERVAL '30 minutes');
CREATE MATERIALIZED VIEW metrics_daily
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 day', bucket) AS day,
device_id,
min(min_v) AS min_v, max(max_v) AS max_v,
sum(sum_v) AS sum_v, sum(n) AS n
FROM metrics_hourly
GROUP BY day, device_id
WITH NO DATA;
SELECT add_continuous_aggregate_policy('metrics_daily',
start_offset => INTERVAL '6 days',
end_offset => INTERVAL '1 day',
schedule_interval => INTERVAL '6 hours');
Why these numbers:
end_offset => 1 hourleaves the current, still-filling hour alone, so the refresh does not keep recomputing a bucket that is changing every second.start_offset => 3 daysmeans every refresh re-examines the last 3 days, which absorbs late data (a device that was offline for up to about 3 days and then uploads its backlog still lands in the aggregate). TimescaleDB only recomputes buckets whose raw data actually changed, so the wide window costs little when nothing is late.- The daily cagg's window (6 days) sits inside the hourly cagg's 2-year retention, so it always has hourly rows to read. The first time the daily refresh reaches a given daily bucket, at
end_offset= 1 day, that bucket's most recent hour is only about 1 hour old, well inside the hourly policy's 3-day catch-up window, so that first materialization can still change later; it is not yet final. What actually keeps the design correct is that the daily policy keeps re-examining the same bucket on every 6-hour run for as long as it sits inside the 6-daystart_offsetwindow. At the last such re-examination, right before the bucket exits that window, its most recent hour is 6 days minus the bucket's own 24-hour width, so 5 days (120 hours) old, which is past the hourly policy's 3-day (72-hour) finalization point by about 2 days (49 hours), not 3: comparing the twostart_offsetvalues directly (6 minus 3) overlooks that the daily bucket's own 24-hour width eats a day of that apparent margin. Astart_offsetof 3 days is provably too small: the bucket's last re-examination happens with its most recent hour at 49 hours old, still inside the hourly window, so the daily row can exit stale. Four days is only barely enough in the idealized case (a 1-hour margin) and is not safe in practice, because the refresh runs only every 6 hours, so the actual last run can land anywhere in that 6-hour slop and miss the 1-hour window entirely. Six days is the smallest of the three that survives that scheduling slop with room to spare. Itsend_offsetof 1 day leaves the current day open. - Min, max, sum and count, not avg. The daily level must combine hourly rows exactly. Average is computed at query time as
sum_v / n. An average of hourly averages is wrong whenever hours have different sample counts.
(b) Downsampling raw into the aggregates
Downsampling means storing data at a coarser resolution than it was collected at (one row per hour or per day instead of one row per raw reading), so long-range queries scan far fewer rows. Downsampling is what the refresh policy does: each run materializes the hourly buckets in its window from raw rows. There is no separate copy job. Two operational additions:
- Backfill once after creating the views, because
WITH NO DATAstarts them empty:CALL refresh_continuous_aggregate('metrics_hourly', NULL, now() - INTERVAL '1 hour');then the same formetrics_daily. - Late data older than 3 days is outside the automatic window. If a known batch of old data arrives, run
refresh_continuous_aggregatemanually for exactly that range, and only while its raw chunks still exist (younger than 7 days).
(c) Remove raw chunks after 7 days without breaking older queries
SELECT add_retention_policy('metrics', drop_after => INTERVAL '7 days');
SELECT add_retention_policy('metrics_hourly', drop_after => INTERVAL '2 years');
SELECT add_retention_policy('metrics_daily', drop_after => INTERVAL '2 years');
The ordering guarantee, stated as a timeline for a raw row written at time T:
| Time after T | What happens |
|---|---|
| 1 h to 3 days | Refresh policy materializes and, if needed, re-materializes its hour bucket |
| 3 days | Leaves the refresh window: its aggregate row is now final |
| 7 days | Raw chunk is dropped. The aggregate row is untouched, because no refresh looks at this range any more |
| 2 years | Aggregate chunk is dropped |
The 4-day gap between "final" and "raw dropped" is the safety margin. If someone later widens start_offset to 10 days, refreshes would cover days 7-10, where raw chunks are gone, and TimescaleDB would recompute those buckets from missing data and erase the aggregates. Guard it with a check in your deployment tooling that start_offset < drop_after for every cagg and its source.
Queries: anything older than 7 days reads metrics_hourly or metrics_daily, which still hold it. For the most recent hour (not yet materialized), either query raw metrics directly or enable real-time aggregation with ALTER MATERIALIZED VIEW metrics_hourly SET (timescaledb.materialized_only = false); so the view unions materialized buckets with a live computation over raw rows for the newest hour.
Worked example: what gets stored
For 5,000 devices sending one reading every 10 seconds:
raw rows per dayraw rows kept (7 days)hourly rows (2 years)daily rows (2 years)=5,000×8,640=43,200,000=302,400,000=5,000×24×730=87,600,000=5,000×730=3,650,000A 1-year chart for one device reads 365 daily rows instead of about 3.15 million raw rows (8,640 x 365), and those raw rows no longer exist anyway.
Trade-offs and pitfalls
- The offset rule is the whole design.
start_offsetsmaller than rawdrop_afteris stated in TimescaleDB's own documentation for combining the two policies. Violating it silently deletes aggregated history. - Percentiles need a mergeable structure. A single stored p95 (95th percentile) value from one hour cannot be combined with another hour's p95 to get a correct p95 over both hours; only the underlying distribution can be combined correctly. If dashboards need p95 over months, store a histogram (a count of readings per value bucket) or a sketch (a small approximate summary of the distribution that can be merged across time buckets, unlike a single percentile number; the timescaledb_toolkit extension provides
percentile_agg) in the hourly view, not a raw p95 value. - Chunk interval vs retention: retention drops whole chunks that are entirely older than 7 days, so with 1-day chunks raw data actually lives between 7 and 8 days. That is fine; just do not promise an exact deletion time.
- What would change the design: if 7 days of late data must be accepted, the refresh window must widen and raw retention must grow with it (for example refresh 8 days, retain 14). If dashboards rarely go beyond a month, drop the daily level and keep only hourly.
Unlock Full Question Bank
Get access to all 33 Geospatial and Time-Series Data interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.