Database & Performance··2 min read

PostgreSQL Partitioning at Scale: Declarative Range Partitioning and pg_partman for Multi-TB Audit Logs

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

PostgreSQL Partitioning at Scale: Declarative Range Partitioning and pg_partman for Multi-TB Audit Logs

Why Bulk DELETE Statements Paralyze Large PostgreSQL Tables

In PostgreSQL's MVCC storage engine, DELETE does not immediately free disk space. Deleting 40 million expired audit log rows marks 40 million tuples as dead, writes gigabytes of WAL traffic, and forces autovacuum to scan the entire table and all of its B-Tree indexes.

Even worse, once a single unpartitioned B-Tree index exceeds available RAM, random index insertions across UUIDs cause continuous disk page thrashing.


1. Declarative Monthly Range Partitioning

By partitioning append-only tables (audit_events, webhook_deliveries, telemetry_logs) by RANGE (created_at), each month's data and indexes live in a compact, self-contained physical table:

CREATE TABLE audit_events (
    id UUID NOT NULL,
    tenant_id UUID NOT NULL,
    actor_id UUID NOT NULL,
    action_type VARCHAR(64) NOT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL,
    PRIMARY KEY (created_at, id)
) PARTITION BY RANGE (created_at);

CREATE TABLE audit_events_2026_11 PARTITION OF audit_events
    FOR VALUES FROM ('2026-11-01 00:00:00+00') TO ('2026-12-01 00:00:00+00');

CREATE INDEX idx_audit_events_2026_11_tenant
    ON audit_events_2026_11 (tenant_id, created_at DESC);

2. Partition Pruning and Zero-Bloat Retention Drops

  1. Automatic Partition Pruning: When a tenant queries the last 7 days of audit logs (WHERE created_at >= NOW() - INTERVAL '7 days'), the PostgreSQL planner completely ignores older monthly partitions and scans only the current hot partition in RAM.
  2. 4-Millisecond Retention Cleanup: Instead of running DELETE, archiving a 90-day-old partition uses ALTER TABLE audit_events DETACH PARTITION audit_events_2026_07 CONCURRENTLY followed by DROP TABLE, freeing gigabytes of disk space instantaneously with zero dead tuples and zero autovacuum overhead.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles