Skip to main content

14 - Building Sensor Time Series in PostgreSQL

Monthly partitions, a BRIN index and a rollup are enough to keep a hundred sensors in PostgreSQL: the experiment measures sizes, query plans and retention.

What do you think about this article?

14 - Building Sensor Time Series in PostgreSQL
PropTechfedericocalo.dev

At a Glance

Monthly partitions, a BRIN index and a rollup are enough to keep a hundred sensors in PostgreSQL: the experiment measures sizes, query plans and retention.

One hundred sensors, a full year of readings: where you store them and how you chart them

Once the sensors are talking (the format of topics and registers is covered in the article on smart buildings and IoT), the next question is simple and heavy: where do the readings end up, and how do you show last month's chart without reading all of them. The answer of this article is that for one building, or a small portfolio of buildings, plain PostgreSQL is enough, provided you use three tools: time-range partitions, a BRIN index on the time column and a rollup table that keeps sums and counts per hour. In the experiment below, a BRIN index is more than one hundred times smaller than a B-tree and answers the same question in a time of the same order; deleting a month of data costs milliseconds if it is a partition, and a fraction of a second, with the result of freeing not a single byte, if it is a DELETE.

This is about storage and querying, not delivery: how readings arrive, in what order, with what delays and how many duplicates is the subject of the article on the real-time pipeline, from which only date_bin is reused here. I do not demonstrate the performance of TimescaleDB or InfluxDB, which are not installed on the test machine: I describe the features they have and plain PostgreSQL lacks, with sources, without numerical comparisons.

The sample: one hundred invented sensors, a whole year

The data is synthetic, generated with generate_series and a fixed seed. Each sensor produces one reading every ten minutes for the whole of 2025, with a daily cycle of three degrees up or down, an offset specific to the sensor and random noise; about 1% of the readings are missing, as happens when a node loses the network. I chose ten minutes rather than one to keep loading under twenty seconds: with one reading per minute the rows would be ten times as many, and the sizes on this page should be read multiplied accordingly (the ratio between B-tree and BRIN does not change, the absolute times do).

The table is range-partitioned on the ts column: twelve partitions, one per month, created with a loop. Two lines matter. The first is SET timezone = 'UTC': the bounds of a partition are midnight in the session time zone, and my first run, with the Rome time zone, failed with "no partition of relation found" on the last reading of the year, because midnight in Rome is an hour before midnight UTC. The second is ORDER BY t, s in the insert: rows enter in time order, as in real life, and that is the physical order on disk that BRIN depends on.

Table partitioned by month and 5.2 million synthetic readings
SET client_min_messages = warning;
-- Partition bounds are midnight IN THE SESSION TIME ZONE: pin it to UTC.
SET timezone = 'UTC';
DROP TABLE IF EXISTS reading CASCADE;
CREATE TABLE reading (
  sensor_id integer          NOT NULL,
  ts        timestamptz      NOT NULL,
  value     double precision NOT NULL
) PARTITION BY RANGE (ts);

-- One partition per month of 2025, created with a loop.
DO $$
DECLARE m date;
BEGIN
  FOR m IN SELECT generate_series(date '2025-01-01', date '2025-12-01', interval '1 month')::date LOOP
    EXECUTE format('CREATE TABLE reading_%s PARTITION OF reading FOR VALUES FROM (%L) TO (%L)',
                   to_char(m, 'YYYY_MM'), m, (m + interval '1 month')::date);
  END LOOP;
END $$;

-- SYNTHETIC data: 100 sensors, one reading every 10 minutes for all of 2025,
-- daily cycle (+-3 degrees) plus a per-sensor offset plus noise, about 1% of readings missing.
-- Inserted in time order, as they would arrive from the field: this matters for BRIN.
SELECT setseed(0.42) AS seed \gset
INSERT INTO reading
SELECT s, t,
       20 + (s % 5) * 0.4
          + 3 * sin(2 * pi() * (extract(hour FROM t AT TIME ZONE 'UTC') + extract(minute FROM t AT TIME ZONE 'UTC') / 60.0 - 9) / 24)
          + (random() - 0.5)
FROM generate_series(timestamptz '2025-01-01 00:00:00+00', timestamptz '2025-12-31 23:50:00+00', interval '10 minutes') AS t,
     generate_series(1, 100) AS s
WHERE random() > 0.01
ORDER BY t, s;
ANALYZE reading;

SELECT count(*) AS rows, count(DISTINCT sensor_id) AS sensors,
       min(ts) AS first, max(ts) AS last FROM reading;
SELECT pg_size_pretty(sum(pg_relation_size(c.oid))) AS table_size
FROM pg_partition_tree('reading') p JOIN pg_class c ON c.oid = p.relid WHERE p.isleaf;

-- Output:
--   rows   | sensors |         first          |          last
-- ---------+---------+------------------------+------------------------
--  5203479 |     100 | 2025-01-01 00:00:00+00 | 2025-12-31 23:50:00+00
-- (1 row)
--
--  table_size
-- ------------
--  259 MB
-- (1 row)

The output says 5,203,479 rows over 100 sensors, from 2025-01-01 to 2025-12-31 23:50, in 259 MB of tables without indexes. The row count is below the 5,256,000 expected instants precisely because of the 1% of gaps, which we will find again later. One advantage of partitions that shows immediately is that a query for one month touches only that month's partition: the planner discards the others (partition pruning), which in the next plan you can read from the fact that only one table appears. The documentation adds that the benefit applies mostly when the table would otherwise be very large.

B-tree or BRIN on time: 35 MB against 288 kB

The building chart asks for "all sensors, two days". The listing runs it three times on the same June partition: with no index on time, with a B-tree and with a BRIN. A BRIN (Block Range Index) index does not store one entry per row but, for each group of adjacent pages, the minimum and maximum of the column: it is useful when the value is correlated with the physical position in the table, which is exactly the case of an append-only table in time order. The last query of the listing checks it: the correlation of ts in that partition is 1.000, that of sensor_id is 0.023. That is why a BRIN on ts works and a BRIN on sensor_id would be useless.

The same query with no index, with a B-tree and with a BRIN
SET client_min_messages = warning;
SET timezone = 'UTC';
SET max_parallel_workers_per_gather = 0;  -- comparable plans: a single process

-- Typical chart query: all sensors, two days of June.
\echo '=== No index on time ==='
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF)
SELECT sensor_id, avg(value) FROM reading
WHERE ts >= '2025-06-14' AND ts < '2025-06-16' GROUP BY sensor_id;

\echo '=== B-tree on (ts) ==='
CREATE INDEX reading_ts_btree ON reading (ts);
ANALYZE reading;
SELECT pg_size_pretty(sum(pg_relation_size(i.indexrelid))) AS btree_index_size
FROM pg_index i JOIN pg_class c ON c.oid = i.indrelid WHERE c.relname LIKE 'reading\_2025\_%';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF)
SELECT sensor_id, avg(value) FROM reading
WHERE ts >= '2025-06-14' AND ts < '2025-06-16' GROUP BY sensor_id;
DROP INDEX reading_ts_btree;

\echo '=== BRIN on (ts) ==='
CREATE INDEX reading_ts_brin ON reading USING brin (ts);
ANALYZE reading;
SELECT pg_size_pretty(sum(pg_relation_size(i.indexrelid))) AS brin_index_size
FROM pg_index i JOIN pg_class c ON c.oid = i.indrelid WHERE c.relname LIKE 'reading\_2025\_%';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF)
SELECT sensor_id, avg(value) FROM reading
WHERE ts >= '2025-06-14' AND ts < '2025-06-16' GROUP BY sensor_id;

-- Physical correlation is the condition for everything: 1 = rows in time order.
SELECT tablename, attname, round(correlation::numeric, 3) AS correlation
FROM pg_stats WHERE tablename = 'reading_2025_06' AND attname IN ('ts', 'sensor_id');

-- Output:
-- === No index on time ===
--                                                                  QUERY PLAN
-- --------------------------------------------------------------------------------------------------------------------------------------------
--  HashAggregate (actual rows=100 loops=1)
--    Group Key: reading.sensor_id
--    Batches: 1  Memory Usage: 32kB
--    Buffers: shared read=2725
--    ->  Seq Scan on reading_2025_06 reading (actual rows=28496 loops=1)
--          Filter: ((ts >= '2025-06-14 00:00:00+00'::timestamp with time zone) AND (ts < '2025-06-16 00:00:00+00'::timestamp with time zone))
--          Rows Removed by Filter: 399284
--          Buffers: shared read=2725
--  Planning:
--    Buffers: shared hit=137 read=21 dirtied=1
--  Planning Time: 1.025 ms
--  Execution Time: 58.958 ms
-- (12 rows)
--
-- === B-tree on (ts) ===
--  btree_index_size
-- ------------------
--  35 MB
-- (1 row)
--
--                                                                    QUERY PLAN
-- ------------------------------------------------------------------------------------------------------------------------------------------------
--  HashAggregate (actual rows=100 loops=1)
--    Group Key: reading.sensor_id
--    Batches: 1  Memory Usage: 32kB
--    Buffers: shared read=209
--    ->  Index Scan using reading_2025_06_ts_idx on reading_2025_06 reading (actual rows=28496 loops=1)
--          Index Cond: ((ts >= '2025-06-14 00:00:00+00'::timestamp with time zone) AND (ts < '2025-06-16 00:00:00+00'::timestamp with time zone))
--          Buffers: shared read=209
--  Planning:
--    Buffers: shared hit=39 read=1
--  Planning Time: 0.242 ms
--  Execution Time: 9.773 ms
-- (11 rows)
--
-- === BRIN on (ts) ===
--  brin_index_size
-- -----------------
--  288 kB
-- (1 row)
--
--                                                                       QUERY PLAN
-- ------------------------------------------------------------------------------------------------------------------------------------------------------
--  HashAggregate (actual rows=100 loops=1)
--    Group Key: reading.sensor_id
--    Batches: 1  Memory Usage: 32kB
--    Buffers: shared hit=4 read=257
--    ->  Bitmap Heap Scan on reading_2025_06 reading (actual rows=28496 loops=1)
--          Recheck Cond: ((ts >= '2025-06-14 00:00:00+00'::timestamp with time zone) AND (ts < '2025-06-16 00:00:00+00'::timestamp with time zone))
--          Rows Removed by Index Recheck: 11696
--          Heap Blocks: lossy=256
--          Buffers: shared hit=4 read=257
--          ->  Bitmap Index Scan on reading_2025_06_ts_idx (actual rows=2560 loops=1)
--                Index Cond: ((ts >= '2025-06-14 00:00:00+00'::timestamp with time zone) AND (ts < '2025-06-16 00:00:00+00'::timestamp with time zone))
--                Buffers: shared hit=4 read=1
--  Planning:
--    Buffers: shared hit=38
--  Planning Time: 0.210 ms
--  Execution Time: 10.573 ms
-- (16 rows)
--
--     tablename    |  attname  | correlation
-- -----------------+-----------+-------------
--  reading_2025_06 | ts        |       1.000
--  reading_2025_06 | sensor_id |       0.023
-- (2 rows)

Without an index the plan is a Seq Scan on the June partition alone: 2,725 pages read, 399,284 rows discarded, 59 ms. With the B-tree the index weighs 35 MB in total (summed over the twelve partitions) and the pages read drop to 209, with 10 ms. With the BRIN the index weighs 288 kB; the plan is a Bitmap Heap Scan with Heap Blocks: lossy=256, meaning the index points to groups of pages and not rows, and indeed "Rows Removed by Index Recheck: 11696" says the database read 11,696 more rows than necessary and discarded them. The time is 11 ms, the same order as the B-tree. These are the numbers of one run on this machine, with the cache in an uncontrolled state: they are not a benchmark, and the difference between 10 and 11 ms must not be read as a victory of either index.

The trade-off has to be stated in full. The B-tree finds the exact row, whatever the physical order, and is needed for point lookups; the BRIN costs very little in space and in writes but loses precision if the arrival order breaks, for example when devices suddenly redeliver hours of late readings, or after many UPDATEs. For "one sensor, one month" queries you still need an index that starts from sensor_id, for example the primary key (sensor_id, ts), which I did not create in order to keep the comparison on a single column. The documentation also reminds us that on a partitioned table a primary key must include the partition column.

The rollup: store the sum and the count, never the mean

Even with an index, a one-year chart does not need to read every reading. The rollup is a second table with one row per sensor and per hour: count, sum, minimum and maximum. I store the sum and the count and not the mean, for a precise reason: the mean of a month can be derived from sums and counts (adding the sums and dividing by the sum of the counts), but not from the mean of the hourly means, because the hours do not all have the same number of readings. The listing computes June in the three ways.

Hourly rollup table with date_bin and idempotent recomputation
SET client_min_messages = warning;
SET timezone = 'UTC';
DROP TABLE IF EXISTS rollup_hour;
CREATE TABLE rollup_hour (
  sensor_id integer          NOT NULL,
  hour      timestamptz      NOT NULL,
  n         integer          NOT NULL,   -- how many readings contributed
  total     double precision NOT NULL,   -- we store the SUM, not the mean
  min_value double precision NOT NULL,
  max_value double precision NOT NULL,
  PRIMARY KEY (sensor_id, hour)
);

-- Recompute an interval: rerunning it replaces the values, it does not double them.
CREATE OR REPLACE PROCEDURE recompute_rollup(from_ts timestamptz, to_ts timestamptz) LANGUAGE sql AS $$
  INSERT INTO rollup_hour
  SELECT sensor_id,
         date_bin('1 hour', ts, timestamptz '2025-01-01 00:00:00+00') AS hour,
         count(*), sum(value), min(value), max(value)
  FROM reading
  WHERE ts >= from_ts AND ts < to_ts
  GROUP BY 1, 2
  ON CONFLICT (sensor_id, hour) DO UPDATE
    SET n = EXCLUDED.n, total = EXCLUDED.total, min_value = EXCLUDED.min_value, max_value = EXCLUDED.max_value;
$$;

CALL recompute_rollup('2025-01-01', '2026-01-01');
SELECT count(*) AS rollup_rows FROM rollup_hour;
CALL recompute_rollup('2025-06-01', '2025-07-01');   -- second pass over the same month
SELECT count(*) AS rollup_rows_after_second_pass FROM rollup_hour;

-- June: three ways to compute "the average temperature of the month".
SELECT (SELECT avg(value) FROM reading WHERE ts >= '2025-06-01' AND ts < '2025-07-01')            AS mean_from_raw,
       (SELECT sum(total) / sum(n) FROM rollup_hour WHERE hour >= '2025-06-01' AND hour < '2025-07-01') AS mean_from_rollup,
       (SELECT avg(total / n) FROM rollup_hour WHERE hour >= '2025-06-01' AND hour < '2025-07-01')      AS mean_of_means;

-- The one-month chart for one sensor: rows to read.
SELECT (SELECT count(*) FROM reading     WHERE sensor_id = 7 AND ts   >= '2025-06-01' AND ts   < '2025-07-01') AS raw_rows,
       (SELECT count(*) FROM rollup_hour WHERE sensor_id = 7 AND hour >= '2025-06-01' AND hour < '2025-07-01') AS rollup_rows;

-- Output:
--  rollup_rows
-- -------------
--       876000
-- (1 row)
--
--  rollup_rows_after_second_pass
-- -------------------------------
--                         876000
-- (1 row)
--
--    mean_from_raw    | mean_from_rollup  |   mean_of_means
-- --------------------+-------------------+--------------------
--  20.799682908830967 | 20.79968290883107 | 20.799553432104954
-- (1 row)
--
--  raw_rows | rollup_rows
-- ----------+-------------
--      4284 |         720
-- (1 row)

date_bin('1 hour', ts, origin) groups readings into one-hour windows aligned to a fixed origin (the same function as in the article on the pipeline: here it is only used to create the key). The clause ON CONFLICT ... DO UPDATE SET n = EXCLUDED.n replaces the values instead of adding them: that is why the second pass over June leaves the rows at 876,000, and why the recomputation can be rerun after a delay without distorting the totals. Adding ("n = rollup_hour.n + EXCLUDED.n") would be faster, but doubles the counts at the first repetition.

The three ways of computing the June mean give 20.7996829 from the raw data, the same figure to the eleventh decimal place from the rollup sums, and 20.7995534 from the mean of the means. The difference is small (about 0.00013 degrees) because the gaps are few and randomly distributed, but it is a systematic error lying in wait: with sensors missing for days it would be large. The monthly chart of one sensor, which with raw data would require 4,284 rows, reads 720 from the rollup: the ratio is about 6 because I have one reading every 10 minutes, with one per minute it would be about 60. The hourly rollup has a limit to know: the current hour is incomplete, so it has to be recomputed (as the procedure does) until it is closed.

Retention: dropping a partition or deleting rows

Raw data from two years ago is rarely needed. The listing removes a month in two ways, on two months of similar size (22 and 20 MB with indexes): January with a DELETE and February by detaching and dropping the partition. The PostgreSQL documentation says that dropping a partition, or detaching it with DETACH PARTITION, is much faster than a bulk delete, and avoids the VACUUM work that follows a DELETE.

Retention with DELETE against DETACH and DROP of a partition
SET client_min_messages = warning;
SET timezone = 'UTC';
SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS size_with_indexes
FROM pg_class WHERE relname IN ('reading_2025_01', 'reading_2025_02') ORDER BY relname;

-- January: row-level retention. The time shown is that of the DELETE alone.
\timing on
DELETE FROM reading WHERE ts < '2025-02-01';
\timing off
SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS size_after_delete
FROM pg_class WHERE relname = 'reading_2025_01';

-- February: partition-level retention. The time is that of DETACH plus DROP.
\timing on
ALTER TABLE reading DETACH PARTITION reading_2025_02;
DROP TABLE reading_2025_02;
\timing off
SELECT count(*) AS partitions_left FROM pg_partition_tree('reading') WHERE isleaf;

-- The rollup outlives the raw data: February can still be read.
SELECT count(*) AS february_rollup_rows FROM rollup_hour WHERE hour >= '2025-02-01' AND hour < '2025-03-01';

-- Output:
--      relname     | size_with_indexes
-- -----------------+-------------------
--  reading_2025_01 | 22 MB
--  reading_2025_02 | 20 MB
-- (2 rows)
--
-- Time: 613.093 ms
--      relname     | size_after_delete
-- -----------------+-------------------
--  reading_2025_01 | 22 MB
-- (1 row)
--
-- Time: 5.132 ms
-- Time: 9.624 ms
--  partitions_left
-- -----------------
--               11
-- (1 row)
--
--  february_rollup_rows
-- ----------------------
--                 67200
-- (1 row)

January's DELETE took 613 ms and, right after, the partition still occupies 22 MB: the rows are only marked dead, the space becomes reusable by VACUUM and returns to the operating system only with a VACUUM FULL (apart from empty pages at the end of the table). DETACH plus DROP of February took about 15 ms in all (5 and 10 ms), and the 20 MB are freed at once. The price is a lock: DROP TABLE of a partition requires an ACCESS EXCLUSIVE lock on the parent table, and DETACH PARTITION CONCURRENTLY reduces it to a less invasive one, with the restrictions described in the documentation. Note the last row too: the February rollup, 67,200 rows, is intact. The pattern is this: raw data for a few months, rollup for years, and a procedure that first recomputes the month's rollup and then drops the partition.

When a reading is missing: finding the gaps

A sensor that goes silent produces no rows, so the gap is not found by looking at the data but by comparing it with what was expected. The listing generates the grid of expected ten-minute instants with generate_series and runs a LEFT JOIN against the readings: where the right side is empty, the reading is missing.

Expected instants against readings present
SET client_min_messages = warning;
SET timezone = 'UTC';
-- Which expected instants (one reading every 10 minutes) are missing for sensor 7 on 15 June?
SELECT expected AS missing_minute
FROM generate_series(timestamptz '2025-06-15 00:00:00+00', timestamptz '2025-06-15 23:50:00+00', interval '10 minutes') AS expected
LEFT JOIN reading r ON r.sensor_id = 7 AND r.ts = expected
WHERE r.ts IS NULL
ORDER BY expected;

-- How many gaps over the whole of 2025, and how many would I expect with 1% loss?
SELECT count(*) AS total_expected_instants,
       count(*) - (SELECT count(*) FROM reading) AS missing_readings,
       round(100.0 * (count(*) - (SELECT count(*) FROM reading)) / count(*), 2) AS percentage
FROM generate_series(timestamptz '2025-01-01 00:00:00+00', timestamptz '2025-12-31 23:50:00+00', interval '10 minutes') AS expected,
     generate_series(1, 100) AS s;

-- Output:
--      missing_minute
-- ------------------------
--  2025-06-15 12:20:00+00
-- (1 row)
--
--  total_expected_instants | missing_readings | percentage
-- -------------------------+------------------+------------
--                  5256000 |            52521 |       1.00
-- (1 row)

For sensor 7 on 15 June a single reading is missing, the one at 12:20. Over the year 52,521 are missing out of 5,256,000, that is 1.00%: the figure the data was generated with, and therefore proof that the check finds what is there. The query declares the expected step (ten minutes) inside the code, and that is the fragile point: a sensor with a variable step or event-driven sampling produces false gaps. In that case you count how much time passes between one reading and the next and flag it when it exceeds a threshold, and the threshold is decided by whoever knows the sensor.

What plain PostgreSQL does not do, and where the others are

Everything I have shown I had to write myself: the rollup procedure, the creation of future months' partitions, the retention loop. A database specialised in time series offers them as functions. TimescaleDB, which is a PostgreSQL extension, describes in its documentation continuous aggregates, that is materialized views refreshed by an automatic policy, and real-time aggregation, which combines the pre-aggregated data with the most recent readings. For InfluxDB I have not read the documentation on retention and I do not write about it. I measured neither of the two, so there is no performance comparison.

The criterion for choosing is organisational before it is technical. If you already have PostgreSQL and data in the order of tens of millions of rows, partitions, BRIN and a rollup you write in one page are enough, and you have one system fewer to run. If the readings are billions, or you need dozens of different aggregations maintained by a declarative policy, the specialised tool saves work that would otherwise become yours. Of one thing only I am sure: you will not find the threshold in this article, you will find it by measuring your own data.

Where it fits in the series

The data described here is what the wear detector of the article on property management and agents reads to compute its statistics, and the range query with the gaps flagged is what it needs to avoid mistaking a silent sensor for a fault. Event times, delays and windows are in the article on the real-time data pipeline; the format of topics and readings is in smart buildings and IoT.

Previous in the series: 13. The Listing Map: Vector Tiles with PostGIS. Next in the series: 15. Listing Events: Outbox, Offsets and Exactly-Once.

What you can do now

You can create a readings table partitioned by month and say why the bounds depend on the session time zone. You can choose between B-tree and BRIN by looking at the physical correlation of the column, and read in the plan lossy and "Rows Removed by Index Recheck" to understand what the BRIN costs you. You can build a rollup that is recomputed without distorting the totals, you know why the mean is derived from sum and count, and you can remove old data by detaching a partition instead of deleting rows. You can also find the gaps, and you know where plain PostgreSQL ends and a database made for time series begins.

Sources

The five SQL listings were run on 2026-11-12 on PostgreSQL 17.10, in a temporary cluster that was then deleted, in the order 01, 02, 03, 04, 05. The data is generated with a fixed seed; rows, bytes and milliseconds are those of a single run on this machine, not a benchmark.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects