KODVEXATECHNOLOGIES

SaaS Development

Designing Multi-Tenancy for SaaS: Isolation, Data and Noisy Neighbours

Multi-tenancy decisions made early in a SaaS product are expensive to change later. This guide compares isolation models, data partitioning approaches, noisy neighbour controls and billing hooks.

Kodvexa Engineering · · 8 min read

Multi-tenancy means serving many customers, or tenants, from a single product while keeping each tenant's data and experience separate. It is what makes software as a service economical: one codebase, one deployment process and shared infrastructure instead of a separate installation per customer. It is also one of the few architectural decisions that touches almost every part of a SaaS product, from the database schema to billing.

Getting it right early matters because changing the tenancy model of a live product means migrating customer data. This article covers the main choices and the trade-offs between them.

The main isolation models

Tenancy models sit on a spectrum from fully shared to fully isolated. Each step towards isolation improves separation and flexibility but increases cost and operational effort.

Shared database, shared schema

All tenants share the same tables, and every row carries a tenant identifier. This is the cheapest and simplest model to operate, since there is one database to migrate, back up and monitor. Onboarding a new tenant is just inserting a row. The risk is that isolation depends entirely on the application filtering correctly; a single missing filter can expose one tenant's data to another.

Shared database, schema per tenant

Each tenant gets its own schema within a shared database. Isolation is stronger because queries naturally target one schema, and per-tenant customisation is easier. However, migrations must run against every schema, and very large numbers of schemas can strain database tooling and connection management.

Database per tenant

Each tenant has a dedicated database. This gives the strongest data isolation, simple per-tenant backup and restore, and the option to place a tenant's data in a specific region. It also costs the most and requires automation for provisioning, migrating and monitoring many databases. Elastic pools on Azure SQL and similar offerings on other platforms can reduce the cost of this model.

Hybrid approaches

Many mature SaaS products mix models. Smaller customers share a pooled database, while larger customers with contractual or regulatory requirements get dedicated databases or even dedicated deployments. Designing the application so that the tenant's data location is resolved through a catalogue, rather than hard-coded, makes this possible later.

Making shared-schema isolation safe

If you choose a shared schema, tenant filtering should never depend on developers remembering to add a condition to every query. Enforce it centrally so that the safe path is the default path.

  • Resolve the tenant once per request from a trusted source, such as a claim in a validated token, never from a value the client can freely change
  • Store the current tenant in a request-scoped context available to the data layer
  • Apply tenant filters automatically in the data access layer or ORM
  • Use database-level row-level security as a second line of defence where your database supports it
  • Include the tenant identifier in unique indexes and foreign keys so that cross-tenant references cannot be created
  • Write automated tests that attempt cross-tenant access and confirm it fails

In Entity Framework Core, a global query filter applies the tenant condition to every query against an entity type, and saving logic can stamp the tenant on new records:

csharp
public class AppDbContext : DbContext
{
    private readonly ITenantContext _tenant;

    public AppDbContext(DbContextOptions<AppDbContext> options, ITenantContext tenant)
        : base(options) => _tenant = tenant;

    public DbSet<Invoice> Invoices => Set<Invoice>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>()
            .HasQueryFilter(i => i.TenantId == _tenant.TenantId);

        modelBuilder.Entity<Invoice>()
            .HasIndex(i => new { i.TenantId, i.Number })
            .IsUnique();
    }

    public override Task<int> SaveChangesAsync(CancellationToken ct = default)
    {
        foreach (var entry in ChangeTracker.Entries<ITenantOwned>()
                     .Where(e => e.State == EntityState.Added))
        {
            entry.Entity.TenantId = _tenant.TenantId;
        }
        return base.SaveChangesAsync(ct);
    }
}

Be aware of the escape hatches. Raw SQL, stored procedures, reporting queries and background jobs may bypass the ORM filter, and EF Core's IgnoreQueryFilters method disables it deliberately. Review those paths carefully, and make sure background jobs establish the tenant context explicitly before touching data.

Tenant context beyond the database

Isolation applies to more than tables. Caches, file storage, search indexes and message queues all need tenant awareness. Prefix cache keys and storage paths with the tenant identifier, include it in messages so that consumers can set the correct context, and filter search queries by tenant. Logs and traces should carry the tenant identifier too, which makes support and debugging much easier.

Dealing with noisy neighbours

In shared infrastructure, one tenant's heavy usage can degrade performance for everyone else. A large data import, an expensive report or an integration stuck in a retry loop can all consume a disproportionate share of resources.

  • Apply rate limits per tenant on APIs, not just globally, with limits that can vary by plan
  • Move heavy operations such as imports, exports and reports to background queues with per-tenant concurrency limits
  • Set query timeouts and pagination limits so that a single request cannot scan unbounded data
  • Monitor resource usage by tenant so that you can identify who is causing load
  • Keep the option to move a demanding tenant to dedicated capacity without code changes

Hooks for metering and billing

Pricing models change as a SaaS business learns what customers value. Even if you start with simple per-seat subscriptions, building the hooks for usage metering early keeps future options open.

  • Emit usage events for billable actions, such as active users, documents processed or API calls, tagged with the tenant
  • Store usage in an append-only record that can be aggregated and audited later
  • Keep entitlements, meaning which features and limits each plan includes, in configuration rather than scattered through code
  • Check entitlements in one place so that plan changes take effect consistently
  • Integrate with a billing provider through a clear boundary, so that the provider can be changed without rewriting product logic

Operational considerations

Tenant lifecycle needs as much design as the data model. Automate onboarding so that creating a tenant provisions everything required, including any dedicated resources. Plan offboarding too: customers leaving the service may be entitled to an export of their data, and you will need a reliable way to delete it afterwards in line with your contracts and applicable law.

Support teams often need to see a tenant's view to diagnose problems. Build this as an audited, time-limited impersonation feature rather than giving staff direct database access.

Summary

Pick the isolation model that your customers' requirements actually call for, enforce tenant boundaries centrally rather than by convention, extend tenant awareness to every shared resource, and build in metering and per-tenant controls before you need them. These foundations let a SaaS product grow from its first customer to its thousandth without a disruptive rebuild.

Want to discuss this with our engineers?

Tell us about your system and the decision in front of you. We will share a practical perspective.