Platform Engineering · Lesson 168

SaaS and Multi-Tenant Architecture: Isolation, Noisy Neighbours, and Cost per Tenant

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: isolation, limits, and cost

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.

500 tenantsblast radius
$11cost per tenant a month
180 msothers' p99 during a big import

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Multi-tenant SaaS grows in four levels: reading tenant context, building isolation, controlling neighbours and cost, and running cells and tiers at scale.

Basic — Read tenant context

At the basic level you can find which tenant a request, a log line, or a cost belongs to.

  • The tenant claim in the token; tenant_id in logs, metrics, and traces.
  • Silo, pool, and bridge, and which one each layer uses.
  • The tenant catalogue: tier, cell, limits.

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.

Intermediate — Build isolation

At the intermediate level isolation is enforced, and tested.

  • Row-level security, separate schemas, or separate databases, depending on tier.
  • Object storage prefixes per tenant with scoped access.
  • Cross-tenant tests in CI: act as tenant A, assert nothing from tenant B.

Try it: Intermediate

What does a cross-tenant test do?

Now do it: Write one cross-tenant test for a list endpoint.

Advanced — Neighbours and cost

At the advanced level every tenant has a ceiling and a cost.

  • Rate and concurrency limits per tenant; throttled per-tenant queues for bulk work.
  • Usage metering per tenant; shared costs allocated by meters; margin per tier.
  • Per-tenant SLO views, so one tenant's bad day is visible.

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.

Master — Cells and tiers at scale

At the master level the product runs as many cells with tier-based placement.

  • Cell-based architecture with a routing layer that maps tenants to cells.
  • Ring deployments by cell; per-tenant feature flags.
  • Onboarding and offboarding as tested workflows, including data deletion proof.

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.

Go deeper

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:

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. One query, one missing filter.

Timeline

  • 10:00A new invoices report ships to all tenants. Its query joins invoices to payments and filters payments by tenant_id, but not invoices.
  • 13:05A customer emails support a screenshot showing another company's invoice numbers.
  • 13:20The report is disabled with a feature flag. Access logs show which tenants opened it and which rows each could have seen.
  • Next 2 daysAffected tenants are notified, the privacy team reports as required, and row-level security is enabled and forced on every tenant table.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Start a throwaway PostgreSQL.

    Reversible

    docker run -d --name rls-lab -e POSTGRES_PASSWORD=lab -p 5433:5432 postgres:16
    sleep 5; docker exec rls-lab pg_isready

    Options: -d runs it in the background; -p 5433:5432 avoids clashing with a local PostgreSQL.

    Expect: accepting connections.

    Clean up: docker rm -f rls-lab removes it and its data.

  2. Create a pooled table with rows for two tenants, a non-owner app role, and a row-level security policy.

    Reversible

    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

    Options: The policy compares each row with the session setting app.tenant_id; true returns NULL instead of an error when it is not set.

    Expect: CREATE TABLE, INSERT 0 3, and the role, grant, and policy created.

  3. Query as the app for acme, with no WHERE clause at all: only acme's rows come back.

    Reversible

    docker exec -i rls-lab psql -U app -d postgres -c "BEGIN; SET LOCAL app.tenant_id = 'acme'; SELECT * FROM invoices; COMMIT;"

    Expect: Two rows, both acme. The forgotten filter is harmless.

  4. Query with no tenant set: nothing comes back, instead of everything.

    Reversible

    docker exec -i rls-lab psql -U app -d postgres -c "SELECT count(*) FROM invoices;"

    Expect: 0: the policy fails closed. Then clean up with docker rm -f rls-lab.

2. Python: tenants.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A B2B SaaS product has 6,000 tenants on one shared stack, and its three largest customers want stronger isolation. Design the target architecture.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Tenant filter in app code onlyHop 4: Data partitioningBreaksIsolation 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 limitsHop 5: Noisy neighboursBreaksThere are no per-tenant limits on imports. A tenant starts a 40-million-row import through the API at full speed.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Onboarding → Tenant context → Isolation model → Data partitioning → Noisy neighbours → Tiers → Metering and cost → Cells and rings → Offboarding. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

Architecture framework

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.

Design problem

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.

Constraints

Trade-offs

ChoiceGainsCosts
Pooled (shared everything, tenant id in every row)Cheapest and simplest to runIsolation depends on code; noisy neighbours
Siloed (stack per tenant)Strong isolation, per-tenant limitsCost and operations grow with tenants
Bridge (shared app, database per tenant)A middle ground; easy to move big tenantsMany databases to patch and migrate

Security boundaries

Cost

Observability plan

SignalMeasured byAlert when
Per-tenant latency and errorsMetrics labelled by tenant tier, not by tenant id (cardinality)A tier over its SLO
Noisy neighboursRate-limit rejections per tenantOne tenant over 20% of a shared resource
Cross-tenant access attemptsAuthorisation denials with tenant mismatchAny

Disaster recovery plan

RPO
Per plan: 5 minutes for enterprise, 24 hours for free.
RTO
Per plan, written in the contract.
Strategy
Per-tenant restore must be possible without restoring everyone.
Test
Restore one tenant's data into a scratch environment each month.

Runbook commands

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.

  1. Can tenant A's role read tenant B's objects? (It should be denied.)AWS
    aws iam simulate-principal-policy --policy-source-arn TENANT_A_ROLE_ARN --action-names s3:GetObject --resource-arns arn:aws:s3:::BUCKET/tenant-b/*
  2. What did each tenant cost last month?AWS
    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=tenant
  3. Can a tenant's service account read another namespace's secrets?Kubernetes
    kubectl auth can-i list secrets --namespace tenant-b --as=system:serviceaccount:tenant-a:app
  4. Which quotas limit each tenant namespace?Kubernetes
    kubectl get resourcequota --all-namespaces

Validation and cleanup

The 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.

Checklist for this design

Then review it against the ten general areas below.

Architecture review checklist

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.

  1. Business outcomeWhich result for users or the business does this design serve, and which number shows it is working?
  2. SecurityWho and what can reach each part, how is identity proven, and how is data protected in transit and at rest?
  3. ReliabilityWhat is the target (SLO), which single failures does the design survive, and how was that tested?
  4. PerformanceWhat latency and throughput are required at peak, and where is the first bottleneck?
  5. OperationsHow is it deployed, observed, and changed safely, and who is paged when it breaks?
  6. CostWhat does it cost per month and per unit of work (request, tenant, model call), and what grows the bill?
  7. SustainabilityWhich resources sit idle, which region and hardware does it run on, and what can scale to zero?
  8. GovernanceWhich policies, guardrails, and compliance rules apply, and how are they enforced in code?
  9. OwnershipWhich team owns each component, its budget, and its on-call, and where is that written down?
  10. Failure and recovery planWhat is the RTO and RPO, what is the runbook for a region or dependency loss, and when was it last rehearsed?

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 169
Data Lakehouse Architecture: Open Tables, Medallion Layers, and Governance

A lakehouse keeps data in cheap object storage, like a data lake, and adds what a warehouse gives you: tables with schemas, ACID transactions, time travel, and fast SQL.

Go to Lesson 169 →

Or browse the full course from the Lessons index.