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.
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.
"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 withSESSION_CONTEXTso 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
tidclaim in the token, into a scopedITenantContext. 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
Whereis a notifiable data breach under the Privacy Act. Isolation needs a backstop the developer can't bypass."
| 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 |
| 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 |
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
| 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 |
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.
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
Red flags
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.
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.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.TenantId, so each tenant's queries seek into its own range; this also keeps plans stable.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.
| 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.
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).
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.
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.
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.
FromSql query and confirm RLS still filters.ITenantOwned lacks the filter.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);
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.TenantId. Why it is wrong: queries scan across tenants and plans vary wildly between small and large tenants. Instead: tenant-leading keys and indexes.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.
There are three models.
TenantId and EF Core applies a filter. Cheapest, one migration, but isolation is only as good as your code, and tenants compete for resources.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.
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.
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.
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.DbContext.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.
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.
Last updated 23 Nov 2026.