📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📰 One Codebase, Many Tenants: How ShiftTracko Isolates Customer Data in ASP.NET Core

One Codebase, Many Tenants: How ShiftTracko Isolates Customer Data in ASP.NET Core

In a normal web app, a bug in a query usually means someone sees the wrong page or a broken list. In a multi-tenant app, the same bug can mean one business sees another business's staff, clients, jobs or timesheets. That's not just a bug report. It's a trust problem, and possibly a privacy one.

Since August 2025 I've been building ShiftTracko, a multi-tenant, multi-domain SaaS for employee and tradie management. It has an ASP.NET Core Web API backend, an ASP.NET Core MVC frontend and OAuth authentication. Every customer shares the same codebase, so the most important rule in the whole system is simple to say and surprisingly easy to break: a tenant must only ever see its own data.

This post is about how I think about that rule in ASP.NET Core: which isolation model to choose, how a request works out which tenant it belongs to, and the safety nets that stop one forgotten Where clause from leaking data.

Why I'm building ShiftTracko

When I look at how tradies in Australia run their business, most of them still do it by hand. Jobs live in Excel files, client details sit in phone notes, and the plan for the week is in someone's head or a group chat. There's a real gap between the work that needs doing, the clients who asked for it, and the tradies doing it.

ShiftTracko is built to close that gap. It works for any kind of tradie, whether that's a plumber, an electrician, a carpenter or a cleaner, and it keeps track of jobs, clients, staff and the work in between, all in one place.

That also tells you what the tenants look like. Most of them are small businesses: a sole trader, or a crew of a few people. There are going to be a lot of them, and each one has a fairly small amount of data. That shaped almost every decision below.

The three ways to split tenant data

Before writing any code, you have to decide where the walls go. There are three common models:

Model How it works Good at Watch out for
Database per tenant Each tenant gets its own database Strongest isolation, easy per-tenant backup and restore More databases to migrate, monitor and pay for
Schema per tenant One database, a schema per tenant Some isolation, fewer servers Migrations multiply, tooling support is patchier
Shared tables + TenantId Every row carries a TenantId column Cheapest, simplest to run, one migration Isolation depends entirely on your code being right

None of these is "the correct one". They trade isolation against cost and operational effort. A bank's customers might expect a database each. A small-business app with many small tenants usually leans towards shared tables.

Why ShiftTracko uses shared tables with a TenantId

For ShiftTracko I went with shared tables and a TenantId column on every tenant-owned row. These were the main reasons:

  • The tenants are many and small. Microsoft's guidance on multitenant data puts it simply: the more tenants you fit on the same infrastructure, the lower the cost per tenant. A sole trader with a few dozen jobs a month doesn't need a database of their own, and giving each one a database would cost more to run than many of them would pay.
  • Signing up should be instant. A new tradie should be able to sign up and start adding jobs straight away. With shared tables, a new tenant is just a new row. There's no database to create, no connection string to store, and no migration to run before they can log in.
  • One schema, one migration. Every release runs one set of EF Core migrations against one database. With a database per tenant, every schema change has to be rolled out to every tenant database, and you have to deal with the ones that fail halfway.
  • EF Core supports it well. The EF Core docs list global query filters as the way to handle a tenant column, and database-per-tenant as a configuration concern. Schema per tenant is the model EF Core doesn't support directly, so I ruled that out early.
  • It doesn't close the door. If a large customer ever needs its own database for compliance or performance, the same TenantId design can move to a hybrid model later, with most tenants in the shared database and a few on their own.

The cost of this choice is clear: the database won't protect me, so the application code has to. The rest of this post is about the safety nets that make that realistic.

Step one: work out who the tenant is

Every request has to answer one question before it touches any data: which tenant is this?

ShiftTracko is multi-domain. A business can use a subdomain of the main ShiftTracko domain, or point its own domain at the app. So the request's host name is the natural place to start. Other common sources are a claim in the user's token, a route segment like /t/{tenant}/..., or a header that a frontend sends to the API.

Each source has trade-offs:

  • Host name or subdomain feels clean for customers and works well with custom domains, but you need DNS and TLS set up for each one.
  • A claim in the token is hard to tamper with, because the identity provider signs it.
  • A header is easy to send from your own frontend, but anyone can set a header, so you must never trust it on its own.

The rule I follow: the tenant you resolve must be checked against the signed-in user. The domain tells you which tenant the request claims to be for. The user's identity tells you whether they're actually allowed in.

Subdomains and custom domains

In ShiftTracko, the ASP.NET Core MVC app works out the tenant from the host name. That means keeping a mapping from host names to tenants, which covers both cases:

  • joes-plumbing.<main-domain> is a subdomain we hand out at sign-up.
  • jobs.joesplumbing.com.au is the tenant's own domain, added later and pointed at the app.

Custom domains add a few things to think about:

  • Normalise the host first. Lower-case it, strip the port, and decide whether www. counts as the same domain. Otherwise Jobs.JoesPlumbing.com.au and jobs.joesplumbing.com.au look like two different tenants.
  • Verify ownership before it goes live. Someone shouldn't be able to add a domain they don't own to their tenant. A DNS record check before the domain is marked active handles this.
  • TLS for every domain. Every custom domain needs its own certificate, issued and renewed automatically.
  • Unknown hosts get nothing. If a host doesn't map to an active tenant, the answer is 404, not a default tenant.

Here's a simplified example of resolving the tenant in middleware. This is illustrative code written for this post, not code from ShiftTracko.

// Example only: a scoped holder for the current tenant.
public interface ITenantContext
{
    Guid TenantId { get; }
    bool IsResolved { get; }
}

public sealed class TenantContext : ITenantContext
{
    public Guid TenantId { get; private set; }
    public bool IsResolved { get; private set; }

    public void Set(Guid tenantId)
    {
        if (IsResolved)
            throw new InvalidOperationException("Tenant is already set for this request.");

        TenantId = tenantId;
        IsResolved = true;
    }
}

// Example only: resolve the tenant from the host, then check the user belongs to it.
public sealed class TenantResolutionMiddleware
{
    private readonly RequestDelegate _next;

    public TenantResolutionMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext context, TenantContext tenant, ITenantStore store)
    {
        // Normalise: lower-case, no port. Subdomains and custom domains share one lookup.
        var host = context.Request.Host.Host.ToLowerInvariant();
        var tenantId = await store.FindActiveIdByHostAsync(host, context.RequestAborted);

        if (tenantId is null)
        {
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            return;
        }

        if (context.User.Identity?.IsAuthenticated == true)
        {
            var claim = context.User.FindFirst("tenant_id")?.Value;
            if (claim != tenantId.Value.ToString())
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                return;
            }
        }

        tenant.Set(tenantId.Value);
        await _next(context);
    }
}

Two details matter here. The tenant context is scoped, so it lives for exactly one request. And it can only be set once, so nothing further down the pipeline can quietly switch tenants halfway through a request.

The host lookup runs on every request, so it's worth caching. Just make sure the cache entry is cleared when a domain is removed or a tenant is suspended, or the old mapping will keep working until it expires.

When there's no host name

Host-based resolution works well for a website. It doesn't work for a mobile app, which calls the API directly and has no subdomain of its own. So for API calls, the signed-in user's token has to carry the tenant, and the API has to treat that claim as the source of truth.

That's one reason I like keeping the real isolation rules in the API and the DbContext, not in the frontend. Whichever app sends the request, it hits the same walls.

Step two: make the database filter by default

With shared tables, the scariest bug is a query that forgets .Where(x => x.TenantId == currentTenant). On a big codebase, someone will forget it eventually. That someone might be me at 11pm, or an AI assistant generating a new endpoint.

So the filter shouldn't depend on anyone remembering. EF Core has global query filters for exactly this: a filter you declare once on the model, which is added to every query for that entity.

// Example only: every tenant-owned entity implements this.
public interface ITenantOwned
{
    Guid TenantId { get; set; }
}

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

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

    public DbSet<Client> Clients => Set<Client>();
    public DbSet<Job> Jobs => Set<Job>();
    public DbSet<Employee> Employees => Set<Employee>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Client>().HasQueryFilter(c => c.TenantId == _tenant.TenantId);
        modelBuilder.Entity<Job>().HasQueryFilter(j => j.TenantId == _tenant.TenantId);
        modelBuilder.Entity<Employee>().HasQueryFilter(e => e.TenantId == _tenant.TenantId);

        // Index TenantId first: almost every query now starts with it.
        modelBuilder.Entity<Employee>().HasIndex(e => new { e.TenantId, e.Email }).IsUnique();
        modelBuilder.Entity<Job>().HasIndex(j => new { j.TenantId, j.ScheduledFor });
    }
}

Now _db.Jobs.ToListAsync() only returns the current tenant's jobs, even if the developer never thought about tenants at all.

A few things I keep in mind with query filters:

  • They're per entity. Add a new tenant-owned table and forget the filter, and you're back to square one. A reflection-based loop over every ITenantOwned type in OnModelCreating helps, and so does a test that fails when one is missing (more on that below).
  • IgnoreQueryFilters() is a loaded gun. It's sometimes needed for platform admin screens or background jobs. I treat every use of it as something that needs a comment explaining why, and a careful review.
  • Raw SQL isn't filtered. FromSql and Dapper queries bypass the model filter, so they need the tenant condition written by hand.
  • Unique indexes should include TenantId. Two different businesses can both have an employee called [email protected]. The index above allows that, while still stopping duplicates inside one tenant.
  • Composite indexes should start with TenantId. Almost every query now filters by tenant first, so the indexes should match.

Step three: stamp the tenant on every write

Reads are only half the story. If a new record is saved with the wrong TenantId, or an empty one, it either disappears from its owner's view or shows up in someone else's.

Rather than trusting every handler to set TenantId, I'd rather the DbContext do it for me and refuse anything that looks wrong:

// Example only: set TenantId on new rows and block cross-tenant edits.
public override Task<int> SaveChangesAsync(CancellationToken ct = default)
{
    if (!_tenant.IsResolved)
        throw new InvalidOperationException("No tenant set for this unit of work.");

    foreach (var entry in ChangeTracker.Entries<ITenantOwned>())
    {
        switch (entry.State)
        {
            case EntityState.Added:
                entry.Entity.TenantId = _tenant.TenantId;
                break;

            case EntityState.Modified:
            case EntityState.Deleted:
                if (entry.Entity.TenantId != _tenant.TenantId)
                    throw new InvalidOperationException("Cross-tenant write blocked.");
                break;
        }
    }

    return base.SaveChangesAsync(ct);
}

It's a small piece of code, but it means a handler can't save a row into the wrong tenant even if it tries. The application code gets simpler too, because nobody has to remember to set TenantId on create. The IsResolved check at the top also stops a job or a test from saving data with an empty tenant id by accident.

Step four: don't forget the work outside a request

Middleware works nicely for HTTP requests. But a real SaaS does a lot of work outside requests too, and ShiftTracko is no different: it runs scheduled jobs, sends emails, and generates reports. There's no host name and no signed-in user in any of those places, so the tenant has to be passed in explicitly.

The pattern I use is to make the tenant part of the job's input, and set the tenant context at the start of the job's scope:

// Example only: a background job runs inside one tenant's scope.
public sealed class SendJobRemindersJob
{
    private readonly IServiceScopeFactory _scopes;

    public SendJobRemindersJob(IServiceScopeFactory scopes) => _scopes = scopes;

    public async Task RunAsync(Guid tenantId, CancellationToken ct)
    {
        using var scope = _scopes.CreateScope();
        scope.ServiceProvider.GetRequiredService<TenantContext>().Set(tenantId);

        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var tomorrow = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(1));

        var jobs = await db.Jobs
            .Where(j => j.ScheduledFor == tomorrow)
            .ToListAsync(ct); // already filtered to this tenant

        // send reminders to the assigned tradies and their clients...
    }
}

A job that loops over all tenants should create a fresh scope for each tenant, rather than reusing one DbContext across tenants. Reusing it means the change tracker and the tenant context can carry one tenant's data into the next.

The same thinking applies to everything else that runs in the background:

  • Emails. An email belongs to a tenant too. The links inside it should point at that tenant's own domain or subdomain, and the branding and reply-to address should be theirs, not another customer's.
  • Reports. A report is just a set of queries, so it should run inside the tenant's scope like any other job. If the report is saved as a file, the storage path should include the tenant id, and the download link should check the tenant again.
  • Caching. A cache key like "jobs-this-week" will happily serve one tenant's list to another. Every key for tenant data should include the tenant id, for example $"tenant:{tenantId}:jobs-this-week".
  • File uploads. Photos of a finished job or a signed quote should be stored under the tenant, and served only after checking the tenant on the request.

Step five: test the walls, not just the features

Most tests check that a feature works for one user. For multi-tenancy, the more important test is the opposite: tenant A must not see tenant B's data.

These are the isolation tests I treat as must-haves for ShiftTracko. Each one catches a different kind of mistake.

1. The two-tenant read test

Seed two tenants, read as one, and make sure the other one never shows up:

// Example only: an isolation test with two tenants.
[Fact]
public async Task Clients_from_another_tenant_are_never_returned()
{
    var tenantA = Guid.NewGuid();
    var tenantB = Guid.NewGuid();

    await SeedClientAsync(tenantA, "Alex Builders");
    await SeedClientAsync(tenantB, "Blair Electrical");

    await using var db = CreateDbContextFor(tenantA);
    var names = await db.Clients.Select(c => c.Name).ToListAsync();

    Assert.Equal(new[] { "Alex Builders" }, names);
}

2. The "every table has a filter" test

This one uses reflection to find every entity that implements ITenantOwned and fails if any of them has no query filter. It catches the "new table, forgot the filter" mistake before it ships, which is the one I'm most worried about.

// Example only: fail the build if a tenant-owned entity has no query filter.
[Fact]
public void Every_tenant_owned_entity_has_a_query_filter()
{
    using var db = CreateDbContextFor(Guid.NewGuid());

    var missing = db.Model.GetEntityTypes()
        .Where(t => typeof(ITenantOwned).IsAssignableFrom(t.ClrType))
        .Where(t => t.GetQueryFilter() is null) // EF Core 10: use GetDeclaredQueryFilters()
        .Select(t => t.ClrType.Name)
        .ToList();

    Assert.Empty(missing);
}

3. The cross-tenant write test

Load a record as tenant A, then try to update or delete it from a context for tenant B. The SaveChangesAsync guard should throw. This proves the write side holds, not just the read side.

4. The API-level "guess the id" test

Using WebApplicationFactory, sign in as a user from tenant A and ask for a job id that belongs to tenant B. The right answer is 404 Not Found, not 403 Forbidden. A 403 confirms the record exists, which is already a small leak. Because the query filter hides tenant B's row, the endpoint simply doesn't find it, which is exactly what you want.

5. The tenant resolution tests

A few small tests around the middleware:

  • An unknown host returns 404.
  • A custom domain that hasn't been verified yet returns 404.
  • A user whose token says tenant A, calling tenant B's domain, gets 403.
  • Mixed-case hosts and hosts with a port resolve to the same tenant.

None of these tests are big, but together they cover reads, writes, schema changes, the API and the front door. That's where isolation usually breaks.

The mistake I made: responsive first instead of mobile first

Not every lesson was about the database. One of the biggest ones was about the frontend.

ShiftTracko needs three apps: a mobile app, a web app, and an admin app that only runs on the web. When I started, I built the web app as a normal responsive site. Desktop layout first, then made it shrink down for phones.

Part way through, I realised that was the wrong way round for this audience. A tradie isn't sitting at a desk. They're on site, between jobs, in a van, checking the next address or ticking off a job on their phone. For them, the phone isn't the small version of the app. It's the main one.

So I switched to a mobile-first design. I now design each screen for a phone first and then let it grow for bigger screens, instead of squeezing a desktop page down. It's more reliable on the devices that actually get used, the important actions are easier to reach with one hand, and the screens stay simpler because there's no room for clutter.

It also connected back to multi-tenancy in a way I didn't expect. Once I planned for a mobile app and an admin app alongside the web app, it was clear that tenant isolation can't live in any one frontend. The mobile app has no subdomain. The admin app is the one place that legitimately needs to look across tenants, which makes it exactly where IgnoreQueryFilters() gets tempting. The only safe place for the rules is the API and the data layer, where every app passes through the same checks.

What I've learned so far

  • Know your tenants before you choose a model. ShiftTracko has many small tenants, so shared tables with a TenantId were the right fit. A different customer base could easily point the other way.
  • Decide the isolation model early. Moving from shared tables to a database per tenant later is a big migration. It's worth thinking about early, even if you pick the simplest option.
  • Never trust a tenant id from the client on its own. Domains and headers say which tenant a request is for. The signed-in user decides whether it's allowed.
  • Treat custom domains as a security feature. Verify ownership, normalise hosts, and return 404 for anything you don't recognise.
  • Make the safe path the default. Global query filters and SaveChanges stamping mean a developer has to go out of their way to break isolation.
  • Treat IgnoreQueryFilters() and raw SQL as review hotspots. These are where leaks hide.
  • Remember the work outside requests. Jobs, emails, reports, caches and file storage all need the tenant passed in explicitly.
  • Test the walls. A cross-tenant test is cheap to write and expensive to skip.
  • Design for the device people actually use. For tradies, that's the phone, so mobile first.

Final thoughts

Multi-tenancy isn't one feature you add at the end. It's a rule that runs through the middleware, the DbContext, the background jobs, the cache, the emails and the tests. Get it right and nobody ever notices. Get it wrong once, and it's the only thing a customer remembers.

ShiftTracko is still in active development, and I'm sure I'll change some of these decisions as it grows, especially once the mobile app is in tradies' hands. I'll write about those changes in future posts.

How do you handle tenant isolation in your .NET apps? Do you prefer shared tables with a TenantId, or a database per tenant? Let me know in the comments.

X / Twitter LinkedIn

Comments (0)

No comments yet. Be the first!

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me