One application serving hundreds of companies, each seeing only its own data, users and settings. That's multi-tenancy — and it's how almost every SaaS product you use is built.
The alternative is one deployment per customer. Ten customers, ten deploys, ten sets of upgrades to run on release day. It works until it doesn't.
HOW IT WORKS
The application identifies which tenant a request belongs to, then scopes every query to that tenant. A `tenant_id` column is the simplest version:
WHERE tenant_id = 42
Company A's query returns Company A's rows. Company B's are in the same table and are never returned.
THREE WAYS TO SEPARATE TENANTS
Shared table — a tenant_id column on every row. Cheapest, densest, easiest to operate. Also the one where a single missing WHERE clause is a breach.
Schema per tenant — one database, one schema each. Clearer separation, easier per-tenant backup and restore, more migrations to run.
Database per tenant — full separation. Strongest isolation and the easiest story for compliance-heavy customers. Most expensive and most operational overhead.
Plenty of real systems are a hybrid: shared tables for small accounts, a dedicated database for the enterprise customer who asked for one in the contract. There's no single correct answer — it depends what you're isolating for: cost, blast radius, compliance, or noisy-neighbour performance.
THE PART THAT MATTERS
`tenant_id: 42` is an illustration, not a security mechanism. Multi-tenancy doesn't give you isolation — it gives you the *obligation* to implement isolation. One `Invoice.all` where you meant `Invoice.where(tenant_id: current_tenant.id)` and you've served one customer's data to another.
Make scoping the default, not something each developer remembers. Default scopes, a tenant-aware base class, row-level security in Postgres — whatever fits. Then test it: write the spec that asserts Tenant A cannot read Tenant B's records, and run it in CI like any other security control.
—
#Astmation — #software #systems, #automation, and #AI-powered #applications.
Build. Automate. Evolve.
Watch on YouTube