Skip to content

Multi-Tenant SaaS Architecture: Choosing a Tenant Isolation Model

Shared tables, schema-per-tenant or database-per-tenant? Trade-offs, enforcing isolation with PostgreSQL row-level security and Spring Boot, and per-org roles.

Agatti One Engineering4 min read

The first real architecture decision in a SaaS product is how to keep one customer's data away from another's. It affects your schema, your migrations, your hosting costs, your support workflow and how you sleep at night. It is also hard to change later, so it is worth getting right early.

There are three common models. None of them is universally correct. The right choice depends on how many tenants you expect, how different their needs are, and what your customers will ask about during a security review.

The three isolation models

Shared database, shared tables, tenant_id column

Every tenant-owned table has a tenant_id column, and every query filters by it. This is the simplest to operate: one database, one set of migrations, one connection pool. It scales well to large numbers of small tenants and makes cross-tenant reporting for your own team straightforward.

The risk is obvious: a single missing WHERE clause leaks data. You need a mechanism that enforces the filter even when a developer forgets, which we cover below. Noisy neighbors are also a concern, since one heavy tenant shares resources with everyone.

Schema per tenant

Each tenant gets its own PostgreSQL schema with identical tables. Isolation is stronger by default, and per-tenant backup or export is easier. The cost is operational: migrations must run across every schema, connection handling becomes more involved, and catalog overhead grows as the number of schemas grows. It works well for tens or low hundreds of tenants, and gets painful beyond that.

Database per tenant

Each tenant has a dedicated database, sometimes on dedicated infrastructure. This gives the strongest isolation, easy per-tenant restore, and the option to place data in a specific region. It is also the most expensive and the most work to operate. It makes sense for a small number of large customers with contractual isolation requirements, and it is common to offer it as a premium tier on top of a shared model.

Our default: shared tables with enforced isolation

For most business SaaS products we start with shared tables and a tenant_id column, then enforce isolation at two layers: the application and the database. If a large customer later needs dedicated infrastructure, the same schema can be deployed to a separate database for them without changing the code.

The database layer is PostgreSQL row-level security. Each request sets the current tenant on the connection, and a policy restricts every read and write to rows for that tenant. Even a query that forgets to filter will only ever see its own tenant's data.

Row-level security policy keyed on a per-transaction setting.sql
ALTER TABLE invoice ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoice FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoice
  USING (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

-- Set per transaction, so it cannot leak to the next request on a pooled connection
SELECT set_config('app.tenant_id', '6f1c2e3a-0b7d-4c2e-9a51-3d8f0e2b7c44', true);

Two details matter here. FORCE ROW LEVEL SECURITY makes the policy apply to the table owner too, and the application should connect as a role that is not a superuser and does not have BYPASSRLS. Passing true as the third argument to set_config scopes the value to the current transaction, which is important with connection pooling.

Carrying tenant context through Spring Boot

On the application side, the tenant is resolved once per request, typically from a claim in the authenticated user's token, never from a header the client can set freely. It is stored in a request-scoped holder and applied to the database connection at the start of each transaction.

Resolve the tenant from the verified token, then set it on the transaction.java
@Component
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth instanceof JwtAuthenticationToken jwt) {
            TenantContext.set(UUID.fromString(jwt.getToken().getClaimAsString("tenant_id")));
        }
        try {
            chain.doFilter(request, response);
        } finally {
            TenantContext.clear();
        }
    }
}

@Component
@RequiredArgsConstructor
public class TenantConnectionPreparer {

    private final JdbcTemplate jdbc;

    // Call at the start of each transactional unit of work
    public void apply() {
        UUID tenantId = TenantContext.require();
        jdbc.queryForObject("SELECT set_config('app.tenant_id', ?, true)",
                String.class, tenantId.toString());
    }
}

In practice we wire the apply step into a transaction-level hook or an aspect around service methods so that nobody has to remember to call it. The filter must also be registered after Spring Security's filter chain so that the authentication object is available. Background jobs and message consumers need the same treatment: they should set tenant context explicitly from the job payload rather than inherit it by accident.

Roles and permissions per organization

Multi-tenancy is not only about data isolation. A single user may belong to more than one organization, with a different role in each. Model this explicitly:

  • A user table that is global, holding identity and login details.
  • A membership table linking user, tenant and role, so that roles are always scoped to an organization.
  • Permissions expressed as fine-grained actions, such as invoice.approve or member.invite, grouped into roles. Checks in code refer to permissions, not role names.
  • Tenant-defined custom roles only when customers actually ask for them. Fixed roles cover more cases than people expect.

When a user switches organizations, issue a new token scoped to that tenant rather than letting the client pass a tenant identifier on each request. It keeps the trust boundary in one place.

Choosing for your product

If you expect many small or mid-sized customers and a mostly uniform feature set, shared tables with row-level security is a strong default. If you have a handful of large customers with strict contractual requirements, plan for database-per-tenant, at least as an option. Schema-per-tenant sits in between and is reasonable when the tenant count will stay modest. Whichever model you pick, make the tenant boundary explicit in the code, enforce it in the database, and test it continuously.

  • SaaS
  • multi-tenancy
  • PostgreSQL
  • Spring Boot
  • security

Keep reading

Start a project

Have a business process that needs better software?

Tell us what you're trying to improve. We'll help you understand what can be automated, built or integrated.