The Extension Model, Hypertables, Chunks and Ingestion

Article · 11:00

What the extension adds, creating hypertables, choosing a chunk interval, chunk exclusion, efficient ingestion, and the limits that matter.

TimescaleDB is an extension, not a fork, and that is the most important fact about it. You install it into PostgreSQL, add it to shared_preload_libraries, and CREATE EXTENSION timescaledb. After that your tables are still PostgreSQL tables, your queries are still SQL, your transactions are still PostgreSQL transactions, and psql still works exactly as it did. Everything you know still applies, which is a genuinely different experience from learning any other database in this programme.

A hypertable is a table that is automatically partitioned into chunks by time. You create an ordinary table with a timestamp column, then call create_hypertable. From then on inserts are routed to the chunk covering their timestamp, and new chunks are created as time advances. You continue to INSERT, SELECT, UPDATE and DELETE against the hypertable as though it were one table, because it is one table - the chunks are child tables you normally never name.

What the partitioning buys is three things, and they are the reasons to use this at all. Chunk exclusion: a query with a time predicate skips chunks that cannot contain matching rows, so a query over the last hour reads one chunk instead of a year of data. Smaller indexes: each chunk has its own indexes, so the B-tree you are descending is the size of a chunk rather than the size of the table, which keeps inserts fast as the table grows - and that is precisely the problem a plain PostgreSQL table hits at scale. Cheap retention and compression: dropping or compressing a chunk is a whole-chunk operation rather than a row-by-row one.

The chunk interval is the main tuning decision and it has a real rule of thumb: a chunk's data plus its indexes should fit comfortably in memory - the commonly cited target is that all actively written chunks together occupy no more than about a quarter of available memory. Too large and inserts stop being index-friendly and compression gets unwieldy; too small and you get thousands of chunks, and the planning cost of considering them starts to dominate short queries. The default is seven days, which is right for modest rates and wrong for high ones. Work it out from your ingest rate rather than accepting the default - and know that set_chunk_time_interval affects only chunks created afterwards, so changing it is a forward decision, not a migration.

Ingestion. Ordinary INSERT works and is what most applications use; the throughput ladder is the familiar one: single-row inserts in autocommit at the bottom, multi-row INSERT next, and COPY at the top, usually by an order of magnitude or more. For a steady feed, batched multi-row inserts from a few connections is the practical choice; for a backfill, COPY. Both are ordinary PostgreSQL, and so is the advice about synchronous_commit - relaxing it trades durability for throughput and should be a stated decision rather than a found setting.

The limits to know now, because two of them are architectural: multi-node was deprecated and removed, so horizontal scale-out of a single hypertable is not available - plan to scale up. UPDATE and DELETE on a hypertable work but are ordinary PostgreSQL row operations with ordinary PostgreSQL costs, and they generate dead tuples that autovacuum must clean; time-series workloads that update heavily are fighting the design. Unique constraints and primary keys must include the partitioning column, which is a real schema constraint rather than a technicality. And you inherit PostgreSQL's whole operational surface - vacuum, WAL, connection limits - which is not a criticism but is a thing to staff for.

Laboratory exercise 1 - provision, partition and measure.

Stand up PostgreSQL with TimescaleDB in Docker, recording both versions precisely. Verify the extension loaded and shared_preload_libraries contains it.

Write the ride telemetry generator that the rest of the course depends on: vehicles, trips, positions with latitude and longitude, speed, battery state and discrete events, at a configurable rate, with configurable vehicle cardinality, and the ability to emit points timestamped hours in the past. Everything later needs both knobs.

Then the chunk interval experiment, which is the module's main artefact. Build the same 200 million row dataset four times, with chunk intervals of one hour, one day, seven days and thirty days. For each, record: the number of chunks, the chunk size on disk, the insert rate, the latency of a one-hour query and of a one-month query, and the planning time for a short query. The planning cost of thousands of chunks is visible in that last number and it is the thing people do not expect.

Demonstrate chunk exclusion with EXPLAIN (ANALYZE, BUFFERS): a query with a time predicate, the same query without one, and a query whose time predicate is hidden inside a non-immutable function call. Record how many chunks each one touched.

Measure the ingestion ladder: single-row autocommit, multi-row batches of 100, 1,000 and 10,000, COPY, and COPY from four parallel connections. Then repeat the best one with synchronous_commit = off and state what you traded.

Deliverable: the Docker setup with both versions recorded, the generator as reusable code, the four-way chunk interval comparison with planning time included, the three chunk-exclusion plans, the ingestion ladder, and a stated chunk interval choice with the arithmetic behind it.

-- ==================================================================
-- *** IT IS AN EXTENSION, NOT A FORK. That is the most important
-- *** fact about it: EVERYTHING YOU KNOW STILL APPLIES. ***
-- ==================================================================
--   postgresql.conf:  shared_preload_libraries = 'timescaledb'
CREATE EXTENSION IF NOT EXISTS timescaledb;
SELECT extname, extversion FROM pg_extension WHERE extname = 'timescaledb';
SELECT version();
-- *** RECORD BOTH VERSIONS PRECISELY. *** The compression and
-- continuous-aggregate features have MOVED SUBSTANTIALLY across
-- minor versions, so an answer from two years ago may describe
-- behaviour you do not have.

-- ==================================================================
-- A HYPERTABLE is a table AUTOMATICALLY PARTITIONED INTO CHUNKS BY
-- TIME. It is still one table - you query it as one.
-- ==================================================================
CREATE TABLE vehicle_telemetry (
    time         TIMESTAMPTZ      NOT NULL,
    vehicle_id   INT              NOT NULL,
    trip_id      BIGINT,
    latitude     DOUBLE PRECISION,
    longitude    DOUBLE PRECISION,
    speed_kph    REAL,
    battery_pct  REAL,
    odometer_km  DOUBLE PRECISION
);

SELECT create_hypertable('vehicle_telemetry', by_range('time',
                         INTERVAL '1 day'));
--   older syntax, still common in the wild:
--   SELECT create_hypertable('vehicle_telemetry', 'time',
--                            chunk_time_interval => INTERVAL '1 day');

-- ==================================================================
-- *** WHAT THE PARTITIONING BUYS - the three reasons to use this. ***
-- ==================================================================
-- 1. *** CHUNK EXCLUSION *** - a query with a TIME PREDICATE skips
--    chunks that cannot match. One chunk instead of a year.
-- 2. *** SMALLER INDEXES *** - each chunk has its OWN indexes, so
--    the B-tree you descend is the size of a CHUNK, not the TABLE.
--    This is what keeps inserts fast as the table grows, and it is
--    EXACTLY the problem a plain PostgreSQL table hits at scale.
-- 3. *** CHEAP RETENTION AND COMPRESSION *** - dropping or
--    compressing a CHUNK is a whole-chunk operation, not a
--    row-by-row one.

-- ==================================================================
-- *** THE CHUNK INTERVAL IS THE MAIN TUNING DECISION, and it has a
-- *** REAL RULE OF THUMB: ***
-- ==================================================================
--   *** ALL ACTIVELY WRITTEN CHUNKS TOGETHER SHOULD OCCUPY NO MORE
--   *** THAN ABOUT 25% OF AVAILABLE MEMORY (data + indexes). ***
--
--   TOO LARGE  -> inserts stop being index-friendly; compression
--                 gets unwieldy; retention granularity is coarse
--   TOO SMALL  -> *** THOUSANDS OF CHUNKS, and the PLANNING COST of
--                 considering them dominates short queries *** -
--                 the thing people do not expect
--
--   Work it out from the INGEST RATE, do not accept the default (7
--   days, right for modest rates and wrong for high ones):
--     rate  200,000 rows/s x 180 bytes/row = 36 MB/s
--     1 hour of data                       = 130 GB   -> too large
--     5 minutes of data                    = 10.8 GB  -> plausible
--                                             on a 64 GB machine
--
SELECT set_chunk_time_interval('vehicle_telemetry', INTERVAL '5 minutes');
-- *** THIS AFFECTS ONLY CHUNKS CREATED AFTERWARDS. *** Changing it
-- is a FORWARD decision, not a migration - existing chunks keep
-- their interval.

-- Inspect what you actually have:
SELECT hypertable_name, num_chunks,
       pg_size_pretty(total_bytes) AS total,
       pg_size_pretty(total_bytes / GREATEST(num_chunks,1)) AS per_chunk
FROM timescaledb_information.hypertables h
JOIN LATERAL hypertable_detailed_size(format('%I.%I', h.hypertable_schema,
                                             h.hypertable_name)) s
  ON true;

SELECT chunk_name, range_start, range_end,
       pg_size_pretty(total_bytes) AS size, is_compressed
FROM timescaledb_information.chunks
WHERE hypertable_name = 'vehicle_telemetry'
ORDER BY range_start DESC LIMIT 10;

-- ==================================================================
-- *** THE CHUNK INTERVAL EXPERIMENT - the module's main artefact. ***
-- ==================================================================
--   interval  chunks   per chunk   insert/s   1h query   1mo query   PLANNING
--   1 hour     8,760      24 MB     182,000      11 ms     1,840 ms   *** 94 ms ***
--   1 day        365     580 MB     198,000      14 ms       420 ms         6 ms
--   7 days        52     4.1 GB     174,000      38 ms       310 ms         2 ms
--   30 days       12      17 GB     121,000     140 ms       290 ms         1 ms
--
-- *** READ THE PLANNING COLUMN. *** At 8,760 chunks the PLANNER
-- spends 94 ms deciding which to touch, before executing anything -
-- which is nine times the execution time of the query it is
-- planning. That is the cost of too-small chunks, and it is
-- INVISIBLE unless you look at planning time separately.

-- ==================================================================
-- *** CHUNK EXCLUSION, read in the plan. The diagnostic skill. ***
-- ==================================================================
EXPLAIN (ANALYZE, BUFFERS)
SELECT vehicle_id, AVG(speed_kph)
FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '1 hour'
GROUP BY vehicle_id;
--   -> Append  (1 chunk)      *** EXCLUSION WORKED ***

EXPLAIN (ANALYZE, BUFFERS)
SELECT vehicle_id, AVG(speed_kph) FROM vehicle_telemetry
GROUP BY vehicle_id;
--   -> Append  (365 chunks)   *** NO TIME PREDICATE = EVERY CHUNK ***

-- *** AND THE ONE THAT CATCHES PEOPLE: a time predicate hidden
-- *** inside a NON-IMMUTABLE function call: ***
CREATE FUNCTION window_start() RETURNS TIMESTAMPTZ AS
$$ SELECT now() - INTERVAL '1 hour' $$ LANGUAGE sql VOLATILE;

EXPLAIN (ANALYZE, BUFFERS)
SELECT AVG(speed_kph) FROM vehicle_telemetry WHERE time >= window_start();
--   -> *** every chunk. *** The planner cannot see the value, and a
--      VOLATILE function is re-evaluated per row, so no exclusion.
--      Mark it STABLE, or pass the timestamp as a PARAMETER:
--        WHERE time >= $1
--   *** THIS IS THE SINGLE MOST COMMON CAUSE OF A SLOW TIMESCALEDB
--   *** QUERY, AND THE PLAN SAYS SO IMMEDIATELY. ***

-- ==================================================================
-- INGESTION: the familiar ladder.
-- ==================================================================
--   single-row INSERT, autocommit        ~   3,100 rows/s
--   multi-row INSERT, 100 rows           ~  84,000 rows/s
--   multi-row INSERT, 1,000 rows         ~ 198,000 rows/s
--   multi-row INSERT, 10,000 rows        ~ 221,000 rows/s
--   *** COPY ***                         ~ 690,000 rows/s
--   COPY, 4 parallel connections         ~ 1,840,000 rows/s
--
--   STEADY FEED  -> batched multi-row inserts, a few connections
--   BACKFILL     -> *** COPY ***
COPY vehicle_telemetry (time, vehicle_id, trip_id, latitude, longitude,
                        speed_kph, battery_pct, odometer_km)
FROM '/data/telemetry.csv' WITH (FORMAT csv);
--
-- And the ordinary PostgreSQL advice applies, because it IS
-- PostgreSQL:
--   SET synchronous_commit = off;     -- a DURABILITY trade:
--   -- a committed transaction can be lost on a crash. State it as a
--   -- DECISION rather than leave it as a FOUND SETTING.

-- ==================================================================
-- *** THE LIMITS TO KNOW NOW. Two are architectural. ***
-- ==================================================================
--   * *** MULTI-NODE WAS DEPRECATED AND THEN REMOVED. *** Horizontal
--     scale-out of a single hypertable IS NOT AVAILABLE. Plan to
--     SCALE UP; shard at the application level or use the managed
--     service. Know this BEFORE you design.
--   * *** A UNIQUE CONSTRAINT OR PRIMARY KEY MUST INCLUDE THE
--     *** PARTITIONING COLUMN: ***
--       PRIMARY KEY (vehicle_id, time)        -- fine
--       PRIMARY KEY (reading_id)              -- *** REJECTED ***
--     A real schema constraint, not a technicality.
--   * UPDATE and DELETE WORK, and are ordinary PostgreSQL row
--     operations with ordinary costs and dead tuples for autovacuum
--     to clean. A time-series workload that updates heavily is
--     FIGHTING THE DESIGN.
--   * you inherit PostgreSQL's WHOLE OPERATIONAL SURFACE - vacuum,
--     WAL, connection limits, the planner, a long transaction
--     holding back cleanup. Not a criticism; a thing to STAFF FOR.
--   * *** AND THE RELIEF, if you have come from InfluxDB: HIGH
--     *** CARDINALITY IS NOT A CRISIS HERE. *** A million distinct
--     vehicles is a million values IN A COLUMN, not a million index
--     entries competing for memory. That changes the modelling
--     conversation entirely - see the next topic.

Discussion

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