| Building Resilient Applications Using Polly :👈 | 👉:CQRS and Event-Driven Architecture |
ASP.NET Core Multi-Tenant Architecture: Database-per-Tenant vs Shared Database |
ASP.NET Core Multi-Tenant Architecture: Database-per-Tenant vs Shared Database
1. What Is Multi-Tenant Architecture?
Multi-tenancy is an architecture in which a single application instance serves multiple customers (tenants), while keeping each tenant's data logically or physically isolated.
A tenant is typically a customer, organization, company, or business using your application.
Example: Imagine building an ASP.NET Core SaaS application for multiple companies.
- Company A uses the application.
- Company B uses the same application.
- Company C uses the same application.
All three companies use the same application, but each company should access only its own data.
2. How Multi-Tenant Architecture Works
The application identifies the tenant for every request and ensures that database operations use the correct tenant's data.
3. Common Multi-Tenant Database Strategies
There are three commonly used database strategies:
- Database-per-Tenant
- Shared Database with Separate Schema per Tenant
- Shared Database with Shared Schema
4. Database-per-Tenant
In this approach, every tenant has its own separate database. The application identifies the tenant and connects to the corresponding database.
Architecture
Example
Suppose three companies use your SaaS application:
| Tenant | Database |
|---|---|
| Company A | CompanyA_DB |
| Company B | CompanyB_DB |
| Company C | CompanyC_DB |
Company A's data is stored in CompanyA_DB. Company B's data is stored in CompanyB_DB. Company C's data is stored in CompanyC_DB.
Advantages
- Strong data isolation: Each tenant has a separate database.
- Independent backup: You can back up individual tenant databases.
- Independent restore: You can restore one tenant without restoring all tenants.
- Customization: Different tenants can have different database configurations or controlled schema versions.
- Performance isolation: One tenant's database workload is less likely to directly affect another tenant's database.
- Compliance: It can help meet requirements for separate data storage.
Disadvantages
- Managing hundreds or thousands of databases can become difficult.
- Database provisioning and migrations require automation.
- Infrastructure and licensing costs may increase.
- Cross-tenant reporting becomes more complicated.
- Connection management and monitoring require additional effort.
When to Use Database-per-Tenant
- Enterprise SaaS applications.
- Customers with strict data isolation requirements.
- Applications with tenant-specific backup and restore requirements.
- Customers requiring independent database performance and capacity management.
- Applications where customers need controlled database-level customization.
5. Shared Database with Separate Schema per Tenant
In this approach, multiple tenants share one database server and database, but each tenant has a separate schema.
A schema is a logical container for database objects such as tables, views, and procedures.
Architecture
Example
Suppose the database is named SaaS_DB.
| Tenant | Schema | Example Table |
|---|---|---|
| Company A | tenant_a | tenant_a.Customers |
| Company B | tenant_b | tenant_b.Customers |
| Company C | tenant_c | tenant_c.Customers |
All tenants use the same database, but their tables are separated by schema.
Advantages
- Better logical separation than sharing the same tables.
- One database server and database to manage.
- Tenant-specific database permissions can be configured.
- Can simplify some tenant-specific data operations.
Disadvantages
- Schema creation and migrations become more complicated as tenant count grows.
- All tenants still share database-level resources.
- Cross-tenant reporting requires querying multiple schemas.
- Schema-based separation is not automatically a complete security boundary.
6. Shared Database with Shared Schema
This is one of the most common approaches for SaaS applications with many tenants.
All tenants share the same database and tables. Each tenant's records are identified using a TenantId column.
Architecture
Example Database Table
Consider a Customers table:
| CustomerId | TenantId | CustomerName |
|---|---|---|
| 1 | 101 | Customer A1 |
| 2 | 101 | Customer A2 |
| 3 | 102 | Customer B1 |
| 4 | 103 | Customer C1 |
Tenant A can access records with TenantId = 101. Tenant B can access records with TenantId = 102.
SQL Query Example
SELECT *
FROM Customers
WHERE TenantId = 101;
In a real application, the TenantId must come from a trusted tenant-resolution process, not from an unverified value supplied by the user.
Advantages
- Lower infrastructure cost.
- Easy database provisioning because tenants share the same database.
- Simple database migrations because tables are shared.
- Efficient resource utilization for applications with many tenants.
- Cross-tenant reporting is easier.
- Suitable for large SaaS applications with many small and medium-sized tenants.
Disadvantages
- Requires strict tenant-based data filtering.
- A missing TenantId filter can expose another tenant's data.
- Heavy workloads from one tenant can affect other tenants.
- Tenant-specific schema customization is difficult.
- Individual tenant backup and restore is more complicated.
7. Database Strategy Comparison
| Feature | Database-per-Tenant | Shared Schema | Separate Schema |
|---|---|---|---|
| Database | Separate database | Shared database | Shared database |
| Tables | Separate | Shared | Separate by schema |
| Data Isolation | Strong | Depends on filtering and controls | Logical separation |
| Infrastructure Cost | Generally higher | Generally lower | Generally moderate |
| Migration | Per database | One shared schema migration | Across tenant schemas |
| Backup | Per tenant database | Usually database-level | Usually database-level |
| Cross-Tenant Reporting | More complicated | Easier | More complicated |
| Tenant Count | Often suitable for fewer or larger tenants | Often suitable for many tenants | Depends on database and schema limits |
8. How to Identify a Tenant in ASP.NET Core
Before accessing tenant-specific data, the application must identify which tenant is making the request.
Common tenant identification strategies include:
- Subdomain: companyA.example.com
- Custom domain: portal.companyA.com
- JWT claim: TenantId stored as a claim in an authenticated token.
- Request header: X-Tenant-Id, validated against the authenticated user's permissions.
- Route: example.com/tenant/companyA/dashboard
Important: Never trust a tenant ID simply because it appears in a URL, header, or request body. Validate it against the authenticated user's authorized tenant memberships.
9. Implementing Tenant Resolution in ASP.NET Core
Step 1: Create a Tenant Model
public class Tenant
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Identifier { get; set; } = string.Empty;
public string ConnectionString { get; set; } = string.Empty;
}
The tenant information can be stored in a central tenant registry database.
Step 2: Create an ITenantProvider Interface
public interface ITenantProvider
{
Tenant? CurrentTenant { get; }
void SetTenant(Tenant tenant);
}
Step 3: Implement TenantProvider
public class TenantProvider : ITenantProvider
{
public Tenant? CurrentTenant { get; private set; }
public void SetTenant(Tenant tenant)
{
CurrentTenant = tenant;
}
}
Step 4: Create Tenant Resolution Middleware
The middleware identifies the tenant for the current request. This simplified example resolves a tenant from its subdomain using a tenant registry service.
public interface ITenantRegistry
{
Task<Tenant?> FindByHostAsync(
string host,
CancellationToken cancellationToken);
}
public class TenantResolutionMiddleware
{
private readonly RequestDelegate _next;
public TenantResolutionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(
HttpContext context,
ITenantProvider tenantProvider,
ITenantRegistry tenantRegistry)
{
var host = context.Request.Host.Host;
var tenant = await tenantRegistry.FindByHostAsync(
host,
context.RequestAborted);
if (tenant == null)
{
context.Response.StatusCode =
StatusCodes.Status404NotFound;
await context.Response.WriteAsync(
"Tenant not found.");
return;
}
tenantProvider.SetTenant(tenant);
await _next(context);
}
}
The registry must validate the complete host against a trusted tenant record. Do not blindly treat arbitrary subdomain text as a valid tenant.
Step 5: Register Services and Middleware
builder.Services.AddScoped<ITenantProvider, TenantProvider>();
// Register your tenant registry implementation.
builder.Services.AddScoped<ITenantRegistry, TenantRegistry>();
var app = builder.Build();
app.UseAuthentication();
app.UseMiddleware<TenantResolutionMiddleware>();
app.UseAuthorization();
app.MapControllers();
app.Run();
In this example, tenant resolution runs after authentication. If tenant resolution depends on authenticated claims, this ordering is important. If it uses only a host name, the design may differ, but authorization must still validate tenant membership.
10. Database-per-Tenant Using Entity Framework Core
For database-per-tenant, the connection string is selected based on the resolved tenant.
DbContext
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers => Set<Customer>();
}
Register DbContext
builder.Services.AddDbContext<AppDbContext>(
(serviceProvider, options) =>
{
var tenantProvider =
serviceProvider.GetRequiredService<ITenantProvider>();
var tenant = tenantProvider.CurrentTenant
?? throw new InvalidOperationException(
"Tenant has not been resolved.");
options.UseSqlServer(tenant.ConnectionString);
});
Important: The tenant must be resolved before the DbContext is first created. Keep the DbContext scoped to the request and do not reuse tenant-specific DbContext instances across requests.
11. Shared Database Using Entity Framework Core
For a shared database, add a TenantId column to every tenant-owned entity.
Entity
public class Customer
{
public int Id { get; set; }
public int TenantId { get; set; }
public string Name { get; set; } = string.Empty;
}
DbContext with Global Query Filter
public class AppDbContext : DbContext
{
private readonly ITenantProvider _tenantProvider;
public AppDbContext(
DbContextOptions<AppDbContext> options,
ITenantProvider tenantProvider)
: base(options)
{
_tenantProvider = tenantProvider;
}
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasQueryFilter(customer =>
customer.TenantId ==
_tenantProvider.CurrentTenant!.Id);
}
}
EF Core automatically applies this filter to normal queries for the entity.
Query Example
var customers = await dbContext.Customers
.ToListAsync();
If the current tenant has ID 101, EF Core applies the equivalent of:
SELECT *
FROM Customers
WHERE TenantId = 101;
Important security considerations:
- Do not allow the client to choose an arbitrary TenantId.
- Set TenantId from the validated tenant context when creating records.
- Do not rely only on global query filters for security.
- EF Core's IgnoreQueryFilters() can bypass filters.
- Raw SQL and other data-access paths must also enforce tenant isolation.
- Consider database-level row-level security as an additional protection.
12. Automatically Assign TenantId When Saving Data
For shared-table architecture, new records should receive the current tenant ID automatically.
public override int SaveChanges()
{
ApplyTenantId();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default)
{
ApplyTenantId();
return base.SaveChangesAsync(cancellationToken);
}
private void ApplyTenantId()
{
var tenantId = _tenantProvider.CurrentTenant?.Id
?? throw new InvalidOperationException(
"Tenant context is missing.");
foreach (var entry in ChangeTracker.Entries<Customer>())
{
if (entry.State == EntityState.Added)
{
entry.Entity.TenantId = tenantId;
}
}
}
For a production implementation, also validate tenant ownership when updating or deleting records. Apply the same rules to every tenant-owned entity, not only Customer.
13. Database-Level Security with SQL Server Row-Level Security
SQL Server Row-Level Security (RLS) can restrict which rows a database user or session can access.
For a shared database, RLS can provide an additional layer of tenant isolation.
Conceptual Example
CREATE FUNCTION dbo.fn_TenantFilter
(
@TenantId INT
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT 1 AS accessResult
WHERE @TenantId =
TRY_CONVERT(INT, SESSION_CONTEXT(N'TenantId'))
);
GO
CREATE SECURITY POLICY dbo.TenantSecurityPolicy
ADD FILTER PREDICATE dbo.fn_TenantFilter(TenantId)
ON dbo.Customers,
ADD BLOCK PREDICATE dbo.fn_TenantFilter(TenantId)
ON dbo.Customers AFTER INSERT,
ADD BLOCK PREDICATE dbo.fn_TenantFilter(TenantId)
ON dbo.Customers AFTER UPDATE
WITH (STATE = ON);
GO
The application must set the correct session context for each database connection before executing tenant queries.
EXEC sys.sp_set_session_context
@key = N'TenantId',
@value = 101;
Important: With connection pooling, session context must be managed carefully. Ensure it is set correctly for every logical connection use and cannot leak between tenants. Test insert, update, delete, connection reuse, and background-job scenarios. RLS is an additional security layer, not a replacement for application authorization.
14. Tenant-Specific Database Migrations
In database-per-tenant architecture, each tenant database must be updated when the application database schema changes.
Example:
foreach (var tenant in tenants)
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer(tenant.ConnectionString)
.Options;
await using var dbContext =
new AppDbContext(options, tenantProvider);
await dbContext.Database.MigrateAsync();
}
This is only an illustrative example. A production migration service should handle tenant context, migration locks, failures, retries, progress tracking, and controlled rollout.
For a large number of tenants, do not migrate every database simultaneously without considering database capacity and deployment risk.
15. Tenant Isolation and Security Best Practices
- Validate tenant identity: Resolve tenants through trusted records and validate the user's membership.
- Enforce authorization: Authentication identifies the user; authorization determines which tenant resources the user may access.
- Use global query filters: Apply tenant filtering consistently in EF Core.
- Use database constraints: Include TenantId in relevant unique constraints and relationships.
- Protect raw SQL: Explicitly apply tenant restrictions to raw SQL and stored procedures.
- Secure background jobs: Pass and validate tenant context explicitly when processing tenant-specific work.
- Audit access: Record tenant ID, user ID, operation, and relevant resource identifiers.
- Protect connection strings: Store secrets in a secure configuration system such as Azure Key Vault.
- Test isolation: Test that one tenant cannot read, modify, or delete another tenant's data.
- Monitor noisy neighbors: Monitor database CPU, query duration, storage, and tenant-level usage.
16. Common Mistakes to Avoid
- Using a client-supplied TenantId without authorization checks.
- Forgetting TenantId filters in repository or raw SQL queries.
- Assuming global query filters cannot be bypassed.
- Sharing a tenant-specific DbContext across requests.
- Using a singleton service to store the current tenant.
- Failing to set tenant context in background jobs.
- Not including TenantId in unique constraints where uniqueness is tenant-specific.
- Running database migrations without tracking failures.
- Ignoring tenant-specific rate limits and resource usage.
- Exposing connection strings or tenant configuration through APIs or logs.
17. Hybrid Multi-Tenant Architecture
You do not have to use only one database strategy. A hybrid model can support different customer requirements.
For example:
- Small customers use a shared database.
- Medium customers use a shared database with stronger resource controls.
- Enterprise customers use dedicated databases.
Architecture
This approach offers flexibility, but the application must consistently route each tenant to the correct storage strategy.
18. Which Approach Should You Choose?
| Requirement | Suggested Approach |
|---|---|
| Many small tenants | Shared database with shared schema |
| Strict database isolation | Database-per-tenant |
| Tenant-specific backup and restore | Database-per-tenant |
| Low infrastructure cost | Shared database with shared schema |
| Different tenant database configurations | Database-per-tenant |
| Enterprise and small customers together | Hybrid architecture |
There is no universally best approach. Choose based on tenant count, security requirements, operational complexity, performance, cost, and backup/restore needs.
19. Interview Questions and Answers
Q1. What is multi-tenancy?
Multi-tenancy is an architecture where a single application serves multiple customers while maintaining separation of their data and access.
Q2. What is a tenant?
A tenant is an organization, company, or customer using a shared application.
Q3. What is database-per-tenant architecture?
Each tenant has an independent database. The application selects the correct database based on the resolved tenant.
Q4. What is shared database architecture?
Multiple tenants use the same database. In a shared-schema model, tenant-owned tables contain a TenantId column to identify each tenant's records.
Q5. Which approach provides stronger database isolation?
Database-per-tenant generally provides stronger physical separation because each tenant has a separate database. However, correct access control and infrastructure security are still necessary.
Q6. What is a global query filter in EF Core?
A global query filter is a condition automatically applied to queries for an entity. It can be used to filter records based on the current TenantId.
Q7. What is tenant resolution?
Tenant resolution is the process of identifying which tenant a request belongs to using a validated domain, subdomain, authenticated claim, or other trusted context.
Q8. What is the noisy-neighbor problem?
It occurs when one tenant consumes excessive shared resources, affecting the performance of other tenants.
Q9. How do you secure a shared database?
Use validated tenant context, authorization checks, global query filters, tenant-aware constraints, careful raw SQL handling, and optionally database-level Row-Level Security.
Q10. How do you handle tenant-specific migrations?
For database-per-tenant, maintain a tenant registry and run controlled migrations against each tenant database. Track migration status and failures.
Q11. Can we use both shared and separate databases?
Yes. A hybrid architecture can place smaller tenants in a shared database and larger enterprise tenants in dedicated databases.
Q12. How do you prevent one tenant from accessing another tenant's data?
Validate tenant membership, enforce authorization, apply tenant filters, validate writes and relationships, and test all data-access paths for cross-tenant access.
20. Final Summary
- Database-per-Tenant: Separate database for each tenant; stronger isolation and independent database operations, but higher operational complexity.
- Shared Database with Shared Schema: Same tables for all tenants, with TenantId identifying each tenant's records; cost-effective and convenient for many tenants, but requires rigorous isolation controls.
- Shared Database with Separate Schemas: One database with separate schemas for each tenant; provides logical separation but adds schema-management complexity.
- Hybrid Architecture: Combines shared and dedicated databases to meet different customer requirements.
Key interview point: Multi-tenancy is not just about selecting a database strategy. It also requires tenant identification, authorization, data isolation, connection management, migrations, monitoring, and secure background processing.
| Building Resilient Applications Using Polly :👈 | 👉:CQRS and Event-Driven Architecture |