site_id everywhere: multi-tenancy without leaks

This note is about multi-tenancy and one rule: site_id everywhere. In a multi-tenant SaaS, bugs aren't all the same size. A broken button is bad; a customer of site A seeing site B's orders means trust is gone. So in SimaCMS tenancy is one of the few places with no discounts.
One column, one name, everywhere
Every row that belongs to a site has a site_id column, under that exact name, in every table. Not tenant_id here and shop_id there. One name means a guard can check it, and a person or an agent can tell at a glance whether a query is right.
In Laravel: a global scope
In the Laravel version every model had a global scope limiting queries to the current site. With no site in context the query failed, rather than quietly returning everything. To read across sites on purpose (say, in the platform's own admin), you had to say so explicitly.
In Go: explicit, in every query
When I moved the backend to Go there was no ORM and no magic scope. We write SQL by hand with pgx, and the rule is: every site-scoped query names site_id itself. It looked like a step back at first, but it turned out the other way: nothing is hidden any more. Reading a query, you see whether it's scoped. An agent writing a new query learns the pattern from the ones beside it.
The current site comes from the request's context, never from user input. We never accept site_id from a form or a URL.
Outside the request
The HTTP request is the easy part. The harder ones:
- Jobs: each job carries its site and re-enters it when it runs.
- Scheduled work: loops over sites one by one, never over the whole table.
- Cache and Redis: every key includes the site. A cache shared across sites means one day someone sees someone else's page.
- Files: media paths are per site too.
- The edge cache: a page personalised for one visitor never goes into a shared cache.
Tests nobody deletes
We write few tests, but tenancy always has them. At least one refusal per boundary: "a user of site A asks for a row of site B and gets a 404". Nobody, person or agent, deletes these on their own reading.
Next to them we run a full audit every so often, searching every query for a missing site_id. The last one found a few small cases, and they were fixed.
The main multi-tenancy lesson
Data isolation isn't something you fix once. It has to live in the shape of the code, so that getting it wrong is harder than getting it right, and something, a guard or a test, shouts when someone does.
Multi-tenancy is only one of the lines that must hold; I wrote about the line between modules in modular architecture with one question, and why these paths get tests when others don't in static guards. The OWASP multi-tenant security cheat sheet is worth a read too.
Comments
Sign in to leave a comment.
Sign inLoading…


