Design a Multi-Tenant SaaS Platform
On this page
Learning Objective
Design the platform layer of a multi-tenant SaaS product: tenant lifecycle, host-based tenant resolution checked against membership, plan entitlements and per-tenant limits, metered billing with idempotent provider events, enterprise features such as per-tenant SSO and custom domains, and safe tenant export and deletion.
Concept Explanation
Day 68 covered isolating tenant data. A SaaS platform needs more around it: a way for customers to sign up, choose a plan, invite their users, be limited to what they pay for, be billed for what they use, connect their own identity provider, and eventually leave with their data. Requirements: self-service onboarding, several plans with different entitlements, enterprise customers with single sign-on and dedicated resources, usage-based billing, and support staff who can help without gaining blanket access to customer data. Non-functional: strict isolation, predictable performance for every tenant, auditability, and compliance with privacy law including data export and deletion on request.
Start with the identity model. A user account and a tenant are separate things connected by a membership: one person can belong to several tenants with different roles in each, so authorization always evaluates the pair of user and tenant, never the user alone. Resolve the current tenant from something the user cannot forge freely, typically the host name, such as acme.app.example, or a route segment, and then verify against the database that the authenticated user is a member of that tenant before accepting it. The tenant claim in the token from Day 68 is the fast path, but the request's host must agree with it, or requests are rejected. Enterprise customers configure their own identity provider, so the platform stores per-tenant OpenID Connect or SAML settings, routes sign-in by tenant, validates the issuer per tenant, and often supports automated user provisioning through SCIM.
Plans and limits are business rules that must be enforced on the server in one place. Model entitlements as data: a plan grants features, such as SSO or audit export, and quotas, such as members, projects, storage, and API calls per month. An entitlement check in the request path answers can this tenant do this now, returning a clear 402 or 403 style response with an upgrade hint when a limit is hit. Rate limiting is partitioned by tenant with plan-dependent limits, so one tenant's traffic cannot starve others, the noisy neighbor problem. Consider a tiered topology as customers grow: most tenants share a pooled database and compute, while large or regulated customers get dedicated resources in their own deployment stamp, following the deployment stamps pattern, with the same code and a routing layer that knows where each tenant lives.
Billing turns usage into money, and it is an integration problem with the same hazards as checkout in Day 94. Meter usage as events written to the outbox, aggregate them per tenant and period, and report them to the billing provider with idempotency keys, so a retried report does not double count. Subscription state, whether a tenant is active, past due, or canceled, arrives through signed webhooks that are verified and processed idempotently, and it feeds the entitlement service, which should degrade gracefully: a past-due tenant is warned and then moved to read-only, not deleted. Custom domains add a specific security risk: if a tenant points a domain at your service and later removes the record while the platform still accepts it, or you release the underlying resource but leave the DNS name dangling, someone else can claim it, called subdomain takeover. Require proof of ownership with a DNS TXT record before activating a custom domain and monitor for dangling records.
Support access and lifecycle events are where privacy is won or lost. Support staff should not have standing access to tenant data. Provide time-limited, tenant-approved impersonation, logged in the audit trail with the reason, or view-only diagnostic tools that expose metadata. For offboarding, provide a data export in a portable format and a deletion process that removes tenant data from the database, blob storage, caches, search indexes, and backups on a documented schedule, with verification, since privacy regulations such as the GDPR give individuals a right to erasure. A tenant status field with states such as active, suspended, and deleting lets every layer respond consistently.
| Concern | Design | Reason |
|---|---|---|
| Identity model | Users and tenants linked by memberships with roles | One person, many tenants, per-tenant permissions |
| Tenant resolution | Host name checked against the user's memberships | Cannot be forged by a header or body value |
| Entitlements | Plan features and quotas as data, enforced in one service | Consistent limits, clear upgrade responses |
| Noisy neighbors | Per-tenant rate limits and quotas, dedicated stamps for large tenants | Fair performance for everyone |
| Billing | Metered events via outbox, idempotent reporting, signed webhooks | No double counting, no forged subscription changes |
| Enterprise features | Per-tenant OIDC or SAML, SCIM provisioning, verified custom domains | SSO without shared secrets, no domain takeover |
| Support and lifecycle | Approved, audited impersonation; export and verified deletion | Privacy and compliance |
Worked Example: Tenant Resolution, Entitlements, Per-Tenant Limits, Metering and Domain Verification
The listings show the tenant tables, resolution middleware, an entitlement check with quotas, per-tenant rate limiting, a usage meter, and DNS ownership verification.
CREATE TABLE dbo.Tenants (
Id UNIQUEIDENTIFIER NOT NULL CONSTRAINT PK_Tenants PRIMARY KEY, Slug VARCHAR(63) NOT NULL CONSTRAINT UQ_Tenants_Slug UNIQUE,
Plan VARCHAR(20) NOT NULL, Status VARCHAR(12) NOT NULL CONSTRAINT CK_Tenants_Status CHECK (Status IN ('active','suspended','deleting')),
Region VARCHAR(20) NOT NULL, CreatedAt DATETIMEOFFSET NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE TABLE dbo.TenantMembers (TenantId UNIQUEIDENTIFIER NOT NULL, UserId UNIQUEIDENTIFIER NOT NULL, Role VARCHAR(20) NOT NULL,
CONSTRAINT PK_TenantMembers PRIMARY KEY (TenantId, UserId));
CREATE TABLE dbo.PlanEntitlements (Plan VARCHAR(20) NOT NULL, Feature VARCHAR(40) NOT NULL, Limit BIGINT NULL, -- NULL means unlimited
CONSTRAINT PK_PlanEntitlements PRIMARY KEY (Plan, Feature)); -- e.g. ('team','members',25), ('enterprise','sso',1). No row: not in the plan. NULL limit: unlimited.
CREATE TABLE dbo.UsageEvents (Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY, TenantId UNIQUEIDENTIFIER NOT NULL, Metric VARCHAR(40) NOT NULL,
Quantity BIGINT NOT NULL, At DATETIMEOFFSET NOT NULL, ReportedAt DATETIMEOFFSET NULL);
CREATE TABLE dbo.CustomDomains (Domain VARCHAR(253) NOT NULL PRIMARY KEY, TenantId UNIQUEIDENTIFIER NOT NULL, VerifyToken VARCHAR(64) NOT NULL, VerifiedAt DATETIMEOFFSET NULL);// 1. Resolve the tenant from the host, then require an active membership. Never trust a header or body value.
public sealed class TenantResolutionMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext ctx, AppDb db, ITenantContext tenantContext, IMemoryCache cache)
{
var host = ctx.Request.Host.Host.ToLowerInvariant(); // acme.app.example.com
var slug = host.EndsWith(".app.example.com") ? host[..^".app.example.com".Length] : null;
Tenant? tenant = slug is not null
? await cache.GetOrCreateAsync($"tenant:{slug}", async e => { e.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
return await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Slug == slug); })
: await db.CustomDomains.AsNoTracking().Where(d => d.Domain == host && d.VerifiedAt != null) // only VERIFIED custom domains
.Join(db.Tenants, d => d.TenantId, t => t.Id, (d, t) => t).FirstOrDefaultAsync();
if (tenant is null) { ctx.Response.StatusCode = 404; return; }
if (tenant.Status != "active") { ctx.Response.StatusCode = 403; await ctx.Response.WriteAsync("This workspace is not available."); return; }
if (ctx.User.Identity?.IsAuthenticated == true)
{
var uid = ctx.User.GetUserId();
var role = await db.TenantMembers.AsNoTracking().Where(m => m.TenantId == tenant.Id && m.UserId == uid).Select(m => m.Role).FirstOrDefaultAsync();
if (role is null) { ctx.Response.StatusCode = 404; return; } // not a member: the tenant does not exist for you
tenantContext.Set(tenant.Id, tenant.Plan, role);
}
await next(ctx);
}
}
// 2. Entitlements: one place answers "may this tenant do this now?" and produces a helpful refusal.
public sealed class Entitlements(AppDb db, ITenantContext tenant, HybridCache cache)
{
public async Task<EntitlementResult> CheckAsync(string feature, long currentUsage, CancellationToken ct)
{
var limit = await cache.GetOrCreateAsync($"ent:{tenant.Plan}:{feature}",
async t => await db.PlanEntitlements.AsNoTracking().Where(e => e.Plan == tenant.Plan && e.Feature == feature)
.Select(e => new EntitlementRow(e.Limit)).FirstOrDefaultAsync(t), cancellationToken: ct);
if (limit is null) return EntitlementResult.NotIncluded(feature); // feature not part of the plan
if (limit.Limit is { } max && currentUsage >= max) return EntitlementResult.LimitReached(feature, max);
return EntitlementResult.Allowed;
}
}
app.MapPost("/api/members", async (InviteMember body, Entitlements ent, AppDb db, ITenantContext t, CancellationToken ct) =>
{
var count = await db.TenantMembers.CountAsync(m => m.TenantId == t.Id, ct);
var check = await ent.CheckAsync("members", count, ct);
if (!check.IsAllowed) return Results.Problem(check.Message, statusCode: 402, extensions: new Dictionary<string, object?> { ["upgrade"] = "/billing/plans" });
/* create the invitation ... */
return Results.Accepted();
}).RequireAuthorization("TenantAdmin");// 3. Per-tenant rate limits with plan-dependent budgets: one tenant cannot starve the others.
builder.Services.AddRateLimiter(o => o.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, Guid>(ctx =>
{
var t = ctx.RequestServices.GetRequiredService<ITenantContext>();
var perMinute = t.Plan switch { "enterprise" => 6000, "team" => 1200, _ => 300 };
return RateLimitPartition.GetTokenBucketLimiter(t.Id, _ => new TokenBucketRateLimiterOptions
{ TokenLimit = perMinute / 4, TokensPerPeriod = perMinute / 60, ReplenishmentPeriod = TimeSpan.FromSeconds(1), QueueLimit = 0 });
}));
// 4. Usage metering: an event per billable action, written with the business change; reported later with idempotency.
db.UsageEvents.Add(new UsageEvent { Id = Guid.CreateVersion7(), TenantId = t.Id, Metric = "api.export", Quantity = 1, At = clock.GetUtcNow() });
public sealed class UsageReporter(IServiceScopeFactory scopes, IBillingClient billing) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync(ct))
{
using var scope = scopes.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDb>();
var groups = await db.UsageEvents.Where(u => u.ReportedAt == null && u.At < DateTimeOffset.UtcNow.AddMinutes(-1))
.GroupBy(u => new { u.TenantId, u.Metric }).Select(g => new { g.Key.TenantId, g.Key.Metric, Qty = g.Sum(x => x.Quantity), Ids = g.Select(x => x.Id).ToList() }).Take(200).ToListAsync(ct);
foreach (var g in groups)
{
var key = $"usage-{g.TenantId}-{g.Metric}-{g.Ids.Min()}-{g.Ids.Max()}"; // stable for the same batch: a retry cannot double count
await billing.ReportUsageAsync(g.TenantId, g.Metric, g.Qty, idempotencyKey: key, ct);
await db.UsageEvents.Where(u => g.Ids.Contains(u.Id)).ExecuteUpdateAsync(s => s.SetProperty(u => u.ReportedAt, DateTimeOffset.UtcNow), ct);
}
}
}
}// 5. Custom domains: prove ownership with a DNS TXT record BEFORE the domain can select a tenant. This prevents hijacking and takeover.
public async Task<bool> VerifyDomainAsync(string domain, string token, CancellationToken ct)
{
var lookup = new LookupClient(); // DnsClient package
var result = await lookup.QueryAsync($"_verify.{domain}", QueryType.TXT, cancellationToken: ct);
return result.Answers.TxtRecords().SelectMany(r => r.Text).Any(t => t == $"taskboard-verification={token}");
}
// A scheduled job re-verifies active domains weekly and disables any whose CNAME no longer points at the platform,
// and every decommissioned resource removes its DNS entry first, so no name is left dangling for someone else to claim.// 6. Offboarding: export, then a verified deletion across every store, tracked as a job with a checklist.
public sealed record TenantDeletionPlan(Guid TenantId)
{
public static readonly string[] Steps = ["suspend", "export-delivered", "delete-sql-rows", "delete-blobs", "purge-cache", "purge-search-index", "revoke-idp-config", "remove-domains", "schedule-backup-expiry", "verify-and-attest"];
}
// Each step is idempotent, recorded in an audit table, and the final step queries every store to confirm nothing remains for the tenant id.The support impersonation feature should follow the same pattern: a tenant admin grants a time-limited approval, the session is marked with an impersonation claim and a visible banner, every action is written to the tenant-visible audit log, and the approval expires on its own.
Real-World Examples
- Microsoft's Azure Architecture Center publishes guidance on multitenant solutions that describes tenancy models from fully multitenant to single-tenant, and the deployment stamps pattern, in which independent copies of the whole stack serve groups of tenants. The guidance covers tenant isolation, noisy neighbors, and per-tenant configuration, and reflects how large SaaS products place small customers on shared infrastructure and large or regulated ones on dedicated stamps.
- Subdomain takeover through dangling DNS records is a well-documented problem on Azure and other clouds: a CNAME left pointing at a deleted resource lets an attacker create a resource with the same name and serve content on your domain. Microsoft's documentation on preventing dangling DNS entries recommends removing records before deleting resources and validating domain ownership, which is the check used for custom domains here.
Review Questions & Answers
The host tells you which tenant the request is aimed at, but not that the caller may access it. Without a membership check, any authenticated user could visit another tenant's subdomain and see its data. Verifying membership, and returning not found when it is absent, ensures the tenant boundary is enforced by data the caller cannot forge.
The key is derived deterministically from the tenant, metric, and the batch of events being reported, so if the reporter crashes after the provider accepted the report but before marking the events as reported, the retry sends the same key and the provider recognizes it as the same operation instead of adding the usage again.
It occurs when a DNS name still points at a cloud resource that no longer exists, allowing an attacker to claim that resource and serve content under the victim's domain. Requiring a DNS TXT proof of ownership before activating a custom domain, re-verifying periodically, and removing DNS records before deleting resources prevents both hijacking by other tenants and dangling names.
Standing access creates a large insider risk and weakens the isolation guarantee customers rely on. Time-limited, tenant-approved impersonation, with a visible banner and full audit logging, lets support help when needed while keeping every access deliberate, reviewable, and limited to what the customer permitted.