Chapter 14 — Lisbon Can't See Porto#
Tenant isolation enforced by PostgreSQL itself, and still one round trip behind PgBouncer.
enable_rls()create_policy()local_settings=PgBouncer-safeexamples/118_multitenancy_rls.pyMonth 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:
- create a
DeskNotetable and enable forced RLS with typedpgdorm.migrateDDL operations, - attach a
USING+WITH CHECKpolicy bound tocurrent_setting('app.dorm_code', true), - pass
local_settings={"role": ..., "app.dorm_code": "LIS"}intopool.transaction(...)soset_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:
Notice we use pgdorm.migrate (pgm) for DDL operations — zero raw SQL strings even when granting permissions or creating RLS policies:
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),)
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 andFORCE ROW LEVEL SECURITYso even the table owner obeys the policy when assumingpgdorm_rls_user(NOBYPASSRLS).pgm.create_policy(...)defines bothUSING(filters reads/updates/deletes) andWITH CHECK(rejects cross-tenant inserts/updates) against PostgreSQL'scurrent_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:
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"})compilesset_config('role', $1, true)andset_config('app.dorm_code', $2, true). Thetrueflag means transaction-local (SET LOCAL): the momentCOMMITorROLLBACKruns, PostgreSQL resets every setting automatically — 100% safe for Rocco's transaction pooler!- Fused with
tx.pipeline(commit=True),BEGIN+set_config+INSERT+COMMITall 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'sWITH CHECKpolicy rejects it with SQLSTATE42501(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.migrateDDL - Scoped tenant context per transaction with
local_settings=(set_config(..., true)) - Fused
BEGIN+ tenant setup + write +COMMITinto 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!"
← PreviousChapter 13 · The Nightly FeedChapter 13 · Staging & MERGE RETURNING
Next →Chapter 15 · A Million Door ScansChapter 15 · Range Partitioning