Skip to content

Chapter 9 — The Endless Guest List#

Act III · Chapter 9 Month 2 · 20:15 7 min readDifficulty 3 of 5

Page 10,000 is as fast as page 1, and the planner's index choice is asserted in tests.

pg.tuple_()keyset paginationexplain()lateral_jsonb()
▶ Run it yourself · examples/121_keyset_pagination_plans.py
Month 2, 20:15. Reception is scrolling past page 400 of the guest directory. The spinner is hypnotic.

Month 2, 20:15. Reception is scrolling past page 400 of the guest directory. The spinner is hypnotic.

Maya: Page 1 takes two milliseconds. Page 10,000 takes two seconds — and when a new guest checks in, half the list shifts and appears twice!

Panda: Just use OFFSET 200000 LIMIT 20! Everybody uses OFFSET!

Ferris: OFFSET 200000 makes PostgreSQL scan and throw away 200,000 rows every single time. Ask for everything after the last row you saw instead.

The mission#

A growing guest directory exposes two silent performance killers: OFFSET pagination and fetching nested child lists with repeated queries. Maya fixes both and adds an automated planner check so neither can regress:

  1. paginate guests with a row-value keyset cursor (last_name, guest_id) > ($1, $2) that stays O(log N) on page 10,000,
  2. prove with pool.explain() that PostgreSQL actually uses the composite (last_name, guest_id) index,
  3. return a dormitory with its nested sorted rooms in one query via pg.lateral_jsonb().

The Panda's plan

SELECT * FROM guest ORDER BY last_name OFFSET 100000 LIMIT 20. PostgreSQL has to walk past all 100,000 skipped rows before returning row 100,001 — and if someone inserts "Aaardvark" while you're reading page 2, the last row of page 2 reappears as the first row of page 3.

1. Keyset pagination that never slows down#

OFFSET 45000 LIMIT 50 WHERE (last_name, guest_id) > cursor reads and throws away 45,000 rows to return 50 slower on every page, and rows shift when guests check in index seek straight to the cursor in idx_guest_directory same speed on page 1 and page 10,000

In examples/schema.py, Guest declares a composite index matching the sort order: pg.Index("last_name", "guest_id") (named deterministically via ix_<8-char-hash>). Adding guest_id as a tie-breaker guarantees a strict total order even when two elephants share a last name (like Pip and Dumbo Kinabatangan).

examples/121_keyset_pagination_plans.py · paginate_guest_directory
async def paginate_guest_directory(pool: pg.Pool) -> None:
    await pool.execute(
        pg.insert_many(
            Guest,
            [
                Guest(
                    email="[email protected]",
                    first_name="Ada",
                    last_name="Amboseli",
                    species=Species.SAVANNA,
                ),
                Guest(
                    email="[email protected]",
                    first_name="Babar",
                    last_name="Celesteville",
                    species=Species.FOREST,
                ),
                Guest(
                    email="[email protected]",
                    first_name="Dumbo",
                    last_name="Kinabatangan",
                    species=Species.PYGMY,
                ),
            ],
        )
    )

    # Page 1: deterministic tie-breaker on `(last_name, guest_id)` matches `idx_guest_directory`.
    page1 = await pool.all(
        pg.select(Guest).order_by(Guest.last_name.asc(), Guest.guest_id.asc()).limit(2)
    )
    print("page 1:", [g.full_name for g in page1])
    # => page 1: ['Ada Amboseli', 'Babar Celesteville']

    # Page 2+: row-value tuple comparison `(last_name, guest_id) > ($1, $2)` stays O(log N)
    # at page 10,000 and never skips/duplicates rows when new guests check in mid-scroll.
    cursor = (page1[-1].last_name, page1[-1].guest_id)
    page2_q = (
        pg.select(Guest)
        .where(pg.tuple_(Guest.last_name, Guest.guest_id) > cursor)
        .order_by(Guest.last_name.asc(), Guest.guest_id.asc())
        .limit(2)
        .tag("examples.guest_keyset_page")
    )
    page2 = await pool.all(page2_q)
    print("page 2:", [g.full_name for g in page2])
    # => page 2: ['Jumbo Kalahari', 'Pip Kinabatangan']

    cursor2 = (page2[-1].last_name, page2[-1].guest_id)
    page3 = await pool.all(
        pg.select(Guest)
        .where(pg.tuple_(Guest.last_name, Guest.guest_id) > cursor2)
        .order_by(Guest.last_name.asc(), Guest.guest_id.asc())
        .limit(2)
    )
    print("page 3:", [g.full_name for g in page3])
    # => page 3: ['Dumbo Kinabatangan', 'Bram Pleistocene']

    dir_idx = next(
        i.name for i in Guest.__pg_resolved_indexes__ if i.columns == ("last_name", "guest_id")
    )
    plan = await pool.explain(page2_q, disable_seqscan=True)
    plan.assert_uses_index(dir_idx)
    print(f"keyset query hit composite index: {dir_idx in plan.summary()}")
    # => keyset query hit composite index: True

What just happened

  • pg.tuple_(Guest.last_name, Guest.guest_id) > cursor compiles to PostgreSQL's native row-value comparison ("last_name", "guest_id") > ($1, $2).
  • Because the tuple order matches idx_guest_directory (last_name, guest_id), PostgreSQL jumps straight into the B-tree at the cursor — page 10,000 does the exact same work as page 1.
  • Notice Pip Kinabatangan (page 2) and Dumbo Kinabatangan (page 3): identical last_name, cleanly split by guest_id with zero skipped or duplicated rows.
  • .tag("examples.guest_keyset_page") appends a trailing /* op:examples.guest_keyset_page */ comment so pg_stat_statements attributes latency straight back to this code path.
  • plan.assert_uses_index("idx_guest_directory") turns the planner's index choice into a real assertion you can run in CI.

2. Nested child JSON with LATERAL#

When an API endpoint wants a dormitory alongside an ordered JSON array of its rooms in a single query without row duplication, pg.lateral_jsonb() builds a correlated LEFT JOIN LATERAL (...) that aggregates child rows inside PostgreSQL:

examples/121_keyset_pagination_plans.py · nested_rooms_with_lateral_jsonb
async def nested_rooms_with_lateral_jsonb(pool: pg.Pool) -> None:
    # LATERAL JSONB aggregates child rooms directly in PostgreSQL without Cartesian bloat.
    q_lat = (
        pg.lateral_jsonb(
            Dormitory,
            Room,
            on=(Dormitory.dormitory_id, Room.dormitory_id),
            fields=[("number", "number"), ("floor", "floor")],
            alias="rooms_json",
            child_order_by=(Room.number.asc(),),
        )
        .where(Dormitory.code == "LIS")
        .tag("examples.dorm_lateral_rooms")
    )
    rows = await pool.all(q_lat)
    raw_rooms = rows[0][-1]
    rooms_list = json.loads(raw_rooms) if isinstance(raw_rooms, str) else raw_rooms
    assert isinstance(rooms_list, list)
    first_three = [r["number"] for r in rooms_list[:3] if isinstance(r, dict)]
    print(f"lateral_jsonb nested {len(rooms_list)} rooms (first 3: {first_three})")
    # => lateral_jsonb nested 12 rooms (first 3: ['101', '102', '103'])

What just happened

  • PostgreSQL collects only the requested Room fields (number, floor), sorted by Room.number.asc(), directly into a JSONB array column (rooms_json).
  • Even if a dormitory has zero rooms, LEFT JOIN LATERAL preserves the parent row with an empty array instead of dropping it.
Ferris' basement: why disable_seqscan=True in explain()?

On a tiny 6-row test table, PostgreSQL's cost planner rightly decides a sequential scan of one 8 KB heap page is cheaper than touching an index page plus a heap page. Passing disable_seqscan=True runs SET LOCAL enable_seqscan = off inside a rolled-back EXPLAIN transaction so you verify that your index is structurally usable (matching columns, operator class, and predicate) without needing to seed a million rows in every unit test.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 10 statements in 9 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/keyset_pagination_plans.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 "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;
-- → 3 affected

-- ── round trip 6 ──
SELECT
  "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"
FROM "guest"
ORDER BY "last_name" ASC, "guest_id" ASC
LIMIT $1;
-- → 2 rows

-- ── round trip 7 ──
SELECT
  "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"
FROM "guest"
WHERE ("last_name", "guest_id") > ($1, $2)
ORDER BY "last_name" ASC, "guest_id" ASC
LIMIT $3
/* op:examples.guest_keyset_page */;
-- → 2 rows

-- ── round trip 8 ──
SELECT
  "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"
FROM "guest"
WHERE ("last_name", "guest_id") > ($1, $2)
ORDER BY "last_name" ASC, "guest_id" ASC
LIMIT $3;
-- → 2 rows

-- ── round trip 9 ──
WITH "_p" AS NOT MATERIALIZED (
SELECT
  "dormitory_id",
  "region_id",
  "code",
  "name",
  "city",
  "country",
  "timezone",
  "check_in",
  "check_out",
  "city_tax",
  "opened_on"
FROM "dormitory"
WHERE "code" = $1
)
SELECT "_p"."dormitory_id", "_p"."region_id", "_p"."code", "_p"."name", "_p"."city", "_p"."country", "_p"."timezone", "_p"."check_in", "_p"."check_out", "_p"."city_tax", "_p"."opened_on", "_lat"."rooms_json"
FROM "_p"
LEFT JOIN LATERAL (
  SELECT COALESCE(jsonb_agg(jsonb_build_object('number', "_c"."number", 'floor', "_c"."floor") ORDER BY "_c"."number" ASC), '[]'::jsonb) AS "rooms_json"
  FROM "room" AS "_c"
  WHERE "_c"."dormitory_id" = "_p"."dormitory_id"
) AS "_lat" ON TRUE
/* op:examples.dorm_lateral_rooms */;
-- → 1 row

Shift report

  • Paginated with row-value keyset cursors (pg.tuple_(...) > cursor)
  • Verified B-tree index usage with pool.explain() and assert_uses_index()
  • Tagged hot queries with .tag() for pg_stat_statements visibility
  • Nested ordered child objects in one query with pg.lateral_jsonb()

Try it yourself

Change the order_by on page2_q to Guest.first_name.asc(), Guest.guest_id.asc() and run the script. Watch plan.assert_uses_index("idx_guest_directory") catch the mismatch immediately.

Go deeper: tests/integration/analytics/test_keyset_and_locks.py · tests/integration/plans/test_plans.py (live PostgreSQL test suites & snapshots)

Note

Also in pgdorm: For general O(W·K) index-backed Top-K per group beyond JSON nesting, compose correlated lateral joins with Select.join_lateral(...) — see Field Note 6 · Search, JSON & Advanced DML.

Sticky note from Management

"I'm working from the harbour café today. The Wi-Fi ping is 15 ms and loading the desk screen takes forever. Fix the round trips!"