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

📚 Interview question

Design a multi-tenant SaaS platform, for example a rostering or practice-management product sold to hundreds of Australian businesses. Walk me through tenant isolation in the data and compute layers, how you stop one noisy tenant hurting the others, how a new tenant is onboarded, and how you meet a customer who insists their data stays in Australia.

A full multi-tenant SaaS design: requirements and tenant-mix estimates, tenant resolution, pooled vs siloed data and compute (shared schema with TenantId and row-level security, database per tenant in elastic pools), noisy-neighbour controls, automated onboarding, per-tenant observability and cost, and data residency in Azure Australia East/Southeast.

Senior SystemDesign Advanced azure-sql data-residency multi-tenancy saas system-design tenant-isolation

🎯 Key points

  • Clarify: number and size spread of tenants, isolation and compliance tiers, residency, per-tenant customisation, SLA
  • Tenant resolved once at the edge (subdomain or token claim tid), carried in an ITenantContext, never from the request body
  • Pool by default: shared schema, TenantId on every row, EF Core global query filter (named filters in EF Core 10) plus SQL Server row-level security as the backstop
  • Silo the few that pay or must: database per tenant in an elastic pool, a tenant catalogue maps tenant to shard
  • Noisy neighbours: per-tenant rate limits and concurrency caps, fair queues, move whales to their own database
  • Onboarding and offboarding are idempotent workflows; churned tenants are exported, retained for a set period, then purged with a record
  • Residency: Australia East primary, Southeast for geo-replicas and backups; logs, backups and third parties stay in region
  • Per-tenant metrics for cost-to-serve, so isolation tiers are priced and tenants are moved on data, not guesswork

⏱ 30-second answer

I start from the tenant mix: usually hundreds of small tenants and a few whales. So I use a hybrid model: most tenants live in a pooled shared-schema database with TenantId on every row, enforced twice, by an EF Core global query filter and by SQL Server row-level security as the backstop. Tenants that pay for isolation or are big enough to hurt others get a database per tenant in an elastic pool, located through a tenant catalogue. The tenant is resolved once at the edge from the subdomain or token. Noisy neighbours are handled with per-tenant rate limits, concurrency caps and separate queues. Onboarding is an automated, idempotent workflow. Data residency means everything, including backups, logs and replicas, stays in Australia East / Southeast. The trade-off: pooling is cheap and simple to operate; siloing buys isolation at a per-tenant cost.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start by asking about the tenant mix, because it drives everything. For a practice-management product I'd assume [500] tenants: most are small clinics with 5 to 20 users, and a handful are chains with thousands. I'd ask whether any customer contractually needs dedicated infrastructure, whether everyone needs data in Australia, and what the SLA is. Then the big decision: pooled, siloed, or a mix. My default is a hybrid. Small tenants share one schema in a pooled Azure SQL database, every table has a TenantId, and I enforce it in two places: an EF Core global query filter so developers can't forget it, and SQL Server row-level security with SESSION_CONTEXT so a raw SQL query or a reporting tool still can't cross tenants. Large or regulated tenants get their own database in an elastic pool, and a tenant catalogue tells the app which connection string to use.

The tenant is resolved once, at the edge: from the subdomain or the tid claim in the token, into a scoped ITenantContext. Never from a route value or the request body. For noisy neighbours, I put a per-tenant rate limiter and concurrency cap on the API, give background work a per-tenant fair queue, and when one tenant's usage dominates a pool, I move it to its own database without code changes, because the catalogue is the indirection. For example, at [company] we [had one large tenant's month-end reports saturate the shared database]; [moving them to a dedicated database in the pool] [brought p95 for everyone else back from 2 s to 250 ms].

Onboarding is a workflow, not a script someone runs: a message starts it, each step is idempotent, and the tenant only goes Active when every step succeeds. Residency is easy to promise and easy to break: the primary in Australia East and geo-replicas in Australia Southeast is the start, but backups, Application Insights, support exports and any AI or email provider must be in Australia too.

The mistake I see is trusting the application alone to filter by tenant. One missing Where is a notifiable data breach under the Privacy Act. Isolation needs a backstop the developer can't bypass."


Requirements

Type Requirement Assumption
Functional Tenants sign up, invite users, configure settings Self-service plus sales-led enterprise
Functional Tenant admins see only their tenant's data Plus a platform support role with audited access
Non-functional Zero cross-tenant data access Enforced by DB, not only code
Non-functional One tenant can't degrade others Per-tenant limits, ability to move tenants
Non-functional Data stays in Australia Australia East + Southeast only
Non-functional 99.9% availability, p95 < 300 ms Zone-redundant tiers

Capacity estimate

Quantity Arithmetic Result
Users 480 small × 15 + 20 large × 1,500 ≈ 37,000
Requests 37,000 users × 400 req/day ≈ 15M/day ≈ 170 req/s, peak ×4 ≈ 700 req/s
Data 480 × 2 GB + 20 × 60 GB ≈ 2.2 TB, growing ~40%/year
Largest tenant share 1 chain = 12% of traffic Whales justify siloing

High-level design

Users ──► Front Door (WAF, *.app.example.com.au) ──► API (ASP.NET Core, Container Apps / AKS)
                                                    │ TenantResolutionMiddleware → ITenantContext
                                                    │ per-tenant rate limiter
                                                    ▼
                                        Tenant catalogue (Azure SQL: tenant → tier, shard, status)
                                                    │
              ┌─────────────────────────────────────┼───────────────────────────┐
              ▼                                     ▼                           ▼
   Pooled DB (shared schema,           Elastic pool: DB per tenant      Service Bus (sessions per tenant)
   TenantId + RLS)                     (whales, regulated)              → workers (fair scheduling)
   Australia East, geo-replica Southeast; backups and logs in region

Isolation models

Model Isolation Cost per tenant Operations Fits
Shared schema + TenantId Logical (filter + RLS) Lowest One schema to migrate Long tail of small tenants
Schema per tenant Moderate Low Many schemas to migrate Rarely worth it
Database per tenant (elastic pool) Strong data isolation, shared compute Medium Fleet migrations, catalogue Large or regulated tenants
Dedicated stack (stamp) Full Highest Separate deployment Contractual isolation, government

Production example

A rostering SaaS with [600] tenants ran pooled for small customers and [25] databases in two elastic pools for the largest. Moving the top [3] tenants out of the shared database cut its peak DTU from [95%] to [55%], and RLS caught [one] missing filter in a reporting query during testing before it reached production.

🔍 What the interviewer is checking

Checks that the candidate chooses isolation models from the tenant mix, enforces isolation with a backstop, and handles noisy neighbours, onboarding and residency as first-class design concerns.

Green flags

  • Hybrid pooled/siloed model with a tenant catalogue
  • Tenant resolved at the edge and enforced by both EF Core filters and RLS
  • Per-tenant rate limits, fair queues and a way to move whales
  • Residency covers backups, logs and third parties

Red flags

  • Tenant id taken from the request body
  • Only application-level filtering
  • Database per tenant for everyone without discussing cost and migrations
  • No answer for a noisy tenant

📚 Learn in depth

1. Tenant resolution

Request ─► Host: acme.app.example.com.au  or  JWT claim tid=7f3...
         ─► TenantResolutionMiddleware ─► catalogue lookup (cached 60 s)
         ─► ITenantContext { TenantId, Tier, ConnectionString, Status }

Resolve once, early, and reject requests for suspended tenants there. The user's token must also belong to that tenant: a user of tenant A calling b.app.example.com.au must get 403, otherwise the subdomain becomes an attack vector.

2. Enforcing isolation in a pooled database

  • EF Core global query filter HasQueryFilter(e => e.TenantId == _tenant.TenantId) on every tenant-owned entity, applied by a convention so new entities can't miss it. Inserts get TenantId set in SaveChanges.
  • Row-level security: a security policy with a filter predicate (reads) and block predicate (writes) comparing TenantId to SESSION_CONTEXT(N'TenantId'). A DbConnectionInterceptor sets sp_set_session_context when the connection opens. Connection pooling reuses connections, so set it on every open, and mark it read-only.
  • Indexes lead with TenantId, so each tenant's queries seek into its own range; this also keeps plans stable.

3. Database per tenant and the catalogue

The catalogue holds tenant → server, database, tier, region, status, schema version. Data-dependent routing picks the connection string per request. Migrations become a fleet operation: a job applies EF Core migration bundles tenant by tenant, records the version, and can pause on failure. Keep schema changes backward compatible (expand, migrate, contract) because the fleet is never all on one version at once.

4. Noisy neighbours

Layer Control
API PartitionedRateLimiter keyed by tenant; concurrency limit per tenant
Background work Service Bus sessions or a queue per tier; fair round-robin across tenants
Database Big tenants out of the shared DB; elastic pool per-database max vCores
Reporting Read replica or a separate analytics store for heavy reports
Storage Quotas per tenant, enforced at upload

Measure per-tenant resource use (requests, SQL CPU via Query Store tagged by tenant, queue depth) so you can see the noisy one before customers complain.

5. Onboarding

SignUp ─► TenantRequested (Service Bus) ─► Provisioner:
   1. catalogue row (Provisioning)      4. identity: Entra External ID / invite admin
   2. pooled rows or new pool DB         5. DNS / custom domain cert
   3. seed reference data               6. status = Active, welcome email

Every step is idempotent and checks whether it already ran, so the workflow can be retried after any failure. Deprovisioning is the same in reverse, with retention rules (keep for 30 days, then purge and record it).

6. Data residency and Australian obligations

Australia East (Sydney) as primary, Australia Southeast (Melbourne) for geo-replicas and backup storage (choose geo-redundant backup within the Australian pair). Check every data flow: Application Insights workspace region, email and SMS providers, support tools, AI services. The Privacy Act 1988 (APP 8) makes you accountable for overseas disclosure, and a cross-tenant leak is likely an eligible data breach under the NDB scheme.

7. Per-tenant cost and observability

Tag logs, traces and metrics with tenant.id. Use it for support, noisy-neighbour detection and cost-to-serve (which tenants are unprofitable on their plan). Beware metric cardinality: per-tenant metrics for 500 tenants are fine; per-user are not.

8. AWS mapping

RDS/Aurora with PostgreSQL RLS or database per tenant, a DynamoDB or RDS catalogue, SQS per tier, API Gateway usage plans per tenant, Sydney (ap-southeast-2) and Melbourne (ap-southeast-4) regions.

Try it yourself

  1. Add a global query filter and RLS policy to a sample app, then run a raw FromSql query and confirm RLS still filters.
  2. Write an architecture test that fails if any entity implementing ITenantOwned lacks the filter.
  3. Load-test with one tenant sending 10× traffic and watch other tenants' p95 with and without a per-tenant limiter.
  4. Script onboarding as an idempotent workflow and kill it mid-way, then re-run it.
  5. Apply a migration bundle across 20 tenant databases and handle one failure.

💻 Code

Tenant resolution, an EF Core filter with an interceptor that sets SESSION_CONTEXT for row-level security, and a per-tenant rate limiter.

using System.Data.Common;
using System.Threading.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Saas;

public interface ITenantOwned { Guid TenantId { get; set; } }

public sealed class TenantContext { public Guid TenantId { get; set; } public string Tier { get; set; } = "Pooled"; }

public sealed class Appointment : ITenantOwned
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public DateTimeOffset StartsAt { get; set; }
}

public sealed class AppDbContext(DbContextOptions<AppDbContext> options, TenantContext tenant) : DbContext(options)
{
    public DbSet<Appointment> Appointments => Set<Appointment>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        // First line of defence: developers can't forget the filter.
        b.Entity<Appointment>().HasQueryFilter(a => a.TenantId == tenant.TenantId);
        b.Entity<Appointment>().HasIndex(a => new { a.TenantId, a.StartsAt }); // tenant-leading index
    }
}

// Backstop: SQL Server row-level security reads SESSION_CONTEXT, so raw SQL is filtered too.
public sealed class TenantSessionInterceptor(TenantContext tenant) : DbConnectionInterceptor
{
    public override async Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData data, CancellationToken ct = default)
    {
        await using var cmd = connection.CreateCommand();
        cmd.CommandText = "EXEC sp_set_session_context @key = N'TenantId', @value = @t, @read_only = 1;";
        var p = cmd.CreateParameter(); p.ParameterName = "@t"; p.Value = tenant.TenantId; cmd.Parameters.Add(p);
        await cmd.ExecuteNonQueryAsync(ct);
    }
}
// Program.cs (excerpt)
builder.Services.AddScoped<TenantContext>();
builder.Services.AddScoped<TenantSessionInterceptor>();
builder.Services.AddDbContext<AppDbContext>((sp, o) => o
    .UseSqlServer(builder.Configuration.GetConnectionString("Pooled"))
    .AddInterceptors(sp.GetRequiredService<TenantSessionInterceptor>()));

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    // One bucket per tenant: a noisy tenant exhausts only its own tokens.
    o.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(ctx =>
    {
        var t = ctx.RequestServices.GetRequiredService<TenantContext>();
        var perSecond = t.Tier == "Enterprise" ? 200 : 50;
        return RateLimitPartition.GetTokenBucketLimiter(t.TenantId.ToString(), _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = perSecond * 2, TokensPerPeriod = perSecond,
            ReplenishmentPeriod = TimeSpan.FromSeconds(1), QueueLimit = 0
        });
    });
});
// Tenant resolution middleware must run before UseRateLimiter.
CREATE FUNCTION Security.fn_TenantPredicate(@TenantId uniqueidentifier)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN SELECT 1 AS ok WHERE @TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS uniqueidentifier);
GO
CREATE SECURITY POLICY Security.TenantPolicy
  ADD FILTER PREDICATE Security.fn_TenantPredicate(TenantId) ON dbo.Appointments,
  ADD BLOCK  PREDICATE Security.fn_TenantPredicate(TenantId) ON dbo.Appointments AFTER INSERT
  WITH (STATE = ON);

⚠ Common mistakes

  • Mistake: Relying only on Where(x => x.TenantId == ...) in application code. Why it is wrong: one forgotten filter, raw SQL or reporting query leaks another tenant's data, likely a notifiable data breach. Instead: global query filters by convention plus row-level security as a database backstop.
  • Mistake: Reading the tenant id from the request body or a route value. Why it is wrong: a user can change it and act in another tenant. Instead: resolve from the host or token, and check the user belongs to that tenant.
  • Mistake: Choosing database per tenant for everyone on day one. Why it is wrong: hundreds of tiny databases cost more and make every migration a fleet operation. Instead: pool by default and silo the tenants that need it.
  • Mistake: Choosing shared schema with no way out. Why it is wrong: when a whale arrives you cannot move them without a rewrite. Instead: a tenant catalogue as the routing indirection from the start.
  • Mistake: Global rate limits only. Why it is wrong: one tenant can use the whole budget and starve everyone. Instead: per-tenant partitions and fair queues.
  • Mistake: Manual onboarding scripts. Why it is wrong: half-provisioned tenants after a failure, and steps forgotten. Instead: an idempotent, retryable workflow with a status in the catalogue.
  • Mistake: Promising Australian data residency but sending logs or emails through overseas services. Why it is wrong: breaks the contract and APP 8 obligations. Instead: map every data flow and pin regions.
  • Mistake: Indexes that don't lead with TenantId. Why it is wrong: queries scan across tenants and plans vary wildly between small and large tenants. Instead: tenant-leading keys and indexes.

🏛 Senior insight: trade-offs

Multi-tenancy is a business decision expressed in architecture: the isolation tier is part of the price list. I design for movement, so the catalogue lets a tenant go from pooled to dedicated database to a dedicated deployment stamp without code changes, and I make cost-to-serve visible per tenant so pricing is grounded in data.

Churn is part of the design. SaaS tenants leave as often as they join. Offboarding runs the onboarding workflow in reverse: suspend (read-only), offer a data export, keep data for the contractual retention period (say 30–90 days), then purge rows or drop the tenant database and its backups when retention allows, and record that it happened. In a pooled database, a purge is a batched delete by TenantId, run off-peak so it doesn't hurt everyone else; in a siloed tenant it is a database drop, which is one reason regulated tenants are easier to silo.

Cost per tier. A pooled tenant may cost cents a month; a dedicated database in an elastic pool costs a share of the pool's vCores; a dedicated stamp costs a full environment. Elastic pools pay off when many databases peak at different times; if they all peak together (month-end), size for that or split pools.

Option When it fits Cost When not to
Pooled shared schema + RLS Many small tenants Lowest per tenant Contractual physical isolation
DB per tenant in elastic pool Whales, regulated customers Medium, fleet migrations Thousands of tiny tenants
Deployment stamps per region or segment Scale limits, residency, blast radius Highest, more pipelines Early-stage product

I measure cross-tenant access attempts blocked by RLS (should be zero in normal code), per-tenant p95 and resource share, onboarding and offboarding time and failure rate, and cost per tenant per month. Query filters add a predicate to every query, which is cheap when indexes lead with TenantId and expensive when they don't, so I check plans for the largest tenants.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions pooled versus siloed databases Why: Checks the data-layer trade-offs between shared schema, schema per tenant and database per tenant
    How to answer

    There are three models.

    • Shared schema: every row has a TenantId and EF Core applies a filter. Cheapest, one migration, but isolation is only as good as your code, and tenants compete for resources.
    • Schema per tenant: little real isolation gain for a lot of EF Core friction (model caching per schema, migrations per schema). Rarely worth it.
    • Database per tenant: the strongest isolation, per-tenant restore, region and scale, made affordable by Azure SQL elastic pools. The cost is operations: migrating and monitoring N databases.

    Most SaaS products end up hybrid: small tenants share, large or regulated tenants get their own database, routed through a tenant catalogue. The trade-off is isolation and flexibility against cost and operational complexity.

  2. When: Candidate mentions tenant admins managing their own users Why: Checks tenant-defined roles and permission caching
    How to answer

    Separate permissions (fine-grained actions in code, such as invoices.approve) from roles (tenant-defined bundles of permissions stored as data). Endpoints only ever check permissions.

    • Permissions in the token avoid a lookup but bloat the token and stay stale until it expires.
    • Server-side lookup keeps tokens small and changes immediate, at the cost of a cache and invalidation.

    For tenant-defined roles I keep sub and tenant_id in the token and resolve permissions server-side, cached with HybridCache keyed by a permission version that is bumped on every role change. A custom IAuthorizationPolicyProvider turns "perm:invoices.approve" into a policy on demand, with one generic handler. The trade-off: freshness and flexibility in exchange for a cache you have to operate.

  3. When: Candidate mentions DbContext pooling or a scoped tenant context Why: Checks diagnosing a cross-tenant leak through pooling or caching
    How to answer

    First contain it: it is a likely data breach, so switch off the suspect path, preserve logs and start the Notifiable Data Breaches assessment. Then look for shared state, because a leak you cannot reproduce locally usually needs concurrency:

    • AddDbContextPool reusing a context whose tenant field was set once in the constructor.
    • A singleton capturing a scoped tenant provider or a DbContext.
    • A query filter that captured a value when the model was built.
    • A cache keyed without the tenant.

    Reproduce it with a load test that alternates tenants and checks every row. Fix by disabling pooling or setting the tenant on every lease, and add row-level security as a backstop. The trade-off: pooling saves microseconds per request, and a leak costs far more.

🛠 Real-world problems: how you handle them

One tenant's month-end reports slowed the whole shared database
Situation
A [practice-management] SaaS with [500] tenants on a pooled Azure SQL database in Australia East; one [hospital group] tenant had [30%] of the data.
Signals
Every tenant's p95 rose from [250 ms] to [2 s] on the first business day of each month; DTU at [100%]; support tickets from small clinics.
Investigation
Query Store top queries by CPU showed [reporting queries] all filtered on one TenantId; Application Insights showed the slowdown tracked that tenant's report runs. Per-tenant request metrics confirmed the share.
Resolution
Immediate: per-tenant concurrency limit on the report endpoint and moved reports to the readable secondary. Long term: created a tenant catalogue and moved the [3] largest tenants to their own databases in an elastic pool with an online copy and a short cutover.
Prevention
Per-tenant resource dashboards and an alert when one tenant exceeds [20%] of a pooled database; a documented threshold for moving tenants; load tests with skewed tenant sizes.

How to tell it (STAR)

**S:** At [company] our pooled database slowed for every customer at month-end, and small clinics were complaining. **T:** I had to protect everyone else from one large tenant without a rewrite. **A:** I used Query Store and per-tenant metrics to show one [hospital group]'s reports drove [most] of the CPU. I added a per-tenant concurrency limit and pointed reports at the readable secondary straight away, then introduced a tenant catalogue so we could move the [three] largest tenants into their own databases in an elastic pool. **R:** p95 for other tenants went from [2 s] back to [250 ms] at month-end, and moving a tenant became a [one-hour] runbook instead of a project.

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me