My account

Multi-tenancy

A multi-tenant system serves many customers (tenants) from one running app. It is cheaper and easier to update than one copy per customer, but one missing filter can show one customer's data to another. Pick an isolation model, put the tenant in one place in every request, and add a safety net in the database.

Not reviewedWritten with AI helpReading time: 17 minExample of a platform that hosts many online shopsC# and EF Core codePostgreSQL

Author: bezzad

Contents

The problem: one app, many shops

Our company sells a platform for online shops. Each shop owner gets their own site, like shop-a.myshop.com, but all shops run on the same app and the same servers. Each shop is a tenant.

We have 4,000 small shops and a few very big ones. Three things can go wrong:

  1. A data leak: one query forgets the shop filter, and shop A sees shop B’s orders. This is the worst bug a SaaS product can have. Customers leave, and in many countries it is a legal problem.
  2. A noisy neighbor: one big shop runs a sale, and all small shops get slow.
  3. Different needs: a big customer wants its data in a separate database, in a certain country.

Multi-tenancy is how we design for all three.

Three isolation models

Shared schemaorderstenant_id = shop-atenant_id = shop-btenant_id = shop-cSchema per tenantshop_a.ordersshop_b.ordersshop_c.ordersDatabase per tenantdb_shop_adb_shop_bdb_shop_ccheapest, one migrationweakest isolationmiddle costmany schemas to migratemost expensivestrongest isolationmore isolation, more cost
From left to right, isolation gets stronger and cost gets higher. Many products use a mix: shared for small tenants, separate for big ones.
  1. Shared schema: all tenants are in the same tables, and every table has a tenant_id column. Cheapest, one migration for everyone, easy to add thousands of tenants. But isolation depends only on your code.
  2. Schema per tenant: one database, but a separate schema (set of tables) per tenant. Better isolation. But a migration must run on thousands of schemas, and some will fail halfway.
  3. Database per tenant: each tenant has its own database. Strongest isolation, separate backup and restore, and the data can be in the country the customer wants. But it is expensive, and managing thousands of databases needs automation.

A common choice is a hybrid: small tenants share, big or special tenants get their own database. A small tenant catalog table says where each tenant’s data lives, and the app connects to the right place.

Put the tenant in one place

Requestshop-a.myshop.comFind the tenantfrom the host name or tokenTenant contextTenantId = shop-aDatabase queryWHERE tenant_id = @tCache keyshop-a:product:42Logs and metricstenant=shop-aSafety net: Row-Level Securitythe database also checks tenant_id, even if the app code forgets
The app finds the tenant once, at the start of the request. Everything after that reads it from the tenant context, never from user input.

The tenant must come from something the user cannot change freely: the host name, or a claim inside a signed token. Never trust a tenantId in the request body or the query string.

public interface ITenantContext
{
    string TenantId { get; }
}

public sealed class TenantMiddleware(RequestDelegate next)
{
    public async Task Invoke(HttpContext http, TenantContext ctx,
        ITenantCatalog catalog)
    {
        // shop-a.myshop.com -> "shop-a"
        var slug = http.Request.Host.Host.Split('.')[0];
        var tenant = await catalog.FindAsync(slug);
        if (tenant is null)
        {
            http.Response.StatusCode = 404;
            return;
        }
        ctx.Set(tenant.Id);
        await next(http);
    }
}
  1. TenantContext is registered as scoped, so each request has its own copy.
  2. If the user is signed in, also check that the user belongs to this tenant. A valid user of shop B must not use shop A’s site.
  3. Background jobs and queue messages have no HTTP request. Put the tenant id inside the message, and set the tenant context before the job runs.

A filter you cannot forget

Writing Where(o => o.TenantId == tenantId) in every query does not work. Someone will forget it one day. Put the filter in one place instead. In EF Core, a global query filter adds it to every query on that entity:

public sealed class ShopDb(DbContextOptions<ShopDb> options,
    ITenantContext tenant) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Order>()
            .HasQueryFilter(o => o.TenantId == tenant.TenantId);
        b.Entity<Order>()
            .HasIndex(o => new { o.TenantId, o.CreatedAt });
    }
}
  1. Now db.Orders.ToListAsync() only returns orders of the current shop.
  2. Set TenantId on new rows in one place too, for example in SaveChanges, not in each handler.
  3. Indexes start with tenant_id. Almost every query filters by tenant, so the index must too.
  4. Unique keys include the tenant: two shops can both have an order number 1001.
  5. Raw SQL and IgnoreQueryFilters() skip the filter. Search for them in code review.

A safety net in the database

The app filter can still have a hole: a raw SQL query, a reporting script, a new developer. In PostgreSQL, Row-Level Security (RLS) makes the database itself check the tenant:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id'));
// at the start of each transaction, before other queries
await db.Database.ExecuteSqlAsync(
    $"SELECT set_config('app.tenant_id', {tenant.TenantId}, true)");
  1. If the app forgets the filter, the database still returns only the current tenant’s rows.
  2. The value true means “only for this transaction”. This matters with a connection pool, where the next request may get the same connection.
  3. The app must connect with a normal database user, not the table owner or a superuser, because those can skip RLS.
  4. FORCE makes the policy apply to the table owner too.

Everything else needs the tenant too

A leak is not only in SQL. Check every place that keeps data:

  1. Cache keys: product:42 is shared by all shops. Use shop-a:product:42.
  2. File storage: put files under a tenant folder, like shop-a/invoices/, and check the tenant before you give a download link.
  3. Search indexes and queues: add the tenant to every document and every message.
  4. Logs, metrics and traces: add a tenant tag. Then you can answer “is it slow for everyone, or only for shop A?”

The noisy neighbor

In the shared model, all tenants use the same CPU, database and queue. To protect them from each other:

  1. Rate limits per tenant, not only per user.
  2. Quotas: max products, max file size, max API calls per plan.
  3. Separate queues or workers for heavy jobs like big exports, so one shop’s report does not delay everyone’s emails.
  4. Move a tenant that grows too big to its own database. Design the catalog from the start so this is a config change, not a rewrite.

Common mistakes

Mistake Result Better way
tenantId from the request body A user changes it and reads another shop. Take it from the host name or the signed token.
A Where on tenant in each query One forgotten query leaks data. A global query filter, plus RLS.
Cache key without the tenant Shop B sees shop A’s product page. Start every key with the tenant id.
Index without tenant_id first Slow queries as the table grows. Indexes and unique keys start with tenant_id.
Background job without a tenant It runs on the wrong data, or all data. Put the tenant id in the message.
One database for everyone, forever A big tenant slows all others. A tenant catalog, and move big tenants out.

Summary in 6 lines

  1. Multi-tenancy is many customers on one app. It is cheap, but a data leak between tenants is the worst bug.
  2. Models: shared schema, schema per tenant, database per tenant. Many products mix them with a tenant catalog.
  3. Find the tenant once per request, from the host name or a signed token, never from user input.
  4. Put the filter in one place (a global query filter), and add a safety net in the database (Row-Level Security).
  5. Cache keys, files, search, queues, logs and jobs all need the tenant too.
  6. Protect tenants from each other with per-tenant limits and quotas, and move big tenants to their own database.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.