Multi-tenant Django with PostgreSQL row-level security
BilimQR started as five separate certificate systems, one per training centre. Turning it into one SaaS meant putting every centre's students and certificates in the same tables. This is how I made the database itself refuse to show one centre another centre's rows, and the six things that surprised me.
Why not just filter by tenant?
The usual approach is a tenant foreign key on every table and a .filter(tenant=request.tenant) on every query, usually hidden in a custom manager. It works until someone forgets it once: a new admin view, a report, a raw SQL query, an export. Then one client sees another client's students, with their names and personal data. For a product that verifies certificates, that would be the end of it.
I had used the other common approach before. In a retail project, each business gets its own PostgreSQL schema (django-tenants). It isolates well, but every migration runs once per schema, and the number of schemas grows with every new client.
Row-level security (RLS) sits in between. All tenants share the same tables, and PostgreSQL adds the tenant condition to every query by itself, including queries I forget about.
The core idea
Each tenant table gets a policy that compares the row's tenant_id with a per-transaction setting. The application sets that setting once per request:
ALTER TABLE certificates_certificate ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON certificates_certificate
USING (tenant_id = current_setting('app.tenant_id', true)::bigint)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);
USING filters what you can read, update and delete. WITH CHECK stops you from writing a row into another tenant. The policy lives in a normal Django migration (RunSQL), so it is versioned and reviewed like any other change. In BilimQR, 25 migrations apply it table by table.
1The table owner ignores your policies
This one costs people hours. PostgreSQL does not apply RLS to the role that owns the table. If Django connects as the same user that ran the migrations, every policy is silently skipped and everything looks fine in testing.
The fix is two database roles. An owner role runs migrate and owns the tables. A separate app role, with only the privileges it needs, is what the running site connects as. The owner bypasses RLS, and that's fine because only migrations use it. The app role can't.
2Use SET LOCAL, inside a transaction
The tenant setting must not outlive the request. With persistent connections, a plain SET would stay on the connection, and the next request on it would run as the previous tenant. SET LOCAL lasts only until the end of the current transaction, so the middleware wraps the whole request in one:
with transaction.atomic():
with connection.cursor() as cur:
cur.execute("SET LOCAL app.tenant_id = %s", [str(tenant.id)])
return self.get_response(request)
3Fail closed, not open
The second argument in current_setting('app.tenant_id', true) means "return NULL if it was never set" instead of raising an error. tenant_id = NULL is never true, so a request that never got a tenant sees zero rows. Forgetting to set the tenant gives an empty page, not a leak. That's the right way round.
There's one catch I only found while writing tests for this post. Once a connection has used SET LOCAL app.tenant_id, later transactions on it read the setting as an empty string, not NULL, and ''::bigint raises an error. That still doesn't leak anything, but the request crashes instead of getting an empty result. Wrapping it as NULLIF(current_setting('app.tenant_id', true), '')::bigint makes it a clean "zero rows" too.
4Django ignores your column default
My first idea for inserts was a SQL default: tenant_id DEFAULT current_setting('app.tenant_id', true)::bigint. It works for raw SQL, but not for Django. The ORM sends a value for every column on INSERT, and an unset foreign key goes in as an explicit NULL. The default never applies, and the WITH CHECK policy rejects the row.
So the tenant also lives in Python, in a ContextVar set next to SET LOCAL. A pre_save signal fills in tenant_id on new rows from it. The SQL default stays for non-ORM inserts.
5Authentication becomes a chicken-and-egg problem
Users belong to tenants too, so the user table is protected as well. That breaks Django's normal order. AuthenticationMiddleware loads request.user from the user table, but the tenant isn't known until we know the user, and the user can't be read until the tenant is set.
The way out is to work out the user's id without touching the user table. It comes from the validated JWT's claims for the API, or from the raw session store for server-rendered pages. Then the tenant comes from a small membership table without RLS. The tenant middleware sits before AuthenticationMiddleware, and by the time Django loads the user, the tenant is already set.
6Public pages need a narrow door
Anyone can scan a certificate's QR code, without logging in. There is no user, so there is no tenant, and RLS correctly shows nothing. But the page must find the certificate.
The answer is one small SQL function marked SECURITY DEFINER, so it runs with the owner's rights. It takes the certificate's random id and returns only its tenant id. The view calls it, sets app.tenant_id, and every query after that goes through RLS as normal. EXECUTE is granted to the app role only. It isn't a general bypass, just one narrow lookup.
CREATE FUNCTION resolve_tenant_for_certificate(p_unique_id text)
RETURNS bigint LANGUAGE sql SECURITY DEFINER STABLE AS $$
SELECT tenant_id FROM certificates_certificate
WHERE unique_id = p_unique_id;
$$;
REVOKE ALL ON FUNCTION resolve_tenant_for_certificate(text) FROM PUBLIC;
Testing that it actually isolates
Because of gotcha 1, tests that connect as the owner prove nothing. The settings have a second database alias that connects as the restricted app role, and the tests use it. The isolation tests create data for tenant A and tenant B as the owner, then query through the app role and check three things:
- tenant A sees its own rows,
- tenant B sees none of A's rows,
- a connection with no tenant set sees nothing at all.
What it costs
- Every request with a tenant runs inside one transaction, so slow requests hold it open longer.
- Anything outside a request, like a management command or a background job, has to set the tenant itself, or it sees nothing. That's annoying, but it fails safe.
- Policies are SQL, not Python, so the team has to read migrations, not only models.
For a product where a leak would be the worst possible bug, I think that's a good trade. The database is the last line of defence, and with RLS it's a real one.
More writing
I’m Aysulu, a backend developer (Python, Django) in Nukus, Uzbekistan, open to remote work. If your team deals with this kind of thing, I’d like to hear about it: aysulu.mambetnazarova@gmail.com. Or see my projects.