A SaaS product serves many customers (tenants) from one system. The central design choice is isolation: a silo gives each tenant its own stack (strong isolation, high cost), a pool shares everything (cheap, and every tenant's safety depends on code being right), and a bridge mixes the two, for example shared compute with a database per tenant, or a silo for the largest customers. Around it sit tenant context in every request, data partitioning, noisy-neighbour controls, metering and cost per tenant, and deployments that roll out by tenant. This lesson follows one tenant from sign-up to a busy Monday, and shows the two failures that end SaaS companies' good weeks: one tenant seeing another's data, and one tenant's import slowing everyone.
Difficulty: Master · Know this first: Lesson 167, Lesson 81
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from sign-up to a tenant's first successful request. It is a worked example, not a measurement. The data partitioning and noisy-neighbour hops are where a pooled design fails its tenants.
Pick the isolation model, how data isolation is enforced, and whether tenants have limits. The readouts show the blast radius, the cost per tenant, and what one noisy tenant does.
Three questions. No score is saved anywhere — this is just you against the material.
Multi-tenant SaaS grows in four levels: reading tenant context, building isolation, controlling neighbours and cost, and running cells and tiers at scale.
At the basic level you can find which tenant a request, a log line, or a cost belongs to.
Where it breaks: taking the tenant from a URL or header the client can change.
Try it: Basic
Where should a service read the tenant ID from?
Now do it: Check where your services read the tenant from.
At the intermediate level isolation is enforced, and tested.
Try it: Intermediate
What does a cross-tenant test do?
Now do it: Write one cross-tenant test for a list endpoint.
At the advanced level every tenant has a ceiling and a cost.
Try it: Advanced
A tenant consistently uses 30% of a cell's database. What do you do?
Now do it: Rank your tenants by resource use.
At the master level the product runs as many cells with tier-based placement.
Trade-off: more cells mean smaller blast radius and more operational overhead; automation decides how many you can run.
Try it: Master
Why deploy to a canary cell before the others?
Now do it: Design the rollout order for your cells.
Row-level security in PostgreSQL: the application sets the tenant for each transaction, and the database returns only that tenant's rows, even if a query forgets its filter. Use a role that does not own the tables (owners bypass RLS unless it is forced).
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);
-- in the application, per transaction, from the verified token:
BEGIN;
SET LOCAL app.tenant_id = 'a3c9…';
SELECT * FROM invoices WHERE created_at > now() - interval '30 days'; -- only this tenant's rows
COMMIT;
Choosing isolation per layer:
This is a composite of a failure pattern that keeps repeating; the details are illustrative. One query, one missing filter.
Isolation is enforced by RLS, a cross-tenant test suite runs on every pull request, new features roll out to a canary cell first, and reports read through a view that is itself filtered by the tenant setting.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Docker, to run a throwaway PostgreSQL for the row-level security steps, and Python 3.
Type each one, read what it prints, and compare it with the note above it.
Start a throwaway PostgreSQL.
docker run -d --name rls-lab -e POSTGRES_PASSWORD=lab -p 5433:5432 postgres:16 sleep 5; docker exec rls-lab pg_isready
Create a pooled table with rows for two tenants, a non-owner app role, and a row-level security policy.
docker exec -i rls-lab psql -U postgres <<'EOF'
CREATE TABLE invoices (id serial, tenant_id text, amount int);
INSERT INTO invoices (tenant_id, amount) VALUES ('acme', 100), ('acme', 250), ('globex', 900);
CREATE ROLE app LOGIN PASSWORD 'app';
GRANT SELECT ON invoices TO app;
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices USING (tenant_id = current_setting('app.tenant_id', true));
EOFQuery as the app for acme, with no WHERE clause at all: only acme's rows come back.
docker exec -i rls-lab psql -U app -d postgres -c "BEGIN; SET LOCAL app.tenant_id = 'acme'; SELECT * FROM invoices; COMMIT;"
Query with no tenant set: nothing comes back, instead of everything.
docker exec -i rls-lab psql -U app -d postgres -c "SELECT count(*) FROM invoices;"
tenants.pyThis program runs one busy hour in a pooled cell. It shows a report query that forgets its tenant filter with isolation in application code and with the database enforcing it, a noisy tenant's import with and without per-tenant token buckets, and cost per tenant allocated from metered usage. Save it as tenants.py, then run it.
# tenants.py
ROWS = [("acme", "INV-1", 100), ("acme", "INV-2", 250), ("globex", "INV-9", 900), ("initech", "INV-4", 40)]
def report(tenant, enforced_by_db):
rows = ROWS
if enforced_by_db:
rows = [r for r in rows if r[0] == tenant] # what row-level security does below the query
# the new report query forgot: WHERE tenant_id = ?
return [r[1] for r in rows]
print("report for acme, filter forgotten")
print(" isolation in app code: ", report("acme", False))
print(" row-level security: ", report("acme", True))
print()
CAPACITY = 10_000 # database work units per second for the cell
DEMAND = {"acme": 800, "globex": 1200, "initech": 300, "bigimport": 40_000}
LIMIT = 2_000 # per-tenant ceiling (token bucket refill rate)
def serve(limits):
asked = {t: min(d, LIMIT) if limits else d for t, d in DEMAND.items()}
total = sum(asked.values())
share = min(1.0, CAPACITY / total)
return {t: round(a * share) for t, a in asked.items()}, total / CAPACITY
for limits in (False, True):
got, load = serve(limits)
others = ", ".join(f"{t} {got[t]}/{DEMAND[t]}" for t in ("acme", "globex", "initech"))
print(f"{'with per-tenant limits' if limits else 'no limits':<23} load {load:4.1f}x capacity; served {others}; bigimport {got['bigimport']}")
print()
CELL_COST = 3_600.0 # dollars a month for the shared cell
METERS = {"acme": 0.22, "globex": 0.31, "initech": 0.07, "bigimport": 0.40} # share of metered usage
PRICE = {"acme": 900, "globex": 900, "initech": 300, "bigimport": 0} # what each pays a month
for t, share in METERS.items():
cost = CELL_COST * share
print(f"{t:<10} cost {cost:7.0f} pays {PRICE[t]:4d} margin {PRICE[t] - cost:+7.0f}")
Run it, and you should see this output:
$ python3 tenants.py report for acme, filter forgotten isolation in app code: ['INV-1', 'INV-2', 'INV-9', 'INV-4'] row-level security: ['INV-1', 'INV-2'] no limits load 4.2x capacity; served acme 189/800, globex 284/1200, initech 71/300; bigimport 9456 with per-tenant limits load 0.4x capacity; served acme 800/800, globex 1200/1200, initech 300/300; bigimport 2000 acme cost 792 pays 900 margin +108 globex cost 1116 pays 900 margin -216 initech cost 252 pays 300 margin +48 bigimport cost 1440 pays 0 margin -1440
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/saas-multi-tenant-architecture && cd ~/labs/saas-multi-tenant-architecture) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "SaaS and Multi-Tenant Architecture: Isolation, Noisy Neighbours, and Cost per Tenant", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Start a throwaway PostgreSQL.'
'Create a pooled table with rows for two tenants, a non-owner app role, and a row-level security policy.'
'Query as the app for acme, with no WHERE clause at all: only acme'\''s rows come back.'
'Query with no tenant set: nothing comes back, instead of everything.'
)
step_1() {
docker run -d --name rls-lab -e POSTGRES_PASSWORD=lab -p 5433:5432 postgres:16
sleep 5; docker exec rls-lab pg_isready
}
step_2() {
docker exec -i rls-lab psql -U postgres <<'EOF'
CREATE TABLE invoices (id serial, tenant_id text, amount int);
INSERT INTO invoices (tenant_id, amount) VALUES ('acme', 100), ('acme', 250), ('globex', 900);
CREATE ROLE app LOGIN PASSWORD 'app';
GRANT SELECT ON invoices TO app;
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices USING (tenant_id = current_setting('app.tenant_id', true));
EOF
}
step_3() {
docker exec -i rls-lab psql -U app -d postgres -c "BEGIN; SET LOCAL app.tenant_id = 'acme'; SELECT * FROM invoices; COMMIT;"
}
step_4() {
docker exec -i rls-lab psql -U app -d postgres -c "SELECT count(*) FROM invoices;"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
A B2B SaaS product has 6,000 tenants on one shared stack, and its three largest customers want stronger isolation. Design the target architecture.
Which isolation model for each layer and tier? How is tenant context carried and enforced? How are noisy neighbours controlled? How do you meter cost per tenant? How do cells and deployments work? How do you migrate without downtime?
Say 6,000 tenants, the top 3 generating 25% of load, a 99.9% SLA for standard and 99.95% for enterprise, and a data-protection requirement to delete a tenant within 30 days of leaving.
Cells of about 500 tenants with a routing layer; pooled compute and a pooled PostgreSQL per cell with forced RLS; silos (separate accounts) for the three enterprise tenants with customer-managed keys; tenant ID from the IdP token, propagated everywhere; per-tenant rate limits at the gateway and throttled per-tenant import queues; usage metering into billing; ring deployments by cell; onboarding and offboarding workflows with deletion proof; migration cell by cell, moving tenants with dual writes and a cut-over per tenant.
Silos for the top tenants triple their infrastructure cost and remove most of the noisy-neighbour risk; more cells mean more to run; RLS costs a little query performance and removes a whole class of breach.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Tenant filter in app code only | Hop 4: Data partitioning | Breaks | Isolation relies on every query adding WHERE tenant_id = ?. A new invoices report joins two tables and filters only one. For three hours, tenants who open the report see other tenants' invoices. A customer reports it. |
| No per-tenant limits | Hop 5: Noisy neighbours | Breaks | There are no per-tenant limits on imports. A tenant starts a 40-million-row import through the API at full speed. |
This design, the way an architecture review would take it apart. The animated diagram near the top of the page shows the path a request takes, the Design exercise asks you to make the main decisions, Failure modes lists what breaks, and the hands-on lab builds part of it on your machine. This section adds the rest.
A SaaS product grows from ten to a thousand customers, some of them large and regulated. Design tenant isolation, noisy-neighbour protection, and cost per tenant.
| Choice | Gains | Costs |
|---|---|---|
| Pooled (shared everything, tenant id in every row) | Cheapest and simplest to run | Isolation depends on code; noisy neighbours |
| Siloed (stack per tenant) | Strong isolation, per-tenant limits | Cost and operations grow with tenants |
| Bridge (shared app, database per tenant) | A middle ground; easy to move big tenants | Many databases to patch and migrate |
| Signal | Measured by | Alert when |
|---|---|---|
| Per-tenant latency and errors | Metrics labelled by tenant tier, not by tenant id (cardinality) | A tier over its SLO |
| Noisy neighbours | Rate-limit rejections per tenant | One tenant over 20% of a shared resource |
| Cross-tenant access attempts | Authorisation denials with tenant mismatch | Any |
Read-only: each one shows state and changes nothing. They run against a real account with the provider named, so the course does not run them for you; replace the words in capitals with your own names.
aws iam simulate-principal-policy --policy-source-arn TENANT_A_ROLE_ARN --action-names s3:GetObject --resource-arns arn:aws:s3:::BUCKET/tenant-b/*aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-11-01 --granularity MONTHLY --metrics UnblendedCost --group-by Type=TAG,Key=tenantkubectl auth can-i list secrets --namespace tenant-b --as=system:serviceaccount:tenant-a:appkubectl get resourcequota --all-namespacesThe runbook commands change nothing, so there is nothing to undo after them. The lab ends with its own check and cleanup step. If you build this design in a real account, create it with infrastructure as code, check it with the runbook commands, then remove it with the same tool (for example terraform destroy) and look at the billing page the next day.
Then review it against the ten general areas below.
Review the design in this lesson, or your own, against these ten areas. Tick an area when you can answer its question with evidence: a number, a test, a document, or an owner. Your ticks stay in this browser.
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.