8 · Multi-Tenant RLS Request (rls_tenant_query)#
← All benchmarks · Related chapter: Chapter 14 · Lisbon Can't See Porto
Switch to a NOBYPASSRLS PostgreSQL role and tenant context (app.tenant_id), read all rows visible under PostgreSQL FORCE ROW LEVEL SECURITY (no WHERE tenant_id = … clause — the database policy enforces isolation), update one item's balance with RETURNING, and commit. pgdorm fuses BEGIN, both transaction-scoped set_config(..., true) calls (designed for PgBouncer transaction pooling; measured here on direct PostgreSQL), the SELECT, the UPDATE … RETURNING, and COMMIT into 1 single round trip. Peers require 5–7 RTTs per request.
Chart & metrics#
| ORM | RTTs | Instr (Client + PG) | Server ms | Sent / Recv | ms (med) |
|---|---|---|---|---|---|
| pgdorm | 1 | 3.4M (1.7M + 1.7M) | 0.11 ms | 351 B / 1.7 KiB | 1.55 ms |
| Peewee | 5 | 7.6M (3.2M + 4.4M) | 0.11 ms | 621 B / 1.7 KiB | 3.58 ms |
| SQLAlchemy 2 | 5 | 9.9M (5.9M + 4.0M) | 0.12 ms | 287 B / 1.7 KiB | 4.31 ms |
| SQLModel | 5 | 10.1M (6.2M + 3.9M) | 0.11 ms | 287 B / 1.7 KiB | 4.48 ms |
| Piccolo ORM | 6 | 7.2M (3.3M + 3.9M) | 0.11 ms | 316 B / 1.8 KiB | 3.32 ms |
| SQLDataclass | 6 | 7.2M (2.7M + 4.5M) | 0.10 ms | 599 B / 1.7 KiB | 3.53 ms |
| Django ORM | 6 | 15.9M (4.0M + 11.8M) | 0.11 ms | 722 B / 1.8 KiB | 4.14 ms |
| Tortoise ORM | 7 | 9.6M (4.5M + 5.0M) | 0.15 ms | 398 B / 1.9 KiB | 4.16 ms |
Ferris' basement: Tenant isolation with zero extra round trips
Many teams avoid PostgreSQL Row-Level Security because issuing BEGIN, SET LOCAL ROLE, SET LOCAL app.tenant_id, the actual queries, and COMMIT sequentially multiplies request latency. pool.transaction(local_settings=...) + tx.pipeline(commit=True) pipelines every set_config(..., true) alongside your statements and COMMIT in one network turnaround.
Contender implementations#
Every tab below is AST-extracted directly from bench/adapters/ — zero hand-copied snippets.
pgdorm 0.10.0 (pgdorm-wire (Rust)) · 1 RTT · 1.7M instr · 1.55 ms · pgdorm_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._pool is not None
# BEGIN + set_config(role, tenant) + SELECT (RLS-filtered) + UPDATE + COMMIT in 1 RTT.
async with (
self._pool.transaction(
local_settings={"role": RLS_ROLE, "app.tenant_id": tenant_id}
) as tx,
tx.pipeline(commit=True) as pipe,
):
h_rows = pipe.add(
pg.select(BenchTenantItem).order_by(BenchTenantItem.bench_tenant_item_id.asc())
)
h_upd = pipe.add(
pg.update(BenchTenantItem)
.set(balance=BenchTenantItem.balance + delta)
.where(BenchTenantItem.code == target_code)
.returning(BenchTenantItem.balance)
)
(new_bal,) = h_upd.one()
return len(h_rows.all()), Decimal(new_bal)
SQLAlchemy 2 2.1.9 (asyncpg) · 5 RTTs · 5.9M instr · 4.31 ms · sqlalchemy_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._session_factory is not None
async with self._session_factory() as s, s.begin():
await s.execute(
select(
sa.func.set_config("role", RLS_ROLE, True),
sa.func.set_config("app.tenant_id", tenant_id, True),
)
)
rows = (
await s.scalars(select(_TenantItem).order_by(_TenantItem.bench_tenant_item_id))
).all()
new_bal = await s.scalar(
sa.update(_TenantItem)
.where(_TenantItem.code == target_code)
.values(balance=_TenantItem.balance + delta)
.returning(_TenantItem.balance)
)
assert new_bal is not None
return len(rows), Decimal(new_bal)
SQLModel 0.0.50 (asyncpg) · 5 RTTs · 6.2M instr · 4.48 ms · sqlmodel_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._session_factory is not None
async with self._session_factory() as s, s.begin():
await s.execute(
sa.select(
sa.func.set_config("role", RLS_ROLE, True),
sa.func.set_config("app.tenant_id", tenant_id, True),
)
)
rows = (
await s.exec(
select(_SMTenantItem).order_by(col(_SMTenantItem.bench_tenant_item_id))
)
).all()
new_bal = await s.scalar(
sa.update(_SMTenantItem)
.where(col(_SMTenantItem.code) == target_code)
.values(balance=col(_SMTenantItem.balance) + delta)
.returning(col(_SMTenantItem.balance))
)
assert new_bal is not None
return len(rows), Decimal(new_bal)
SQLDataclass 0.4.3 (psycopg3 (sync)) · 6 RTTs · 2.7M instr · 3.53 ms · sqldataclass_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._engine is not None
tbl = SdTenantItem.__table__
with self._engine.begin() as conn:
conn.execute(text(f"SET LOCAL ROLE {RLS_ROLE}"))
conn.execute(text("SELECT set_config('app.tenant_id', :tid, true)"), {"tid": tenant_id})
items = load_all(conn, select(tbl).order_by(tbl.c.bench_tenant_item_id), SdTenantItem)
new_bal = Decimal(
conn.execute(
update(tbl)
.where(tbl.c.code == target_code)
.values(balance=tbl.c.balance + delta)
.returning(tbl.c.balance)
).scalar_one()
)
return len(items), new_bal
Django ORM 6.1.3 (psycopg3) · 6 RTTs · 4.0M instr · 4.14 ms · django_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._TenantItem is not None
with transaction.atomic():
with connection.cursor() as cur:
cur.execute(
"SELECT set_config('role', %s, true), set_config('app.tenant_id', %s, true)",
[RLS_ROLE, tenant_id],
)
rows = list(self._TenantItem.objects.order_by("bench_tenant_item_id"))
self._TenantItem.objects.filter(code=target_code).update(balance=F("balance") + delta)
updated: Any = self._TenantItem.objects.get(code=target_code)
return len(rows), Decimal(updated.balance)
Tortoise ORM 1.1.9 (asyncpg) · 7 RTTs · 4.5M instr · 4.16 ms · tortoise_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
async with in_transaction() as conn:
await conn.execute_query(
"SELECT set_config('role', $1, true), set_config('app.tenant_id', $2, true)",
[RLS_ROLE, tenant_id],
)
rows = await _TTenantItem.all().using_db(conn).order_by("bench_tenant_item_id")
await (
_TTenantItem.filter(code=target_code)
.using_db(conn)
.update(balance=F("balance") + delta)
)
updated = await _TTenantItem.get(code=target_code).using_db(conn)
return len(rows), Decimal(updated.balance)
Piccolo ORM 1.39.0 (asyncpg) · 6 RTTs · 3.3M instr · 3.32 ms · piccolo_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._engine is not None
async with self._engine.transaction():
await self._TenantItem.raw(
"SELECT set_config('role', {}, true), set_config('app.tenant_id', {}, true)",
RLS_ROLE,
tenant_id,
)
rows = await self._TenantItem.objects().order_by(self._TenantItem.bench_tenant_item_id)
target = next(r for r in rows if r.code == target_code)
updated = (
await self._TenantItem.update(
{self._TenantItem.balance: Decimal(target.balance) + delta}
)
.where(self._TenantItem.code == target_code)
.returning(self._TenantItem.balance)
)
return len(rows), Decimal(updated[0]["balance"])
Peewee 4.5.3 (psycopg3) · 5 RTTs · 3.2M instr · 3.58 ms · peewee_adapter.py
async def rls_tenant_request(
self, tenant_id: str, target_code: str, delta: Decimal
) -> tuple[int, Decimal]:
assert self._db is not None
with self._db.atomic():
pw.Select(
columns=[
pw.fn.set_config("role", RLS_ROLE, True),
pw.fn.set_config("app.tenant_id", tenant_id, True),
]
).bind(self._db).execute()
rows = list(_PWTenantItem.select().order_by(_PWTenantItem.bench_tenant_item_id))
updated = list(
_PWTenantItem.update(balance=_PWTenantItem.balance + delta)
.where(_PWTenantItem.code == target_code)
.returning(_PWTenantItem.balance)
.tuples()
.execute()
)
return len(rows), Decimal(updated[0][0])