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

📚 Interview question

You are designing the data architecture for a multi-tenant SaaS product on EF Core and Azure SQL. Compare a shared schema with a TenantId column, schema per tenant, and database per tenant (with elastic pools). How do you weigh isolation, cost, performance, migrations and operations, and how would you support tenants that need different levels of isolation?

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.

Staff / Architect Architecture Expert architecture azure-sql data-residency ef-core elastic-pools multi-tenancy

🎯 Key points

  • Shared schema (TenantId + filter + RLS): cheapest and simplest to operate, weakest isolation, noisy neighbours, one migration
  • Schema per tenant: modest isolation gain; EF Core 10 still has no built-in schema-per-tenant support, so you need a custom IModelCacheKeyFactory (one cached model per schema, more memory and start-up cost) and per-schema migrations
  • Database per tenant: strongest isolation, per-tenant restore, scaling and simple offboarding; cost and operations grow with tenant count
  • Azure SQL elastic pools share vCores across many databases; size by aggregate peak and cap per-database usage
  • Migrations across N databases need orchestration: bundles applied in waves, a tenant catalogue tracking schema version, and backward-compatible changes
  • A tenant catalogue maps tenant to tier, region and connection; the DbContext is created with the tenant's connection per request
  • Data residency and the Privacy Act: regional pools (Australia East / Southeast) for customers that require onshore data, APP 8 for cross-border disclosure, and APP 11.2 destruction made simple by dropping a tenant's database
  • Hybrid tiering decided with numbers: tenant size distribution, contractual isolation, residency needs and team operations capacity, with a tested tenant move path

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 TenantId on 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 custom IModelCacheKeyFactory, 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."


Comparison

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

Hybrid design

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts from requirements: tenant distribution, contracts, residency, operations capacity
  • Knows elastic pools and sizing by aggregate peak
  • Plans migrations across many databases with waves and backward compatibility
  • Proposes a catalogue and a hybrid model with a move path

Red flags

  • One model presented as always right
  • No plan for migrating N databases
  • Ignores noisy neighbours, restore or data residency

📚 Learn in depth

1. The isolation spectrum

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).

2. EF Core mechanics per model

  • Shared schema: global query filter on a context member, tenant stamped on save, indexes leading with TenantId.
  • Schema per tenant: 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.
  • Database per tenant: the model is identical; only the connection string differs. Create the context with UseSqlServer(connectionStringForTenant) in a factory, or set Database.SetConnectionString before first use. With pooling, set the connection per lease.

3. Elastic pools

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.

4. Migrating N databases

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.

5. Tenant catalogue and routing

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.

6. Moving tenants between tiers

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.

7. Cross-tenant analytics

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.

Try it yourself

  1. Implement a DbContext factory that picks a connection string from a tenant catalogue, and run two tenants against two local databases.
  2. Try schema-per-tenant with HasDefaultSchema and observe the model cache problem; fix it with IModelCacheKeyFactory.
  3. Build a migration bundle and write a small orchestrator that applies it to 20 local databases in waves.
  4. Estimate pool size from 30 days of per-tenant CPU metrics (aggregate peak versus sum of peaks).
  5. Write and time a tenant move from a shared database to a dedicated one.

💻 Code

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

⚠ Common mistakes

  • Mistake: Choosing database per tenant on day one without a requirement. Why it is wrong: Migrations, monitoring and cost grow with every tenant before isolation pays off. Instead: Start shared with a catalogue so you can move tenants later.
  • Mistake: Choosing schema per tenant for isolation. Why it is wrong: Compute is still shared, and EF Core needs a custom model cache key and per-schema migrations. Instead: Shared schema with RLS, or database per tenant.
  • Mistake: Shared schema with no row-level security for personal data. Why it is wrong: One application bug exposes every tenant. Instead: Add RLS as a backstop.
  • Mistake: Migrating hundreds of databases in one big bang. Why it is wrong: A failure leaves a random subset on a new schema. Instead: Waves, a catalogue of schema versions, and backward-compatible migrations.
  • Mistake: Sizing an elastic pool by the sum of every tenant's peak. Why it is wrong: It overspends; pools work because peaks don't align. Instead: Size by aggregate peak and cap per-database usage.
  • Mistake: Ignoring residency. Why it is wrong: Some Australian government and health customers require data to stay onshore. Instead: Regional pools and a region field in the catalogue.
  • Mistake: No tested tenant move path. Why it is wrong: Hybrid tiering is theoretical until you can move a tenant safely. Instead: Build and rehearse the move tool early.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate chooses a shared schema Why: Checks the EF Core implementation of shared-schema tenancy
    How to answer

    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.

  2. When: Candidate mentions row-level security Why: Checks combining EF filters with SQL Server RLS
    How to answer

    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.

  3. When: Candidate proposes hybrid tiering Why: Checks that the hybrid model is operationally realistic
    How to answer

    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.

🛠 Real-world problems: how you handle them

Noisy neighbour forced a move to hybrid tenancy
Situation
[B2B SaaS on Azure SQL, Australia East, ~600 tenants in one shared Business Critical database]. Two enterprise customers signed contracts requiring per-tenant restore and onshore data, and one of them ran heavy month-end reports.
Signals
Month-end CPU at 95%+ on the shared database, p95 latency for all tenants tripling for [a few hours], support tickets from small tenants, and a contract clause the current design could not meet.
Investigation
Query Store grouped by query tag (`tenant:<id>`) showed [3] tenants producing [60%] of CPU at month end. Per-tenant size and CPU metrics over 90 days showed a long tail of tiny tenants and a dozen large ones with non-overlapping peaks, a good fit for an elastic pool.
Resolution
Immediate: moved the month-end reports of the heaviest tenant to a readable secondary. Real fix: introduced a tenant catalogue and context factory, built and rehearsed a tenant move tool, and moved [12] large tenants into an elastic pool in Australia East with per-database caps. Migrations moved to a bundle applied in waves with versions recorded in the catalogue.
Prevention
An ADR with triggers for moving a tenant (CPU share, size, contract), a dashboard of per-tenant resource use, wave-based migration in the pipeline, and a quarterly rehearsal of a tenant move and a per-tenant restore.

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.

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me