Video in progress
In a multi-tenant SaaS, you need to bound the in-memory cache fairly for each tenant. How do you design it?
In a single shared LRU, a big tenant squeezes out the small ones, and a strict separate cache per tenant wastes memory. I choose a hybrid: a cache bounded by total weight, with quotas and metrics per tenant.
📖 Answer
The problem: 500 tenants, and one of them (a large bank) accounts for 60% of traffic. In a shared cache with maximumSize(100_000), it keeps evicting the small tenants' entries and their latency gets worse. That is the "noisy neighbor".
The options:
-
A separate cache per tenant:
Map<TenantId, Cache<K, V>>. Fair, but with many tenants memory is split rigidly, and an inactive tenant's quota sits unused. If the number of tenants varies, the outer map has to be managed too. -
A shared cache, with the key
(tenantId, key)and a bound by weight. Caffeine hasmaximumWeight+weigher, where every entry is counted by an estimate in bytes. This bounds memory correctly, but doesn't ensure fairness. -
A hybrid: a shared cache + per-tenant accounting. Each tenant's current weight is kept in a
ConcurrentHashMap<TenantId, LongAdder>(it grows on insert and shrinks in the removal listener). For a tenant over its quota, new entries aren't put in the cache, or its oldest ones are removed.
Cache<TenantKey, Value> cache = Caffeine.newBuilder()
.maximumWeight(512L * 1024 * 1024)
.weigher((TenantKey k, Value v) -> v.sizeInBytes())
.removalListener((TenantKey k, Value v, RemovalCause c) ->
usage.get(k.tenant()).add(-v.sizeInBytes()))
.build();
This scheme is approximate: Caffeine performs eviction asynchronously, so the accounting lags a little. If strict isolation is required (an SLA by contract), it is better to move big tenants to a separate pod or a separate cache instance.
Monitoring is a must: hit rate, weight and eviction count per tenant. But putting 500 tenants in a metric label blows up cardinality, so I export the top 20 separately and the rest as "other".
And the most important question goes to the product side: how is fairness defined, an equal share, by pricing plan, or by activity? That is not a technical decision but a business one, and it should be agreed in writing.
Sign up to mark studied questions and save your progress.