Part 3 of 12 · 2 min read
Enforcing the filter instead of trusting convention
A rule every endpoint is supposed to follow gets forgotten somewhere; a rule the data layer enforces cannot be.
Think of a shared rule like "always lock the door behind you" posted in a building with a hundred doors, versus doors that lock themselves automatically. The posted rule gets forgotten eventually; the self-locking door cannot be.
In plain words: a tenant filter that every endpoint must remember to apply will eventually be forgotten somewhere, but a filter built into the only path for reading data cannot be skipped.
A worked example. Across 20 endpoints with a 5 percent chance each one forgets to pass the tenant filter, the forgetful endpoints leaked 60 other-tenant rows in total. Routing every read through a single scoped repository, one that pulls the tenant from the request context and has no code path that skips it, leaked 0 rows. There was never an unscoped query to forget.
The key lines.
# from code/mini-tenancy/tenancy.py
class ScopedRepo:
def __init__(self, db): self._db = db
def insert(self, ctx, data): self._db.insert(ctx.tenant, data)
def query(self, ctx): return self._db.query(tenant=ctx.tenant)
Read it as: every method on this class takes the authenticated context, not a tenant argument, and pulls the tenant out of it itself. There is no call signature that lets a caller omit the filter even by mistake. Database row-level security is the backup layer behind this. It is a policy the database itself checks, in case the application code ever has a bug.
Row-level security
Database-enforced policies that restrict which rows a given session is allowed to read or write, independent of what the application code asks for.
Example: a policy that compares a row's tenant column against the session's tenant, rejecting any query that doesn't match — a second layer behind the scoped repository above.