Skip to content

Chapter 15 — A Million Door Scans#

Act IV · Chapter 15 Month 6 · 00:00 on the 1st 7 min readDifficulty 3 of 5

Monthly partitions with a safety-net default, and EXPLAIN proof that old months are skipped.

PartitionBy.range()create_partition()default partitionpartition pruning
▶ Run it yourself · examples/114_partitioning_door_events.py
Month 6, 00:00 on the 1st. Every trunk-activated keycard scanner in Lisbon and Porto logs weight, room number, badge code, and timestamp.

Month 6, 00:00 on the 1st. Every trunk-activated keycard scanner in Lisbon and Porto logs weight, room number, badge code, and timestamp.

Maya: One giant door_event table grows by a million rows every month. DELETE FROM door_event WHERE scanned_at < ... causes massive bloat, and June queries keep dragging through May's data.

Panda: Just keep everything in one table and run a big DELETE cron job on Sunday night! Wait… why did autovacuum freeze the lobby?

Ferris: Declarative monthly range partitions. PostgreSQL routes every insert automatically, skips untouched months at query time, and retires old months by dropping one partition in milliseconds.

The mission#

Time-series telemetry like DoorEvent begs for PostgreSQL's built-in declarative partitioning. Maya configures it cleanly in Python:

  1. declare DoorEvent with pg.PartitionBy.range(cls.scanned_at) inside @classmethod def __constraints__(cls),
  2. attach monthly child partitions (door_event_2026_05, door_event_2026_06) plus a safety-net default=True partition so an unexpected future date never fails an insert,
  3. prove with pool.explain() that querying June prunes May completely and scans only door_event_2026_06.

The Panda's plan

Dump every IoT event into one monolithic table forever, then run DELETE FROM door_event WHERE scanned_at < now() - interval '90 days'. That dirties gigabytes of heap and index pages, triggers endless VACUUM I/O, and still leaves bloated indexes behind.

1. Declarative range partitioning with a default catch-all#

door_event PARTITION BY RANGE (scanned_at) door_event_2026_05 pruned door_event_2026_06 scanned door_event_default pruned WHERE scanned_at in June The planner skips partitions that can't match. Old months can be dropped instead of DELETEd.

Look at DoorEvent in examples/schema.py: PostgreSQL requires the partition key (scanned_at) to be part of any primary key on a partitioned table, so pgdorm's strict PK check explicitly allows (door_event_id, scanned_at):

examples/schema.py · DoorEvent
class DoorEvent(pg.Table):
    door_event_id: Col[int] = pg.pk(default=pg.identity())
    scanned_at: Col[datetime] = pg.pk()
    dormitory_id: Col[int] = pg.fk(Dormitory)
    room_number: Col[Code]
    badge_code: Col[str]
    species_code: Col[str]
    granted: Col[bool]
    weight_kg: Col[float]
    tariff_eur: Col[Money]
    tags: Col[list[str]] = pg.col(default_factory=list)

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (pg.PartitionBy.range(cls.scanned_at),)

Now create the monthly partitions, add a catch-all default partition, and insert events spanning May, June, and August:

examples/114_partitioning_door_events.py · setup_partitions_and_events
async def setup_partitions_and_events(pool: pg.Pool, dormitory_id: int) -> None:
    await pool.create_partition(
        DoorEvent,
        name="door_event_2026_05",
        for_values="FROM ('2026-05-01 00:00:00+00') TO ('2026-06-01 00:00:00+00')",
    )
    await pool.create_partition(
        DoorEvent,
        name="door_event_2026_06",
        for_values="FROM ('2026-06-01 00:00:00+00') TO ('2026-07-01 00:00:00+00')",
    )
    await pool.create_partition(
        DoorEvent,
        name="door_event_default",
        default=True,
    )

    # PostgreSQL routes each row transparently to May, June, or the default partition.
    await pool.execute(
        pg.insert_many(
            DoorEvent,
            [
                DoorEvent(
                    scanned_at=datetime(2026, 5, 18, 21, 0, tzinfo=UTC),
                    dormitory_id=dormitory_id,
                    room_number="101",
                    badge_code="MAY-01",
                    species_code="pygmy",
                    granted=True,
                    weight_kg=1850.0,
                    tariff_eur=Decimal("45.00"),
                ),
                DoorEvent(
                    scanned_at=datetime(2026, 6, 12, 8, 30, tzinfo=UTC),
                    dormitory_id=dormitory_id,
                    room_number="304",
                    badge_code="JUN-01",
                    species_code="mammoth",
                    granted=True,
                    weight_kg=8100.0,
                    tariff_eur=Decimal("250.00"),
                ),
                DoorEvent(
                    scanned_at=datetime(2026, 8, 1, 14, 0, tzinfo=UTC),
                    dormitory_id=dormitory_id,
                    room_number="203",
                    badge_code="AUG-DEF",
                    species_code="savanna",
                    granted=True,
                    weight_kg=5400.0,
                    tariff_eur=Decimal("120.00"),
                ),
            ],
        )
    )
    (total,) = await pool.one(pg.select(DoorEvent).columns(pg.count()))
    print(f"routed {total} scans across May, June, and default partitions")
    # => routed 3 scans across May, June, and default partitions

What just happened

  • pool.create_partition(DoorEvent, name=..., for_values=...) attaches typed child tables for May and June 2026.
  • pool.create_partition(DoorEvent, name="door_event_default", default=True) creates a safety net: when the August 1 scan arrives before August's partition exists, PostgreSQL routes it safely into door_event_default instead of throwing an error at midnight on the 1st!
  • Your application code inserts into and queries only DoorEvent — partition routing is 100% transparent.

2. Prove partition pruning with EXPLAIN#

Let's query June scans and inspect the live PostgreSQL plan to confirm May is never even touched:

examples/114_partitioning_door_events.py · verify_partition_pruning
async def verify_partition_pruning(pool: pg.Pool) -> None:
    june_q = (
        pg.select(DoorEvent)
        .where(
            (DoorEvent.scanned_at >= datetime(2026, 6, 1, tzinfo=UTC))
            & (DoorEvent.scanned_at < datetime(2026, 7, 1, tzinfo=UTC))
        )
        .order_by(DoorEvent.scanned_at.asc())
        .tag("examples.partition_june_only")
    )
    june_rows = await pool.all(june_q)
    print("June scans:", [(r.badge_code, r.species_code) for r in june_rows])
    # => June scans: [('JUN-01', 'mammoth')]

    plan = await pool.explain(june_q)
    plan_text = plan.summary()
    pruned_may = "door_event_2026_05" not in plan_text
    hit_june = "door_event_2026_06" in plan_text
    print(f"EXPLAIN pruned May={pruned_may}, scanned June={hit_june}")
    # => EXPLAIN pruned May=True, scanned June=True

What just happened

  • The half-open timestamp range [2026-06-01, 2026-07-01) matches door_event_2026_06 exactly.
  • pool.explain(june_q) proves door_event_2026_05 is pruned out of the execution plan completely (pruned May=True, scanned June=True).
  • When May ages out next year, retiring a million rows is a single metadata-only DROP TABLE door_event_2026_05 (or DETACH PARTITION CONCURRENTLY) — zero bloat, zero vacuum storm.
Ferris' basement: always use half-open [start, end) time bounds

Just like hotel stay dates in Chapter 6, PostgreSQL range partitions are half-open: FROM ('2026-06-01') TO ('2026-07-01') includes 2026-06-01 00:00:00+00 and excludes 2026-07-01 00:00:00+00. Writing (scanned_at >= start) & (scanned_at < next_month) matches the partition boundaries identically and never misses a microsecond at 23:59:59.999999.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 8 statements in 7 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 21 statements omitted · full transcript in examples/__wire__/partitioning_door_events.sql

-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row

-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
  ($1, $2, $3, $4, $5, $6, $7, $8),
  ($9, $10, $11, $12, $13, $14, $15, $16),
  ($17, $18, $19, $20, $21, $22, $23, $24),
  ($25, $26, $27, $28, $29, $30, $31, $32),
  ($33, $34, $35, $36, $37, $38, $39, $40),
  ($41, $42, $43, $44, $45, $46, $47, $48),
  ($49, $50, $51, $52, $53, $54, $55, $56),
  ($57, $58, $59, $60, $61, $62, $63, $64),
  ($65, $66, $67, $68, $69, $70, $71, $72),
  ($73, $74, $75, $76, $77, $78, $79, $80),
  ($81, $82, $83, $84, $85, $86, $87, $88),
  ($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows

-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows

-- ── round trip 4 ──
COMMIT;

-- ── round trip 5 ──
INSERT INTO "door_event" ("scanned_at", "dormitory_id", "room_number", "badge_code", "species_code", "granted", "weight_kg", "tariff_eur", "tags")
VALUES
  ($1, $2, $3, $4, $5, $6, $7, $8, $9),
  ($10, $11, $12, $13, $14, $15, $16, $17, $18),
  ($19, $20, $21, $22, $23, $24, $25, $26, $27);
-- → 3 affected

-- ── round trip 6 ──
SELECT COUNT(*)
FROM "door_event";
-- → 1 row

-- ── round trip 7 ──
SELECT
  "door_event_id",
  "scanned_at",
  "dormitory_id",
  "room_number",
  "badge_code",
  "species_code",
  "granted",
  "weight_kg",
  "tariff_eur",
  "tags"
FROM "door_event"
WHERE "scanned_at" >= $1 AND "scanned_at" < $2
ORDER BY "scanned_at" ASC
/* op:examples.partition_june_only */;
-- → 1 row

Shift report

  • Declared a range-partitioned table (PartitionBy.range("scanned_at"))
  • Created monthly partitions plus a safety-net default=True partition
  • Inserted rows transparently into the parent DoorEvent table
  • Verified with pool.explain() that untouched months are pruned from the query plan

Try it yourself

Add a query for May (2026-05-01 to 2026-06-01) in verify_partition_pruning and assert that door_event_2026_06 is pruned while door_event_2026_05 is scanned.

Go deeper: tests/integration/models/partitioning/test_partitioning.py · tests/integration/plans/test_plans.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"The Polar Bears from the Arctic analytics office just landed. They have a Polars DataFrame of door scans to load AND they want to analyze June's scans in Polars. Do NOT convert rows into Python dicts!"