Skip to content

Field Note 1 — The Phantom Guestbook#

Field Notes · ORM Design · 🕛 Post-Launch · 14:30 · ⏱ 13 min read · 🥜🥜🥜🥜◌

Patch[T] · RETURNING OLD/NEW · currval() 1-RTT · by_name=True · __slots__

▶ Run it yourself: examples/191_uow_and_identity_map.py

Post-Launch, 14:30. The lobby is quiet for once. Maya leans over the server-room railing with a printed ORM textbook under her arm.

Post-Launch, 14:30. The lobby is quiet for once. Maya leans over the server-room railing with a printed ORM textbook under her arm.

Maya: Ferris, I just finished reading the classic ORM architecture chapters — Identity Maps, Unit of Work, AsyncSession.flush(). Did we take a shortcut by skipping all of that?

Ferris: Fair question. Classic Unit-of-Work ORMs like SQLAlchemy's Session solve a real problem — mutating sprawling object graphs in RAM. We didn't forget them; we made the opposite bet.

Maya: Show me on our actual hostel tables. Same four shifts, side by side.

Two schools of ORM design#

When engineers say "ORM", they often conflate two fundamentally different architectures:

  • Stateful object-graph ORMs (SQLAlchemy ORM Session, Hibernate, Entity Framework) maintain an Identity Map ((Table, pk) → single Python object) and a Unit of Work (dirty-tracking every attribute write on _sa_instance_state so session.commit() diffs RAM and flushes SQL in foreign-key order). (Among Python ORMs in our Benchmarks, only SQLAlchemy 2 / SQLModel implement a true Identity Map + Unit of Work; Django, Tortoise, Piccolo, and Peewee do not.)
  • Explicit, data-first ORMs (pgdorm, Drizzle, Kysely, jOOQ, Diesel) treat hydrated rows as lightweight, detached values (__slots__) and model every write as an explicit, set-based PostgreSQL command.

Below are four everyday shifts at The Elephant Dormitory comparing SQLAlchemy 2 (AsyncSession) and pgdorm head-to-head against live PostgreSQL. Every pgdorm snippet is extracted directly from our runnable example, and every SQLAlchemy 2 claim is verified against the same PostgreSQL instance in test_field_notes_uow.py.


1. The masked receipt — silent writes vs. explicit Patch[T]#

Pip stops by the front desk asking for a redacted receipt (p***@borneo.org) for her expense report. A display helper mutates guest.email on the hydrated object inside an open transaction block, and later the desk saves Pip's new phone number.

In pgdorm (stateless · explicit Patch[T]):

examples/191_uow_and_identity_map.py · masked_receipt_without_silent_write
async def masked_receipt_without_silent_write(pool: pg.Pool, guest_id: int) -> None:
    # 1. Hydrated models are detached __slots__ values: formatting or mutating a local
    #    display copy never schedules a hidden UPDATE on commit.
    async with pool.trace() as tr_read:
        pip = await pool.get(Guest, guest_id)
    assert pip is not None

    async with pool.trace() as tr_preview, pool.transaction():
        pip.email = f"{pip.email[0]}***@{pip.email.split('@', 1)[1]}"
    print(f"preview={pip.email} (db_writes={tr_preview.statement_count}, reads={tr_read.rtts} RTT)")
    # => preview=p***@borneo.org (db_writes=0, reads=1 RTT)

    # 2. Writes are explicit commands: Patch[Guest] carries only the dirty column in 1 RTT.
    patch = pg.Patch(Guest, phone="+60 88 555 019")
    async with pool.trace() as tr_write:
        updated = await pool.one(
            pg.update(Guest).patch(patch).where(Guest.guest_id == guest_id).returning(Guest)
        )
    print(f"persisted email={updated.email} phone={updated.phone} ({tr_write.rtts} RTT)")
    # => persisted [email protected] phone=+60 88 555 019 (1 RTT)

In SQLAlchemy 2 (AsyncSession · Unit of Work):

SQLAlchemy 2 · attached mutation persists on commit()
async with session_factory() as s, s.begin():
    sa_pip = await s.get(SaGuest, pip_id)
    # Mutating an attached ORM instance marks `_sa_instance_state` dirty:
    # unless you remembered to `expunge()` or copy first, commit() silently
    # executes `UPDATE fn_guest SET email = 'p***@borneo.org' ...`!
    sa_pip.email = f"{sa_pip.email[0]}***@{sa_pip.email.split('@', 1)[1]}"

What just happened

  • Because pgdorm models carry no _sa_instance_state dirty tracker, changing pip.email on a Python object inside pool.transaction() executes 0 statements (db_writes=0). Accidental "action at a distance" writes cannot happen.
  • Persisting a change requires an explicit command (pg.Patch(Guest, phone=...) → pg.update(Guest).patch(patch)), which sends only the single dirty column in 1 RTT while leaving email untouched:
-- captured live from PostgreSQL · examples/__wire__/uow_and_identity_map.sql
UPDATE "guest"
SET "phone" = $1
WHERE "guest_id" = $2
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";

2. Two desks, one elephant — Identity Map aliasing vs. RETURNING OLD/NEW#

14:40. Both the check-in desk and the loyalty kiosk look up Jumbo while PostgreSQL awards him 250 peanut points and updates his surname.

14:40. Both the check-in desk and the loyalty kiosk look up Jumbo while PostgreSQL awards him 250 peanut points and updates his surname.

Jumbo: Two hundred and fifty peanuts! Does the lobby screen show my new full name right away?

Ferris: PostgreSQL already computed both the new balance and your virtual generated full_name on the server. One RETURNING, zero stale cache, zero reload SELECT.

In an Identity Map, loading primary key 1 twice inside a Session returns the exact same Python object reference (a is b). That keeps in-memory Python mutations synchronized across helpers — but as soon as PostgreSQL computes values server-side (an atomic peanut_points = peanut_points + 250 expression, a GENERATED column like full_name, a trigger, or a DEFAULT), the Identity Map copy in Python RAM is immediately stale until you force a refresh() or expire_on_commit=True reload query.

In pgdorm (value objects · 1-RTT RETURNING OLD/NEW):

examples/191_uow_and_identity_map.py · atomic_points_and_generated_truth
async def atomic_points_and_generated_truth(pool: pg.Pool, guest_id: int) -> None:
    # No Identity Map: two lookups yield equal, independent value objects (never aliased).
    desk_a = await pool.get(Guest, guest_id)
    desk_b = await pool.get(Guest, guest_id)
    assert desk_a is not None and desk_b is not None
    print(f"equal={desk_a == desk_b} aliased={desk_a is desk_b}")
    # => equal=True aliased=False

    # Compute the increment and virtual GENERATED full_name in PostgreSQL — returned in 1 RTT.
    async with pool.trace() as tr:
        old_pts, new_pts, full_name = await pool.one(
            pg.update(Guest)
            .set(
                last_name="Kalahari-Okavango",
                loyalty_tier=LoyaltyTier.SILVER,
                peanut_points=Guest.peanut_points + 250,
            )
            .where(Guest.guest_id == guest_id)
            .returning(pg.old(Guest.peanut_points), pg.new(Guest.peanut_points), Guest.full_name)
        )
    print(f"atomic update: {full_name} points={old_pts}->{new_pts} ({tr.rtts} RTT)")
    # => atomic update: Jumbo Kalahari-Okavango points=0->250 (1 RTT)

In SQLAlchemy 2 (AsyncSession · Identity Map):

SQLAlchemy 2 · Identity Map aliasing & stale server-side UPDATE
async with session_factory() as s, s.begin():
    a = await s.get(SaGuest, jumbo_id)
    b = await s.scalar(sa.select(SaGuest).where(SaGuest.fn_guest_id == jumbo_id))
    assert a is b  # Same Python object via Identity Map

    await s.execute(
        sa.update(SaGuest)
        .where(SaGuest.fn_guest_id == jumbo_id)
        .values(peanut_points=SaGuest.peanut_points + 250)
        .execution_options(synchronize_session=False)
    )
    assert a.peanut_points == 0  # Identity Map still holds stale 0!
    await s.refresh(a)           # Extra SELECT round trip to resync
    assert a.peanut_points == 250

What just happened

  • desk_a == desk_b is True (value equality), while desk_a is desk_b is False (no hidden shared mutable state between call sites).
  • The atomic UPDATE … RETURNING OLD."peanut_points", NEW."peanut_points", "full_name" returns the before/after points and PostgreSQL's freshly evaluated virtual GENERATED full_name in 1 RTT — with zero stale Python cache and no follow-up SELECT.
-- captured live from PostgreSQL · examples/__wire__/uow_and_identity_map.sql
UPDATE "guest"
SET
  "last_name" = $1,
  "loyalty_tier" = $2,
  "peanut_points" = "peanut_points" + $3
WHERE "guest_id" = $4
RETURNING OLD."peanut_points", NEW."peanut_points", "full_name";

3. Checking in & charging the mud spa — UoW flush() vs. 1-RTT currval()#

Bram checks in for three nights and immediately adds three opening charges (penthouse rate, glacier-mud spa pass, and roasted peanut platter).

  • With a Unit of Work, you append SaCharge(...) objects onto booking.charges and call s.add(booking). The UoW topologically sorts the foreign key automatically — very ergonomic on deeply nested graphs — but must round-trip INSERT booking RETURNING booking_id back to Python before copying the primary key onto each SaCharge and sending the child INSERTs.
  • With pgdorm, tx.pipeline(commit=True) + pg.currval(Booking.booking_id) + by_name=True fuses BEGIN, the parent Booking, all three Charge rows (returning PostgreSQL's stored generated amount), and COMMIT into one single round trip:

In pgdorm (explicit pipeline · 1 RTT):

examples/191_uow_and_identity_map.py · checkin_and_charges_in_one_rtt
async def checkin_and_charges_in_one_rtt(pool: pg.Pool, dorm_id: int, guest_id: int) -> None:
    opening = [
        OpeningCharge(
            kind=ChargeKind.NIGHTLY_RATE,
            description="Savanna penthouse (3 nights)",
            quantity=3,
            unit_price=Decimal("180.00"),
        ),
        OpeningCharge(
            kind=ChargeKind.MUD_SPA,
            description="Glacier-mud spa pass",
            quantity=1,
            unit_price=Decimal("45.00"),
        ),
        OpeningCharge(
            kind=ChargeKind.PEANUT_BAR,
            description="Roasted peanut platter",
            quantity=2,
            unit_price=Decimal("15.00"),
        ),
    ]

    # Explicit 1-RTT pipeline: BEGIN + parent Booking + 3 currval() Charges + COMMIT.
    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, 10, 1), upper=date(2026, 10, 4)),
                    reference_code="FN-UOW-001",
                )
            )
            .returning(Booking)
        )
        h_charges = [
            pipe.add(
                pg.insert(Charge)
                .values(item, by_name=True, booking_id=pg.currval(Booking.booking_id))
                .returning(Charge)
            )
            for item in opening
        ]

    booking = h_booking.one()
    charges = [h.one() for h in h_charges]
    total = sum((c.amount for c in charges), Decimal("0.00"))
    print(
        f"checked in {booking.reference_code} with {len(charges)} charges "
        f"(EUR {total}) in {tr.rtts} RTT ({tr.statement_count} stmts)"
    )
    # => checked in FN-UOW-001 with 3 charges (EUR 615.00) in 1 RTT (6 stmts)

In SQLAlchemy 2 (AsyncSession · UoW graph flush()):

SQLAlchemy 2 · automatic FK topo-sort across multiple hops
async with session_factory() as s, s.begin():
    bk = SaBooking(
        fn_guest_id=bram_id,
        reference_code="SA-UOW-001",
        check_in_on=date(2026, 10, 1),
        charges=[
            SaCharge(description="Suite", quantity=3, unit_price=Decimal("180.00")),
            SaCharge(description="Mud spa", quantity=1, unit_price=Decimal("45.00")),
            SaCharge(description="Peanuts", quantity=2, unit_price=Decimal("15.00")),
        ],
    )
    s.add(bk)
# Flush sends BEGIN -> INSERT booking RETURNING id -> INSERT charges -> COMMIT
Ferris' basement: Why asyncio and Unit of Work clash (MissingGreenlet)

Object-graph ORMs expect synchronous attribute access (booking.charges or booking.guest.email) to trigger lazy SELECTs when a relation wasn't preloaded. Because Python's __getattr__ cannot await, async UoW ORMs need greenlet bridges and throw MissingGreenlet whenever code touches an unloaded relationship. pgdorm models never perform I/O on attribute access — related rows are always fetched explicitly via .join(...), pool.split_load(...), or pg.lateral_jsonb(...).


4. Nightly agency sync & slotted memory — set-based SQL vs. RAM diffing#

When a partner feed arrives with updates for existing guests and brand-new arrivals, loading every matching row into an Identity Map just to diff fields in Python and flush updates burns both round trips and heap memory (every tracked ORM instance carries a __dict__, _sa_instance_state, weakrefs, and original-value snapshots).

In pgdorm, rows are pure __slots__ objects (hasattr(g, "__dict__") == False, ~354 B/row in our OLTP Read benchmark), and bulk reconciliation stays set-based in 1 RTT:

examples/191_uow_and_identity_map.py · set_based_upsert_and_slotted_rows
async def set_based_upsert_and_slotted_rows(pool: pg.Pool) -> None:
    # Set-based upsert in 1 RTT (no Identity Map preload/diff), preserving Jumbo's loyalty state.
    async with pool.trace() as tr:
        synced = await pool.all(
            pg.insert_many(
                Guest,
                [
                    Guest(
                        email="[email protected]",
                        first_name="Jumbo",
                        last_name="Kalahari-Okavango",
                        species=Species.SAVANNA,
                        country="BW",
                        phone="+267 71 555 001",
                    ),
                    Guest(
                        email="[email protected]",
                        first_name="Koko",
                        last_name="Odzala",
                        species=Species.FOREST,
                        country="CG",
                    ),
                ],
            )
            .on_conflict_do_update(
                Guest.email,
                by_name=True,
                exclude=(Guest.loyalty_tier, Guest.peanut_points),
            )
            .returning(Guest)
        )
    has_dict = any(hasattr(g, "__dict__") for g in synced)
    summary = ", ".join(f"{g.first_name}[{g.loyalty_tier.name}:{g.peanut_points}]" for g in synced)
    print(f"set-based sync ({tr.rtts} RTT, __dict__={has_dict}): {summary}")
    # => set-based sync (1 RTT, __dict__=False): Jumbo[SILVER:250], Koko[CALF:0]

When a stateful Unit of Work does win#

Maya's tip: Pick the model that fits your domain

Skipping Identity Maps and Unit of Work is an architectural trade-off, not a free lunch. A classic SQLAlchemy Session genuinely shines when you are maintaining a sprawling Domain-Driven Design (DDD) aggregate — say, an enterprise order or ERP graph of 15+ interconnected entities passed through ten pure-Python business-rule services that mutate attributes and child collections arbitrarily in memory without knowing about SQL or write ordering.

For stateless HTTP/gRPC APIs, batch ETL/reverse-ETL feeds, high-concurrency PostgreSQL services behind PgBouncer, and latency-sensitive multi-statement writes, explicit commands (Patch[T], currval() pipelines, on_conflict_do_update(..., by_name=True), pg.merge(...)) eliminate hidden queries, accidental writes, stale caches, and per-row state-tracking overhead.

Quick translation map#

Concern Stateful UoW ORM (AsyncSession) Explicit data-first (pgdorm)
Partial updates Mutate obj.phone = ... in RAM; flush() diffs _sa_instance_state Typed 3-state pg.Patch[T] (UNSET vs None vs value) → update(T).patch(p)
Server-computed values refresh() / expire_on_commit=True extra SELECT RETURNING OLD/NEW & generated columns in the same 1 RTT
Parent + child inserts parent.children.append(...); UoW topo-sorts across multiple hops tx.pipeline(commit=True) + pg.currval(Parent.pk) in 1 RTT
Optimistic locking version_id_col checked during Session.flush() Native PostgreSQL xmin (optimistic_lock=True, update_versioned())
Bulk reconciliation Load existing rows into Identity Map → diff in Python → flush on_conflict_do_update(..., by_name=True) or pipe.stage() + pg.merge() (1 RTT)
Row memory overhead __dict__ + _sa_instance_state + history snapshots Bare __slots__ (zero __dict__, zero tracker overhead)

What PostgreSQL actually received#

🔭 What PostgreSQL received: 17 statements in 11 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/uow_and_identity_map.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 ──
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 "guest_id" = $1;
-- → 1 row

-- ── round trip 6 ──
UPDATE "guest"
SET "phone" = $1
WHERE "guest_id" = $2
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";
-- → 1 row

-- ── 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 "guest_id" = $1;
-- → 1 row

-- ── 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 "guest_id" = $1;
-- → 1 row

-- ── round trip 9 ──
UPDATE "guest"
SET
  "last_name" = $1,
  "loyalty_tier" = $2,
  "peanut_points" = "peanut_points" + $3
WHERE "guest_id" = $4
RETURNING OLD."peanut_points", NEW."peanut_points", "full_name";
-- → 1 row

-- ── round trip 10 · 6 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
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
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 11 ──
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
ON CONFLICT ("email") DO UPDATE SET
  "first_name" = EXCLUDED."first_name",
  "last_name" = EXCLUDED."last_name",
  "species" = EXCLUDED."species",
  "phone" = EXCLUDED."phone",
  "country" = EXCLUDED."country",
  "birth_date" = EXCLUDED."birth_date",
  "preferences" = EXCLUDED."preferences",
  "marketing_opt_in" = EXCLUDED."marketing_opt_in"
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";
-- → 2 rows

Shift report

  • Contrasted detached __slots__ + explicit Patch[T] against attached Unit-of-Work silent writes
  • Compared Identity Map aliasing and stale server-side updates against 1-RTT RETURNING OLD/NEW
  • Pipelined a parent Booking and three by_name=True Charge rows with pg.currval() in 1 RTT
  • Reconciled a batch set-based via on_conflict_do_update(..., by_name=True, exclude=...) with zero __dict__ overhead

Go deeper: tests/integration/docs/test_field_notes_uow.py (live PostgreSQL test suites & snapshots)