← back to the blog

Designing a Time-Series Table That Survives Its Own Growth

The dashboard query had been fine for months. Then one Monday it started timing out. The first idea in the channel was a bigger server. That would only have hidden the problem. I had built the table as if it would never get big, and it did.

You need basic SQL and to know what an index is (a sorted lookup list that makes searches fast). The examples are PostgreSQL. You'll be able to design a time-series table with monthly partitions and implement hourly summaries for a dashboard.

The problem: one huge table

Devices send a reading every few seconds. Each reading is one row. The table has an id as primary key and an index on recorded_at. It is the day-one schema, and on day one it is fine.

01_naive_readings.sql
CREATE TABLE readings (
1  id          bigserial PRIMARY KEY,
  device_id   bigint NOT NULL,
  recorded_at timestamptz NOT NULL,
  value       double precision NOT NULL
);

2CREATE INDEX readings_recorded_at_idx ON readings (recorded_at);
  1. No query uses id. Every lookup is by device and time, so it only costs an index and 8 bytes per row.
  2. This index knows about time only. It cannot jump to one device.

Two things hurt as the table grew:

  1. The dashboard asks about one device and a time range, but my index only knew about time.
  2. The nightly job deleted rows older than 90 days, and that was slow and messy.
  1. Askdevice 42, last Tuesday
  2. Index finds Tuesdaythe index is on `recorded_at` only
  3. Read every device's rows from Tuesdaymostly rows I don't need
  4. Keep device 42throw the rest away
An index on `(device_id, recorded_at)` jumps straight to the right rows.
Fireside chat: why not just DELETE?
You
Every night I delete rows older than 90 days. Simple.
Database
Simple for you. I have to find each old row and mark it dead, one by one.
You
But then the space comes back, right?
Database
Vacuum lets me reuse the space later and can sometimes return empty pages at the end of the file to the operating system. Reclaiming free space scattered through the file generally needs a rewrite such as VACUUM FULL, which locks the table.
You
So deleting means work now, and usually leaves the file about the same size.
Database
Right. Keep each month in its own box. Then removing a month means throwing away one box.

The big idea: one notebook per month

Picture one giant notebook where every reading is a line. The time index takes you to last Tuesday, but you still check readings from every device in that range to find yours. Now picture one notebook per month. You open only the months your query needs. When a whole month is old, you throw its notebook away instead of erasing lines one by one. That is partitioning.

Where a reading goes

A device inserts into the readings table. PostgreSQL files the row in the June or July partition by its recorded_at. A rollup job sums each hour into a small summary table, and the dashboard chart reads that summary table.

Device sends a reading
readings (parent table)
June partition
July partition
readings_hourly (summary)
Dashboard chart
  • Device sends a reading → readings (parent table): INSERT
  • readings (parent table) → June partition: recorded_at is in June
  • readings (parent table) → July partition: recorded_at is in July
  • readings (parent table) → readings_hourly (summary): rollup job sums each hour
  • readings_hourly (summary) → Dashboard chart: chart reads the small table
  1. List the queriesdevice + time range; all devices, last hour
  2. Set retentionraw 90 days, rollups longer
  3. Choose the key(device_id, recorded_at)
  4. Partition by timeone partition per month
  5. Add rollupshourly summaries
Retention is a design input. If you decide it last, you end up deleting rows one at a time.

Step 1: change the key

I dropped id and made (device_id, recorded_at) the primary key. Now 'one device, time range' jumps straight to the right rows. It also adds a rule the old table never had: one reading per device per timestamp.

For new data, retried deliveries use ON CONFLICT (device_id, recorded_at) DO NOTHING, which keeps the reading already stored. The old table may already hold duplicates. A plain copy into the new key would fail on them, and ON CONFLICT DO NOTHING with no defined order would keep an arbitrary one. So the migration picks the lowest id on purpose. If your devices can really send two different readings with the same timestamp, keep an extra column in the key.

Step 2: split the table by month

PostgreSQL cannot turn an existing table into a partitioned one. So this is a migration: make a new partitioned table, copy every retained row into it, then swap the names.

  1. Stop writersno new inserts
  2. Let in-flight writes finishdrain
  3. Copy everythingone transaction with the swap
  4. Swap the namesreadings_old / readings
  5. Restart writersagainst the new table
If the copy fails, the transaction rolls back and nothing is swapped.

Don't copy while writers are still running. Row ids are handed out before commit, so a lower-id duplicate can show up after the copy started and lose to a row I already copied. Updates and deletes during the copy would be missed too. The price is a pause as long as the copy takes. Three more things to know:

  • Copy the whole retained range. Rows left in readings_old disappear from the dashboard after the swap.
  • Create, copy and swap run in one transaction, so a failed copy rolls back instead of swapping in a half-empty table.
  • Renaming does not move dependents. Views, foreign keys and grants stay on readings_old, so recreate them on the new table before restarting writers.
02_partitioned_readings.sql
1SET timezone = 'UTC';

2BEGIN;

CREATE TABLE readings_new (
  device_id   bigint NOT NULL,
  recorded_at timestamptz NOT NULL,
  value       double precision NOT NULL,
3  PRIMARY KEY (device_id, recorded_at)
) PARTITION BY RANGE (recorded_at);

-- Check min(recorded_at) and max(recorded_at) on readings first. Add one
-- partition per month until the whole range is covered.
4CREATE TABLE readings_2026_06 PARTITION OF readings_new
  FOR VALUES FROM ('2026-06-01 00:00:00+00') TO ('2026-07-01 00:00:00+00');

CREATE TABLE readings_2026_07 PARTITION OF readings_new
  FOR VALUES FROM ('2026-07-01 00:00:00+00') TO ('2026-08-01 00:00:00+00');

-- Writers stopped and drained. No WHERE clause: a row outside the partitions
-- fails the INSERT and aborts the transaction, so nothing is swapped.
INSERT INTO readings_new (device_id, recorded_at, value)
5SELECT DISTINCT ON (device_id, recorded_at) device_id, recorded_at, value
FROM readings
ORDER BY device_id, recorded_at, id;

6ALTER TABLE readings RENAME TO readings_old;
ALTER TABLE readings_new RENAME TO readings;

COMMIT;
-- Compare readings with the distinct (device_id, recorded_at) pairs in
-- readings_old, spot-check values, then DROP TABLE readings_old.
  1. Offset-free timestamptz bounds depend on the session TimeZone; the explicit +00 bounds here identify the same instants in every session. I keep UTC for consistent display and later hourly bucketing.
  2. Create, copy and swap are one transaction. After a failed statement PostgreSQL rejects the rest and COMMIT rolls back, even in a client like default psql that keeps running after errors.
  3. PostgreSQL requires the partition key to be part of any primary key on a partitioned table. That pushed me toward this composite key.
  4. A query with a recorded_at range only touches the partitions that overlap it. This is partition pruning.
  5. DISTINCT ON with this ORDER BY keeps the lowest id for each duplicate pair, so the surviving reading is the same every time.
  6. The swap is two renames. readings_old stays until you have checked the new table.

Step 3: throw old months away

Once the whole month is past the cutoff, I stop writes to that time range and drain any already in flight, then rebuild all its hourly summaries under the shared rollup lock and detach the partition before resuming ingestion; if rebuilding or detaching fails, writes to that range stay stopped until a successful retry. I permanently reject arrivals for finalized months at ingestion, without recreating their partitions: the rollup lock alone does not stop inserts. That costs far less than deleting rows, but it still takes a short, strong lock. DETACH PARTITION locks the parent table (ACCESS EXCLUSIVE), so it waits for running queries and makes new ones queue behind it. I set a lock_timeout and retry. DETACH PARTITION ... CONCURRENTLY avoids that lock, but it cannot run inside a transaction block and has other limits, so read the docs first. A month goes only when its last day is 90 days old, so rows live between 90 and about 120 days.

03_retention.sql
SET timezone = 'UTC';
1SET lock_timeout = '5s';

-- First stop and drain writes to this month, then successfully rebuild all
-- its hours under the shared rollup lock. Keep range writes stopped through
-- detachment (including retries); permanently reject finalized-month arrivals.
-- readings_2026_06 meets the age check from 2026-09-29 00:00 UTC.
ALTER TABLE readings DETACH PARTITION readings_2026_06;
DROP TABLE readings_2026_06;
  1. While the detach waits for its lock, inserts queue behind it. The timeout limits that wait. After 5 seconds the statement fails, so the scheduler must catch the failure and retry.

Nobody creates next month's partition for you. I create partitions two months ahead from a scheduled job, and I alert if fewer exist.

Step 4: keep a small summary table

The new key and the partitions help the database find rows faster. I changed both together, so I can't say which helped the dashboard query most, and I don't have a before-and-after timing to show you. Compare plans with EXPLAIN on your own workload. But the 'last 30 days, per hour' chart still has to add up every matching raw reading. So I keep the hourly totals in a second table and let the chart read that.

Rows read for a 30-day hourly chart, one device

Assuming one device sends one reading every 10 seconds, 30 days is 259,200 raw rows. The same 30 days as hourly summary rows is 720 rows. The numbers come from that assumed rate, not from a measurement.

Illustrative dataUnit: rows
LabelValue (rows)
Raw readings259200
Hourly summary720

The summary is a second copy of information the raw table already holds. I have to keep the two in agreement. That works only because I treat raw readings as insert-only, late ones included, and remove them only by dropping a partition. If you delete or correct readings, rebuilding a window with this upsert leaves a stale total for any hour whose rows are all gone. An upsert is an insert that updates the row if it already exists.

04_hourly_rollup_table.sql
CREATE TABLE readings_hourly (
  device_id    bigint NOT NULL,
  hour         timestamptz NOT NULL,
1  sum_value    double precision NOT NULL,
  max_value    double precision NOT NULL,
  sample_count integer NOT NULL,
  PRIMARY KEY (device_id, hour)
);
  1. I store the sum and the count, not the average. An average of hourly averages is wrong when hours have different sample counts. Sums and counts combine correctly.

The recurring job is a separate script. Every scheduled run and every manual backfill uses it, with the same lock key. A backfill is the same statement with the 48-hour WHERE swapped for an hour-aligned recorded_at >= start AND recorded_at < end, which keeps the lock and the full-hour rebuild. Before switching the chart to readings_hourly, I must run an initial backfill covering its full historical range (30 days here), with hour-aligned bounds and the same advisory lock, and check that it completes successfully.

05_hourly_rollup_run.sql
1SET timezone = 'UTC';

BEGIN;

-- Every run, scheduled or manual, uses this same key. Take it first.
2SELECT pg_advisory_xact_lock(726001);

INSERT INTO readings_hourly (device_id, hour, sum_value, max_value, sample_count)
SELECT device_id,
       date_trunc('hour', recorded_at),
       sum(value),
       max(value),
       count(*)
FROM readings
3WHERE recorded_at >= date_trunc('hour', now()) - interval '48 hours'
GROUP BY 1, 2
ON CONFLICT (device_id, hour) DO UPDATE SET
  sum_value    = EXCLUDED.sum_value,
  max_value    = EXCLUDED.max_value,
  sample_count = EXCLUDED.sample_count;

COMMIT;
  1. date_trunc('hour', ...) on a timestamptz uses the session TimeZone. The scheduled job must set it too, or its hours can differ from this script's.
  2. An advisory lock is a lock you name yourself, here with a number. It lasts until COMMIT, so a second run waits for the first run's writes.
  3. The window starts on a whole hour and has no upper bound, so the current, partly filled hour is included and the next run replaces it. 48 hours is an example. Set yours from how late your devices really reconnect.

One hour, from arrival to expiry

The life of one hour of readings

One device and one hour, simplified. The values 4, 6 and 5 are invented to show how the state changes. They are not real data.

Step 1 of 5Two readings land

Each reading goes to the partition chosen by its `recorded_at`, not by when it arrived. The rollup has not run yet.

Raw readings, hour 10:00
2 readings: 4, 6
Summary row for hour 10:00
no row yet
Dashboard chart
no point for 10:00

Step-by-step transcript

  1. Two readings land

    Each reading goes to the partition chosen by its `recorded_at`, not by when it arrived. The rollup has not run yet.

    Raw readings, hour 10:00
    2 readings: 4, 6
    Summary row for hour 10:00
    no row yet
    Dashboard chart
    no point for 10:00
  2. The rollup runs

    The job rebuilds the hour from its raw rows and upserts one small row. The chart reads that row, not the raw table.

    Raw readings, hour 10:00
    2 readings: 4, 6
    Summary row for hour 10:00
    sum 10, count 2
    Dashboard chart
    point from the summary
  3. A late reading arrives

    A device reconnects and uploads a reading for 10:00. The raw table is right at once. The summary and the chart are now stale.

    Raw readings, hour 10:00
    3 readings: 4, 6, 5
    Summary row for hour 10:00
    sum 10, count 2 (stale)
    Dashboard chart
    still shows count 2
  4. The next run covers the hour

    The hour is inside the trailing window, so the next run rebuilds it from all three raw rows and the summary catches up.

    Raw readings, hour 10:00
    3 readings: 4, 6, 5
    Summary row for hour 10:00
    sum 15, count 3
    Dashboard chart
    matches the raw table
  5. The month expires

    Once the whole month is past retention, its partition is detached and dropped, with no row-by-row `DELETE`. The raw rows go and the summary stays. That is why it exists.

    Raw readings, hour 10:00
    gone with the partition
    Summary row for hour 10:00
    sum 15, count 3
    Dashboard chart
    still shows the hour

What can go wrong: late readings

The summary is a second copy of the truth, and it can be wrong. A device goes offline, comes back and uploads yesterday's readings. If the job already finished that hour, the chart disagrees with the raw table. That is step 3 above.

My fix is plain: every run rebuilds all the hours in a trailing window, not just the newest one. The window starts on a whole hour, so each hour is rebuilt from all of its raw rows. The upsert alone is not enough. A window that cut an hour in half would overwrite a full sum and count with partial ones. The current hour is the one deliberate exception. It is partial on purpose, and the next run replaces it.

That sets how stale a chart can be. A reading inside the window shows up once the next run finishes successfully. The run interval sets how stale recent hours can get. The window width sets how late a device can be before I have to rerun that range by hand. I would rather tell people the charts are slightly stale than pretend they are exact.

There are no dumb questions
Q: What is a partition, really?
A: A smaller table that PostgreSQL treats as part of a bigger one. You query the parent table, and PostgreSQL looks only in the small tables that can hold your rows.
Q: Why not just add more indexes to the original table?
A: Every index is extra work on every insert, and this table is write-heavy. Indexes also don't help retention: deleting millions of old rows still means visiting and marking each one.
Q: Is a dedicated time-series database the better answer?
A: Sometimes. I stayed on PostgreSQL because the rest of the system already used it and the volume didn't justify a second database. If your volume is much larger, or you need built-in downsampling, evaluate one.
Q: Why monthly partitions?
A: They match retention, because I drop whole months. Daily partitions mean many more tables for the planner, but they keep retention closer to exactly 90 days. Pick the size that matches how you expire data.
Sharpen your pencil
A second dashboard needs 'every device's readings in the last five minutes'. With the primary key (device_id, recorded_at), why is that query usually a poor fit, and what would you check before adding an index to fix it?
Show the answer
Pruning keeps the months that overlap the window. That is usually one month, but two at a month boundary. Inside them the key starts with device_id, which is usually a poor fit for a filter on recorded_at alone when there are many devices. The planner may scan widely, but it is not forced to: PostgreSQL 18 can sometimes use a B-tree skip scan, depending on how many distinct devices there are and on cost. Before adding an index on recorded_at, weigh its write cost on every insert, and look at the real plan with EXPLAIN. A small partition scan may already be fast enough.
Bullet points
  • Design time-series tables from the queries and the retention period, not from an entity diagram.
  • Drop the surrogate key on append-only data when every query filters by device and time. Then decide how duplicates are handled, at ingest and in the historical copy.
  • Partition by time so removing old data is a DROP, not a huge DELETE. Dropping still takes a lock, and monthly partitions keep rows at least 90 days, not exactly 90.
  • Migrate by copying the whole retained range with writers paused, in one transaction. The swap does not carry views, foreign keys or grants over.
  • Create partitions ahead of time and alert on it. A missing partition makes inserts fail.
  • Keep hourly summaries as stored derived data: sums and counts, whole hours rebuilt from raw rows, and one advisory lock for every run. That assumes raw readings are only inserted. Be honest about how stale the charts can be.

Cite this article

Mohamed Hosny, “Designing a Time-Series Table That Survives Its Own Growth”, www.mohamed-hosny.dev, . https://www.mohamed-hosny.dev/blog/understanding-database-design

Referencing this? Please credit Mohamed Hosny and link to the original page.

Keep reading

More from the notebook