Skip to content

Chapter 10 — Harbour Wi-Fi#

Act III · Chapter 10 Month 2 · 07:45 7 min readDifficulty 4 of 5

BEGIN, two inserts and COMMIT in a single round trip, even over terrible Wi-Fi.

pipeline()currval()pg.prepare()read_only()stream()
▶ Run it yourself · examples/124_pipelining_prepared_stream.py
Month 2, 07:45. The harbour café serves great espresso and 15-millisecond Wi-Fi.

Month 2, 07:45. The harbour café serves great espresso and 15-millisecond Wi-Fi.

Maya: Loading the desk sends three SELECTs. Creating a booking with an opening charge sends BEGIN, INSERT booking, INSERT charge, COMMIT — four round trips! Over this link that's 60 ms just waiting on air.

Panda: Just buy faster Wi-Fi! Or cache everything in a second database!

Ferris: Hold my claws. PostgreSQL's wire protocol lets us pack all of those into a single Sync. One round trip total.

The mission#

Network latency multiplies every sequential await. Over a 15 ms link, four round trips cost 60 ms even if PostgreSQL finishes in 0.4 ms. Maya applies four wire-level superpowers:

  1. Read pipelining (pool.pipeline()): load the dormitory, its 12 rooms, and all guests in 1 RTT.
  2. Write pipelining (tx.pipeline(commit=True) + pg.currval()): send BEGIN, INSERT booking, INSERT charge, and COMMIT in 1 RTT — without waiting for the booking ID to come back first!
  3. Compile-once prepared queries & ReadPool: compile a hot query once at import time (pg.prepare()) and route reads through pool.read_only().
  4. Server-side portal streaming (ro.stream()): iterate large results in fixed chunks without buffering the entire table in Python memory.

The Panda's plan

tests/unit/docs/test_doc_guide_snippets.py · story10_panda_tx
async with pool.transaction() as tx:  # RTT 1: BEGIN
    b = await tx.one(insert_booking)  # RTT 2: INSERT booking
    c = await tx.one(insert_charge)  # RTT 3: INSERT charge
    # RTT 4: COMMIT

Four sequential network round trips for two tiny inserts — and on a busy API server, holding a pooled connection idle across four network waits ties up pool capacity for ~4× as long per request when network latency dominates.

1. Three queries, one network trip#

The Panda's way: 4 round trips pgdorm pipeline: 1 round trip app PostgreSQL app PostgreSQL BEGIN INSERT booking INSERT charge COMMIT 4 × 15 ms Wi-Fi = 60 ms BEGIN INSERT booking INSERT charge … currval() COMMIT Sync all results come back together 1 × 15 ms = 15 ms 4× faster

pool.pipeline() queues every query into one wire buffer and sends a single Sync when the async with block exits:

examples/124_pipelining_prepared_stream.py · load_desk_in_one_rtt
async def load_desk_in_one_rtt(pool: pg.Pool, dorm_id: int) -> None:
    # Pipeline three independent queries into one TCP flush / Sync = 1 single round trip.
    async with pool.trace() as tr, pool.pipeline() as pipe:
        h_dorm = pipe.add(pg.select(Dormitory).where(Dormitory.dormitory_id == dorm_id))
        h_rooms = pipe.add(
            pg.select(Room).where(Room.dormitory_id == dorm_id).order_by(Room.number.asc())
        )
        h_guests = pipe.add(pg.select(Guest).order_by(Guest.guest_id.asc()))

    dorm = h_dorm.one()
    print(
        f"desk loaded {dorm.code}: {len(h_rooms.all())} rooms, "
        f"{len(h_guests.all())} guests in {tr.rtts} RTT"
    )
    # => desk loaded LIS: 12 rooms, 3 guests in 1 RTT

What just happened

  • pipe.add(...) registers each query and hands back a typed handle (h_dorm, h_rooms, h_guests). Nothing hits the network until the with block exits.
  • On exit, Ferris flushes all three statements under one Sync (tr.rtts == 1), then populates every handle with its hydrated results.

2. BEGIN + parent + child + COMMIT in 1 RTT#

Normally you can't pipeline a child insert behind a parent insert because you don't know the parent's auto-generated primary key yet. pg.currval(Booking.booking_id) solves that inside PostgreSQL itself:

examples/124_pipelining_prepared_stream.py · book_and_bill_in_one_rtt
async def book_and_bill_in_one_rtt(pool: pg.Pool, dorm_id: int, guest_id: int) -> None:
    # BEGIN + INSERT booking + INSERT charge referencing currval(booking_id) + COMMIT = 1 RTT!
    async with pool.trace() as tr, pool.transaction() as tx, tx.pipeline(commit=True) as pipe:
        h_booking = pipe.add(
            pg.insert(Booking)
            .values(
                Booking(
                    dormitory_id=dorm_id,
                    primary_guest_id=guest_id,
                    stay=pg.Range(lower=date(2026, 9, 1), upper=date(2026, 9, 4)),
                    reference_code="PIPE-901",
                )
            )
            .returning(Booking)
        )
        h_charge = pipe.add(
            pg.insert(Charge)
            .values(
                Charge(
                    booking_id=pg.currval(Booking.booking_id),
                    kind=ChargeKind.NIGHTLY_RATE,
                    description="3-night savanna stay",
                    quantity=3,
                    unit_price=Decimal("110.00"),
                )
            )
            .returning(Charge)
        )

    booking = h_booking.one()
    charge = h_charge.one()
    print(
        f"booked {booking.reference_code} + charged EUR {charge.amount} "
        f"({tr.statement_count} stmts in {tr.rtts} RTT)"
    )
    # => booked PIPE-901 + charged EUR 330.00 (4 stmts in 1 RTT)

What just happened

  • tx.pipeline(commit=True) fuses lazy BEGIN, the Booking insert, the Charge insert, and COMMIT into one TCP flush: 4 statements in 1 RTT.
  • pg.currval(Booking.booking_id) resolves the exact identity sequence value PostgreSQL just allocated for Booking on the same session — no extra round trip to fetch booking_id back to Python first.
  • Both .returning(...) payloads ride back in the same response.

3. Compile-once queries, ReadPool, and portal streaming#

For hot endpoints, pg.prepare(...) compiles the AST and Rust SQL once at module import time:

tests/unit/docs/test_doc_guide_snippets.py · story10_prepare
FIND_GUEST_BY_EMAIL = pg.prepare(lambda email: pg.select(Guest).where(Guest.email == email))

Pair it with pool.read_only() and chunked server-side portal streaming:

examples/124_pipelining_prepared_stream.py · prepared_readonly_and_streaming
async def prepared_readonly_and_streaming(pool: pg.Pool) -> None:
    # ReadPool enforces BEGIN READ ONLY at the type & wire layer in 1 RTT.
    ro = pool.read_only()
    async with ro.trace() as tr:
        jumbo = await ro.one(FIND_GUEST_BY_EMAIL.bind("[email protected]"))
    print(f"prepared ReadPool hit: {jumbo.full_name} in {tr.rtts} RTT")
    # => prepared ReadPool hit: Jumbo Kalahari in 1 RTT

    # E6: stream rooms incrementally in fixed server-side portal chunks without buffering all rows.
    batch_sizes: list[int] = []
    async for batch in ro.stream(pg.select(Room).order_by(Room.number.asc()), batch_size=5):
        batch_sizes.append(len(batch))
    print(f"streamed 12 rooms in batches: {batch_sizes}")
    # => streamed 12 rooms in batches: [5, 5, 2]

    # Early break cleanly closes the server portal without poisoning the pool.
    first_chunk: list[str] = []
    async for batch in ro.stream(pg.select(Room).order_by(Room.number.asc()), batch_size=3):
        first_chunk = [r.number for r in batch]
        break
    print(f"early-break stream peeked: {first_chunk}")
    # => early-break stream peeked: ['101', '102', '103']

What just happened

  • FIND_GUEST_BY_EMAIL.bind("[email protected]") skips Python AST construction and Rust SQL compilation completely — only the bound parameter changes.
  • pool.read_only() returns a ReadPool that enforces BEGIN READ ONLY at both the type level (write queries won't typecheck) and the wire layer, fused into 1 RTT.
  • ro.stream(..., batch_size=5) fetches 5 rows at a time from a server-side PostgreSQL portal ([5, 5, 2] for 12 rooms). Breaking out early cleanly closes the portal without leaving the connection dirty.
Ferris' basement: lazy BEGIN and eager Close(Portal)

In pgdorm, entering async with pool.transaction() does not immediately send a BEGIN packet. It waits for your first statement (or pipeline) and prefixes BEGIN onto the same TCP write! Likewise, pgdorm sends Execute { max_rows: 0 } (which keeps PostgreSQL parallel query workers eligible) and an eager Close(Portal) before Sync so server-side memory frees immediately.

What PostgreSQL actually received#

Open the transcript and notice round trip 6 · 4 statements pipelined — BEGIN, both INSERTs, and COMMIT riding inside a single flush:

🔭 What PostgreSQL received: 19 statements in 11 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/pipelining_prepared_stream.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 · 3 statements pipelined ──
SELECT
  "dormitory_id",
  "region_id",
  "code",
  "name",
  "city",
  "country",
  "timezone",
  "check_in",
  "check_out",
  "city_tax",
  "opened_on"
FROM "dormitory"
WHERE "dormitory_id" = $1;
-- → 1 row
SELECT
  "room_id",
  "dormitory_id",
  "number",
  "floor",
  "category",
  "max_weight_kg",
  "max_guests",
  "amenities",
  "out_of_service"
FROM "room"
WHERE "dormitory_id" = $1
ORDER BY "number" ASC;
-- → 12 rows
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 "guest_id" ASC;
-- → 3 rows

-- ── round trip 6 · 4 statements pipelined ──
BEGIN;
INSERT INTO "booking" ("dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code")
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING "booking_id", "dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code", "created_at";
-- → 1 row
INSERT INTO "charge" ("booking_id", "kind", "description", "quantity", "unit_price")
VALUES (currval(pg_get_serial_sequence('"booking"', 'booking_id')), $1, $2, $3, $4)
RETURNING "charge_id", "booking_id", "kind", "description", "quantity", "unit_price", "amount";
-- → 1 row
COMMIT;

-- ── round trip 7 · 3 statements pipelined ──
BEGIN READ ONLY;
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 "email" = $1;
-- → 1 row
COMMIT;

-- ── round trip 8 ──
BEGIN READ ONLY;

-- ── round trip 9 ──
SELECT
  "room_id",
  "dormitory_id",
  "number",
  "floor",
  "category",
  "max_weight_kg",
  "max_guests",
  "amenities",
  "out_of_service"
FROM "room"
ORDER BY "number" ASC;
-- → 12 rows

-- ── round trip 10 ──
COMMIT;

-- ── round trip 11 ──
BEGIN READ ONLY;

Shift report

  • Loaded 3 independent queries in 1 RTT with pool.pipeline()
  • Fused BEGIN + parent insert + currval() child insert + COMMIT into 1 RTT
  • Compiled a hot query once at import time with pg.prepare()
  • Enforced read-only access with pool.read_only()
  • Streamed rows in fixed chunks with ro.stream(), including clean early break

Try it yourself

In book_and_bill_in_one_rtt, try removing commit=True from tx.pipeline(). How many RTTs does tr.rtts report now, and which statement moved into the extra round trip?

Go deeper: tests/integration/runtime/pipelining/test_pipelining.py · tests/integration/crud/test_readonly.py · tests/integration/runtime/wire/test_wire.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"Porto is open! Every morning at 06:00 I want a revenue digest: city subtotals, peanut-bar split, grand total, AND the biggest charge per city. Do NOT download every row into Python!"