Home / Insights / Web and SaaS Development

Web and SaaS Development

Proving Tenant Isolation in a Multi-Tenant SaaS: Controls and Tests That Hold Up

One customer seeing another customer’s data is the incident most SaaS businesses fear most. Preventing it takes layered controls and, just as importantly, tests that prove those controls work on every release.

TopicsWeb and SaaS DevelopmentQA and Software Testing

Key takeaways

  • Establish tenant context once, early in each request, from a server-verified membership check, never from a client-supplied ID alone.
  • Enforce isolation in the database (for example PostgreSQL row-level security) as well as in application code; ORM filters alone miss raw queries and new code paths.
  • Caches, file storage, search indexes, background jobs and exports leak data as often as primary queries do.
  • Write an automated cross-tenant test suite that runs in CI and fails on any table or endpoint without an isolation control.
  • Be able to answer an enterprise customer’s security questionnaire with evidence, not assurances.

Most multi-tenant SaaS products share infrastructure between customers: the same application servers, the same database cluster and often the same tables. That is what makes SaaS economical. It also means a single missing filter can expose one tenant’s data to another.

Our article on planning a SaaS product around tenancy, billing and operations covers how to choose a tenancy model. This one assumes the model is chosen and asks a narrower question: how do you enforce isolation consistently, and how do you prove it to yourself, your auditors and enterprise buyers?

Where cross-tenant leaks actually happen

Teams usually think about the main database query. In practice, leaks tend to come from the edges.

SurfaceTypical failure
API endpointsA record fetched by ID without checking it belongs to the caller’s tenant (an insecure direct object reference)
CachingA cache key without the tenant ID, so one tenant’s dashboard is served to another
Files and blobsPredictable storage paths or signed URLs issued without checking the exact object
Background jobsA queued job that carries a tenant ID nobody re-verifies, or runs with privileged database access
Search indexesA shared index queried without a mandatory tenant filter
Exports and reportsAggregation queries written in raw SQL that skip the ORM’s tenant scope
Connection poolingA session-level tenant setting left on a pooled connection and reused by the next request
Support toolsAdmin “view as customer” features without audit trails or scoping

A credible isolation strategy addresses every row in this table, not just the first.

Establish tenant context once, and trust only the server’s version

Every request should resolve a single, verified tenant context before any business logic runs, typically in middleware. The OWASP Multi-Tenant Security Cheat Sheet makes an important distinction: a tenant ID supplied by the client (in a header, subdomain, URL or token claim) is a selector, not proof. The server must confirm the authenticated user currently holds membership in that tenant.

  • Resolve the tenant from the request, then check membership against your own records.
  • Attach the verified context to the request and pass it to services, repositories and jobs explicitly.
  • Do not let downstream code replace the verified context with a value taken from the payload.
  • Fail closed: if tenant context is missing, the request errors rather than running unscoped.

Users who belong to several tenants, such as consultants, accountants or agency staff, are the common edge case. Model membership as a many-to-many relationship from the start, and make switching tenant an explicit action.

Enforce isolation in the database, not only in code

Application-level filters, such as an ORM scope that adds tenant_id = ? to every query, are useful but brittle. A developer writing a raw query for a report, a new service using a different data access library, or a migration script can bypass them.

Row-level security in PostgreSQL

For shared-table designs on PostgreSQL, row-level security (RLS) puts the rule in the database itself. Points that matter in practice:

  • Enable RLS and force it on every tenant-owned table, so the table owner is also subject to it.
  • Run normal application requests under a database role that is neither a superuser nor granted BYPASSRLS; both bypass policies. Keep privileged connections for migrations and audited admin jobs.
  • Set the tenant per transaction (for example with SET LOCAL) rather than per session, because session settings can carry over on pooled connections.
  • Write policies so that a missing tenant setting returns no rows, not all rows.

Separate schemas or databases

Separate schemas or databases give a stronger boundary, but only if credentials, network access, backups and admin paths are separated too. They are often used for a subset of enterprise customers alongside a shared default, which is the hybrid approach many SaaS products settle on. Whatever the mix, document which boundary applies to which data and test each one.

Isolation beyond the primary database

  • Caches: classify cached data as global, tenant-scoped or user-scoped. Include the tenant ID in keys for anything tenant-specific, and authorise before returning cached protected data.
  • Files: partition storage by tenant prefix or bucket, and check the requester may access the exact object before issuing a signed URL.
  • Queues and jobs: bind tenant context to messages through trusted metadata and re-verify it in the consumer. Avoid giving workers blanket privileged access.
  • Search: enforce a tenant filter in a shared query layer so individual features cannot forget it, or use per-tenant indexes for higher-risk data.
  • Encryption: per-tenant keys are worth considering where contracts or regulation require cryptographic separation.
  • Audit logs: record verified tenant and acting identity on security events, keep logs append-only and alert on denied cross-tenant attempts.

Building a cross-tenant test suite

Controls drift as the product grows. A new table is added without a policy; a new endpoint skips the membership check. The defence is an automated suite that runs on every pull request.

What the suite should include

  1. Two-tenant fixtures: seed tenants A and B with comparable data, plus a user who belongs to both.
  2. Endpoint matrix: for each API endpoint, call it as a user of tenant A with tenant B’s resource IDs and assert a denial (typically 404 to avoid confirming existence).
  3. Schema coverage check: compare the list of tenant-owned tables against the database catalogue and fail the build if any lacks RLS or a policy. Treat unclassified tables as failures.
  4. Role check: assert that the application’s runtime database role has no superuser or bypass privileges in deployed environments.
  5. Pooled-connection test: run requests for both tenants on reused connections and confirm nothing carries over.
  6. Cache, file and search tests: fetch as tenant A after tenant B has warmed the cache or uploaded a file.
  7. Backup restore test: periodically restore one tenant’s data in isolation and confirm no other tenant’s data is present.

Run the suite through the same connection pool and roles the application uses in production; tests that connect as a superuser will pass while production is vulnerable. This fits naturally into the pipeline described in continuous testing in DevOps, and periodic external penetration testing should include cross-tenant scenarios explicitly.

Turning controls into evidence for enterprise buyers

Enterprise customers will ask how their data is separated. A short internal document that describes the tenancy model, the enforcement layers, the automated test suite and the audit logging makes security questionnaires faster and more credible. Include how support staff access customer data and how that access is logged.

PoliteTech’s SaaS product development service treats tenancy as a platform layer with an owner, tests and documentation, and supports clients with customer security questionnaires.

Frequently asked questions

Is row-level security enough on its own?

No. It is a strong database-level control, but data also flows through caches, files, search indexes, queues and exports. Use RLS as one layer alongside verified tenant context and tests for each surface.

Should every enterprise customer get a separate database?

Not necessarily. Separate databases add operational cost for migrations, monitoring and backups. Many products use shared tables by default and offer dedicated instances to customers whose contracts or regulators require them.

What HTTP status should a cross-tenant request return?

Many teams return 404 rather than 403 so that the response does not confirm the resource exists. Whichever you choose, apply it consistently and log the attempt.

How often should we run cross-tenant tests?

On every pull request for the automated suite, with the schema coverage check blocking merges. Backup restore tests and external penetration tests can run on a periodic schedule.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. OWASP Cheat Sheet Series: Multi-Tenant Security Cheat Sheet — Supported guidance on treating client tenant IDs as selectors, PostgreSQL RLS with forced policies and non-bypass roles, transaction-scoped tenant settings, cache and file isolation, and cross-tenant test practices.

Could you prove your SaaS keeps every tenant’s data separate?

We can review your tenancy controls and help you build a cross-tenant test suite into your pipeline.