Skip to content

Chapter 14 — Lisbon Can't See Porto#

Act IV · Chapter 14 Month 6 · 09:00 7 min readDifficulty 4 of 5

Tenant isolation enforced by PostgreSQL itself, and still one round trip behind PgBouncer.

enable_rls()create_policy()local_settings=PgBouncer-safe
▶ Run it yourself · examples/118_multitenancy_rls.py
Month 6, 09:00. Porto's receptionist opens the desk-notes screen and reads "Extra peanuts for Jumbo — Room 304 (Lisbon)."

Month 6, 09:00. Porto's receptionist opens the desk-notes screen and reads "Extra peanuts for Jumbo — Room 304 (Lisbon)."

Maya: Someone forgot .where(DeskNote.dorm_code == current_dorm) on one endpoint. One missing filter and two cities can see each other's notes!

Panda: Just remember to write WHERE dorm_code = ... on every single query forever! Or run SET app.dorm_code = 'LIS' on the connection!

Rocco: Do NOT use session-level SET behind me! When Lisbon's transaction finishes, I hand that connection straight to Porto — they'll inherit Lisbon's tenant!

The mission#

Application-level WHERE tenant_id = ... filters fail open: forget it once and you have a data leak. Session-level SET breaks catastrophically behind PgBouncer in transaction pooling mode. Maya enforces database-level Row-Level Security (RLS) that is 100% PgBouncer-safe and still costs 1 RTT:

  1. create a DeskNote table and enable forced RLS with typed pgdorm.migrate DDL operations,
  2. attach a USING + WITH CHECK policy bound to current_setting('app.dorm_code', true),
  3. pass local_settings={"role": ..., "app.dorm_code": "LIS"} into pool.transaction(...) so set_config(..., true) is transaction-scoped and fused into the same 1-RTT pipeline.

The Panda's plan

Either rely on human discipline to never miss a WHERE dorm_code = ? across 200 endpoints, or execute session-scoped SET app.dorm_code = 'LIS' before queries. Behind Rocco's transaction pooler, a forgotten RESET leaks Tenant A's credentials straight into Tenant B's next request.

1. Enable forced RLS with typed DDL#

Note

Chapter demo role: PostgreSQL superusers bypass RLS unless you switch to a NOBYPASSRLS role. To run this chapter locally on a stock PostgreSQL container, create the demo role once:

CREATE ROLE pgdorm_rls_user NOLOGIN NOBYPASSRLS;

One table, two front desks, a wall built by PostgreSQL desk_note (FORCE ROW LEVEL SECURITY) LIS · 304 · Extra peanuts OPO · 201 · Warm mud bath Lisbon deskapp.dorm_code = 'LIS' Porto deskapp.dorm_code = 'OPO' set_config(…, true) rides in the same round trip and resets at COMMIT: safe behind PgBouncer

Notice we use pgdorm.migrate (pgm) for DDL operations — zero raw SQL strings even when granting permissions or creating RLS policies:

examples/118_multitenancy_rls.py · DeskNote
class DeskNote(pg.Table):
    desk_note_id: pg.Col[int] = pg.pk(default=pg.identity())
    dorm_code: pg.Col[str] = pg.col()
    room_number: pg.Col[str] = pg.col()
    message: pg.Col[str] = pg.col()

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (pg.Index(cls.dorm_code, cls.room_number),)
examples/118_multitenancy_rls.py · configure_rls
async def configure_rls(pool: pg.Pool) -> None:
    await pool.create_all(DeskNote)
    schema_name = str((await pool.one(pg.select_expr(pg.func("current_schema"))))[0])

    # Typed DDL ops: grant schema privileges, FORCE RLS, and bind policy to `app.dorm_code`.
    await pgm.apply_ddl(
        pool,
        pgm.grant_schema(schema_name, role=RLS_ROLE, scope=pgm.enums.GrantScope.SCHEMA_USAGE),
        pgm.grant_schema(schema_name, role=RLS_ROLE, scope=pgm.enums.GrantScope.ALL_TABLES),
        pgm.grant_schema(schema_name, role=RLS_ROLE, scope=pgm.enums.GrantScope.ALL_SEQUENCES),
        pgm.enable_rls(DeskNote, force=True),
        pgm.create_policy(
            DeskNote,
            name="dorm_isolation",
            using=DeskNote.dorm_code
            == pg.func("current_setting", "app.dorm_code", True, returns=str),
            with_check=DeskNote.dorm_code
            == pg.func("current_setting", "app.dorm_code", True, returns=str),
        ),
    )

What just happened

  • pgm.enable_rls(DeskNote, force=True) turns on Row-Level Security and FORCE ROW LEVEL SECURITY so even the table owner obeys the policy when assuming pgdorm_rls_user (NOBYPASSRLS).
  • pgm.create_policy(...) defines both USING (filters reads/updates/deletes) and WITH CHECK (rejects cross-tenant inserts/updates) against PostgreSQL's current_setting('app.dorm_code', true).
  • Look at idx_desk_note_tenant_room: putting the tenant key (dorm_code) first in composite indexes lets PostgreSQL serve RLS-filtered queries straight from the index.

2. Fuse local_settings into 1-RTT transactions#

Now Lisbon and Porto run the exact same unfiltered pg.select(DeskNote) — and PostgreSQL guarantees each city only ever sees and writes its own rows:

examples/118_multitenancy_rls.py · exercise_tenant_isolation
async def exercise_tenant_isolation(pool: pg.Pool) -> None:
    # `local_settings` fuses `BEGIN` + `set_config(..., true)` + DML + `COMMIT` in 1 RTT
    # and stays 100% safe under PgBouncer transaction pooling (settings reset at COMMIT).
    async with (
        pool.trace() as tr,
        pool.transaction(local_settings={"role": RLS_ROLE, "app.dorm_code": "LIS"}) as tx,
        tx.pipeline(commit=True) as pipe,
    ):
        pipe.add(
            pg.insert(DeskNote).values(
                DeskNote(dorm_code="LIS", room_number="304", message="Extra peanuts for Jumbo")
            )
        )
    print(f"Lisbon write fused with set_config in {tr.rtts} RTT")
    # => Lisbon write fused with set_config in 1 RTT

    async with pool.transaction(local_settings={"role": RLS_ROLE, "app.dorm_code": "OPO"}) as tx:
        await tx.execute(
            pg.insert(DeskNote).values(
                DeskNote(dorm_code="OPO", room_number="201", message="Warm mud bath for Bram")
            )
        )

    # Lisbon front desk sees ONLY Lisbon rows; Porto sees ONLY Porto rows.
    async with pool.transaction(
        read_only=True,
        local_settings={"role": RLS_ROLE, "app.dorm_code": "LIS"},
    ) as tx_lis:
        lis_notes = await tx_lis.all(pg.select(DeskNote))
    print("Lisbon sees:", [(n.dorm_code, n.message) for n in lis_notes])
    # => Lisbon sees: [('LIS', 'Extra peanuts for Jumbo')]

    async with pool.transaction(
        read_only=True,
        local_settings={"role": RLS_ROLE, "app.dorm_code": "OPO"},
    ) as tx_opo:
        opo_notes = await tx_opo.all(pg.select(DeskNote))
    print("Porto sees:", [(n.dorm_code, n.message) for n in opo_notes])
    # => Porto sees: [('OPO', 'Warm mud bath for Bram')]

    # Cross-tenant write attempt is blocked by PostgreSQL RLS WITH CHECK (SQLSTATE 42501).
    try:
        async with pool.transaction(
            local_settings={"role": RLS_ROLE, "app.dorm_code": "LIS"}
        ) as tx_bad:
            await tx_bad.execute(
                pg.insert(DeskNote).values(
                    DeskNote(dorm_code="OPO", room_number="999", message="Sneaky cross-tenant note")
                )
            )
    except pg.PostgresError as err:
        print(f"cross-tenant insert blocked by RLS: sqlstate={err.sqlstate}")
        # => cross-tenant insert blocked by RLS: sqlstate=42501

What just happened

  • pool.transaction(local_settings={"role": RLS_ROLE, "app.dorm_code": "LIS"}) compiles set_config('role', $1, true) and set_config('app.dorm_code', $2, true). The true flag means transaction-local (SET LOCAL): the moment COMMIT or ROLLBACK runs, PostgreSQL resets every setting automatically — 100% safe for Rocco's transaction pooler!
  • Fused with tx.pipeline(commit=True), BEGIN + set_config + INSERT + COMMIT all cross the wire in 1 RTT (tr.rtts == 1).
  • Reading pg.select(DeskNote) with no .where(...) clause at all returns only Lisbon's note for Lisbon and only Porto's note for Porto.
  • When Lisbon attempts to insert a row tagged dorm_code="OPO", PostgreSQL's WITH CHECK policy rejects it with SQLSTATE 42501 (insufficient_privilege).
Ferris' basement: PgBouncer transaction-pooling hygiene

When connecting through PgBouncer (Pool.connect(..., pool_mode=pg.enums.PoolMode.TRANSACTION)), pgdorm automatically omits startup options (which would otherwise trigger 08P01 protocol errors), supports prepared_statements=False when proxies disable prepared statements, and ensures local_settings= always uses set_config(..., true) inside the transaction so no session state ever leaks between pooled tenants.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 25 statements in 9 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 4 statements omitted · full transcript in examples/__wire__/multitenancy_rls.sql

-- ── round trip 1 ──
SELECT current_schema();
-- → 1 row

-- ── round trip 2 · 5 statements pipelined ──
BEGIN;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
INSERT INTO "desk_note" ("dorm_code", "room_number", "message")
VALUES ($1, $2, $3);
-- → 1 affected
COMMIT;

-- ── round trip 3 · 4 statements pipelined ──
BEGIN;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
INSERT INTO "desk_note" ("dorm_code", "room_number", "message")
VALUES ($1, $2, $3);
-- → 1 affected

-- ── round trip 4 ──
COMMIT;

-- ── round trip 5 · 4 statements pipelined ──
BEGIN READ ONLY;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
SELECT
  "desk_note_id",
  "dorm_code",
  "room_number",
  "message"
FROM "desk_note";
-- → 1 row

-- ── round trip 6 ──
COMMIT;

-- ── round trip 7 · 4 statements pipelined ──
BEGIN READ ONLY;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
SELECT
  "desk_note_id",
  "dorm_code",
  "room_number",
  "message"
FROM "desk_note";
-- → 1 row

-- ── round trip 8 ──
COMMIT;

-- ── round trip 9 · 4 statements pipelined ──
BEGIN;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
INSERT INTO "desk_note" ("dorm_code", "room_number", "message")
VALUES ($1, $2, $3);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 42501

Shift report

  • Enabled forced Row-Level Security and policies with typed pgdorm.migrate DDL
  • Scoped tenant context per transaction with local_settings= (set_config(..., true))
  • Fused BEGIN + tenant setup + write + COMMIT into 1 RTT
  • Proved Lisbon and Porto are isolated on both reads and cross-tenant writes (42501)

Try it yourself

Look at round trip 1 in the wire transcript above. Notice how BEGIN, the set_config calls, the INSERT, and COMMIT all travel in one flush. What would happen if a developer forgot local_settings={"app.dorm_code": ...} completely? (Hint: current_setting('app.dorm_code', true) returns NULL, and dorm_code = NULL is never true — fail-closed!)

Go deeper: tests/integration/runtime/pipelining/test_pipelining.py · tests/integration/runtime/pgbouncer/test_pgbouncer.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"The keycard door scanners just hit one million events a month. Queries for June are scanning last year's logs, and dropping old months locks the whole table. PARTITION IT!"