Chunk Exclusion, EXPLAIN, Batch Ingestion and Aggregate Performance

Article · 8:00

Diagnosing queries by reading chunk exclusion and buffers, chunk sizing effects, parallel ingestion, aggregate performance, and the PostgreSQL settings that matter here.

Everything you know about PostgreSQL performance applies, and this module is mostly about where TimescaleDB adds a layer to look at. That layer is chunk exclusion, and the discipline is: before theorising about a slow query, read the plan and count the chunks it touched.

EXPLAIN (ANALYZE, BUFFERS) is the instrument. The Append node over chunks tells you how many were scanned; BUFFERS tells you how much was read and whether it came from cache; and planning time, reported separately, tells you whether you have too many chunks. That last number is the one people skip, and with thousands of chunks it can exceed execution time several times over.

The failure modes have a short list and it is worth memorising, because nearly every slow TimescaleDB query is on it:

  • No time predicate - every chunk. The commonest cause, and often hidden inside a view or an ORM-generated query.
  • A time predicate the planner cannot evaluate - a VOLATILE function, a non-immutable expression, a value arriving through a join. Mark functions STABLE, pass parameters, or materialise the bound into a variable first.
  • A time predicate on the wrong column - filtering on trip_start when the hypertable is partitioned on time excludes nothing. The planner has no idea the two correlate, and you must supply both predicates.
  • segmentby not matching the filter on compressed chunks - decompressing everything, which the plan shows as a DecompressChunk node doing enormous work.
  • Aggregating raw data where an aggregate exists - the plan is perfect and the query is still slow because it is touching billions of rows. The fix is not a plan fix.
  • A missing composite index, so each chunk is sequentially scanned - visible as a Seq Scan under the Append.

Parallel query works and is worth configuring. TimescaleDB can scan chunks in parallel, which makes large aggregates substantially faster, and the relevant settings are the ordinary PostgreSQL ones: max_parallel_workers_per_gather, max_parallel_workers, and the cost settings that make the planner willing to use them. Verify with the plan that workers were actually launched, because a plan can request workers it does not get.

The PostgreSQL settings that matter most here are the ones a time-series workload stresses differently: shared_buffers and effective_cache_size for the chunks you want resident; work_mem for sorting and hash aggregation, which large GROUP BYs consume per node and per worker; max_wal_size for a write-heavy workload, because too small means constant checkpointing; and autovacuum settings - a time-series workload that only inserts produces few dead tuples but still needs vacuum for the visibility map and for freezing, and the chunk structure means many small tables for autovacuum to get around. The project's own tuning tool is a reasonable starting point and not a substitute for measuring.

Benchmarking honestly is the same discipline as elsewhere, with two TimescaleDB specifics: run long enough that compression and continuous aggregate policies have actually executed, because a benchmark on uncompressed, unaggregated data measures a database you will not be running; and include the planning time in your numbers, since it is part of the latency your users see.

Laboratory exercise 4 - a measured improvement, with the plans.

Load at least 1 billion telemetry rows across 10,000 vehicles, with compression and continuous aggregate policies configured and allowed to run to completion.

Declare a baseline: eight representative queries with p50, p95 and p99 and the planning time separately, plus the buffer counts and chunks touched for each.

Then work the failure list. Produce every item on it deliberately, capture the plan, fix it, and capture the plan again. The wrong-column case and the VOLATILE function case are the two that matter most in practice; do them carefully.

Measure the chunk interval effect on the full workload - not just on inserts as in Module 1, but on all eight queries plus compression ratio and planning time, at three intervals.

Measure parallel query: the same large aggregate with max_parallel_workers_per_gather at 0, 2, 4 and 8, verifying from the plan that the workers were launched each time.

Tune work_mem with evidence: find a query that spills to disk, show the spill in the plan, raise work_mem until it does not, and then state the memory arithmetic - work_mem times nodes times workers times connections - that makes a high global value dangerous.

Measure ingestion again under the real workload: concurrent COPY against a table that has indexes, foreign keys, compression and aggregate policies all active, and compare with Module 1's clean-table number.

Deliverable: the baseline including planning time, the six failure modes with before-and-after plans, the chunk interval effect on the full workload, the parallel query measurements, the work_mem evidence with the memory arithmetic, the realistic ingestion number against the clean-table one, and one change that did not help.

-- ==================================================================
-- *** THE INSTRUMENT. And the discipline: BEFORE THEORISING ABOUT A
-- *** SLOW QUERY, READ THE PLAN AND COUNT THE CHUNKS. ***
-- ==================================================================
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT time_bucket(INTERVAL '1 hour', time) AS h, AVG(speed_kph)
FROM vehicle_telemetry
WHERE vehicle_id = 4471 AND time >= now() - INTERVAL '7 days'
GROUP BY h ORDER BY h;
--
-- WHAT TO READ, in order:
--   Append (N chunks)      <- *** CHUNK EXCLUSION. The first number
--                             to look at. ***
--   Index Scan / Seq Scan  <- is the composite index being used?
--   DecompressChunk        <- how much is being decompressed?
--   Buffers: shared hit=.. read=..   <- cache or disk
--   *** Planning Time: .. ms *** <- REPORTED SEPARATELY, and THE
--                             NUMBER PEOPLE SKIP. With thousands of
--                             chunks it can EXCEED EXECUTION TIME
--                             SEVERAL TIMES OVER.
--   Execution Time: .. ms

-- ==================================================================
-- *** THE FAILURE LIST. Memorise it: nearly every slow TimescaleDB
-- *** query is on it. ***
-- ==================================================================

-- (1) *** NO TIME PREDICATE *** - every chunk. The commonest cause,
--     and OFTEN HIDDEN INSIDE A VIEW OR AN ORM-GENERATED QUERY:
EXPLAIN SELECT AVG(speed_kph) FROM vehicle_telemetry WHERE vehicle_id = 4471;
--   -> Append (365 chunks). Add the range. Always.

-- (2) *** A TIME PREDICATE THE PLANNER CANNOT EVALUATE: ***
EXPLAIN SELECT AVG(speed_kph) FROM vehicle_telemetry
WHERE time >= window_start();                 -- VOLATILE -> no exclusion
--   FIX: mark it STABLE, pass a PARAMETER ($1), or materialise the
--        bound into a variable first.

-- (3) *** A TIME PREDICATE ON THE WRONG COLUMN *** - the subtle one:
EXPLAIN SELECT AVG(t.speed_kph) FROM vehicle_telemetry t
JOIN trips tr ON tr.trip_id = t.trip_id
WHERE tr.started_at >= now() - INTERVAL '1 day';
--   -> *** EVERY CHUNK. *** The hypertable is partitioned on `time`,
--      and *** THE PLANNER HAS NO IDEA THAT started_at AND time
--      CORRELATE. YOU MUST SUPPLY BOTH PREDICATES: ***
EXPLAIN SELECT AVG(t.speed_kph) FROM vehicle_telemetry t
JOIN trips tr ON tr.trip_id = t.trip_id
WHERE tr.started_at >= now() - INTERVAL '1 day'
  AND t.time        >= now() - INTERVAL '1 day'      -- *** ADD THIS ***
  AND t.time        <  now() + INTERVAL '1 hour';
--   -> 2 chunks. This one costs people weeks.

-- (4) *** segmentby NOT MATCHING THE FILTER *** on compressed chunks:
--     the plan shows a DecompressChunk node doing ENORMOUS work.
--     Fix the segmentby (Module 3), not the query.

-- (5) *** AGGREGATING RAW DATA WHERE AN AGGREGATE EXISTS *** - the
--     plan is PERFECT and the query is still slow, because it is
--     touching billions of rows. *** THE FIX IS NOT A PLAN FIX: ***
--       raw, 1 year    31,536,000,000 rows   timed out
--       telemetry_1d        3,650,000 rows        91 ms
--     Point the dashboard at the right level.

-- (6) A MISSING COMPOSITE INDEX -> a Seq Scan under the Append.

-- ==================================================================
-- PARALLEL QUERY: ordinary PostgreSQL settings, real effect.
-- ==================================================================
SET max_parallel_workers_per_gather = 4;
SET max_parallel_workers = 8;
EXPLAIN (ANALYZE) SELECT vehicle_id, AVG(speed_kph)
FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '30 days' GROUP BY vehicle_id;
--   -> Gather  Workers Planned: 4  *** Workers Launched: 4 ***
--   *** VERIFY FROM THE PLAN THAT THE WORKERS WERE ACTUALLY
--   *** LAUNCHED - a plan can REQUEST workers it does not GET *** if
--   the pool is exhausted, and then your measurement is of something
--   else entirely.
--
--   workers   latency
--     0       8,400 ms
--     2       4,300 ms
--     4       2,200 ms
--     8       1,900 ms    <- diminishing; the scan is I/O bound now

-- ==================================================================
-- THE POSTGRESQL SETTINGS A TIME-SERIES WORKLOAD STRESSES
-- DIFFERENTLY.
-- ==================================================================
--   shared_buffers         25% of RAM. Hold the chunks you query.
--   effective_cache_size   ~75% of RAM. Planner guidance only.
--   *** work_mem *** per SORT/HASH node, *** PER WORKER ***:
SET work_mem = '256MB';
EXPLAIN (ANALYZE) SELECT vehicle_id, time_bucket(INTERVAL '1 hour', time) h,
       AVG(speed_kph) FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '90 days' GROUP BY vehicle_id, h;
--   look for: *** "Sort Method: external merge  Disk: 2,180,432kB" ***
--             -> it SPILLED. Raise work_mem and watch it become
--                "quicksort  Memory: 214,096kB".
--   *** AND THE ARITHMETIC THAT MAKES A HIGH GLOBAL VALUE
--   *** DANGEROUS: work_mem x NODES x WORKERS x CONNECTIONS. ***
--     256MB x 3 nodes x 4 workers x 50 connections = 150 GB.
--     *** SET IT PER SESSION FOR THE QUERY THAT NEEDS IT, NOT
--     *** GLOBALLY. ***
--   max_wal_size           too small = CONSTANT CHECKPOINTING on a
--                          write-heavy workload. Watch
--                          pg_stat_bgwriter.checkpoints_req.
--   *** autovacuum *** - an INSERT-ONLY workload produces FEW DEAD
--     TUPLES and *** STILL NEEDS VACUUM for the VISIBILITY MAP (so
--     index-only scans work) and for FREEZING. *** And the chunk
--     structure means MANY SMALL TABLES for autovacuum to get
--     around, so raise max_workers:
--       autovacuum_max_workers = 6
--       autovacuum_naptime = 15s
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
WHERE relname LIKE '_hyper_%' AND n_dead_tup > 10000
ORDER BY n_dead_tup DESC LIMIT 20;

-- ==================================================================
-- *** BENCHMARKING HONESTLY - two TimescaleDB specifics. ***
-- ==================================================================
--   * *** RUN LONG ENOUGH THAT THE COMPRESSION AND CONTINUOUS
--     *** AGGREGATE POLICIES HAVE ACTUALLY EXECUTED. *** A benchmark
--     on UNCOMPRESSED, UNAGGREGATED data measures a database you
--     WILL NOT BE RUNNING:
SELECT job_id, proc_name, hypertable_name, last_run_status,
       last_successful_finish, total_runs, total_failures
FROM timescaledb_information.job_stats ORDER BY job_id;
--   * *** INCLUDE PLANNING TIME IN YOUR NUMBERS *** - it is part of
--     the latency YOUR USERS SEE, and it is where the chunk interval
--     mistake hides.
--
-- And measure ingestion UNDER THE REAL WORKLOAD, not on a clean
-- table:
--   COPY, clean table                                 690,000 rows/s
--   COPY + indexes + FK + compression + CAGG policies 318,000 rows/s
--   -> *** 54%. THE SECOND NUMBER IS THE ONE TO PLAN WITH. ***

SELECT query, calls, mean_exec_time, total_exec_time, rows
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;

Discussion

No questions on this topic yet. Sign in to ask the first one.