A continuous aggregate is an incrementally refreshed materialised view over a hypertable, and it is TimescaleDB's best feature. You define it as a SELECT with a time_bucket, and TimescaleDB maintains it: when new data arrives the affected buckets are marked invalid, and a refresh policy recomputes only those buckets rather than the whole view. A year-long chart then reads thousands of pre-aggregated rows instead of billions of raw ones.
Two behaviours make them subtle, and both deserve your attention.
Real-time aggregation means that by default a query against a continuous aggregate returns materialised data for older buckets plus a live aggregation of raw data for the most recent, not-yet-materialised window. The result is always current, which is usually what you want - and it means a query against the view can be slower than you expect, because part of it is doing real work. You can turn it off with materialized_only = true, and then the view returns only materialised data and the most recent window is simply missing. Both are defensible; the failure is not knowing which you have.
The refresh policy's offsets decide which late data is ever incorporated, and this is the module's most important content. A policy has a start_offset and an end_offset. Each run refreshes buckets in the window from now() - start_offset to now() - end_offset. So:
end_offsetkeeps the refresh away from the most recent, still-arriving data. Too small and you materialise buckets that are still filling, repeatedly.start_offsetis the lateness window, and it is a hard boundary. Data arriving with a timestamp older thannow() - start_offsetwill never be picked up by the refresh policy. The invalidation is recorded, the policy's window does not reach it, and the aggregate stays wrong until someone callsrefresh_continuous_aggregatemanually for that range. Nothing reports this.
That is the same late-data problem as the previous course, with one difference worth valuing: here it is a declared number you can read, compare against your devices' actual lateness, and verify. So measure the real distribution of lateness in your fleet, set start_offset beyond its tail, and monitor for data arriving outside it - because that monitor is the only thing that tells you the number is wrong.
Compression - the columnstore - converts chunks from row to columnar format, typically at ten to twenty times. Two settings decide whether it helps your queries or hurts them. segmentby groups rows by a column so that a query filtering on that column reads only the relevant segments: set it to the identifier you filter on most, usually the entity id. orderby sets the ordering within each compressed batch, normally time DESC. Get segmentby right and compressed queries can be faster than uncompressed ones because there is far less to read; get it wrong - or omit it - and a query filtering on an entity decompresses everything. This is the single highest-leverage tuning decision in the course after the chunk interval.
The behaviour of writes against compressed chunks has improved substantially across versions - older TimescaleDB required decompressing a chunk to modify it, newer versions support inserts and updates directly. Check your version's behaviour rather than trusting an older answer, and either way design so that compression happens after data has stopped changing: compress chunks older than your lateness window, not newer.
Retention is drop_chunks, and it is nearly free because it drops whole chunks - which means your retention granularity is your chunk interval, not a row. A 30-day retention with 7-day chunks keeps between 30 and 37 days of data, and that is correct behaviour rather than a bug.
And then the interaction that loses data, which is this module's trap. If a retention policy drops raw chunks that a continuous aggregate has not yet materialised, that data is gone from both the raw table and the aggregate, permanently. The ordering is the whole game: the continuous aggregate must be refreshed past a bucket before retention removes its source rows. So retention on the raw hypertable must be longer than the continuous aggregate's start_offset, with margin, and that relationship should be written down next to both policies because the next person to shorten retention will not know it.
Laboratory exercise 3 - aggregates, compression and the ordering that matters.
Build a continuous aggregate cascade: one-minute from raw, one-hour from the one-minute aggregate, one-day from the hourly. Configure a refresh policy on each with offsets you can justify.
Measure what they buy: the same dashboard query over one hour, one day, one week, one month and one year, against raw data and against the appropriate aggregate, recording rows read, buffers and latency.
Then the late-data laboratory, which is the centre of the module. Measure the lateness distribution your generator produces. Set start_offset deliberately inside that distribution, inject late data beyond it, and demonstrate that the aggregate is permanently wrong - show the stored value and the recomputed value disagreeing, with no error anywhere. Then fix it two ways: widen start_offset, and add a scheduled manual refresh_continuous_aggregate for the tail. Add the monitor that counts data arriving beyond the window.
Demonstrate real-time aggregation both ways: query the view with it on and off, show the difference in the most recent bucket, and record the latency difference.
Then the compression study, which is the other main artefact. Compress with four segmentby configurations: none, vehicle_id, trip_id, and (fleet_id, vehicle_id). For each record the compression ratio and the latency of four queries - one vehicle's recent history, one trip, a fleet-wide aggregate, and a full scan. Find the configuration where a compressed query beats the uncompressed one, and the configuration where it is ten times worse.
Finally, demonstrate the retention trap deliberately: set retention shorter than the aggregate's start_offset, let it drop unmaterialised chunks, and show the data permanently absent from both. Then correct the ordering and document the relationship.
Deliverable: the aggregate cascade with justified offsets, the raw-against-aggregate measurements, the late-data divergence demonstrated and both fixes, the real-time aggregation comparison, the four-way compression study with the best and worst case identified, the retention trap demonstrated and corrected, and a written policy document stating the relationship between the offsets and retention.
-- ==================================================================
-- A CONTINUOUS AGGREGATE: an INCREMENTALLY REFRESHED materialised
-- view. TimescaleDB's best feature.
-- ==================================================================
CREATE MATERIALIZED VIEW telemetry_1m
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 minute', time) AS bucket,
vehicle_id,
AVG(speed_kph) AS avg_speed,
MAX(speed_kph) AS max_speed,
MIN(battery_pct) AS min_battery,
LAST(battery_pct, time) AS last_battery, -- a hyperfunction
COUNT(*) AS samples
FROM vehicle_telemetry
GROUP BY bucket, vehicle_id
WITH NO DATA; -- then refresh deliberately
-- A CASCADE - an aggregate ON an aggregate:
CREATE MATERIALIZED VIEW telemetry_1h
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 hour', bucket) AS bucket,
vehicle_id,
SUM(avg_speed * samples) / SUM(samples) AS avg_speed, -- *** EXACT ***
MAX(max_speed) AS max_speed,
MIN(min_battery) AS min_battery,
SUM(samples) AS samples
FROM telemetry_1m
GROUP BY bucket, vehicle_id
WITH NO DATA;
-- *** SUM(avg * samples) / SUM(samples), NOT AVG(avg_speed). *** A
-- mean of means is WRONG when the buckets have different sample
-- counts, which is why the lower level carries `samples`. The error
-- is small enough to go unnoticed for a year.
-- ==================================================================
-- *** THE REFRESH POLICY'S OFFSETS DECIDE WHICH LATE DATA IS EVER
-- *** INCORPORATED. The most important content in this module. ***
-- ==================================================================
SELECT add_continuous_aggregate_policy('telemetry_1m',
start_offset => INTERVAL '3 days', -- *** THE LATENESS WINDOW ***
end_offset => INTERVAL '1 minute', -- stay off still-filling data
schedule_interval => INTERVAL '1 minute');
--
-- Each run refreshes buckets from now() - start_offset
-- to now() - end_offset.
--
-- *** end_offset *** keeps the refresh AWAY FROM THE MOST RECENT,
-- STILL-ARRIVING data. Too small and you re-materialise buckets
-- that are still filling, repeatedly.
--
-- *** start_offset IS THE LATENESS WINDOW, AND IT IS A HARD
-- *** BOUNDARY. DATA ARRIVING WITH A TIMESTAMP OLDER THAN
-- *** now() - start_offset WILL NEVER BE PICKED UP BY THE POLICY. ***
-- The invalidation is recorded; the policy's window DOES NOT
-- REACH IT; the aggregate STAYS WRONG until someone calls
-- refresh_continuous_aggregate MANUALLY for that range.
-- *** NOTHING REPORTS THIS. ***
-- DETECT IT - run this on a schedule:
SELECT c.bucket, c.vehicle_id, c.avg_speed AS stored, x.recomputed,
ABS(c.avg_speed - x.recomputed) AS drift
FROM telemetry_1m c
JOIN (SELECT time_bucket(INTERVAL '1 minute', time) AS bucket,
vehicle_id, AVG(speed_kph) AS recomputed
FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '7 days'
GROUP BY 1, 2) x
ON x.bucket = c.bucket AND x.vehicle_id = c.vehicle_id
WHERE ABS(c.avg_speed - x.recomputed) > 0.0001;
-- Expected: no rows.
-- THE TWO FIXES:
-- (1) WIDEN start_offset beyond your fleet's real lateness tail
-- (2) a SCHEDULED MANUAL refresh for the tail:
CALL refresh_continuous_aggregate('telemetry_1m',
now() - INTERVAL '30 days', now() - INTERVAL '3 days');
--
-- *** AND THE MONITOR, because the number IS the policy: ***
-- measure your fleet's ACTUAL lateness distribution first -
-- p50 1.2 s p95 14 s p99 6 min p99.9 4 h max 31 h
-- -> start_offset = 3 days clears even the max, with margin.
-- then COUNT what arrives beyond it, in the ingestion path:
-- if now() - point_time > start_offset: metrics.increment(...)
-- *** THAT COUNTER IS THE ONLY THING THAT TELLS YOU THE NUMBER IS
-- *** WRONG. ***
--
-- The difference from a purpose-built engine is worth valuing:
-- *** HERE THE LATENESS WINDOW IS A DECLARED NUMBER YOU CAN READ,
-- *** COMPARE AGAINST REALITY, AND VERIFY. ***
SELECT view_name, config FROM timescaledb_information.jobs
WHERE proc_name = 'policy_refresh_continuous_aggregate';
-- ==================================================================
-- *** REAL-TIME AGGREGATION: know which one you have. ***
-- ==================================================================
-- DEFAULT (on): a query returns MATERIALISED data for older buckets
-- *** PLUS A LIVE AGGREGATION OF RAW DATA for the most recent,
-- not-yet-materialised window. *** Always current - and part of
-- the query is DOING REAL WORK, so it can be slower than expected.
ALTER MATERIALIZED VIEW telemetry_1m SET (timescaledb.materialized_only = true);
-- -> now it returns ONLY materialised data, and *** THE MOST
-- RECENT WINDOW IS SIMPLY MISSING. ***
--
-- real-time on p95 34 ms latest bucket present
-- real-time off p95 6 ms latest bucket ABSENT
--
-- *** BOTH ARE DEFENSIBLE. THE FAILURE IS NOT KNOWING WHICH YOU
-- *** HAVE *** - and a dashboard that silently lost its newest
-- minute is how people find out.
-- ==================================================================
-- *** COMPRESSION (THE COLUMNSTORE). segmentby is the single
-- *** highest-leverage tuning decision after the chunk interval. ***
-- ==================================================================
ALTER TABLE vehicle_telemetry SET (
timescaledb.compress,
timescaledb.compress_segmentby = 'vehicle_id', -- *** THE ONE ***
timescaledb.compress_orderby = 'time DESC'
);
SELECT add_compression_policy('vehicle_telemetry', INTERVAL '7 days');
-- *** COMPRESS AFTER DATA HAS STOPPED CHANGING: older than your
-- *** LATENESS WINDOW, not newer. ***
-- (Write behaviour on compressed chunks has improved a lot across
-- versions - older TimescaleDB required decompressing to modify;
-- newer supports inserts and updates directly. *** CHECK YOUR
-- VERSION rather than trusting an older answer. ***)
-- *** THE segmentby STUDY - the module's other main artefact: ***
-- segmentby ratio 1 vehicle 1 trip fleet agg full scan
-- (none) 14.2x 3,400 ms 2,900 ms 410 ms 380 ms
-- *** vehicle_id *** 11.8x *** 3 ms *** 890 ms 440 ms 420 ms
-- trip_id 9.1x 1,900 ms *** 4 ms *** 460 ms 450 ms
-- (fleet_id, vehicle_id) 8.4x 6 ms 910 ms *** 38 ms *** 490 ms
--
-- *** GET IT RIGHT AND A COMPRESSED QUERY BEATS THE UNCOMPRESSED ONE
-- *** (3 ms against 2,100 ms) BECAUSE THERE IS FAR LESS TO READ.
-- *** GET IT WRONG - OR OMIT IT - AND A QUERY FILTERING ON AN ENTITY
-- *** DECOMPRESSES EVERYTHING (3,400 ms). ***
-- Note the trade in the ratio column too: more segmentby columns,
-- better targeted queries, SLIGHTLY WORSE COMPRESSION.
SELECT pg_size_pretty(before_compression_total_bytes) AS before,
pg_size_pretty(after_compression_total_bytes) AS after,
ROUND(before_compression_total_bytes::numeric
/ NULLIF(after_compression_total_bytes,0), 1) AS ratio
FROM hypertable_compression_stats('vehicle_telemetry');
-- ==================================================================
-- RETENTION: drop_chunks. Nearly free, because it drops WHOLE
-- CHUNKS.
-- ==================================================================
SELECT add_retention_policy('vehicle_telemetry', INTERVAL '90 days');
SELECT drop_chunks('vehicle_telemetry', older_than => INTERVAL '90 days');
--
-- *** YOUR RETENTION GRANULARITY IS YOUR CHUNK INTERVAL, NOT A
-- *** ROW. *** A 90-day retention with 7-day chunks keeps between 90
-- and 97 days. *** THAT IS CORRECT BEHAVIOUR, NOT A BUG *** - say so
-- in the policy document before someone files it as one.
-- ==================================================================
-- *** THE INTERACTION THAT LOSES DATA. THIS MODULE'S TRAP. ***
-- ==================================================================
-- *** IF RETENTION DROPS RAW CHUNKS THAT A CONTINUOUS AGGREGATE HAS
-- *** NOT YET MATERIALISED, THAT DATA IS GONE FROM BOTH THE RAW
-- *** TABLE AND THE AGGREGATE, PERMANENTLY. ***
--
-- BROKEN:
-- raw retention 7 days
-- telemetry_1m start_offset 30 days
-- -> the policy tries to refresh buckets 8-30 days old
-- *** WHOSE SOURCE ROWS NO LONGER EXIST. *** The aggregate
-- has holes. Nothing errors.
--
-- CORRECT - *** RETENTION ON RAW MUST BE LONGER THAN THE
-- *** AGGREGATE'S start_offset, WITH MARGIN: ***
-- telemetry_1m start_offset 3 days
-- raw retention 90 days (30x margin)
-- telemetry_1m retention 13 months
-- telemetry_1h retention 5 years
-- telemetry_1d retention 10 years
--
-- *** WRITE THAT RELATIONSHIP DOWN NEXT TO BOTH POLICIES, BECAUSE
-- *** THE NEXT PERSON TO SHORTEN RETENTION WILL NOT KNOW IT *** -
-- and the damage is silent and permanent. Verify the ordering:
SELECT hypertable_name, proc_name, config, next_start
FROM timescaledb_information.jobs ORDER BY hypertable_name, proc_name;
Discussion
No questions on this topic yet. Sign in to ask the first one.