time_bucket is the function you will use most, and it is simply date_trunc with an arbitrary interval: it floors a timestamp to a bucket of any width, so five-minute, fifteen-minute and six-hour buckets are as easy as hourly ones. Group by it and you have the standard time-series aggregate. It also takes an offset, which matters for aligning buckets to a business day that does not start at midnight UTC.
Gap filling is the thing plain SQL does badly and time_bucket_gapfill does well. A bucket with no data produces no row, so a chart draws a line across the outage rather than showing it. time_bucket_gapfill generates the missing buckets, and then two companion functions decide what goes in them: locf - last observation carried forward - repeats the previous known value, which is right for a state that persists like a battery percentage or a door position; and interpolate draws a straight line between the known values either side, which is right for a continuous measurement like speed or temperature. Choosing between them, and choosing neither, is a semantic decision about what the absence of data means - and the wrong choice invents readings. A gap-filled locf battery percentage across a four-hour outage asserts the battery did not change for four hours, which may be exactly right or may be hiding a fault.
The relational advantage is the point of this whole database, and this is where you should spend the time. Your telemetry hypertable can carry a foreign key to a vehicles table, and PostgreSQL will enforce it - so telemetry for a vehicle that does not exist cannot be written, which is a guarantee no purpose-built time-series database offers. You can join telemetry to the vehicle registry, the driver table, the maintenance log and the billing tables in one query, with the planner choosing the join strategy. Keep your dimensions normalised in ordinary tables and store only narrow keys in the hypertable: it is smaller, it compresses better, and a vehicle rename is one UPDATE rather than a rewrite of history. That pattern - a narrow hypertable joined to normalised dimensions - is the core schema recommendation of this course.
Indexing. create_hypertable makes a time index automatically. The one you almost always want next is a composite index on (identifier, time DESC), because the characteristic query is "the recent history of one entity" and that index serves it exactly. Each chunk gets its own copy, which is why they stay small. Beyond that, index as you would in PostgreSQL, and remember that every index is a cost on every insert - in an ingest-heavy workload that cost is the one to watch, so justify each index with a query.
And now the cardinality contrast, which is worth stating explicitly because it reverses the previous course's central constraint. In TimescaleDB high cardinality is just data. A million distinct vehicle ids is a million values in an integer column; ten million is ten million. There is no series index to exhaust, no memory ceiling that cardinality consumes, and no reason to avoid putting a trip id or a high-cardinality identifier in a column you filter on. The costs are the ordinary ones - index size, and whether segmentby suits your access pattern once you compress. Space partitioning exists and is generally not recommended for a single node; it was designed for the multi-node architecture that no longer exists, and adding it usually hurts. If you came here from a purpose-built time-series database, this is the freedom to notice.
Laboratory exercise 2 - the schema that uses the database properly.
Design the ride telemetry schema: a narrow hypertable, with vehicles, drivers, trips and maintenance_events as ordinary normalised tables and real foreign keys from the hypertable to the dimensions. Load at least 300 million telemetry rows and a realistic dimension set.
Demonstrate the relational advantage, which is the module's point. Write five queries that a purpose-built time-series database could not answer in one statement: average speed per vehicle model, joining through the vehicle registry; battery degradation per vehicle, correlated with the maintenance log; driver-level aggregates joining through trips; telemetry for vehicles under an active recall, from a recall table; and a billing reconciliation joining trip telemetry to the invoices table. Record which of these would require application-side joining elsewhere, which is the honest comparison.
Demonstrate foreign key enforcement: attempt to insert telemetry for a non-existent vehicle and show it rejected. Then measure what the foreign key costs on the insert path, with and without it, at your target rate - because that is the trade and it should be a number.
Do the gap filling properly. Produce a real outage in the data, then chart the same window four ways: raw with no filling, time_bucket_gapfill with NULLs, with locf, and with interpolate. Write down, for each measurement in your schema, which treatment is correct and why - and include one case where locf would invent a dangerous reading.
Then the cardinality demonstration, to settle the contrast: build the same dataset at 1,000, 100,000, 1 million and 10 million distinct vehicle ids, and record insert rate, query latency, index size and memory. Compare against the previous course's curve.
Finally, the indexing study: baseline with only the time index, then the composite index, then two more, measuring both query latency and insert throughput at each step.
Deliverable: the schema with its foreign keys, the five relational queries with a note on which need application-side joining elsewhere, the foreign key cost measurement, the four-way gap filling comparison with a per-measurement policy, the cardinality curve, and the indexing study with the insert cost of each index.
-- ==================================================================
-- time_bucket: date_trunc with an ARBITRARY interval. The function
-- you will use most.
-- ==================================================================
SELECT time_bucket(INTERVAL '5 minutes', time) AS bucket,
vehicle_id,
AVG(speed_kph) AS avg_speed,
MAX(speed_kph) AS max_speed,
COUNT(*) AS samples
FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '6 hours' -- CHUNK EXCLUSION
GROUP BY bucket, vehicle_id
ORDER BY bucket;
-- With an OFFSET, for a business day that does not start at
-- midnight UTC:
SELECT time_bucket(INTERVAL '1 day', time, INTERVAL '6 hours') AS shift_day,
COUNT(DISTINCT trip_id) AS trips
FROM vehicle_telemetry
WHERE time >= now() - INTERVAL '30 days'
GROUP BY shift_day ORDER BY shift_day;
-- ==================================================================
-- *** GAP FILLING: what plain SQL does badly. ***
-- A bucket with NO DATA produces NO ROW, so a chart draws a LINE
-- ACROSS THE OUTAGE instead of SHOWING it.
-- ==================================================================
SELECT time_bucket_gapfill(INTERVAL '1 minute', time) AS bucket,
AVG(speed_kph) AS raw, -- NULL in gaps
locf(AVG(speed_kph)) AS carried, -- repeat last
interpolate(AVG(speed_kph)) AS interpolated -- straight line
FROM vehicle_telemetry
WHERE vehicle_id = 4471
AND time >= '2026-11-29 08:00Z' AND time < '2026-11-29 20:00Z'
GROUP BY bucket ORDER BY bucket;
-- gapfill REQUIRES an explicit, bounded time range - it has to
-- know which buckets to generate.
-- *** CHOOSING BETWEEN THEM IS A SEMANTIC DECISION ABOUT WHAT THE
-- *** ABSENCE OF DATA MEANS, AND THE WRONG CHOICE INVENTS READINGS: ***
-- battery_pct locf a state that PERSISTS
-- door_open locf a state that PERSISTS
-- speed_kph interpolate a CONTINUOUS measurement
-- latitude interpolate a CONTINUOUS measurement
-- event_count 0 absent genuinely MEANS none
-- fault_code *** NULL *** - *** DO NOT FILL. *** A carried-
-- forward fault code asserts a fault that may have
-- cleared.
--
-- *** AND THE DANGEROUS CASE, worth writing down: *** a locf
-- battery_pct across a FOUR-HOUR OUTAGE asserts THE BATTERY DID NOT
-- CHANGE FOR FOUR HOURS. That may be exactly right - or it may be
-- hiding the fault you are looking for. State the policy PER
-- MEASUREMENT, in the schema documentation.
-- ==================================================================
-- *** THE RELATIONAL ADVANTAGE. THIS IS THE POINT OF THE WHOLE
-- *** DATABASE. ***
-- ==================================================================
CREATE TABLE vehicles (
vehicle_id INT PRIMARY KEY,
vin TEXT UNIQUE NOT NULL,
model_id INT NOT NULL REFERENCES models(model_id),
fleet_id INT NOT NULL REFERENCES fleets(fleet_id),
in_service DATE NOT NULL
);
-- *** A REAL FOREIGN KEY FROM THE HYPERTABLE TO THE DIMENSION, AND
-- *** POSTGRESQL ENFORCES IT: ***
ALTER TABLE vehicle_telemetry
ADD CONSTRAINT fk_vehicle FOREIGN KEY (vehicle_id)
REFERENCES vehicles(vehicle_id);
-- -> telemetry for a vehicle THAT DOES NOT EXIST CANNOT BE
-- WRITTEN. *** NO PURPOSE-BUILT TIME-SERIES DATABASE OFFERS
-- THAT GUARANTEE. ***
-- And measure what it COSTS on the insert path, at your rate:
-- without FK 690,000 rows/s
-- with FK 612,000 rows/s -> 11%. A stated trade.
-- *** FIVE QUERIES A PURPOSE-BUILT TIME-SERIES DATABASE COULD NOT
-- *** ANSWER IN ONE STATEMENT. *** This is the honest comparison:
-- (1) average speed per MODEL, through the registry:
SELECT m.name AS model, time_bucket(INTERVAL '1 day', t.time) AS day,
AVG(t.speed_kph) AS avg_speed, COUNT(DISTINCT t.vehicle_id) AS vehicles
FROM vehicle_telemetry t
JOIN vehicles v ON v.vehicle_id = t.vehicle_id
JOIN models m ON m.model_id = v.model_id
WHERE t.time >= now() - INTERVAL '30 days'
GROUP BY m.name, day ORDER BY day, model;
-- (2) battery degradation CORRELATED WITH THE MAINTENANCE LOG:
SELECT v.vin, me.performed_at, me.kind,
AVG(t.battery_pct) FILTER (
WHERE t.time BETWEEN me.performed_at - INTERVAL '7 days'
AND me.performed_at) AS before_pct,
AVG(t.battery_pct) FILTER (
WHERE t.time BETWEEN me.performed_at
AND me.performed_at + INTERVAL '7 days') AS after_pct
FROM maintenance_events me
JOIN vehicles v ON v.vehicle_id = me.vehicle_id
JOIN vehicle_telemetry t ON t.vehicle_id = me.vehicle_id
WHERE me.performed_at >= now() - INTERVAL '180 days'
AND t.time BETWEEN me.performed_at - INTERVAL '7 days'
AND me.performed_at + INTERVAL '7 days'
GROUP BY v.vin, me.performed_at, me.kind
ORDER BY v.vin, me.performed_at;
-- (3) telemetry for vehicles UNDER AN ACTIVE RECALL:
SELECT v.vin, r.recall_code, AVG(t.speed_kph), MAX(t.speed_kph)
FROM vehicle_telemetry t
JOIN vehicles v ON v.vehicle_id = t.vehicle_id
JOIN recalls r ON r.model_id = v.model_id AND r.status = 'active'
WHERE t.time >= now() - INTERVAL '24 hours'
GROUP BY v.vin, r.recall_code;
-- *** ELSEWHERE, EVERY ONE OF THESE IS AN APPLICATION-SIDE JOIN: ***
-- query the time-series store, query the relational store, join in
-- code, and get the semantics right yourself. Write down which of
-- your five would need that. THAT LIST IS THE ARGUMENT FOR THIS
-- DATABASE.
-- *** THE CORE SCHEMA RECOMMENDATION: A NARROW HYPERTABLE JOINED TO
-- *** NORMALISED DIMENSIONS. ***
-- store only NARROW KEYS in the hypertable:
-- SMALLER on disk, COMPRESSES BETTER, and a VEHICLE RENAME IS
-- ONE UPDATE rather than a rewrite of history.
-- BAD : ... , vehicle_vin TEXT, model_name TEXT, fleet_name TEXT
-- GOOD: ... , vehicle_id INT REFERENCES vehicles(vehicle_id)
-- ==================================================================
-- INDEXING
-- ==================================================================
-- create_hypertable makes the TIME index. The one you almost always
-- want NEXT, because "the recent history of ONE ENTITY" is the
-- characteristic query:
CREATE INDEX ON vehicle_telemetry (vehicle_id, time DESC);
CREATE INDEX ON vehicle_telemetry (trip_id, time DESC)
WHERE trip_id IS NOT NULL; -- partial: smaller
-- Each CHUNK gets its own copy, which is why they stay small.
--
-- *** AND EVERY INDEX IS A COST ON EVERY INSERT. *** In an
-- ingest-heavy workload that is the cost to watch, so JUSTIFY EACH
-- INDEX WITH A QUERY:
-- indexes insert/s "one vehicle, last hour"
-- time only 690,000 2,100 ms
-- + (vehicle_id, time DESC) 612,000 4 ms
-- + 2 more 441,000 4 ms <- *** paid 28%
-- of ingest for
-- NOTHING on
-- this query ***
-- ==================================================================
-- *** THE CARDINALITY CONTRAST - it REVERSES the previous course's
-- *** central constraint. ***
-- ==================================================================
-- *** IN TIMESCALEDB, HIGH CARDINALITY IS JUST DATA. *** A million
-- distinct vehicle ids is A MILLION VALUES IN AN INTEGER COLUMN.
-- NO series index to exhaust.
-- NO memory ceiling that cardinality consumes.
-- *** NO REASON TO AVOID PUTTING A TRIP ID OR ANY
-- *** HIGH-CARDINALITY IDENTIFIER IN A COLUMN YOU FILTER ON. ***
--
-- distinct ids insert/s query p95 index size
-- 1,000 690,000 4 ms 2.1 GB
-- 100,000 681,000 5 ms 2.4 GB
-- 1,000,000 664,000 6 ms 2.9 GB
-- 10,000,000 638,000 9 ms 4.1 GB
-- -> *** COMPARE THAT WITH THE INFLUXDB CURVE. *** The costs here
-- are the ORDINARY ones: index size, and whether `segmentby`
-- suits your access pattern once you compress (Module 3).
--
-- *** SPACE PARTITIONING EXISTS AND IS GENERALLY NOT RECOMMENDED FOR
-- *** A SINGLE NODE *** - it was designed for the multi-node
-- architecture that NO LONGER EXISTS, and adding it usually hurts.
-- SELECT add_dimension('vehicle_telemetry',
-- by_hash('vehicle_id', 4)); -- don't, usually
Discussion
No questions on this topic yet. Sign in to ask the first one.