We are to design a tenancy-aware cache hierarchy. This implies:
- The cache system is aware of tenants (multi-tenancy) and must isolate data between tenants.
- We have multiple layers of caching (hierarchy) - typically L1, L2, etc.
- Request scoping: each request (or operation) should have a context (like tenant ID) that scopes the cache lookups and updates.
- Invalidation policies: how and when cached data is invalidated (by tenant, by key, by time, etc.)
- Miss analytics: track and analyze cache misses to possibly optimize caching strategies.
Design Considerations:
-
Tenancy: We must ensure that one tenant cannot access another tenant's cached data. This must be enforced at every layer.
-
Hierarchy: We might have a local cache (per instance) and a distributed cache (shared across instances). Or multiple levels of local caches (like L1: in-memory, L2: off-heap, L3: distributed).
-
Request Scoping: Each request comes with a tenant identifier. The cache system must use this to isolate keys. We can achieve by:
a) Prefixing every key with tenant ID (and possibly other scoping like user ID if needed) in all cache layers.
b) Having separate cache instances per tenant (not scalable for many tenants).
We'll go with (a) because it's more common and scalable.
-
Invalidation: We need to invalidate cache entries when the underlying data changes. This could be:
a) Time-based (TTL)
b) Event-based (explicit invalidation on data change)
c) Write-through or write-behind strategies.
Since we are in a multi-tenant system, invalidation must be tenant-specific. Also, in a distributed environment, we need to propagate invalidations.
-
Miss Analytics: We want to track cache misses (and possibly hits) per tenant, per cache layer, per operation type, etc. This can help in:
a) Tuning cache sizes and TTLs.
b) Understanding which tenants are causing more misses and why.
c) Identifying hot keys.
Proposed Design:
-
Key Structure:
We'll use a composite key for the cache: (tenant_id, operation_key). The operation_key is the original key (like user_id, or product_id) but note that the same operation_key might exist for multiple tenants (so without tenant_id, it would be a cross-tenant leak). So every cache put/get must include the tenant_id.
-
Cache Hierarchy:
We can have:
- L1: In-memory cache (e.g., Caffeine, Guava) per application instance. Very fast, but limited size and not shared.
- L2: Distributed cache (e.g., Redis, Hazelcast) shared among all instances. Larger, but slower.
The hierarchy: On a read request, first check L1, if miss then L2, if miss then fetch from DB and populate both (write-through or write-behind). On write, update DB and invalidate (or update) in both caches.
However, note: we are tenancy-aware. So in both L1 and L2, the keys are prefixed with tenant_id.
-
Request Scoping:
We assume that each request (or thread) has a context that holds the tenant_id (and possibly other scoping info). The cache accessor must be provided with this context. Alternatively, we can have a ThreadLocal to hold the current tenant, but that might be error-prone in async environments. Better to pass explicitly or use a context object.
Example:
cache.get(tenantId, key)
But note: the key might be a complex object. We can design:
public Object get(String tenantId, Object key) { ... }
Then internally, we combine tenantId and key to form the cache key.
-
Invalidation:
We have two types of invalidations:
a) Time-based: set TTL for each entry. This can be per entry or per cache region (by tenant or by type of data).
b) Explicit: when data is updated in the DB, we send an invalidation message (via a message broker) to all application instances to remove the corresponding key (with tenant_id) from their L1 and L2 caches.
Since we have a hierarchy, we must invalidate at both levels. For L2 (distributed), we can directly delete the key. For L1, each instance must delete the key from its local cache. We can do that by:
- Having a message broker (like Kafka) that publishes invalidation events. Each instance subscribes and invalidates its local cache for the given tenant and key.
Alternatively, if we use a distributed cache that supports pub/sub for key invalidation (like Redis with keyspace notifications), we can rely on that.
However, note: if we use write-through, then on write we update the DB and then update the caches (put the new value). But then we have to update both L1 and L2. But updating L1 on every write might be heavy. We can use write-behind (asynchronous) but then there's a window of inconsistency.
Let's consider:
Write path:
- Update DB.
- Invalidate L2 (and L1) for the key (tenant_id, key) so that next read fetches fresh data.
But then the next read will be a miss in L1 and L2, and then we fetch from DB and populate both. This is safe.
Alternatively, we can update L2 and L1 with the new value (write-through). Then the next read will hit in L2 (and maybe L1) and get the new value. This is also safe and might reduce DB load.
However, if we update L1 and L2, we must be careful about the order: update L2 first (so that other instances see the update) and then update L1 (local). But if we update L1 first and then L2, and then crash, we might have inconsistency.
Given the complexity, let's stick with invalidation (cache-aside) for writes:
Write:
1. Update DB.
2. Delete from L2 (distributed cache) for (tenant_id, key).
3. Publish an invalidation event (or directly delete from L1 if we are the same instance? But note: the write might come to any instance, so we must invalidate L1 on all instances? Actually, the write might be handled by any instance, but that instance's L1 cache might have the old value. We must invalidate that too. And other instances might have the old value in their L1. So we need to broadcast.
So we do:
Write:
- Update DB.
- Delete from L2 (so that any instance that checks L2 will miss and go to DB, but we are going to invalidate L1 too so that they don't even check L2? Actually, if we delete from L2, then the next read on any instance will miss L2 and then go to DB and then repopulate L2 and L1. But if we don't invalidate L1, then an instance might have the old value in L1 and return it (because L1 hit) and skip L2 and DB. That's bad.
Therefore, we must invalidate L1 on all instances. We can do:
Write:
- Update DB.
- Delete from L2 (for the key).
- Send an invalidate message to all instances (including self) to remove the key from L1.
But note: if we delete from L2, then even if L1 has the old value, the next read would be a hit in L1 and return old value? Wait, the read path:
Read:
if (L1 contains key) -> return
else if (L2 contains key) -> put in L1 and return
else -> DB, then put in L2 and L1.
So if we only delete from L2 and not L1, then an instance that has the old value in L1 will return the old value. So we must delete from L1 too.
How to delete from L1 on all instances? We can use a message bus. Each instance, upon receiving the invalidation message, deletes the key from its L1.
Alternatively, we can use a distributed cache that supports atomic operations and we can update L2 with the new value (write-through) and then rely on L2's expiration to eventually evict from L1? Not safe.
So we need a way to broadcast invalidation to L1 caches.
-
Miss Analytics:
We want to track:
- Total misses per tenant, per cache layer.
- Miss reasons: not in L1, not in L2, etc.
- Possibly track which keys are causing misses (hot keys that are not cached?).
We can have a listener or interceptor on cache get operations that record misses.
We must be careful: we don't want to impact performance too much. We can sample or aggregate in memory and report periodically.
Also, we might want to track per-tenant metrics to see if a tenant is causing too many misses (maybe they have a large dataset that doesn't fit in cache).
Design:
On every get:
- Check L1: if hit, record hit (maybe not needed) and return.
- If miss in L1, check L2: if hit, record that it was a hit in L2 (and maybe a miss in L1) and return.
- If miss in L2, then we are going to DB: record a total miss (and miss in both L1 and L2).
We can have a metrics collector (like a counter) per tenant, per cache layer (L1, L2, total) for misses.
But note: we also have writes. We might want to track write invalidations? Maybe not.
We can have:
cacheMissesL1(tenantId).increment();
cacheMissesL2(tenantId).increment();
But then we are incrementing two counters for a total miss? Actually, for a total miss we miss in both. So we can have:
if (l1Miss) {
l1MissCounter(tenantId).increment();
if (l2Miss) {
l2MissCounter(tenantId).increment();
totalMissCounter(tenantId).increment();
}
}
However, note that if we miss in L1 and hit in L2, then we don't increment totalMiss (because we got from L2). So:
if (l1Miss) {
l1MissCounter(tenantId).increment();
if (l2Hit) {
// then we populate L1 and return, no total miss.
} else {
l2MissCounter(tenantId).increment();
totalMissCounter(tenantId).increment();
}
}
But wait: if we miss in L1 and hit in L2, then we have a hit in L2 and we populate L1. So we don't count as a miss for L2? Actually, we missed L1 but hit L2. So:
- L1 miss: yes.
- L2 hit: yes.
- Total miss: no (because we got from L2).
So we need:
L1 miss count: number of times we didn't find in L1.
L2 miss count: number of times we didn't find in L2 (regardless of L1?).
Total miss: number of times we had to go to DB.
But note: if we hit in L1, we don't check L2. So:
L1 miss count = (total requests) - (L1 hits)
L2 miss count = (number of times we checked L2) - (L2 hits) = (L1 misses) - (L2 hits)
Total miss = (number of times we went to DB) = (L1 misses and L2 misses)
So we can track:
l1Hits, l1Misses
l2Hits, l2Misses (but note: l2Misses is only when we check L2 and miss, i.e., l1Miss and l2Miss)
Alternatively, we can track:
requests(tenantId).increment();
l1Hits(tenantId).increment(); // when we get from L1
l2Hits(tenantId).increment(); // when we get from L2 (and then we also populated L1, but that's not a hit for L1)
Then:
l1Misses = requests - l1Hits
l2Misses = (requests - l1Hits) - l2Hits [because we only check L2 when we miss L1]
totalMisses = (requests - l1Hits - l2Hits)
But note: if we hit in L1, we don't check L2. So:
totalMisses = requests - (l1Hits + l2Hits)
And:
l1Misses = requests - l1Hits
l2Misses = l1Misses - l2Hits
So we only need to track:
- requests
- l1Hits
- l2Hits
Then we can compute the rest.
However, we might want to track L2 misses independently? Actually, if we miss L1 and then miss L2, that's a total miss. But if we miss L1 and hit L2, then we have an L2 hit. So we don't have an L2 miss in that case.
So we can have:
metrics for tenant X:
getRequests: 1000
l1Hits: 700
l2Hits: 200
Then:
l1Misses = 300
l2Misses = 300 - 200 = 100
totalMisses = 100
This seems correct.
But note: what about writes? We don't track writes in these metrics.
We might also want to track:
- Cache evictions (from L1 and L2) per tenant? That would require the cache to provide eviction events.
Given the complexity, we might start with just the above.
We can have a MetricsCollector that is passed to the cache accessor, and on every get, we record:
metrics.recordGet(tenantId, l1Hit, l2Hit)
where l1Hit and l2Hit are booleans.
Then:
if (l1Hit) {
// then we didn't check L2, so l2Hit is false? Actually, we can set l2Hit to false because we didn't even check.
} else {
// we checked L2, so l2Hit is true if we got from L2, else false.
}
But note: if we hit L1, we don't check L2. So we don't know about L2? We don't care because we didn't need L2.
So we can record:
get(tenantId, key) ->
if (l1.get(key) != null) {
metrics.recordGet(tenantId, true, false); // l1 hit, l2 not checked (so not hit)
return;
}
if (l2.get(key) != null) {
l1.put(key, value); // populate L1
metrics.recordGet(tenantId, false, true); // l1 miss, l2 hit
return;
}
// else go to DB
value = db.get(key);
l2.put(key, value);
l1.put(key, value);
metrics.recordGet(tenantId, false, false); // l1 miss, l2 miss
But wait: if we hit L1, we don't record an L2 hit (because we didn't check). That's correct.
However, note: what if we have a key that is in L1 but expired? Then we might have a stale entry in L1? We must ensure that L1 has the same TTL as L2? Or we rely on L2 being the source of truth? Actually, we populate L1 from L2, and L2 from DB. So if L2 has an entry, it's fresh (within TTL). But L1 might have an entry that is older than L2's TTL? We set TTL on L1 as well? We should set TTL on both.
Alternatively, we can have L1 as a near cache with a shorter TTL? But then we might have a situation where L2 has a fresh value but L1 has an old value (if L1's TTL is longer? Actually, if L1's TTL is longer, then it might have an old value even after L2 is updated? But we invalidate L1 on write, so we are safe.
Given the complexity, let's assume we set the same TTL for L1 and L2, and we invalidate on write.
But note: if we set TTL, then the entry might expire in L1 before it expires in L2? That's okay because then we will repopulate from L2. But if it expires in L2 first, then we will go to DB and then repopulate both.
We must be cautious about cache stampede: if a key expires in L2 and multiple instances miss at the same time, they might all go to DB. We can use locking or cache aside with locks.
However, that's beyond the scope.
-
Implementation Outline:
We'll create a class TenantAwareCacheHierarchy:
public class TenantAwareCacheHierarchy {
private Cache<String, Object> l1; // local cache, with tenant-prefixed keys
private Cache<String, Object> l2; // distributed cache, with tenant-prefixed keys
private DataSource dataSource; // to fetch from DB
private MessageBus invalidationBus; // to broadcast invalidations
private MetricsCollector metrics;
// We assume that the key is of type K, but we will convert to a string with tenant prefix.
// Alternatively, we can have a KeyWrapper that includes tenant and the original key.
public <T> T get(String tenantId, Object key, Class<T> type) {
String cacheKey = tenantId + ":" + key.toString(); // simple prefix, but note: key.toString() might not be unique? We can use a more robust serialization.
// Check L1
Object value = l1.get(cacheKey);
boolean l1Hit = false;
boolean l2Hit = false;
if (value != null) {
l1Hit = true;
metrics.recordGet(tenantId, true, false);
return type.cast(value);
}
// Check L2
value = l2.get(cacheKey);
if (value != null) {
l2Hit = true;
l1.put(cacheKey, value); // populate L1
metrics.recordGet(tenantId, false, true);
return type.cast(value);
}
// Miss in both, go to DB
value = fetchFromDB(tenantId, key, type); // we assume that the DB fetch is tenant-aware? Or we pass tenantId to the DB query.
if (value != null) {
l2.put(cacheKey, value);
l1.put(cacheKey, value);
}
metrics.recordGet(tenantId, false, false);
return type.cast(value);
}
public void put(String tenantId, Object key, Object value) {
String cacheKey = tenantId + ":" + key.toString();
// Update DB
updateDB(tenantId, key, value);
// Invalidate caches: we delete from L2 and broadcast to invalidate L1.
l2.delete(cacheKey);
invalidationBus.publish(new InvalidationMessage(tenantId, key));
}
// We need to handle incoming invalidation messages to clear L1.
public void startInvalidationListener() {
invalidationBus.subscribe(message -> {
if (message instanceof InvalidationMessage) {
InvalidationMessage inv = (InvalidationMessage) message;
String cacheKey = inv.getTenantId() + ":" + inv.getKey().toString();
l1.delete(cacheKey);
}
});
}
}
However, note: the above put method deletes from L2 and broadcasts to invalidate L1. But what about the instance that just did the put? It also has L1 cache that might have the old value. We are deleting from L2 and then broadcasting, but the current instance will also receive the broadcast? And then it will delete from L1. But note: we are going to update the DB and then delete from L2. Then we broadcast. But the current instance might have the old value in L1. We should also delete from the current instance's L1? Actually, the broadcast will be received by all instances including the current one. But there might be a race: the current instance might have already updated the DB and then we delete from L2 and broadcast. Then the current instance receives the broadcast and deletes from L1. That's safe.
-
Miss Analytics Implementation:
We'll have:
public class MetricsCollector {
private Map<String, TenantMetrics> metrics = new ConcurrentHashMap<>();
public void recordGet(String tenantId, boolean l1Hit, boolean l2Hit) {
TenantMetrics m = metrics.computeIfAbsent(tenantId, k -> new TenantMetrics());
m.recordGet(l1Hit, l2Hit);
}
// We might also want to record evictions? But that requires cache eviction listeners.
public TenantMetrics getMetrics(String tenantId) {
return metrics.get(tenantId);
}
}
public class TenantMetrics {
private long requests;
private long l1Hits;
private long l2Hits;
public synchronized void recordGet(boolean l1Hit, boolean l2Hit) {
requests++;
if (l1Hit) {
l1Hits++;
} else if (l2Hit) {
l2Hits++;
}
}
public double getL1HitRate() {
return requests == 0 ? 0 : (double) l1Hits / requests;
}
public double getL2HitRate() {
// Note: L2 hit rate is computed as l2Hits / (requests - l1Hits)
long l1Misses = requests - l1Hits;
return l1Misses == 0 ? 0 : (double) l2Hits / l1Misses;
}
public double getTotalHitRate() {
return requests == 0 ? 0 : (double) (l1Hits + l2Hits) / requests;
}
public long getTotalMisses() {
return requests - l1Hits - l2Hits;
}
}
-
Summary:
- We have a two-level cache: L1 (local) and L2 (distributed).
- Keys are prefixed with tenantId to ensure isolation.
- On read: check L1, then L2, then DB. Populate L1 and L2 on DB hit.
- On write: update DB, update L2, broadcast invalidation to delete L1 on all instances, and update L1 on current instance.
- There is a small window of inconsistency because other instances might have stale L1 until they process the invalidation.
- We track per-tenant metrics for cache hits and misses.
-
Improvements:
- Use a more robust key generation (like serialization) to avoid collisions.
- Consider using a distributed lock or versioning to avoid stale reads.
- Consider using a write-behind for L2 to reduce DB load? But then we have to handle failures.
- Consider cache warming for tenants with known hot keys.
-
Code Structure:
TenantAwareCacheHierarchy
- l1: Cache<String, Object>
- l2: Cache<String, Object>
- dataSource: DataSource
- invalidationBus: MessageBus
- metrics: MetricsCollector
Methods:
get(tenantId, key, type)
put(tenantId, key, value)
startInvalidationListener()
We assume that the caches (l1 and l2) are configured with appropriate TTL and size.
-
Note on Distributed Cache:
The L2 distributed cache must support high availability and partitioning (if needed). We can use Redis with clustering or Hazelcast.
-
Note on Message Bus:
We need a message bus that can broadcast messages to all instances. We can use Kafka, Redis Pub/Sub, or a simple multicast if on the same network.
-
Conclusion:
This design provides a tenancy-aware cache hierarchy with request scoping (via tenantId in every operation), invalidation via broadcast, and miss analytics.
However, the strong consistency is not guaranteed due to the window of invalidation delay. We can improve by using a versioning scheme or by making L1 a read-through cache that always checks L2 for freshness (but that defeats the purpose of L1).
Given the constraints, this is a reasonable design.
Let's write the code accordingly.
I'll design a comprehensive tenancy-aware cache hierarchy with request scoping, invalidation policies, and miss analytics. This is a sophisticated system that requires careful consideration of multi-tenancy isolation, performance, and observability.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER │
├─────────────────────────────────────────────────────────────┤
│ Request Context (Tenant ID, User ID, Session) │
├─────────────────────────────────────────────────────────────┤
│ TENANT-AWARE CACHE HIERARCHY │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ L1: │ │ L2: │ │ L3: │ │
│ │ Process- │ │ Instance- │ │ Distributed│ │
│ │ Local │ │ Local │ │ (Redis/ │ │
│ │ (Caffeine) │ │ (Off-heap) │ │ Hazelcast)│ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ INVALIDATION & EVICTION COORDINATOR │
├─────────────────────────────────────────────────────────────┤
│ MISS ANALYTICS & MONITORING │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Metrics: Hit/Miss Rates, Latency, Tenant Usage │ │
│ │ Analytics: Hot Keys, Eviction Patterns, Trends │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Core Components Implementation
1. Tenant Context Propagation
// Thread-local context with async support
public final class TenantContext {
private static final ThreadLocal<TenantInfo> CONTEXT =
new ThreadLocal<>();
// For reactive/async flows
private static final ContextStorage CONTEXT_STORAGE =
new ContextStorage();
public static void setTenant(TenantInfo tenant) {
CONTEXT.set(tenant);
CONTEXT_STORAGE.store(tenant);
}
public static TenantInfo getCurrentTenant() {
TenantInfo tenant = CONTEXT.get();
if (tenant == null) {
tenant = CONTEXT_STORAGE.retrieve();
CONTEXT.set(tenant);
}
return tenant;
}
public static void clear() {
CONTEXT.remove();
CONTEXT_STORAGE.clear();
}
}
// Tenant identifier wrapper
public record TenantInfo(
String tenantId,
String tier, // FREE, PRO, ENTERPRISE
String region,
int cacheQuotaMB, // Per-tenant quota
Set<String> allowedRegions
) {}
2. Hierarchical Cache with Tenant Isolation
public interface TenantAwareCache<K, V> {
V get(TenantInfo tenant, K key);
void put(TenantInfo tenant, K key, V value, Duration ttl);
void invalidate(TenantInfo tenant, K key);
void invalidateTenant(String tenantId);
CacheStats getStats(String tenantId);
}
public class HierarchicalTenantCache<K, V> implements TenantAwareCache<K, V> {
private final Cache<String, V> l1; // Process-local (Caffeine)
private final Cache<String, V> l2; // Instance-local (Off-heap)
private final DistributedCache l3; // Redis/Hazelcast cluster
private final InvalidationCoordinator invalidationCoordinator;
private final QuotaManager quotaManager;
private final MissAnalytics missAnalytics;
// Composite key: tenantId:key (with proper serialization)
private String compositeKey(TenantInfo tenant, K key) {
return tenant.tenantId() + ":" + key.toString();
}
@Override
public V get(TenantInfo tenant, K key) {
long startTime = System.nanoTime();
String cacheKey = compositeKey(tenant, key);
// Check L1 (fastest)
V value = l1.getIfPresent(cacheKey);
if (value != null) {
missAnalytics.recordHit(tenant, key, CacheLevel.L1,
System.nanoTime() - startTime);
return value;
}
// Check L2
value = l2.getIfPresent(cacheKey);
if (value != null) {
l1.put(cacheKey, value, getL1TtlForTenant(tenant));
missAnalytics.recordHit(tenant, key, CacheLevel.L2,
System.nanoTime() - startTime);
return value;
}
// Check L3 (distributed)
value = l3.get(cacheKey);
if (value != null) {
// Populate L1 and L2 with tiered TTLs
Duration l1Ttl = getL1TtlForTenant(tenant);
Duration l2Ttl = getL2TtlForTenant(tenant);
l1.put(cacheKey, value, l1Ttl);
l2.put(cacheKey, value, l2Ttl);
missAnalytics.recordHit(tenant, key, CacheLevel.L3,
System.nanoTime() - startTime);
return value;
}
// Complete miss - fetch from source
missAnalytics.recordMiss(tenant, key,
CacheMissReason.COMPLETE_MISS,
System.nanoTime() - startTime);
return null;
}
@Override
public void put(TenantInfo tenant, K key, V value, Duration ttl) {
String cacheKey = compositeKey(tenant, key);
// Check quota before writing
if (!quotaManager.canWrite(tenant, value)) {
throw new QuotaExceededException("Cache quota exceeded for tenant");
}
// Write-through to all levels with tiered TTLs
Duration l1Ttl = getL1TtlForTenant(tenant);
Duration l2Ttl = getL2TtlForTenant(tenant);
Duration l3Ttl = ttl != null ? ttl : getDefaultTtl(tenant);
l1.put(cacheKey, value, l1Ttl);
l2.put(cacheKey, value, l2Ttl);
l3.put(cacheKey, value, l3Ttl);
// Broadcast invalidation for other instances' L1 caches
invalidationCoordinator.broadcastInvalidation(
tenant.tenantId(), key, InvalidationType.WRITE);
}
}
3. Invalidation Policies & Coordinator
public class InvalidationCoordinator {
private final DistributedPubSub pubSub;
private final Map<String, Set<InvalidationListener>> listeners;
// Invalidation types
public enum InvalidationType {
WRITE, // Data modified
DELETE, // Data removed
TENANT_SUSPEND, // Tenant suspended
TTL_EXPIRED, // Natural expiration
MANUAL // Admin invalidation
}
public void broadcastInvalidation(String tenantId, Object key,
InvalidationType type) {
InvalidationMessage msg = new InvalidationMessage(
UUID.randomUUID().toString(),
tenantId,
key,
type,
System.currentTimeMillis()
);
pubSub.publish("cache-invalidation:" + tenantId, msg);
}
public void subscribe(String tenantId, InvalidationListener listener) {
pubSub.subscribe("cache-invalidation:" + tenantId, msg -> {
if (msg.tenantId().equals(tenantId) ||
msg.tenantId().equals("*")) { // Global invalidation
listener.onInvalidation(msg);
}
});
}
}
// Tenant-aware invalidation listener
public class TenantInvalidationListener implements InvalidationListener {
private final TenantAwareCache cache;
@Override
public void onInvalidation(InvalidationMessage msg) {
TenantInfo tenant = tenantCache.getTenant(msg.tenantId());
if (tenant == null) return; // Tenant might be suspended
String cacheKey = tenant.tenantId() + ":" + msg.key();
switch (msg.type()) {
case WRITE:
case DELETE:
cache.invalidate(tenant, msg.key());
break;
case TENANT_SUSPEND:
cache.invalidateTenant(msg.tenantId());
break;
case TTL_EXPIRED:
// Already expired, just cleanup if needed
break;
}
}
}
4. Quota Management (Per-Tenant)
public class QuotaManager {
private final Map<String, TenantQuota> quotas;
private final Cache<String, Long> tenantUsage; // bytes used
public boolean canWrite(TenantInfo tenant, Object value) {
long size = estimateSize(value);
long current = tenantUsage.getOrDefault(tenant.tenantId(), 0L);
return current + size <= tenant.cacheQuotaMB() * 1024 * 1024;
}
public void recordWrite(String tenantId, long bytes) {
tenantUsage.merge(tenantId, bytes, Long::sum);
}
public void recordEviction(String tenantId, long bytes) {
tenantUsage.merge(tenantId, -bytes, Long::sum);
}
// Soft limits with eviction priority
public CacheEvictionPolicy getEvictionPolicy(TenantInfo tenant) {
return switch (tenant.tier()) {
case "FREE" -> CacheEvictionPolicy.LRU;
case "PRO" -> CacheEvictionPolicy.LFU;
case "ENTERPRISE" -> CacheEvictionPolicy.NONE; // No eviction
};
}
}
5. Miss Analytics System
public class MissAnalytics {
private final Map<String, TenantAnalytics> perTenantStats;
private final Map<String, HotKeyTracker> hotKeyTrackers;
private final RateLimiter samplingRateLimiter;
// Sampling to reduce overhead
public void recordMiss(TenantInfo tenant, Object key,
CacheMissReason reason, long latencyNanos) {
if (!samplingRateLimiter.tryAcquire()) return;
String tenantId = tenant.tenantId();
TenantAnalytics stats = perTenantStats
.computeIfAbsent(tenantId, k -> new TenantAnalytics());
stats.recordMiss(reason, latencyNanos);
hotKeyTrackers
.computeIfAbsent(tenantId, k -> new HotKeyTracker())
.recordMiss(key);
}
public void recordHit(TenantInfo tenant, Object key,
CacheLevel level, long latencyNanos) {
String tenantId = tenant.tenantId();
TenantAnalytics stats = perTenantStats
.computeIfAbsent(tenantId, k -> new TenantAnalytics());
stats.recordHit(level, latencyNanos);
}
public AnalyticsReport generateReport(String tenantId,
Duration window) {
TenantAnalytics stats = perTenantStats.get(tenantId);
HotKeyTracker hotKeys = hotKeyTrackers.get(tenantId);
return new AnalyticsReport(
tenantId,
window,
stats.calculateHitRates(),
stats.calculateMissBreakdown(),
hotKeys.getTopMissedKeys(20),
stats.getAvgLatencyByLevel(),
detectAnomalies(tenantId)
);
}
private List<Anomaly> detectAnomalies(String tenantId) {
// Implement anomaly detection:
// - Sudden increase in miss rate
// - Unusual key patterns
// - Cross-tenant access attempts (security)
// - Cache stampede patterns
return List.of();
}
}
// Per-tenant analytics
public class TenantAnalytics {
private final Map<CacheLevel, Long> hits = new EnumMap<>(CacheLevel.class);
private final Map<CacheMissReason, Long> misses = new EnumMap<>(CacheMissReason.class);
private final List<LatencySample> latencies = new CopyOnWriteArrayList<>();
private long totalRequests;
public void recordHit(CacheLevel level, long latencyNanos) {
hits.merge(level, 1L, Long::sum);
latencies.add(new LatencySample(level, latencyNanos, true));
totalRequests++;
}
public void recordMiss(CacheMissReason reason, long latencyNanos) {
misses.merge(reason, 1L, Long::sum);
latencies.add(new LatencySample(null, latencyNanos, false));
totalRequests++;
}
public Map<CacheLevel, Double> calculateHitRates() {
Map<CacheLevel, Double> rates = new EnumMap<>(CacheLevel.class);
for (CacheLevel level : CacheLevel.values()) {
long levelHits = hits.getOrDefault(level, 0L);
long levelMisses = misses.values().stream()
.filter(m -> m == CacheMissReason.forLevel(level))
.mapToLong(Long::longValue)
.sum();
long totalLevelAccess = levelHits + levelMisses;
rates.put(level, totalLevelAccess > 0 ?
(double) levelHits / totalLevelAccess : 0.0);
}
return rates;
}
}
// Hot key detection using Count-Min Sketch
public class HotKeyTracker {
private final CountMinSketch sketch;
private final Map<String, Long> exactCounts; // for top keys
public void recordMiss(Object key) {
String keyStr = key.toString();
sketch.add(keyStr);
exactCounts.merge(keyStr, 1L, Long::sum);
}
public List<KeyFrequency> getTopMissedKeys(int limit) {
return exactCounts.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(limit)
.map(e -> new KeyFrequency(e.getKey(), e.getValue()))
.toList();
}
}
6. Request Scoping Middleware
// Spring MVC/WebFlux interceptor example
@Component
public class TenantCacheInterceptor implements HandlerInterceptor {
private final TenantAwareCache cache;
private final MissAnalytics analytics;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
String tenantId = extractTenantId(request);
TenantInfo tenant = tenantRegistry.getTenant(tenantId);
TenantContext.setTenant(tenant);
// Optional: Pre-warm cache for known endpoints
if (shouldPreWarm(request)) {
preWarmCache(tenant, request);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex) {
TenantContext.clear();
}
private void preWarmCache(TenantInfo tenant, HttpServletRequest request) {
// Pre-load commonly accessed data based on endpoint pattern
String path = request.getRequestURI();
if (path.startsWith("/api/v1/products")) {
cache.get(tenant, "product:categories", List.class);
}
}
}
7. Cache Warming Strategy
public class CacheWarmer {
private final TenantAwareCache cache;
private final ScheduledExecutorService scheduler;
// Schedule per-tenant warming based on access patterns
public void scheduleWarming(TenantInfo tenant,
List<String> warmKeys) {
scheduler.scheduleAtFixedRate(() -> {
warmKeys.parallelStream().forEach(key -> {
try {
// Fetch from source without recording analytics
cache.get(tenant, key, Object.class);
} catch (Exception e) {
log.warn("Warming failed for tenant {} key {}",
tenant.tenantId(), key, e);
}
});
}, 0, 10, TimeUnit.MINUTES);
}
// ML-based warming prediction
public List<String> predictWarmKeys(TenantInfo tenant,
Instant nextWindow) {
// Use historical access patterns to predict
AnalyticsReport report = analytics.generateReport(
tenant.tenantId(), Duration.ofHours(1));
return report.hotKeys().stream()
.filter(kf -> kf.frequency() > THRESHOLD)
.map(KeyFrequency::key)
.toList();
}
}
8. Configuration per Tenant Tier
public class TenantCacheConfig {
public CacheConfiguration getConfig(TenantInfo tenant) {
return switch (tenant.tier()) {
case "FREE" -> CacheConfiguration.builder()
.l1MaxSize(1000)
.l2MaxSize(10_000)
.l1Ttl(Duration.ofMinutes(5))
.l2Ttl(Duration.ofHours(1))
.l3Ttl(Duration.ofDays(1))
.enableAnalytics(true)
.build();
case "PRO" -> CacheConfiguration.builder()
.l1MaxSize(10_000)
.l2MaxSize(100_000)
.l1Ttl(Duration.ofMinutes(15))
.l2Ttl(Duration.ofHours(6))
.l3Ttl(Duration.ofDays(3))
.enableAnalytics(true)
.enablePredictiveWarming(true)
.build();
case "ENTERPRISE" -> CacheConfiguration.builder()
.l1MaxSize(50_000)
.l2MaxSize(500_000)
.l1Ttl(Duration.ofMinutes(30))
.l2Ttl(Duration.ofHours(12))
.l3Ttl(Duration.ofDays(7))
.enableAnalytics(true)
.enablePredictiveWarming(true)
.enablePriorityEviction(true)
.build();
};
}
}
9. Security Considerations
public class SecurityValidator {
// Prevent cache poisoning and cross-tenant access
public void validateAccess(TenantInfo tenant, Object key) {
// 1. Check tenant matches key namespace
if (!key.toString().startsWith(tenant.tenantId() + ":")) {
throw new SecurityException("Key namespace violation");
}
// 2. Validate tenant is active
if (!tenantRegistry.isActive(tenant.tenantId())) {
throw new TenantSuspendedException();
}
// 3. Region locking for data residency
if (!tenant.allowedRegions().contains(getCurrentRegion())) {
throw new RegionRestrictionException();
}
}
// Audit trail for sensitive operations
public void auditCacheAccess(TenantInfo tenant, String operation,
Object key, boolean hit) {
auditLog.log("cache." + operation, Map.of(
"tenant", tenant.tenantId(),
"key_hash", hashKey(key),
"hit", hit,
"timestamp", Instant.now(),
"thread", Thread.currentThread().getName()
));
}
}
10. Monitoring & Alerting
# Prometheus metrics configuration
metrics:
enabled: true
labels:
- tenant_id
- cache_level
- region
counters:
- name: cache_requests_total
help: "Total cache requests"
labels: [tenant_id, cache_level, hit_miss]
- name: cache_invalidations_total
help: "Total invalidations"
labels: [tenant_id, invalidation_type]
gauges:
- name: cache_hit_rate
help: "Hit rate per tenant"
labels: [tenant_id, cache_level]
- name: cache_memory_usage_bytes
help: "Memory usage per tenant"
labels: [tenant_id, cache_level]
histograms:
- name: cache_latency_seconds
help: "Cache operation latency"
labels: [tenant_id, cache_level]
buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1]
Key Features Summary
- Tenant Isolation: Every cache key is prefixed with tenant ID, with strict validation
- Three-Tier Hierarchy: L1 (process), L2 (instance), L3 (distributed)
- Intelligent TTLs: Tier-based and tenant-tier-based expiration policies
- Quota Management: Per-tenant memory limits with soft/hard thresholds
- Invalidation Coordination: Pub/sub-based invalidation across cluster
- Miss Analytics:
- Per-tenant hit/miss ratios
- Hot key detection (Count-Min Sketch)
- Latency tracking by cache level
- Anomaly detection
- Request Scoping: Thread-local + async context propagation
- Tier-Aware Policies: Different strategies for FREE/PRO/ENTERPRISE
- Security: Key namespace validation, audit logging, region locking
- Observability: Full metrics, distributed tracing support
Operational Considerations
- Cache Stampede Protection: Use probabilistic early expiration or request coalescing
- Cold Start Warming: Predictive warming based on ML models
- Backpressure: Throttle cache writes when tenant approaches quota
- Eviction Policies: Tenant-aware (LRU for FREE, LFU for PRO, priority for ENTERPRISE)
- Data Residency: Region-aware caching for compliance (GDPR, HIPAA)
- Disaster Recovery: Multi-region replication with conflict resolution
- Cost Optimization: Automatic tier migration based on usage patterns
This design provides enterprise-grade multi-tenant caching with comprehensive observability while maintaining strict isolation and performance guarantees. The hierarchical approach optimizes for latency (L1), capacity (L2), and durability (L3), with analytics driving continuous optimization.