Circuit Times
Subscribe

Multi-Tenant SaaS: How to Build It and Keep Tenants Isolated

Multi-tenant SaaS explained: tenancy models, how to build tenant isolation, and real PostgreSQL tests of row-level security and performance.

  • 33 min read
  • 38 sections
  • Updated November 19, 2026
Amara Whitlock

Updated

How-to

A multi-tenant SaaS application serves many customers from one running system while keeping each customer's data apart. A tenant is one customer of the system: a company, a team, an organization. Most modern business software works this way.

The hard part is not sharing servers. The hard part is guaranteeing that no tenant can see, alter or drag down another tenant.

This guide explains the tenancy models, how to build each one and where they break, and it includes real tests I ran on a PostgreSQL database.

I ran the tests on PostgreSQL 16.2 on one machine, with small data sets, on October 28, 2026. They show behavior and relative cost, not production benchmarks.

Statements about Microsoft, AWS, OWASP and PostgreSQL come from their own documentation, and I note the source each time.

The short answer

For many SaaS products, especially those with many small tenants, a sensible starting point is a pooled design: one set of tables where every row carries a tenant ID, protected by database row-level security and tested for isolation.

Leave yourself a path to give big or regulated customers their own dedicated resources down the road.

Choose separate schemas or databases only when customers need stronger separation, custom data layouts or independent restore. Whatever the model, treat tenant isolation as a security feature and test it automatically.

Good to know

My numbers come from small experiments on one machine, so use them to see patterns, not to size a production system. For the cost examples I chose made-up prices, only to illustrate the sums.

Multi tenant SaaS meaning: what it is

In multi-tenant software, one deployment of the application and its infrastructure serves several tenants at the same time. A tenant is a customer organization, and it usually has its own users, settings and data inside the shared system.

Microsoft's architecture guidance describes a tenant as a business unit or customer represented in a centralized application, with its own set of users.

Ownership and isolation are both defined at the tenant level. A user belongs to a tenant, and the tenant owns the data.

Tenant, user and account

These words are often mixed up. A user is an individual with a login. An account usually means the billing relationship. A tenant is the line that data must not cross.

In many products they line up one to one, but not always. A consultant may be a user in several tenants, and a company may have several accounts.

Decide early what your tenant is, because the whole design hangs on it. Our single sign-on guide explains how large customers connect their own identity systems to a tenant.

Multi-tenant vs single-tenant

In a single-tenant design, each customer gets its own deployment. A multi-tenant design puts all customers on a single shared deployment. Which one wins depends on the case. This table is our analysis, using the points Microsoft's guidance raises.

QuestionMulti-tenantSingle-tenant
Cost per customerLower, because resources are sharedHigher, because each customer needs its own
IsolationEnforced by software and data designEnforced by separate infrastructure
Noisy neighborsA risk that you must manageUnlikely, according to Microsoft
UpdatesOne rollout reaches everyoneRolled out customer by customer
Custom needsHarder to offerEasier to offer
OperationsOne system to runMany systems to run
ComplianceNeeds careful proof of isolationEasier to show separation

Microsoft's guidance says tenants in a single-tenant deployment are unlikely to affect each other's performance, known as the noisy neighbor problem, and that updates can be rolled out progressively.

It also warns that cost efficiency is low, and that 100 tenants probably need 100 times the infrastructure cost.

It adds that if you expect to scale to a large number of customers, deploying shared infrastructure is important, because otherwise you must maintain a large and growing fleet of instances.

It also says choosing a tenancy model is a commercial decision as well as a technical one.

Multi tenant SaaS examples

Vendors rarely publish the exact tenancy design behind their products, so I do not name real companies.

These invented examples show how the choices play out. Each describes a type of product, and none is a claim about a real company.

ProductTenantsLikely designWhy
A project tracker for small teamsTens of thousands of tiny tenantsPooled tables with row-level securityLow cost per tenant, same data layout for all
An accounting toolThousands of businessesPooled, or schema per tenantFinancial data may justify stronger separation
A data analytics platformHundreds of tenants with large dataDatabase per tenantHeavy and uneven workloads
A tool sold to banksA few dozen large tenantsDedicated deploymentsContracts require strict separation
A platform with both small and enterprise customersMixedHybrid: pooled plus dedicated for large tenantsMatches cost to what each customer pays

If you are looking for a multi tenant SaaS platform to copy, copy the reasoning, not the product. Start from your tenants, your data and your promises, and pick the model that fits them.

The tenancy models

There are four common ways to separate tenants. They differ in where the line between tenants is drawn.

ModelWhat is sharedWhere tenants are separated
Pooled, shared tablesEverything, including tablesBy a tenant ID on each row
Schema per tenantDatabase server and applicationBy a separate set of tables for each tenant
Database per tenantDatabase server and applicationBy a separate database for each tenant
Deployment per tenantNothing but the codeBy separate infrastructure

Real systems mix these. Microsoft describes vertical partitioning, in which most customers run on multitenant infrastructure while customers who need higher performance or stronger isolation get dedicated single-tenant infrastructure. This hybrid is common once enterprise customers arrive.

AWS makes a related point about pooled resources. Its documentation says that for pooled resources, fine-grained policies are needed, and that any attempt to access a tenant's resource should be scoped to just the resources that belong to that tenant.

How to choose

Use these questions to decide. They are ours, informed by the Microsoft considerations on business objectives, isolation requirements and scale.

  • How many tenants will you have? If the answer is thousands of small ones, pooling is the natural fit. A few large ones may justify dedicated resources.
  • How sensitive is the data? Highly regulated data may require stronger separation.
  • How different are tenants? Custom data layouts push toward separate schemas or databases.
  • What will you promise? Per-tenant restore and strict performance guarantees are easier with separation.
  • How big is your team? Many separate deployments need strong automation.

Building a multi-tenant SaaS: the decisions

Every multi-tenant application makes the same set of decisions. Skipping one is how isolation bugs appear. This list is our checklist, and the sections below test the most important ones.

Tenant identification

Decide how each request names its tenant, such as a subdomain, a token claim or a header.

Tenant context

Carry the tenant through the whole request, including background jobs.

Data model

Put a tenant ID on every tenant-owned table, and use it in keys and constraints.

Access control

Enforce tenant checks in one place, and add a second layer in the database.

Caching

Include the tenant in every cache key.

Files and search

Separate storage paths and search indexes by tenant.

Limits

Control how much of the system one tenant can use.

Provisioning

Create, configure and remove tenants automatically.

Billing

Tie plans and usage to the tenant. Our guide to Stripe vs Paddle vs Chargebee covers the payment side.

Observability

Tag logs, metrics and traces with the tenant.

Identifying the tenant on each request

Before any isolation can work, the system must know which tenant a request belongs to, and it must get that right every time. The identification method also shapes your product.

MethodHow it worksStrengthWatch for
Subdomainacme.example.com maps to a tenantClear to users, easy to routeWildcard certificates, reserved names
Path prefixexample.com/acme/Simple to deployLinks that drop the prefix
Token claimThe signed sign-in token names the tenantHard to tamper withUsers in several tenants
Custom domainThe customer's own domain maps to a tenantProfessional lookDomain verification, certificates
HeaderA client sends a tenant headerEasy for internal APIsNever trust it from users

Take the tenant only from something you can trust, like a token whose signature you have checked. A field the user can edit is never acceptable.

OWASP lists modifying the URL or API requests among the common ways to bypass access control, so any tenant identifier supplied by the client must be checked against the signed-in user's memberships.

Resolve the tenant once, early in the request, and store it in a request context. Every later layer reads from that context.

If code takes a tenant ID from request parameters in several places, mistakes are only a matter of time.

Users, roles and switching tenants

Users and tenants form a many-to-many relationship in many products. A person may belong to several organizations, with a different role in each. Model that with a membership record that links a user, a tenant and a role.

Roles are scoped to a tenant. An administrator in one tenant has no rights in another. Check the role against the tenant of the current request, not against a global flag on the user.

When a user switches tenants, treat it as a new context.

Refresh the token or session, clear tenant-specific caches in the client and make sure no data from the previous tenant remains on screen. Test this flow, because it is a common source of leaks.

Invitations deserve care too. An invitation should be tied to one tenant and one email, expire, and be single-use. Do not let a user join a tenant by guessing an identifier.

Hands-on: isolating tenants in shared tables

The pooled model is the most common, so I tested it first. I created two tables, customers and invoices, each with a tenant ID, and loaded data for two tenants. Then I tested what goes wrong and what protects you.

Test 1: the forgotten filter

In a pooled design, every query needs a tenant filter. When a developer leaves it out, the database returns rows from other tenants without complaint. I connected as an application role and asked for invoice 3 without any tenant filter.

RequestResult
SELECT id, tenant_id, amount FROM invoices WHERE id = 3Returned invoice 3 for tenant 2 with an amount of 900

That request came from tenant 1's session and returned tenant 2's row. This is exactly the bug OWASP describes.

Its 2021 Top 10 puts broken access control first, moved up from fifth place. According to OWASP, 94 percent of the applications in its data set were tested for some form of broken access control, and the average incidence rate was 3.81 percent.

So 94 percent describes how many applications were tested for this category, and it does not say that 94 percent were vulnerable.

OWASP's advice has three parts. Enforce access in trusted server-side code, build the checks once and reuse them everywhere, and have developers and QA staff write functional tests for access control.

The remainder of this section is built around those three rules.

Test 2: row-level security

With row-level security, PostgreSQL applies the tenant filter inside the database. A query that forgets the filter in application code then has no way to leak rows.

I enabled it on the invoices table and wrote a policy that compares each row's tenant ID with a setting the application sets for each transaction.

alter table invoices enable row level security;

create policy tenant_isolation on invoices
  using (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int)
  with check (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int);

begin;
select set_config('app.tenant_id', '1', true);
select id, tenant_id, amount from invoices;
commit;

The third argument to set_config is true, which makes the setting last only for the current transaction. That detail matters, as test 3 shows. I ran several requests as the application role.

RequestResult
Tenant 1 reads all invoicesRows 1 and 2, both tenant 1
Tenant 2 reads all invoicesRow 3, tenant 2
Tenant 1 asks for invoice 3 by IDNo rows
No tenant set at allCount of 0
Tenant 1 inserts a row for tenant 2Error: new row violates row-level security policy
Tenant 1 updates tenant 2's invoice0 rows changed

The policy fails closed. When the application fails to set a tenant, queries come back empty instead of returning every row. If something is going to go wrong, empty is the outcome you want. The policy also blocks writes that would put a row in another tenant.

Who bypasses row-level security, and what the tests used

The PostgreSQL documentation states that row security never applies to superusers or to any role carrying the BYPASSRLS attribute. Table owners are normally exempt too, the documentation adds, until FORCE ROW LEVEL SECURITY is set on the table. I ran each of these cases.

ConnectionRows visible out of 3
Superuser3
Superuser after FORCE ROW LEVEL SECURITY3
Non-superuser table owner, no FORCE3
Non-superuser table owner, with FORCE0 (no tenant set)

The lesson is that the application must connect as a role that is neither a superuser nor the table owner.

If your application uses the owner role to run queries, row-level security protects nothing. Use a separate role for migrations and a restricted role for the application.

What this row-level security setup does not cover

The policy is a defense in depth, and it has limits. The tenant comes from a setting that the application sets, and the application role is allowed to set it.

Any code that runs SQL as that role can set the value to another tenant's ID. That includes a SQL injection flaw.

So the policy protects against a forgotten filter, which is a common mistake, and it does not protect against an attacker who can run arbitrary SQL as the application role.

For that, you still need parameterized queries, a trusted way to establish the tenant for each request, restricted database privileges and authorization checks in the application.

The role also matters. In my tests the application role was not a superuser, not the table owner and did not have the BYPASSRLS attribute, and it had only the table privileges it needed.

For convenience, the test script switched to that role with SET ROLE inside an administrator connection, where a real application would connect with its own login role.

A role with more power would bypass the policy, as the next table shows. Treat row-level security as one layer, next to authentication, authorization and tests, and not as a replacement for them.

Test 3: the connection pool trap

Most applications reuse database connections through a pool. If the tenant setting is stored at the session level, it can survive after the request ends and apply to the next request on the same connection. I simulated that.

SetupResult for the next request
Request A sets tenant 1 at session level, request B for tenant 2 forgets to set itRequest B sees tenant 1's rows 1 and 2
Transaction-local setting, next request forgets to set itCount of 0

With a session-level setting, request B read tenant 1's data. With a transaction-local setting, the same mistake returned nothing. Use the transaction-local form, and set the tenant at the start of every transaction.

Test 4: references across tenants

A foreign key that names only the other row's ID does not stop a row from pointing at another tenant's data. I inserted an invoice for tenant 1 that pointed at tenant 2's customer.

SetupResult
Single-column reference, no tenant in the keyThe insert succeeded: invoice 5 for tenant 1 pointing at tenant 2's customer
Composite foreign key on (tenant_id, customer_id)Error: violates foreign key constraint

To fix it, make the parent table unique on (tenant_id, id) and reference both columns. Then the database itself refuses cross-tenant links. This is a cheap protection that most pooled designs forget.

Test 5: uniqueness per tenant

Constraints like unique email addresses must be per tenant, not global. A global unique email lets one tenant discover that an address exists in another tenant, and blocks legitimate users.

ConstraintResult
Global unique on emailThe second tenant's registration of a@x.com failed
Unique on (tenant_id, email)The same email in the second tenant was accepted, and a duplicate inside one tenant failed

Decide which fields are unique across the platform, such as a login handle if you need one, and which are unique inside a tenant. Write that down for every unique constraint.

Performance in the pooled model

Pooled tables grow large, so indexes matter. For queries that filter by tenant, the tenant ID is usually the right first column of the index. I tested that with a table of 1,000,000 events spread across 1,000 tenants.

The query was the latest 50 events for one tenant, ordered by time. I ran it with three index setups and kept the best of three runs.

IndexExecution time
None useful35.1 ms
Index on created_at only2.42 ms
Index on (tenant_id, created_at)0.012 ms

The composite index was about 200 times faster than the time-only index, and nearly 3,000 times faster than no index.

The time-only index still worked, because it could find recent rows, but it had to skip over other tenants' rows to find 50 belonging to this one.

Other tenant-filtered queries follow the same rule. Put the tenant ID first, then the column you filter or sort by.

Indexes for reports that span all tenants may need a different column order. Review your slowest queries for missing tenant-aware indexes before you blame the database.

Schema per tenant

Under this model, every tenant has a private set of tables, and all of them live in one shared database. The application switches between them, often by setting the search path. Tenants cannot accidentally see each other's rows, because the tables are different.

I created 300 tenant schemas, each with one table and 100 rows. Creating them took 0.8 seconds in total, about 3 milliseconds per tenant.

Running a migration that adds a column across all 300 schemas took 0.08 seconds, about 0.3 milliseconds per schema.

The same migration on one shared table with the same 30,000 rows took 0.4 milliseconds. At this small scale, the per-schema cost is tiny.

The 300 schemas also created 900 relations in the database catalog, which shows how the number of objects grows.

What this does and does not show

My test used tiny tables, so the migration time says little about large tenants. It does show that the work scales with the number of schemas.

With thousands of tenants, you need a reliable migration runner, a way to retry failures and a plan for tenants that are out of date.

Schema per tenant gives you cleaner separation and easier per-tenant export. It costs you more operational work, more database objects and more care with tools that scan the whole catalog, such as backup and monitoring.

Database per tenant

In this model a tenant has a whole database to itself, either on a shared server or on a server of its own. Isolation is strong, and restoring one tenant is simple. The cost is overhead and connections.

I created 20 databases and each took about 18 milliseconds. An empty database used 7,105 kB of disk. That is small, but it is per tenant before any data arrives.

The larger limit is connections. PostgreSQL's default maximum was 100 connections on my installation. If each tenant database uses a pool of 10 connections, only 10 databases fit under the limit. Twenty databases would need 200.

You can pool connections more cleverly, or use a connection pooler, but the lesson stands. Database per tenant works well for a modest number of tenants who need strong separation. It becomes hard to run for thousands of small ones.

Comparing the three data models

This table combines the tests with the guidance I read. The last column is my judgment.

ConcernShared tablesSchema per tenantDatabase per tenant
Isolation strengthDepends on code and row securityStronger, by separate tablesStrongest logical separation of the three, though not a compliance guarantee
Cost per tenantLowestLowHigher, about 7 MB empty in my test
MigrationsOne change for allOne change per schemaOne change per database
ConnectionsShared poolShared poolMultiplies with tenants
Per-tenant restoreHardPossibleSimplest of the three, since one database holds one tenant
Custom tenant data layoutHardPossiblePossible
Fits bestMany small tenantsA few hundred tenantsA few large tenants

Removing or exporting a tenant

Customers leave, and some ask for their data. Your design affects how easy that is. I measured deleting one tenant from a shared table and dropping a schema.

OperationTime
DELETE 100,000 rows for one tenant from a 2,000,000 row shared table44 ms
DROP SCHEMA containing 100,000 rows4 ms

Both were fast at this size. The difference grows with data volume and with the cleanup work after a large delete in a shared table, such as vacuuming.

Dropping a schema is cleaner, and exporting a tenant is also easier when its data lives apart.

Whatever you choose, build deletion and export as tested features. Customers and regulators ask for them, and a tenant ID on every row, including logs and backups, makes the job possible.

Noisy neighbors

A noisy neighbor is a tenant that uses so much capacity that others suffer.

Microsoft's guidance names it as a risk of shared deployments, and notes that horizontally partitioned deployments can mitigate it by giving heavy components their own instances per tenant.

I simulated it. Eight workers each process a 50-millisecond job. Twenty small tenants send two requests per second for 60 seconds.

One heavy tenant sends 5 requests a second, then bursts to 300 requests a second for ten seconds. The same 5,763 requests were used in both runs.

PolicySmall tenants p50Small tenants p95Small tenants p99Heavy tenant p95
One shared queue, first come first served50 ms9,725 ms10,980 ms10,689 ms
Limit of 3 workers per tenant50 ms50 ms69 ms37,761 ms

With a single shared queue, the burst delayed everyone. Small tenants waited almost ten seconds at the 95th percentile. With a per-tenant concurrency limit, small tenants stayed at about 50 milliseconds, and the heavy tenant absorbed the delay.

I simulated this in code and did not measure a production system. The idea is real: fairness has to be designed.

The usual controls are per-tenant rate limits, concurrency caps, separate queues for large jobs, quotas and the ability to move a heavy tenant to its own resources.

Caches, files, search and logs

The database is only one place where tenants can mix. Every shared layer needs the same care. Caches are the easiest to get wrong.

I tested a cache keyed only by the setting name. Tenant A requested its plan, and the cache stored it.

Tenant B then asked for the same key and received tenant A's plan. With the tenant included in the key, tenant B got its own plan.

LayerThe rule
CacheInclude the tenant in every key
Object storageUse a tenant prefix and check it on every access
Search indexesFilter by tenant, or use separate indexes
Queues and jobsCarry the tenant ID in every message
Logs and metricsTag every entry with the tenant
Analytics exportsKeep tenant IDs and separate access

Testing isolation

Isolation is a claim you must prove repeatedly. OWASP recommends functional access control tests, and in a multi-tenant system that means tests that act as one tenant and try to reach another's data.

Write these tests early, as our suggestion.

Read tests

Sign in as tenant A and request tenant B's records by ID.

Write tests

Try to create or change records that belong to tenant B.

List tests

Check that lists and searches never include other tenants' rows.

Missing context tests

Run queries with no tenant set and expect nothing.

Job tests

Run background jobs for two tenants and check outputs.

Cache tests

Request the same key as two tenants.

Run them in your automated test pipeline on every change. A new endpoint without a tenant test is a risk.

Security and compliance

Isolation failures are among the most damaging SaaS bugs, because one flaw can expose many customers. Treat them as security incidents.

Customers will ask how you separate their data. Prepare clear answers about your model, your tests and your access controls. Large buyers may ask for audit reports or a dedicated deployment, which is where the hybrid model helps.

Control your own staff's access to tenant data. Support and engineering access should be limited, logged and time-bound. Our privileged access management guide explains how to apply least privilege and control sessions.

Provisioning and tenant lifecycle

Creating a tenant should be automatic. A new customer should get a tenant record, default settings, an owner account and any required resources in seconds, without engineers.

Plan the whole lifecycle. A tenant is created, configured, upgraded, downgraded, suspended for non-payment, exported and deleted. Each step should be tested, and each should leave an audit trail.

Plans and features

Most multi-tenant products offer plans. Store the plan on the tenant and check it in one place. Use feature flags for per-tenant features, and be careful that flags cannot be changed by a tenant's own users.

Our SaaS pricing strategy guide explains how to design plans and limits, and how value metrics tie to what each tenant uses. Usage per tenant also feeds billing, so measure it by tenant from the start.

Scaling: moving tenants between shards

When one database is no longer enough, you can spread tenants across several. Each shard holds a group of tenants, and a routing table says which shard owns which tenant.

Microsoft describes deploying multiple instances of a solution, including geographically, as a way to partition tenants.

This is where a tenant ID on everything pays off. With clean boundaries you can move one tenant to a new shard, balance load or give a large customer its own database. Without them, every move is a project.

Keep the routing layer simple. Store the tenant's location in a small, highly available table, cache it carefully with a tenant-safe key and test what happens when a tenant is mid-move.

Regions and data residency

Some customers want their data stored in a specific country or region, for legal or commercial reasons. Multi-tenant design can support that, but it takes planning.

Microsoft's guidance describes deploying multiple instances of a solution geographically as a way to partition tenants.

Each region runs a copy of the system, and each tenant is assigned to one region. A global routing layer sends requests to the right place.

Decide what must stay in the region: primary data, backups, logs, search indexes and analytics. Anything that copies data elsewhere can break a promise.

I did not research the legal requirements of any country, so check them with a lawyer before you promise residency.

Record the region assigned to each tenant, and guard that record against accidental edits. Moving a tenant between regions is a migration project with its own checks, so plan the tools before a customer asks.

Cost per tenant

What each tenant costs you depends heavily on the tenancy model. To show the shape, I used invented prices. A pooled database costs $400 a month and serves 1,000 tenants.

A dedicated database for one tenant costs $15 a month at the smallest size and $150 for a larger one.

SetupMonthly infrastructure costCost per tenant
1,000 tenants, all pooled$400$0.40
1,000 tenants, each with a $15 database$15,000$15.00
950 pooled and 50 enterprise tenants with $150 databases$7,900$7.90

The hybrid costs about 20 times the pooled design in this example, and it still costs half of a database for every tenant.

The 50 enterprise tenants must pay enough to cover their dedicated resources. So the choice belongs to pricing as well as engineering.

Remember that these prices are made up. Use your own prices, and include operations time, which is often the larger cost with many deployments.

Common mistakes

Forgetting the tenant filter

One missing condition leaks data. Back it up with row-level security in the database.

Using a privileged database role

Row security is then skipped for everything the application runs.

Session-level tenant settings

They can leak through connection pools.

Global unique constraints

They leak existence and block legitimate users.

Cross-tenant foreign keys

Reference both tenant and row IDs.

Shared cache keys

Include the tenant in every key.

No limits per tenant

One heavy tenant can slow everyone.

Untested isolation

A claim without tests is a hope.

No deletion path

Customers and regulators will ask for it.

A build order

This order is our suggestion for a new product.

Step 1

Define the tenant. Decide what a tenant is and how it relates to users and billing.

Step 2

Add the tenant ID everywhere. Put it on every tenant-owned table, message and log.

Step 3

Centralize the context. Resolve the tenant once per request and carry it through.

Step 4

Add row-level security. Use a restricted role and transaction-local settings.

Step 5

Write the isolation tests. Make them part of every build.

Step 6

Add limits. Rate limits and concurrency caps per tenant.

Step 7

Automate provisioning and deletion. Test both.

Step 8

Plan the hybrid. Decide how a large customer would move to dedicated resources.

Reproduce the tests

The row-level security setup is shown above. Three scripts reproduce the measurements. The first reproduces the noisy neighbor simulation and the cache example and needs only Python. Scripts two and three cover the PostgreSQL tests.

They use the pgserver and psycopg2 packages, which start a temporary PostgreSQL server for the test, so you do not need to install a database yourself. Change the rates, limits and sizes to see how each result changes.

import heapq, random

random.seed(7)
WORKERS, SERVICE = 8, 0.050

def make_arrivals():
    arrivals = []
    for tenant in range(20):
        t = 0.0
        while t < 60:
            t += random.expovariate(2.0)
            arrivals.append((t, f"small{tenant}"))
    t = 0.0
    while t < 60:
        rate = 300 if 20 <= t < 30 else 5
        t += random.expovariate(rate)
        arrivals.append((t, "heavy"))
    arrivals.sort()
    return arrivals

def simulate(policy, arrivals, cap=3):
    running, queue, per_tenant, busy = [], [], {}, {}
    latency = {"small": [], "heavy": []}
    i = 0
    def dispatch(now):
        while len(running) < WORKERS:
            job = None
            if policy == "fifo":
                if queue:
                    job = queue.pop(0)
            else:
                eligible = [t for t, q in per_tenant.items() if q and busy.get(t, 0) < cap]
                if eligible:
                    t = min(eligible, key=lambda t: per_tenant[t][0][0])
                    job = per_tenant[t].pop(0)
            if not job:
                break
            arrived, tenant = job
            heapq.heappush(running, (now + SERVICE, tenant, arrived))
            busy[tenant] = busy.get(tenant, 0) + 1
    while i < len(arrivals) or running or queue or any(per_tenant.values()):
        next_arrival = arrivals[i][0] if i < len(arrivals) else float("inf")
        next_finish = running[0][0] if running else float("inf")
        if next_arrival <= next_finish:
            now = next_arrival
            arrived, tenant = arrivals[i]
            i += 1
            if policy == "fifo":
                queue.append((arrived, tenant))
            else:
                per_tenant.setdefault(tenant, []).append((arrived, tenant))
            dispatch(now)
        else:
            now = next_finish
            finish, tenant, arrived = heapq.heappop(running)
            busy[tenant] -= 1
            latency["heavy" if tenant == "heavy" else "small"].append((finish - arrived) * 1000)
            dispatch(now)
    return latency

def percentile(values, p):
    values = sorted(values)
    return values[min(len(values) - 1, int(len(values) * p))]

arrivals = make_arrivals()
for policy in ("fifo", "fair"):
    result = simulate(policy, arrivals)
    small = result["small"]
    print(policy, round(percentile(small, .5)), round(percentile(small, .95)), round(percentile(small, .99)), round(percentile(result["heavy"], .95)))

cache = {}

def get_plan_shared_key(tenant, key):
    if key not in cache:
        cache[key] = f"plan-of-{tenant}"
    return cache[key]

def get_plan_tenant_key(tenant, key):
    tenant_key = f"{tenant}:{key}"
    if tenant_key not in cache:
        cache[tenant_key] = f"plan-of-{tenant}"
    return cache[tenant_key]

print("cache key without tenant:", get_plan_shared_key("A", "settings:plan"), "then tenant B gets:", get_plan_shared_key("B", "settings:plan"))
cache.clear()
print("cache key with tenant:", get_plan_tenant_key("A", "settings:plan"), "then tenant B gets:", get_plan_tenant_key("B", "settings:plan"))

Script 2: isolation tests on PostgreSQL. Install the packages with pip install pgserver psycopg2-binary, then run the file. Its output should match the isolation tables in this guide.

import pgserver, tempfile, psycopg2, time
d = tempfile.mkdtemp(); srv = pgserver.get_server(d); uri = srv.get_uri()
def conn(user=None):
    c = psycopg2.connect(uri); c.autocommit = True
    if user:
        cur = c.cursor(); cur.execute(f"SET ROLE {user}")
    return c
def q(c, sql, params=None, show=True):
    cur = c.cursor()
    try:
        cur.execute(sql, params)
        rows = cur.fetchall() if cur.description else cur.rowcount
        return rows
    except Exception as e:
        c.rollback() if not c.autocommit else None
        return f"ERROR: {str(e).splitlines()[0]}"
adm = conn()
print("version:", q(adm, "select split_part(version(),' ',2)")[0][0])
q(adm, "drop role if exists app_user"); q(adm, "create role app_user nologin")
q(adm, "create table customers (tenant_id int not null, id serial primary key, name text, email text)")
q(adm, "create table invoices (tenant_id int not null, id serial primary key, customer_id int, amount int)")
q(adm, "insert into customers (tenant_id,name,email) values (1,'Acme A','a@x.com'),(2,'Beta B','b@x.com')")
q(adm, "insert into invoices (tenant_id,customer_id,amount) values (1,1,100),(1,1,250),(2,2,900)")
q(adm, "grant select,insert,update,delete on customers,invoices to app_user")
q(adm, "grant usage on all sequences in schema public to app_user")
app = conn("app_user")
print("\nT1 shared tables, no row security. Request for tenant 1 forgets the tenant filter:")
print("  SELECT id, tenant_id, amount FROM invoices WHERE id = 3 ->", q(app, "select id, tenant_id, amount from invoices where id = 3"))
print("\nT2 row-level security with a transaction-local tenant setting")
q(adm, "alter table invoices enable row level security")
q(adm, "create policy tenant_isolation on invoices using (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int) with check (tenant_id = nullif(current_setting('app.tenant_id', true), '')::int)")
def as_tenant(c, tid, sql):
    cur = c.cursor(); cur.execute("begin"); cur.execute("select set_config('app.tenant_id', %s, true)", (str(tid),))
    try:
        cur.execute(sql); r = cur.fetchall() if cur.description else cur.rowcount
    except Exception as e: r = "ERROR: " + str(e).splitlines()[0]
    cur.execute("commit"); return r
print("  tenant 1 reads invoices:", as_tenant(app, 1, "select id, tenant_id, amount from invoices order by id"))
print("  tenant 2 reads invoices:", as_tenant(app, 2, "select id, tenant_id, amount from invoices order by id"))
print("  tenant 1 asks for tenant 2's invoice id 3:", as_tenant(app, 1, "select * from invoices where id = 3"))
print("  no tenant set at all:", q(app, "select count(*) from invoices"))
print("  tenant 1 tries to insert a row for tenant 2:", as_tenant(app, 1, "insert into invoices (tenant_id, customer_id, amount) values (2, 2, 1)"))
print("  tenant 1 tries to update tenant 2's invoice:", as_tenant(app, 1, "update invoices set amount = 0 where id = 3"), "rows changed")
print("\nT2b who bypasses row security (PostgreSQL docs: owners and superusers do)")
print("  table owner/superuser connection sees:", q(adm, "select count(*) from invoices")[0][0], "of 3 rows")
q(adm, "alter table invoices force row level security")
print("  superuser after FORCE ROW LEVEL SECURITY still sees:", q(adm, "select count(*) from invoices")[0][0], "of 3 rows (superusers always bypass)")
q(adm, "create role owner_role nologin"); q(adm, "alter table invoices owner to owner_role"); q(adm, "grant all on invoices to owner_role")
own = conn("owner_role")
q(adm, "alter table invoices no force row level security")
print("  non-superuser table owner, no FORCE:", q(own, "select count(*) from invoices")[0][0], "of 3 rows")
q(adm, "alter table invoices force row level security")
print("  non-superuser table owner, with FORCE:", q(own, "select count(*) from invoices")[0][0], "of 3 rows")
print("\nT3 connection pool hazard: session-level setting leaks to the next request")
cur = app.cursor(); cur.execute("select set_config('app.tenant_id','1', false)")
print("  request A sets tenant 1 at session level, returns connection to the pool")
print("  request B (tenant 2) reuses the connection and forgets to set it:", q(app, "select id, tenant_id from invoices order by id"))
cur.execute("reset app.tenant_id")
print("  with transaction-local settings, the next request on the same connection sees:", q(app, "select count(*) from invoices"))
print("\nT4 cross-tenant references")
q(adm, "alter table invoices no force row level security"); q(adm, "alter table invoices disable row level security"); q(adm, "alter table invoices owner to current_user")
print("  invoice for tenant 1 pointing at tenant 2's customer 2 (single-column reference, no constraint):", q(adm, "insert into invoices (tenant_id,customer_id,amount) values (1,2,5) returning id, tenant_id, customer_id"))
q(adm, "delete from invoices where amount = 5")
q(adm, "alter table customers add constraint customers_tenant_id_uq unique (tenant_id, id)")
q(adm, "alter table invoices add constraint invoices_customer_fk foreign key (tenant_id, customer_id) references customers (tenant_id, id)")
print("  same insert with a composite foreign key (tenant_id, customer_id):", q(adm, "insert into invoices (tenant_id,customer_id,amount) values (1,2,5)"))
print("\nT5 uniqueness")
print("  global UNIQUE(email): second tenant registers a@x.com ->", (q(adm,"alter table customers add constraint email_global unique (email)"), q(adm,"insert into customers (tenant_id,name,email) values (2,'Beta B2','a@x.com')"))[1])
q(adm, "alter table customers drop constraint email_global")
q(adm, "alter table customers add constraint email_per_tenant unique (tenant_id, email)")
print("  UNIQUE(tenant_id,email): same insert ->", q(adm,"insert into customers (tenant_id,name,email) values (2,'Beta B2','a@x.com')"), "row inserted; duplicate inside one tenant ->", q(adm,"insert into customers (tenant_id,name,email) values (1,'Acme dup','a@x.com')"))

Script 3: index, schema, database and deletion measurements. The timings depend on your hardware and will differ, with the same pattern. The figures in this guide come from one run on one machine.

import pgserver, tempfile, psycopg2, time, re
d = tempfile.mkdtemp(); srv = pgserver.get_server(d); uri = srv.get_uri()
def conn(dbname=None):
    u = uri if not dbname else re.sub(r"/[^/?]+(\?|$)", f"/{dbname}\\1", uri)
    c = psycopg2.connect(u); c.autocommit = True; return c
adm = conn(); cur = adm.cursor()
def run(sql, params=None):
    cur.execute(sql, params); return cur.fetchall() if cur.description else cur.rowcount
def timed(sql):
    t = time.perf_counter(); run(sql); return time.perf_counter() - t
print("PostgreSQL", run("select split_part(version(),' ',2)")[0][0], "| max_connections =", run("show max_connections")[0][0])

print("\nT6 index design on a shared table: 1,000,000 events across 1,000 tenants")
run("create table events (tenant_id int not null, id bigserial, created_at timestamptz not null, payload text)")
t0 = time.perf_counter()
run("insert into events (tenant_id, created_at, payload) select (g % 1000) + 1, now() - (g || ' seconds')::interval, 'x' from generate_series(1,1000000) g")
print(f"  loaded in {time.perf_counter()-t0:.1f}s")
q = "select * from events where tenant_id = 500 order by created_at desc limit 50"
def explain(sql):
    best = None
    for _ in range(3):
        cur.execute("explain (analyze, timing off) " + sql); rows = [r[0] for r in cur.fetchall()]
        ms = float(re.search(r"Execution Time: ([\d.]+) ms", rows[-1]).group(1)); best = ms if best is None else min(best, ms)
    plan = rows[0].strip()[:70]
    return best, plan
run("create index events_created_idx on events (created_at desc)"); run("analyze events")
ms, plan = explain(q); print(f"  index on created_at only: {ms:.2f} ms | plan starts: {plan}")
run("drop index events_created_idx"); run("create index events_tenant_created_idx on events (tenant_id, created_at desc)"); run("analyze events")
ms2, plan2 = explain(q); print(f"  index on (tenant_id, created_at): {ms2:.3f} ms | plan starts: {plan2}")
run("drop index events_tenant_created_idx"); ms3, plan3 = explain(q); print(f"  no useful index: {ms3:.1f} ms | plan starts: {plan3}")
print(f"  speedup, composite index vs created_at only: {ms/ms2:,.0f}x")

print("\nT7 schema-per-tenant vs one shared table: running a migration")
N = 300
t0 = time.perf_counter()
for i in range(N):
    run(f"create schema t{i}"); run(f"create table t{i}.items (id serial primary key, name text)"); run(f"insert into t{i}.items (name) select 'n' from generate_series(1,100)")
create_s = time.perf_counter() - t0
print(f"  created {N} tenant schemas, each with 1 table and 100 rows: {create_s:.1f}s ({create_s/N*1000:.0f} ms per tenant)")
t0 = time.perf_counter()
for i in range(N): run(f"alter table t{i}.items add column notes text")
mig_s = time.perf_counter() - t0
print(f"  migration (add one column) across {N} schemas: {mig_s:.2f}s ({mig_s/N*1000:.1f} ms per schema)")
run("create table shared_items (tenant_id int, id serial, name text)")
run(f"insert into shared_items (tenant_id,name) select (g % {N}), 'n' from generate_series(1,{N*100}) g")
t0 = time.perf_counter(); run("alter table shared_items add column notes text"); shared_s = time.perf_counter() - t0
print(f"  same migration on one shared table with the same {N*100:,} rows: {shared_s*1000:.1f} ms")
print(f"  catalog objects created by {N} schemas:", run("select count(*) from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname ~ '^t[0-9]+$'")[0][0], "relations")

print("\nT8 database-per-tenant overhead")
tt = []
for i in range(20):
    t0 = time.perf_counter(); run(f"create database tenant_db_{i}"); tt.append(time.perf_counter() - t0)
print(f"  created 20 databases: avg {sum(tt)/20*1000:.0f} ms each")
print("  size of one empty database:", run("select pg_size_pretty(pg_database_size('tenant_db_0'))")[0][0])
pool = 10
print(f"  with {pool} pooled connections per database, 20 databases need {20*pool} connections; max_connections is {run('show max_connections')[0][0]}")
print(f"  how many databases fit under max_connections at a pool of {pool}:", int(run("show max_connections")[0][0]) // pool)

print("\nT9 removing one tenant: delete rows vs drop schema")
run("create table big_shared (tenant_id int, id serial, v text)")
run("insert into big_shared (tenant_id, v) select (g % 20), 'x' from generate_series(1,2000000) g")
run("create index on big_shared (tenant_id)")
run("create schema bigtenant"); run("create table bigtenant.items (id serial, v text)"); run("insert into bigtenant.items (v) select 'x' from generate_series(1,100000) g")
n = run("select count(*) from big_shared where tenant_id = 7")[0][0]
t0 = time.perf_counter(); run("delete from big_shared where tenant_id = 7"); dt = time.perf_counter() - t0
print(f"  DELETE {n:,} rows of one tenant from a shared table: {dt*1000:.0f} ms")
t0 = time.perf_counter(); run("drop schema bigtenant cascade"); ds = time.perf_counter() - t0
print(f"  DROP SCHEMA with 100,000 rows: {ds*1000:.0f} ms")
print(f"  dead rows left behind in the shared table after the delete:", run("select n_dead_tup from pg_stat_user_tables where relname='big_shared'")[0][0])

The index, schema, database and deletion timings come from a single run on one machine with small data, so treat them as a pattern and not as a benchmark.

Rerun script 3 on your own system, and compare the pattern and not the exact times.

Frequently asked questions

What is multi tenant SaaS?

It is software in which a single running system looks after many customers, known as tenants, and keeps the data and settings of each one apart.

What is a multi-tenant SaaS architecture?

It is the way a product is built so that tenants use one application and one set of infrastructure and still cannot reach each other. The usual options are shared tables, one schema for each tenant, one database for each tenant or a full deployment for each tenant.

What is the difference between single-tenant and multi-tenant SaaS?

Single-tenant gives each customer its own deployment. Multi-tenant shares one deployment. Multi-tenant costs less per customer, and single-tenant isolates customers more easily.

How to build a multi tenant SaaS application?

Define the tenant, put a tenant ID on every tenant-owned table, resolve the tenant once per request, add row-level security, test isolation automatically and set per-tenant limits.

How to build multi tenant SaaS from scratch?

Start with one pooled database, a tenant ID on every table, a restricted database role, row-level security and automated isolation tests, then add limits and provisioning.

What are examples of multi tenant SaaS?

Most business web software serves many customer organizations from shared infrastructure. I do not rely on named examples here, because vendors rarely publish their exact tenancy design.

Is row-level security enough?

It is a strong second layer, but only if the application uses a restricted role, sets the tenant for each transaction and has tests. Owners and superusers bypass it.

Should I use a schema or a database for each tenant?

Use them when tenants need stronger separation or custom layouts, and when the number of tenants is manageable. My tests showed connection limits and per-tenant overhead as the main costs.

What is multi tenant SaaS architecture on Azure?

Searches for multi tenant SaaS architecture Azure usually lead to Microsoft's tenancy guidance. Microsoft publishes guidance on tenancy models, including fully shared, vertically partitioned and single-tenant deployments, and on the considerations for choosing among them.

Is there a multi tenant SaaS boilerplate?

Many starter kits exist. Our SaaS starter kits comparison reads several. Before you use one, check how it identifies tenants, whether it uses row-level security, how it handles caching and jobs, and whether it includes isolation tests.

How do I stop one tenant slowing down others?

Add per-tenant rate limits, concurrency caps and quotas, separate heavy work into its own queues and be ready to move a heavy tenant to dedicated resources.

A quick checklist

Up nextguide to Stripe vs Paddle vs ChargebeeOnce tenants are isolated, you need to bill them correctly. Read our guide to Stripe vs Paddle vs Chargebee, and our merchant of record guide to see who carries tax and compliance for each tenant's payments.

From circuittimes.com/business/multi-tenant-saas/

Was this guide helpful?

Keep going

More in SaaS

See all

The briefing, without the noise.

The stories that matter in technology, every weekday morning.

Free. Unsubscribe in one click.