Video in progress
In a multi-tenant SaaS, every customer (tenant) needs slightly different business rules. How do you design it without burying the code in ifs?
I split the differences into three categories: parameters (tenant settings), swappable behavior (a strategy picked per tenant) and truly custom extensions. The tenant context is determined in one place, and the code doesn't know if (tenant == "X").
📖 Answer
The worst way is if ("bank-a".equals(tenantId)) in code. After 30 tenants nobody knows which rule belongs to whom, and adding a new tenant means searching the whole codebase.
The categories and solutions:
1. Parameters (80% of cases). Limits, commission percentage, the number of approval steps, currencies. A tenant settings table or a configuration service, with a cache, as a typed object:
public record TenantPolicy(Money dailyLimit, Percent fee, int approvalSteps) {}
- Swappable behavior. Some tenants use a different calculation method. Strategy, with the tenant configuration saying which implementation:
@Component
class FeeCalculators {
private final Map<String, FeeCalculator> byName;
FeeCalculator forTenant(TenantPolicy p) { return byName.get(p.feeModel()); }
}
Name strategies by business meaning (TIERED, FLAT), not by tenant name, so another tenant can use them later.
- Custom extensions. A unique integration for one big customer. Outside the core code: a separate module, or a webhook/extension point. The core domain doesn't know about it.
Passing the tenant context:
- it's determined at the start of the request (a filter) and passed as an explicit parameter or through
ScopedValue/ThreadLocal: withThreadLocalyou must clear it at the end of every request and pass it by hand across async boundaries; - a tenant tag in logs and metrics, to isolate problems per tenant.
The risk: an explosion of configuration combinations. 10 flags is 1024 combinations, and you can't test them all. Group the combinations actually in use into "profiles" and support only those.
Sign up to mark studied questions and save your progress.