Multi-tenant data architecture with EF Core 10 and Azure SQL: shared schema, schema per tenant and database per tenant with elastic pools, compared on isolation, noisy neighbours, cost, migrations, data residency and hybrid tiering.
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.
"I'd start from requirements, not technology: how many tenants, how big the largest is compared with the median, what isolation we promise contractually, whether any tenant needs data to stay in a specific region or to be restored on its own, and how much operations capacity the team has. Those answers usually decide it.
Shared schema is the default for many small tenants. One database, a
TenantIdon every row, an EF Core global filter, and SQL Server row-level security as a backstop. It's cheap and one migration covers everyone. The weaknesses are isolation by code and noisy neighbours: one tenant's month-end report can slow everyone. Database per tenant fixes both and gives you per-tenant point-in-time restore, per-tenant region and an easy offboarding story, which matters under the Privacy Act when a customer leaves and asks for their data to be destroyed. Elastic pools make it affordable because hundreds of mostly idle databases share one pool of vCores. The price is operations: every migration runs N times, and you need a catalogue, monitoring per database and a deployment process that tolerates some tenants being one version behind. Schema per tenant sits in between and, with EF Core, mostly gives you the costs of both: you need a customIModelCacheKeyFactory, migrations per schema, and you still share compute.For example, at [company] we started with [one shared database for 600 small tenants] and later moved [our 12 largest enterprise customers] to dedicated databases in an elastic pool, routed by a tenant catalogue. Their p95 dropped [by half], and the shared database stopped having noisy-neighbour incidents. The mistake I see is choosing database per tenant on day one for isolation nobody asked for, then drowning in migrations. I design for the hybrid from the start, a catalogue and a connection per tenant, even if everyone begins in one database."
| Shared schema | Schema per tenant | Database per tenant (elastic pool) | |
|---|---|---|---|
| Isolation | Application filter (+ RLS) | Schema permissions | Database boundary |
| Noisy neighbours | High | High (shared compute) | Low to medium (pool shares vCores; per-database caps) |
| Cost per tenant | Lowest | Low | Higher; pooled to stay affordable |
| Migrations | One | N schemas | N databases, orchestrated |
| Per-tenant restore | Hard (row-level copy) | Possible but fiddly | Native point-in-time restore |
| Residency per tenant | No | No | Yes (pool per region) |
| EF Core fit | Natural | Awkward (model cache key per schema) | Natural (connection per tenant) |
| Offboarding / deletion | Row deletes across tables | Drop schema | Drop database |
| Cross-tenant reporting | Easy | Moderate | Needs a warehouse or fan-out |
| Component | Role |
|---|---|
| Tenant catalogue (small DB or config store) | Tenant → tier, region, connection, schema version |
| Tenant resolver | Validated claim → catalogue lookup (cached) |
| DbContext factory | Builds context with the tenant's connection string; filter still on for shared tiers |
| Migration orchestrator | Applies bundles in waves, records versions, halts on failures |
| Move tool | Copies a tenant from shared to dedicated and flips the catalogue |
Moving [12 enterprise tenants out of a shared database of 600] into an elastic pool in Australia East reduced shared-database CPU peaks from [95% to 55%], and the per-tenant restore requirement in [two enterprise contracts] became a standard point-in-time restore instead of a custom export script.
Checks whether the candidate can make and justify an architecture decision with business, regulatory and operational trade-offs, and knows how each model works with EF Core and Azure SQL.
Green flags
Red flags
cheaper, simpler stronger isolation
◀───────────────────────────────────────────────────────────────────▶
shared schema ── shared + RLS ── schema/tenant ── DB/tenant in pool ── DB/tenant dedicated ── server/subscription per tenant
Isolation covers security (who can read what), performance (who can slow whom), and operations (restore, move, delete one tenant).
TenantId.modelBuilder.HasDefaultSchema(tenantSchema) changes the model, so EF Core's model cache must be keyed by schema with a custom IModelCacheKeyFactory. Migrations are generated for one schema and must be applied per schema (often by rewriting the schema name), which is fragile.UseSqlServer(connectionStringForTenant) in a factory, or set Database.SetConnectionString before first use. With pooling, set the connection per lease.An Azure SQL elastic pool gives a set of databases a shared budget of vCores (or eDTUs) and storage, with optional per-database minimum and maximum. It works when tenants' peaks do not coincide. Size by the aggregate peak, not the sum of peaks; set a per-database max so one tenant cannot take the whole pool; and keep the number of databases per pool within the tier's limit (hundreds, varying by tier). Pools are regional, so a pool in Australia East and another in Australia Southeast (or another country) supports residency commitments.
build: dotnet ef migrations bundle → efbundle
for wave in [canary(5), 10%, 50%, rest]:
for db in wave (parallel, limited):
efbundle --connection <db> # idempotent via __EFMigrationsHistory
catalogue.SetSchemaVersion(db, v)
halt if failures > threshold
Because tenants are briefly on different schema versions, every migration must be backward compatible (expand/contract), and the app must work with version N and N+1. Azure Elastic Jobs or a custom orchestrator in the pipeline can run this.
request → JWT (tid) → catalogue lookup (cached, e.g. HybridCache) → {tier, region, connection}
→ DbContext factory → UseSqlServer(connection) [+ tenant filter for shared tier]
The catalogue is critical infrastructure: cache it, replicate it, and never trust a tenant id from the client without matching it to the user.
A tenant move copies its rows from the shared database to a new database (BCP, SqlBulkCopy or a migration tool), verifies counts and checksums, freezes writes briefly, does a final delta, flips the catalogue entry, and deletes the source rows. Rehearse it; it is the operation that makes hybrid tiering real.
With many databases, reporting moves to a warehouse or lakehouse fed by change feeds or ETL (Microsoft Fabric, Synapse, or Azure Data Factory). Shared schema makes this trivial; database per tenant makes it a project.
DbContext factory that picks a connection string from a tenant catalogue, and run two tenants against two local databases.HasDefaultSchema and observe the model cache problem; fix it with IModelCacheKeyFactory.A tenant catalogue and a context factory that routes each tenant to its database, keeping the filter for shared tiers:
namespace Saas.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Hybrid;
public enum TenantTier { Shared, Dedicated }
public sealed record TenantInfo(Guid Id, TenantTier Tier, string Region, string ConnectionString, string SchemaVersion);
public interface ITenantCatalogue
{
ValueTask<TenantInfo> GetAsync(Guid tenantId, CancellationToken ct);
}
public sealed class CachedTenantCatalogue(CatalogueDbContext db, HybridCache cache) : ITenantCatalogue
{
public ValueTask<TenantInfo> GetAsync(Guid tenantId, CancellationToken ct) =>
cache.GetOrCreateAsync($"tenant:{tenantId}", async token =>
await db.Tenants.AsNoTracking()
.Where(t => t.Id == tenantId)
.Select(t => new TenantInfo(t.Id, t.Tier, t.Region, t.ConnectionString, t.SchemaVersion))
.SingleAsync(token),
cancellationToken: ct);
}
public sealed class AppDbContext(DbContextOptions<AppDbContext> options, TenantInfo tenant) : DbContext(options)
{
public Guid TenantId => tenant.Id;
public bool IsShared => tenant.Tier == TenantTier.Shared;
public DbSet<Invoice> Invoices => Set<Invoice>();
protected override void OnModelCreating(ModelBuilder b) =>
// Same model for every tier; in a dedicated database the filter is harmless but kept as defence in depth.
b.Entity<Invoice>().HasQueryFilter("Tenant", i => i.TenantId == TenantId);
}
public sealed class TenantDbContextFactory(ITenantCatalogue catalogue, ITenantProvider current)
{
public async Task<AppDbContext> CreateAsync(CancellationToken ct)
{
var tenant = await catalogue.GetAsync(current.TenantId, ct);
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer(tenant.ConnectionString, sql => sql.EnableRetryOnFailure())
.Options;
return new AppDbContext(options, tenant);
}
}
Applying one migration bundle to every tenant database in waves:
dotnet ef migrations bundle --self-contained -r linux-x64 \
--project src/Saas.Infrastructure --startup-project src/Saas.Api -o artefacts/efbundle
# canary wave first, then the rest; each run is idempotent via __EFMigrationsHistory
for conn in $(./tenants.sh --wave canary); do
./artefacts/efbundle --connection "$conn" || { echo "halt: $conn failed"; exit 1; }
done
The decision is mostly about operations and contracts, not EF Core. The questions I put to the business are: what isolation have we promised (or will enterprise customers demand), do any customers need onshore data or their own restore, and what is the tenant size distribution? A long tail of tiny tenants with a few whales almost always means a hybrid. I record the decision in an ADR with the triggers for revisiting it, such as the shared database passing a CPU or size threshold, or a contract requiring dedicated isolation.
From a Privacy Act angle, database per tenant makes offboarding and APP 11.2 destruction simple (drop the database after the retention period), and narrows the blast radius of a breach. Shared schema needs both a careful deletion process and strong isolation controls.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Shared schema + RLS | Many small tenants, self-serve SaaS | Lowest | Contractual isolation, per-tenant restore |
| Schema per tenant | Legacy constraints, few tenants | EF Core friction | Most new systems |
| Database per tenant in pools | Enterprise, regulated, residency | Operations, catalogue, migration orchestration | Thousands of tiny tenants |
| Hybrid tiers | Long tail plus large customers | Two paths to run, move tool | Very early products with one tier |
In a shared schema every tenant-owned table gets a TenantId column, and the DbContext declares a global query filter such as e => e.TenantId == TenantId, where TenantId is a property on the context. EF Core treats that member as a parameter, so each query adds WHERE TenantId = @__TenantId. A scoped tenant provider sets it from a validated claim, and a SaveChanges interceptor stamps it on inserts.
The risks are the gaps around the filter: IgnoreQueryFilters(), raw SQL, ExecuteUpdate, pooled contexts keeping the last tenant, and background jobs with no request. The trade-off: one filter gives cheap, convenient isolation, but it is a single line of defence, so high-stakes systems add row-level security in SQL Server as well.
The EF filter keeps normal code tenant-scoped automatically, so handlers stay simple and nobody forgets a Where. Row-level security enforces the same rule in the database: create a security policy with an inline predicate function comparing TenantId to SESSION_CONTEXT(N'TenantId') (plus a block predicate to stop cross-tenant writes), and set the session context from a DbConnectionInterceptor when each connection opens, with @read_only = 1. Together they're defence in depth: raw SQL, IgnoreQueryFilters or a bug still can't read another tenant's rows. Costs: the predicate runs on every query, so TenantId must lead the relevant indexes or RLS can turn seeks into scans on large tables; debugging is harder because rows silently disappear; and the session context must be set on every connection open because of pooling.
Provision the new database from the current migration bundle, then copy the tenant's rows table by table in foreign-key order (SqlBulkCopy or BCP, keeping key values), and verify with counts and checksums. Track changes made during the copy (a ModifiedAt watermark, change tracking or CDC), then take a short write freeze for that tenant, apply the final delta, flip the catalogue entry to the new connection and clear the catalogue cache. Keep the source rows read-only for a rollback window, then delete them. Rehearse on a copy and measure the freeze time first.
How to tell it (STAR)
**S:** At [company] we had [600] tenants in one shared Azure SQL database, and two new enterprise contracts required per-tenant restore and onshore data. **T:** As [lead engineer / architect], I had to meet those contracts and stop month-end slowdowns. **A:** I measured per-tenant load with query tags and Query Store, proposed a hybrid model in an ADR, built a tenant catalogue, a context factory and a tested move tool, and moved [12] large tenants into an elastic pool with wave-based migrations. **R:** Shared-database CPU peaks fell from [95% to 55%], p95 for small tenants returned to normal, and both contracts' restore requirements became a standard point-in-time restore.
Last updated 23 Nov 2026.