Video in progress
How do you design storage and cleanup for an audit/event table that receives 50 million records a day?
I use time-based range partitioning (daily or weekly), create the partitions ahead of time automatically, and clean up old data with DETACH/DROP PARTITION, not DELETE. Indexes are kept minimal, and old partitions go to cheap storage or an archive.
📖 Answer
50 million a day is about 18 billion rows a year. DELETE FROM event WHERE created_at < now() - interval '90 days' doesn't work at this volume: millions of dead rows, huge WAL, a vacuum storm, replica lag.
The design:
CREATE TABLE audit_event (
id bigint NOT NULL,
created_at timestamptz NOT NULL,
actor_id bigint,
action text,
data jsonb
) PARTITION BY RANGE (created_at);
-- daily partitions, pg_partman or my own scheduled job creates them 7 days ahead
Retention:
ALTER TABLE audit_event DETACH PARTITION audit_event_2026_08_01 CONCURRENTLY; -- PG14+
-- if needed: archive to S3 with pg_dump / COPY TO
DROP TABLE audit_event_2026_08_01;
That's a metadata operation: seconds, no dead rows.
Other decisions and their reasons:
- Partition size. Daily gives precise retention, but 730 partitions in 2 years. For planning time I try not to go beyond a few hundred; if you keep data longer, merge old days into monthly ones or pick weekly.
- Minimal indexes. Every index raises the insert cost. Usually
(actor_id, created_at)and nothing else. For scans by time, a BRIN index is very cheap and small. - Primary key. If you don't need global uniqueness, either no PK at all, or
(id, created_at). - Write path. Batch inserts or
COPYfrom the application; if synchronous auditing slows the main transaction, make it asynchronous through an outbox or a queue. - Default partition. If there is one, creating a new partition slows down because it has to check the rows that landed in it; if there isn't, inserts fail when a partition wasn't created. I work without a default, but with an alert for "does tomorrow's partition exist".
If the queries are mostly analytical, moving old data out to a columnar store (ClickHouse and the like) takes load off Postgres.
Sign up to mark studied questions and save your progress.