We are going to design a tenancy-aware cache. The cache should have the following features:
It should be aware of tenants (multi-tenancy) so that keys from one tenant do not interfere with another.
It should support invalidation (by key, by pattern, or by tenant).
It should be fair in terms of resource usage, possibly limiting per-tenant usage or having a fair eviction policy.
We'll consider an in-memory cache for simplicity, but the design should be adaptable to distributed caches.
Let's break down:
Tenancy:
We need to store data per tenant. Each tenant's data should be isolated.
We can achieve this by having a separate cache for each tenant, but that might not be efficient for memory and eviction.
Alternatively, we can have a single cache but with keys prefixed by tenant ID. Then eviction policies must consider tenant boundaries? Not necessarily.
Invalidation:
Invalidate by key: clear a specific key for a tenant.
Invalidate by pattern: clear all keys matching a pattern for a tenant.
Invalidate by tenant: clear all keys for a tenant.
Fairness:
We may want to limit the number of entries or memory usage per tenant.
We could use a weighted eviction policy that considers tenant quotas.
Design:
We'll use a combination of:
A main cache (like a LRU cache) that stores key-value pairs, but keys are prefixed with tenant ID.
To support per-tenant limits, we can track usage per tenant and evict when a tenant exceeds its limit.
However, note that if we use a single LRU cache for all tenants, then one tenant could evict another's data by being more active.
To achieve fairness, we need to have some per-tenant isolation in eviction.
Approaches:
Option 1: Separate caches per tenant (with shared memory pool?).
Each tenant has its own LRU cache with its own limit.
But then we have to manage multiple caches and the total memory might exceed if we set per-tenant limits too high.
Option 2: One cache, but with a hybrid eviction policy.
We can use a policy like "tenant-aware LRU" where we track LRU per tenant and also globally.
When we need to evict, we first check which tenants are over their limit and then evict from the tenants that are over, using their own LRU.
Let's go with Option 2 for more efficient memory usage and fairness.
Steps:
We store each entry as: (tenant_id, key) -> value.
But to make it efficient, we can have a composite key: tenant_id + ":" + key, but then we lose the ability to quickly get all keys for a tenant.
We need to support:
Get(tenant_id, key)
Set(tenant_id, key, value)
Invalidate(tenant_id, key)
InvalidatePattern(tenant_id, pattern) // pattern matching on the key part (without tenant)
InvalidateTenant(tenant_id)
We also need to track per-tenant usage (number of entries or memory size).
We'll maintain:
A global LRU list (or multiple LRUs?) for eviction.
But we want to evict from tenants that are over their quota first.
Alternatively, we can use two levels of LRU:
Global LRU for all entries, but when evicting we consider tenant quotas.
Let's define:
class TenantCache:
- max_total_size: total max entries (or memory) for the entire cache.
- per_tenant_quota: either a fixed number per tenant or a percentage.
We'll maintain:
- A hash map: (tenant_id, key) -> node (which contains value and pointers for LRU)
- A global LRU doubly linked list (most recent at head, least recent at tail).
- A map from tenant_id to a structure that holds:
- current_size: number of entries for this tenant.
- lru_list: a doubly linked list of the tenant's entries in order of least recent? But we have a global LRU.
Actually, if we have a global LRU, then we don't need per-tenant LRU for eviction order? But we need to know which tenant's entry is the least recently used globally?
And then if we have a per-tenant quota, we might want to evict from a tenant that is over quota even if that tenant's entries are recently used?
Let's think about fairness:
We want to ensure that no tenant uses more than its quota. So if a tenant is over, we should evict its entries regardless of global LRU order? But then we might evict a recently used entry from an over-quota tenant, which might be bad.
Alternatively, we can adjust the eviction policy to be:
When we need to evict:
If there are tenants that are over their quota, we evict from the tenant with the highest overage (or the one that is most over) and from that tenant we evict the least recently used entry (by global LRU order? or by tenant LRU?).
If no tenant is over quota, then we evict the global LRU entry.
But note: the global LRU order is across tenants. So the global LRU might be from a tenant that is under quota, and we might be forced to evict from an over-quota tenant that has more recent entries.
This might be acceptable because we are enforcing quotas.
However, we also want to be fair in the sense that if a tenant is under quota, we don't want to evict its entries when there are over-quota tenants.
So:
Eviction policy:
Step 1: Check if any tenant is over quota. If yes, pick the tenant with the largest overage (or the one that is most over) and then from that tenant's entries, pick the least recently used (by global LRU order?).
But wait, we have a global LRU that orders by access time regardless of tenant. So the "least recently used" for a tenant might not be the global LRU? We can get the global LRU entry for that tenant by scanning the global LRU? That would be inefficient.
Alternatively, we can maintain per-tenant LRU lists that are subsets of the global LRU. But then we are duplicating the linked list structure.
We can do:
code
Architecture Overview
python
Key Features & Design Decisions
1. Tenant Isolation
Namespaced keys: All keys are internally scoped as tenant_id:key
Separate storage per tenant: dict[str, dict[str, CacheEntry]]
No cross-tenant key collision: Even if two tenants use same key, they're isolated
2. Fairness Mechanisms
Per-tenant quotas: Configurable limits per tenant (with default)
Fair global eviction: When cache is full, evict from over-quota tenants first
Weighted eviction: Distribute evictions across over-quota tenants
No single tenant starvation: All tenants get their fair share of cache space
3. Invalidation Strategies
python
# Invalidate single key
cache.invalidate("tenant_123", "user:123:profile")
# Invalidate by pattern (regex)
cache.invalidate_pattern("tenant_123", r"user:\d+:profile")
# Invalidate entire tenant
cache.invalidate_tenant("tenant_123")
def _evict_global(self, count):
over_quota_tenants = [t for t in tenants if is_over_quota(t)]
if over_quota_tenants:
# Evict proportionally from over-quota tenants
per_tenant = max(1, count // len(over_quota_tenants))
for tenant in over_quota_tenants:
self._evict_from_tenant(tenant, per_tenant)
else:
# No over-quota tenants, evict fairly from all
# (could implement round-robin or proportional to usage)
6. Metrics & Monitoring
Per-tenant: hit rate, miss rate, current size vs quota
Global: total entries, overall hit rate
Optional disable for production overhead
7. Thread Safety
RLock for all operations
Condition variable for TTL cleaner
No deadlocks (consistent lock ordering)
Usage Example
python
# Initialize cache
cache = TenancyAwareCache(
max_total_size=10000,
default_tenant_quota=1000,
tenant_quotas={"premium": 5000, "free": 500}
)
# Tenant A (premium) stores data
cache.set("premium", "user:1:profile", {"name": "Alice"}, ttl=3600)
cache.set("premium", "user:2:profile", {"name": "Bob"})
# Tenant B (free) stores data
cache.set("free", "user:1:profile", {"name": "Charlie"})
# Get with tenant context
profile = cache.get("premium", "user:1:profile")
# Invalidate all user profiles for free tenant
cache.invalidate_pattern("free", r"user:\d+:profile")
# Check metrics
metrics = cache.get_metrics("premium")
print(f"Premium tenant hit rate: {metrics['hit_rate']:.2%}")
# Global metrics
global_stats = cache.get_metrics()
Advanced Considerations
Dynamic Quota Adjustment
python
def update_tenant_quota(self, tenant_id: str, new_quota: int):
"""Adjust tenant quota dynamically"""
with self._lock:
old_quota = self._get_tenant_quota(tenant_id)
self.tenant_quotas[tenant_id] = new_quota
# If reducing quota, trigger immediate eviction if over new limit
current_size = len(self._data[tenant_id])
if current_size > new_quota:
self._evict_from_tenant(tenant_id, current_size - new_quota)
Priority Classes
python
# Extend to support priority-based fairness
class PriorityTenantCache(TenancyAwareCache):
def __init__(self, priorities: dict[str, int], **kwargs):
super().__init__(**kwargs)
self.priorities = priorities # higher number = higher priority
def _evict_global(self, count):
# Weight eviction by inverse priority
# Low-priority tenants lose entries first
pass
Distributed Extension
For distributed systems:
Use consistent hashing for tenant→node mapping
Implement distributed quotas with token bucket per tenant
Use Redis/Memcached with tenant-prefixed keys
Coordination via Zookeeper/etcd for quota enforcement
Trade-offs
Aspect
Design Choice
Rationale
Memory
Separate dicts per tenant
O(1) tenant lookup, clean isolation
Eviction
Per-tenant first, then global
Enforces quotas while maximizing cache hit rate
TTL
Background cleaner
Minimizes blocking on get/set operations
Complexity
Moderate (2-level tracking)
Balance of fairness and performance
Scalability
Sharding by tenant for distributed
Easy to partition by tenant_id
When to Use This Design
✅ Ideal for:
SaaS applications with clear tenant boundaries
Multi-tenant databases with shared cache layer
Microservices serving multiple customers
Any system requiring strict tenant isolation
❌ Not ideal for:
Single-tenant applications (overhead not justified)
This design provides strong tenant isolation, fair resource allocation, and flexible invalidation while maintaining reasonable performance characteristics. The two-level eviction strategy (tenant-first, then global) ensures no single tenant can starve others while maximizing overall cache utilization.
We have a global doubly linked list of all entries, ordered by most recent at head, least recent at tail.
For each tenant, we also maintain a doubly linked list of its own entries, but in the same order as the global list? That would require updating two lists on every access, which is expensive.
Another idea: use a skip list or a tree that can be queried by both global recency and by tenant? That might be overkill.
Let's simplify:
We'll have:
code
global_lru: a doubly linked list of all entries, from most recent to least recent.
tenant_entries[tenant_id]: a set of (key) for that tenant? But we need to find the least recent entry for a tenant from the global_lru.
How to find the least recent entry for a tenant quickly?
We can store for each tenant a pointer to the least recent entry in the global_lru? But that would require updating that pointer whenever an entry for that tenant is accessed or evicted.
Alternatively, we can store for each entry a pointer to the next and previous in the global list, and also a pointer to the next and previous in the tenant's list? That's two doubly linked lists per entry.
We can try:
code
Entry:
tenant_id
key
value
global_prev, global_next
tenant_prev, tenant_next
Then:
global_lru_head, global_lru_tail
tenant_lru_head[tenant_id], tenant_lru_tail[tenant_id]
When we access an entry (get or set), we move it to the head of the global list and the head of the tenant's list.
Eviction:
To evict from a specific tenant, we take the tenant_lru_tail[tenant_id] (the least recently used for that tenant) and remove it from both lists.
But then we are maintaining two lists. This is acceptable if we are okay with the overhead.
However, note that the global LRU is used when we are not over quota. But if we are over quota, we evict from the over-quota tenant's tail.
But wait, what if we are over quota for multiple tenants? We need to pick one tenant to evict from. We can pick the tenant with the highest overage (or the one that has been over quota the longest?).
Let's define:
code
For each tenant, we have:
quota: the maximum number of entries (or memory) allowed.
current_size: current number of entries.
We consider a tenant over quota if current_size > quota.
Eviction algorithm:
code
When we need to evict (because we are adding a new entry and the total size would exceed max_total_size):
Step 1: Find the set of tenants that are over quota.
Step 2: If there is at least one over-quota tenant, choose the one with the largest (current_size - quota) and then evict the least recently used entry from that tenant (using the tenant's LRU tail).
Step 3: If no tenant is over quota, then we evict the global LRU tail (which is the least recently used overall).
But note: the global LRU tail might be from a tenant that is under quota, and we are evicting it even though there are over-quota tenants? That's why we check over-quota tenants first.
However, what if the over-quota tenant's least recently used entry is actually more recent than the global LRU tail? Then we are evicting a more recent entry from an over-quota tenant and keeping an older entry from an under-quota tenant? That's acceptable because we are enforcing quotas.
But wait, the global LRU tail is the least recently used overall. So if we have an over-quota tenant, we are not using the global LRU order for eviction, but the tenant's own LRU.
This might be acceptable.
However, what if the over-quota tenant's LRU tail is actually more recent than some entries in the global LRU? Then we are evicting a more recent entry from the over-quota tenant and keeping an older entry from an under-quota tenant? That's not ideal for hit rate.
But the goal is to enforce quotas, so we might accept that trade-off.
Alternatively, we can adjust the eviction to:
code
If there are over-quota tenants, then we consider only the over-quota tenants and then evict the least recently used among all over-quota tenants (by global LRU order). That is, we look at the global LRU and find the first entry that belongs to an over-quota tenant and evict that.
This way, we are still using global recency but only among over-quota tenants.
How to do that efficiently? We can traverse the global LRU from tail until we find an entry that is from an over-quota tenant. But that might be O(n) in worst case.
Given the complexity, let's stick to the per-tenant LRU for eviction from over-quota tenants.
Steps for set(tenant_id, key, value):
code
1. If the key exists for the tenant, update the value and move the entry to the head of both global and tenant LRUs.
2. If it doesn't exist:
a. Check if we are at max_total_size (or if adding this entry would exceed max_total_size). If yes, evict.
b. Create a new entry and add it to the head of both global and tenant LRUs.
c. Update tenant's current_size and global current_size.
Eviction:
code
We have two ways:
Option A (per-tenant LRU for over-quota tenants):
if there are over-quota tenants:
pick the tenant with the largest overage (or the one that became over first?).
evict the tail of that tenant's LRU.
else:
evict the tail of the global LRU.
Option B (global LRU among over-quota tenants):
if there are over-quota tenants:
traverse the global LRU from tail until we find an entry that belongs to an over-quota tenant, then evict that.
else:
evict the global LRU tail.
Option B is more fair in terms of recency (we evict the least recently used among the over-quota tenants), but might be slower.
Let's go with Option A for simplicity and because it's O(1) to evict from a specific tenant's tail.
But note: we have to maintain the tenant's LRU list. And when we evict from a tenant, we remove from both the global and the tenant list.
Implementation details:
code
We'll have:
class Entry:
tenant_id: str
key: str
value: any
global_prev: Entry
global_next: Entry
tenant_prev: Entry
tenant_next: Entry
global_lru_head, global_lru_tail: Entry
tenant_lru_heads: dict[tenant_id, Entry] # head of the tenant's LRU (most recent)
tenant_lru_tails: dict[tenant_id, Entry] # tail of the tenant's LRU (least recent)
tenant_sizes: dict[tenant_id, int] # current number of entries per tenant
total_size: int
quotas: dict[tenant_id, int] # or we can have a default quota and override per tenant.
But wait, we also need to be able to invalidate by pattern and by tenant.
Invalidation by key (tenant_id, key) is straightforward: remove the entry from both lists and update sizes.
Invalidation by tenant: remove all entries for that tenant. We can traverse the tenant's LRU list and remove each entry from the global list. Then clear the tenant's list and set size to 0.
Invalidation by pattern: we need to find all keys for the tenant that match the pattern. We can store a separate index: for each tenant, a mapping from key to entry? But we already have the tenant's LRU list. We can traverse the tenant's LRU list and check the key against the pattern.
However, traversing a linked list for pattern matching might be O(n) for the tenant. But if the tenant has many entries, that's acceptable because invalidation by pattern is expected to be less frequent.
Alternatively, we can maintain for each tenant a dictionary: key -> entry. Then we can quickly find by key for invalidation by key, and for pattern we can still iterate over the dictionary keys? But then we are storing two references.
Let's change:
Instead of having only the linked lists for each tenant, we also have a dictionary for each tenant: tenant_key_map[tenant_id] = {key: entry}
Then:
get(tenant_id, key):
if key in tenant_key_map[tenant_id]:
entry = tenant_key_map[tenant_id][key]
move_to_head(entry) # in both global and tenant LRU
return entry.value
else:
return None
set(tenant_id, key, value):
if key in tenant_key_map[tenant_id]:
entry = tenant_key_map[tenant_id][key]
entry.value = value
move_to_head(entry)
else:
if total_size >= max_total_size:
evict()
entry = Entry(tenant_id, key, value)
add_to_head(entry) # in both global and tenant LRU
tenant_key_map[tenant_id][key] = entry
tenant_sizes[tenant_id] += 1
total_size += 1
invalidate(tenant_id, key):
if key in tenant_key_map[tenant_id]:
entry = tenant_key_map[tenant_id][key]
remove_entry(entry)
del tenant_key_map[tenant_id][key]
tenant_sizes[tenant_id] -= 1
total_size -= 1
invalidate_tenant(tenant_id):
for entry in list(tenant_key_map[tenant_id].values()): # we make a list because we are going to modify the dict
remove_entry(entry)
tenant_key_map[tenant_id].clear()
total_size -= tenant_sizes[tenant_id]
tenant_sizes[tenant_id] = 0
invalidate_pattern(tenant_id, pattern):
# pattern could be a regex or a simple string pattern? Let's assume simple string pattern (like key.startswith(pattern) or contains?).
# We'll assume it's a prefix for simplicity, but we can extend.
keys_to_remove = []
for key in tenant_key_map[tenant_id]:
if key.startswith(pattern): # or pattern matching function
keys_to_remove.append(key)
for key in keys_to_remove:
invalidate(tenant_id, key)
Now, the eviction function:
def evict():
# find over-quota tenants
over_quota_tenants = [t for t in tenant_sizes if tenant_sizes[t] > quotas[t]]
if over_quota_tenants:
# pick the tenant with the largest overage
# overage = tenant_sizes[t] - quotas[t]
tenant_to_evict = max(over_quota_tenants, key=lambda t: tenant_sizes[t] - quotas[t])
# get the least recently used entry for this tenant: tenant_lru_tails[tenant_to_evict]
entry = tenant_lru_tails[tenant_to_evict]
else:
# evict the global LRU tail
entry = global_lru_tail
# Now remove the entry
remove_entry(entry)
# Update tenant_key_map, tenant_sizes, total_size
del tenant_key_map[entry.tenant_id][entry.key]
tenant_sizes[entry.tenant_id] -= 1
total_size -= 1
How to remove_entry(entry):
# Remove from global LRU
if entry.global_prev:
entry.global_prev.global_next = entry.global_next
else:
global_lru_head = entry.global_next
if entry.global_next:
entry.global_next.global_prev = entry.global_prev
else:
global_lru_tail = entry.global_prev
# Remove from tenant LRU
tenant_id = entry.tenant_id
if entry.tenant_prev:
entry.tenant_prev.tenant_next = entry.tenant_next
else:
tenant_lru_heads[tenant_id] = entry.tenant_next
if entry.tenant_next:
entry.tenant_next.tenant_prev = entry.tenant_prev
else:
tenant_lru_tails[tenant_id] = entry.tenant_prev
How to add_to_head(entry):
# Add to global LRU head
entry.global_prev = None
entry.global_next = global_lru_head
if global_lru_head:
global_lru_head.global_prev = entry
global_lru_head = entry
if not global_lru_tail:
global_lru_tail = entry
# Add to tenant LRU head
tenant_id = entry.tenant_id
entry.tenant_prev = None
entry.tenant_next = tenant_lru_heads.get(tenant_id)
if tenant_lru_heads.get(tenant_id):
tenant_lru_heads[tenant_id].tenant_prev = entry
tenant_lru_heads[tenant_id] = entry
if not tenant_lru_tails.get(tenant_id):
tenant_lru_tails[tenant_id] = entry
But note: when we remove an entry, we have to update the tenant_lru_tails and tenant_lru_heads accordingly.
This design requires that we maintain two doubly linked lists per entry and two dictionaries (tenant_key_map and the LRU head/tail dicts).
We also need to handle the case when a tenant's LRU list becomes empty: then we should remove the tenant from tenant_lru_heads and tenant_lru_tails.
In remove_entry, if we are removing the head of the tenant's list, then we update tenant_lru_heads[tenant_id] to the next. Similarly for tail.
We are also updating tenant_sizes and total_size.
This is a lot of bookkeeping.
Alternatively, we can use an existing LRU implementation and then have a separate structure for per-tenant quotas? But then we lose the ability to evict by tenant's LRU.
Given the complexity, we might consider a simpler design:
code
We have one global LRU. But we also track per-tenant usage. When we need to evict, we check if there are over-quota tenants. If yes, then we evict from the global LRU until we find an entry that belongs to an over-quota tenant? That would require scanning the global LRU, which is O(n).
Given the requirement for fairness and tenancy, and the fact that we want O(1) operations, the two-LRU approach is acceptable but complex.
Let's see if we can avoid the two-LRU by using a different data structure.
We can use a combination of:
code
- A global LRU (doubly linked list) for all entries.
- For each tenant, we maintain a set of entries (or just the keys) and also the current size.
Then, to evict from a specific tenant, we need to find the least recently used entry for that tenant. We can do:
code
We can store for each entry a pointer to the global LRU node, but we don't have a per-tenant LRU.
How about we store for each tenant a min-heap (priority queue) of (global LRU order, key)? But then we have to update the global LRU order for every access, which would require updating the heap. That's O(log n) per access.
Given the trade-offs, I think the two-LRU approach is the most straightforward for O(1) operations, but with more memory overhead.
However, note that we are already storing the entry object, and we are adding two pointers (tenant_prev, tenant_next) and also the tenant_key_map is storing an extra reference? Actually, the tenant_key_map stores the entry, and the entry is already in the linked lists. So we are storing the entry twice? No, the entry is one object, and we have references to it in the linked lists and in the dictionary.
So the memory overhead is:
code
For each entry:
- Two sets of pointers (global_prev, global_next, tenant_prev, tenant_next) -> 4 pointers.
- The dictionary (tenant_key_map) stores a reference to the entry (so that's one more reference? Actually, the dictionary value is the entry, so that's the same reference.
Additionally, we have:
global_lru_head, global_lru_tail: one entry each.
tenant_lru_heads and tenant_lru_tails: dictionaries that map tenant_id to an entry (so one reference per tenant for head and tail).
So the overhead is about 4 pointers per entry plus the dictionary overhead for tenant_key_map.
We can try to reduce by not having two linked lists? But then we lose O(1) eviction by tenant.
Given the requirement for fairness and the need to evict by tenant quickly, we'll go with the two-LRU.
But wait, what about the invalidation by pattern? We are iterating over the tenant_key_map[tenant_id] dictionary. That's O(n) for the tenant, which is acceptable.
Now, let's code the structure:
code
class TenantCache:
def __init__(self, max_total_size, default_quota, quotas=None):
self.max_total_size = max_total_size
self.quotas = quotas or {}
self.default_quota = default_quota
self.global_lru_head = None
self.global_lru_tail = None
self.tenant_lru_heads = {} # tenant_id -> head entry
self.tenant_lru_tails = {} # tenant_id -> tail entry
self.tenant_key_map = defaultdict(dict) # tenant_id -> {key: entry}
self.tenant_sizes = defaultdict(int)
self.total_size = 0
def get_quota(self, tenant_id):
return self.quotas.get(tenant_id, self.default_quota)
def get(self, tenant_id, key):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
self._move_to_head(entry)
return entry.value
return None
def set(self, tenant_id, key, value):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
entry.value = value
self._move_to_head(entry)
else:
if self.total_size >= self.max_total_size:
self._evict()
entry = Entry(tenant_id, key, value)
self._add_to_head(entry)
self.tenant_key_map[tenant_id][key] = entry
self.tenant_sizes[tenant_id] += 1
self.total_size += 1
def invalidate(self, tenant_id, key):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
self._remove_entry(entry)
del self.tenant_key_map[tenant_id][key]
self.tenant_sizes[tenant_id] -= 1
self.total_size -= 1
def invalidate_tenant(self, tenant_id):
# We need to remove all entries for this tenant.
# We'll iterate over a copy of the keys because we are going to modify the dict.
for key in list(self.tenant_key_map[tenant_id].keys()):
self.invalidate(tenant_id, key)
def invalidate_pattern(self, tenant_id, pattern):
# pattern is a function that takes a key and returns True if it matches.
# We'll assume pattern is a callable, or we can use string methods.
# For example, pattern = lambda key: key.startswith("prefix")
keys_to_remove = []
for key in self.tenant_key_map[tenant_id]:
if pattern(key):
keys_to_remove.append(key)
for key in keys_to_remove:
self.invalidate(tenant_id, key)
def _evict(self):
over_quota_tenants = [t for t in self.tenant_sizes if self.tenant_sizes[t] > self.get_quota(t)]
if over_quota_tenants:
# pick the tenant with the largest overage
tenant_to_evict = max(over_quota_tenants, key=lambda t: self.tenant_sizes[t] - self.get_quota(t))
entry = self.tenant_lru_tails[tenant_to_evict]
else:
entry = self.global_lru_tail
self._remove_entry(entry)
del self.tenant_key_map[entry.tenant_id][entry.key]
self.tenant_sizes[entry.tenant_id] -= 1
self.total_size -= 1
def _add_to_head(self, entry):
# Global LRU
entry.global_prev = None
entry.global_next = self.global_lru_head
if self.global_lru_head:
self.global_lru_head.global_prev = entry
self.global_lru_head = entry
if not self.global_lru_tail:
self.global_lru_tail = entry
# Tenant LRU
tenant_id = entry.tenant_id
entry.tenant_prev = None
entry.tenant_next = self.tenant_lru_heads.get(tenant_id)
if self.tenant_lru_heads.get(tenant_id):
self.tenant_lru_heads[tenant_id].tenant_prev = entry
self.tenant_lru_heads[tenant_id] = entry
if not self.tenant_lru_tails.get(tenant_id):
self.tenant_lru_tails[tenant_id] = entry
def _remove_entry(self, entry):
# Remove from global LRU
if entry.global_prev:
entry.global_prev.global_next = entry.global_next
else:
self.global_lru_head = entry.global_next
if entry.global_next:
entry.global_next.global_prev = entry.global_prev
else:
self.global_lru_tail = entry.global_prev
# Remove from tenant LRU
tenant_id = entry.tenant_id
if entry.tenant_prev:
entry.tenant_prev.tenant_next = entry.tenant_next
else:
self.tenant_lru_heads[tenant_id] = entry.tenant_next
if entry.tenant_next:
entry.tenant_next.tenant_prev = entry.tenant_prev
else:
self.tenant_lru_tails[tenant_id] = entry.tenant_prev
# If the tenant's LRU list becomes empty, remove the tenant from the dicts.
if self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
if self.tenant_lru_tails[tenant_id] is None:
del self.tenant_lru_tails[tenant_id]
def _move_to_head(self, entry):
# Remove from both lists and then add to head.
self._remove_entry(entry)
self._add_to_head(entry)
class Entry:
__slots__ = ('tenant_id', 'key', 'value', 'global_prev', 'global_next', 'tenant_prev', 'tenant_next')
def __init__(self, tenant_id, key, value):
self.tenant_id = tenant_id
self.key = key
self.value = value
self.global_prev = None
self.global_next = None
self.tenant_prev = None
self.tenant_next = None
Note: We are using slots to reduce memory overhead.
However, note that when we evict, we are removing the entry and then the entry becomes garbage. But we are also removing the reference from the tenant_key_map and the linked lists.
This design should work, but it's complex and we have to be careful with the linked list pointers.
Let's test with a simple scenario:
code
cache = TenantCache(max_total_size=3, default_quota=1)
cache.set('t1', 'a', 1) # t1: [a] (global: [a])
cache.set('t2', 'b', 2) # t2: [b] (global: [b, a])
cache.set('t2', 'c', 3) # t2: [c, b] (global: [c, b, a]) -> now total_size=3, t1 has 1 (quota 1) and t2 has 2 (quota 1) -> t2 is over.
Now, if we set('t1', 'd', 4), we need to evict.
Eviction: over-quota tenants: t2 (over by 1). So we evict the tail of t2's LRU, which is 'b'. Then we add 'd' for t1.
After eviction:
t1: [d] (global: [d, a]? Wait, global LRU after evicting 'b':
global was [c, b, a] -> remove b -> [c, a] -> then add d -> [d, c, a]?
But note: when we evicted 'b', we removed it from global and tenant lists. Then we added 'd' to head of global and t1's list.
So global: [d, c, a] and t1: [d] and t2: [c].
Now, t1 has 1 (quota 1) and t2 has 1 (quota 1). All good.
But note: the global LRU order is by recency. We accessed 'a' when we set 'a', then 'b', then 'c' (which updated t2's list and moved 'c' to head of t2 and global). Then we evicted 'b' (the tail of t2). Then we set 'd' for t1, which moved 'd' to head of global and t1.
So global: d (most recent), then c, then a.
But wait, we didn't access 'a' after setting it, so it's the least recent.
This seems correct.
However, note that when we set('t2', 'c', 3), we are updating an existing key? Actually, we set a new key for t2? No, we set a new key 'c' for t2, so it's a new entry.
Correction: in the above, we set 'b' and then 'c' for t2, so two entries for t2.
Now, what if we set('t2', 'b', 5)? That would update the existing 'b' and move it to head.
Let's do:
code
After the above, we have:
t1: [d]
t2: [c]
global: [d, c, a]
Now set('t2', 'b', 5):
'b' is not in t2? Actually, we evicted 'b' from t2. So it's a new key for t2? Then we are adding a new entry for t2.
Then we have to evict again because total_size would become 4 (currently 3).
Over-quota tenants: t1 has 1 (quota 1) -> not over. t2 would become 2 (quota 1) -> over. So we evict from t2's tail, which is 'c'. Then we add 'b' for t2.
Then:
t1: [d]
t2: [b]
global: [b, d, a]? Wait, after evicting 'c', global becomes [d, a] and then we add 'b' -> [b, d, a].
But note: when we evict 'c', we remove it from global and t2's list. Then we add 'b' to head of global and t2's list.
So global: [b, d, a] and t2: [b].
This seems correct.
However, note that the global LRU order is not exactly the same as the tenant's LRU order. For t2, the LRU is just [b] (only one entry). But globally, 'a' is the least recent.
Now, what if we have a tenant that is under quota but has an entry that is the global tail? We don't evict it because we only evict from over-quota tenants first.
But what if all tenants are under quota? Then we evict the global tail, which might be from a tenant that is under quota? That's acceptable because we are not over quota, so we are just doing normal LRU.
This design seems to meet the requirements.
However, note that the eviction by over-quota tenant is based on the current overage. But what if two tenants are over by the same amount? We can pick arbitrarily. We pick the one with the largest overage.
Also, note that when we evict from a tenant, we are evicting the least recently used entry for that tenant. But that entry might be more recent than some entries in the global LRU from other tenants? Yes, but that's because we are enforcing quotas.
We are also tracking the global LRU for when no tenant is over quota.
This design is complex and we have to be cautious about concurrency. We are not handling concurrency here. If we want thread-safety, we need to add locks.
Given the complexity, we might consider using existing data structures and adjust the eviction policy.
But for the purpose of this exercise, we have designed a tenancy-aware cache with invalidation and fairness.
Let's write the code accordingly.
However, note: the above design uses two doubly linked lists per entry and a dictionary per tenant. The memory overhead might be high.
We can reduce the memory by not storing the tenant's LRU as a separate linked list? But then we lose O(1) eviction by tenant.
Alternatively, we can store the tenant's LRU as a separate data structure that only stores the order of keys? But then we have to map from key to entry and then update the tenant's LRU on every access. We are already doing that with the two linked lists.
Given the time, we'll stick to this.
Let's code accordingly.
But note: the above code does not handle the case when we try to evict from a tenant that has no entries? That shouldn't happen because we only consider tenants that are over quota (so current_size > 0). But when we evict the tail, we have to make sure the tenant's LRU tail is not None.
Also, when we remove an entry, we have to update the tenant_lru_tails and tenant_lru_heads. We did that.
One more thing: when we add a new entry for a tenant that didn't have any entries before, we need to initialize the tenant's LRU head and tail. We do that in _add_to_head.
In _add_to_head, we set:
entry.tenant_prev = None
entry.tenant_next = self.tenant_lru_heads.get(tenant_id)
if self.tenant_lru_heads.get(tenant_id):
self.tenant_lru_heads[tenant_id].tenant_prev = entry
self.tenant_lru_heads[tenant_id] = entry
if not self.tenant_lru_tails.get(tenant_id):
self.tenant_lru_tails[tenant_id] = entry
This works.
Now, let's think about the case when we invalidate a tenant and remove all entries. We are using invalidate_tenant which calls invalidate for each key. That will eventually remove all entries and set tenant_sizes[tenant_id] to 0. But we also need to remove the tenant from tenant_lru_heads and tenant_lru_tails when the last entry is removed. That is done in _remove_entry.
So when the last entry of a tenant is removed, _remove_entry will set the head and tail to None and then we remove the tenant from the dictionaries? Actually, in _remove_entry, we check:
code
if self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
if self.tenant_lru_tails[tenant_id] is None:
del self.tenant_lru_tails[tenant_id]
But wait, we set the head and tail to None when we remove the last entry? Let's see:
code
In _remove_entry, for tenant LRU:
if entry.tenant_prev:
... else:
self.tenant_lru_heads[tenant_id] = entry.tenant_next # if entry is head, then new head is entry.tenant_next (which may be None)
if entry.tenant_next:
... else:
self.tenant_lru_tails[tenant_id] = entry.tenant_prev # if entry is tail, then new tail is entry.tenant_prev (which may be None)
So if the entry is the only one, then after removal:
self.tenant_lru_heads[tenant_id] = None (because entry.tenant_next is None)
self.tenant_lru_tails[tenant_id] = None (because entry.tenant_prev is None)
Then we check:
if self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
But note: we are accessing self.tenant_lru_heads[tenant_id] which might not exist? Actually, we are using .get in _add_to_head, but in _remove_entry we are directly accessing.
We should use:
if tenant_id in self.tenant_lru_heads and self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
Similarly for tails.
Alternatively, we can avoid deleting the tenant from the dictionaries until we invalidate the tenant? But we are using the presence of the tenant in tenant_lru_heads to indicate that the tenant has at least one entry?
Actually, we use tenant_lru_heads and tenant_lru_tails only for eviction and for adding/removing. We don't need to keep them for tenants with no entries.
So let's change:
In _remove_entry, after updating the head and tail, we check:
if self.tenant_lru_heads.get(tenant_id) is None:
if tenant_id in self.tenant_lru_heads:
del self.tenant_lru_heads[tenant_id]
if self.tenant_lru_tails.get(tenant_id) is None:
if tenant_id in self.tenant_lru_tails:
del self.tenant_lru_tails[tenant_id]
But note: we are using .get and then checking None. Alternatively, we can do:
if self.tenant_lru_heads[tenant_id] is None: # but if the key doesn't exist, it will throw KeyError.
We are only in _remove_entry for a tenant that has at least one entry (because we are removing an entry of that tenant). So the tenant must be in tenant_lru_heads and tenant_lru_tails.
So we can do:
if self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
if self.tenant_lru_tails[tenant_id] is None:
del self.tenant_lru_tails[tenant_id]
But wait, after we set the head to None (if we removed the head and there was no next), then we check and delete.
However, what if the tenant has multiple entries and we remove one that is not the head or tail? Then the head and tail remain the same and we don't delete.
So this is safe.
Let's adjust the code accordingly.
Given the complexity, we might want to write unit tests.
However, the problem asks to build the cache, so we'll provide the code as above.
One more thing: the eviction policy when there are multiple over-quota tenants with the same overage? We pick one arbitrarily (the first one in the max? Actually, max returns the first one if there are multiple with the same value). We can decide to pick the one with the largest tenant_id? But that's arbitrary.
We can also consider the tenant's current_size relative to quota? We are already using the overage.
Alternatively, we can pick the tenant that has the oldest entry? But we don't track that.
Given the simplicity, we'll stick to the largest overage.
Now, let's write the code accordingly.
We'll also consider that the quotas might be None for some tenants, then we use default_quota.
We'll assume that the quotas are set at the beginning and not changed dynamically. If they change, we need to recalculate over-quota tenants.
But for simplicity, we assume quotas are fixed.
Code:
code
from collections import defaultdict
class Entry:
__slots__ = ('tenant_id', 'key', 'value', 'global_prev', 'global_next', 'tenant_prev', 'tenant_next')
def __init__(self, tenant_id, key, value):
self.tenant_id = tenant_id
self.key = key
self.value = value
self.global_prev = None
self.global_next = None
self.tenant_prev = None
self.tenant_next = None
class TenantCache:
def __init__(self, max_total_size, default_quota, quotas=None):
self.max_total_size = max_total_size
self.default_quota = default_quota
self.quotas = quotas or {}
self.global_lru_head = None
self.global_lru_tail = None
self.tenant_lru_heads = {} # tenant_id -> Entry (head of tenant's LRU, most recent)
self.tenant_lru_tails = {} # tenant_id -> Entry (tail of tenant's LRU, least recent)
self.tenant_key_map = defaultdict(dict) # tenant_id -> {key: Entry}
self.tenant_sizes = defaultdict(int)
self.total_size = 0
def get_quota(self, tenant_id):
return self.quotas.get(tenant_id, self.default_quota)
def get(self, tenant_id, key):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
self._move_to_head(entry)
return entry.value
return None
def set(self, tenant_id, key, value):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
entry.value = value
self._move_to_head(entry)
else:
if self.total_size >= self.max_total_size:
self._evict()
entry = Entry(tenant_id, key, value)
self._add_to_head(entry)
self.tenant_key_map[tenant_id][key] = entry
self.tenant_sizes[tenant_id] += 1
self.total_size += 1
def invalidate(self, tenant_id, key):
if key in self.tenant_key_map[tenant_id]:
entry = self.tenant_key_map[tenant_id][key]
self._remove_entry(entry)
del self.tenant_key_map[tenant_id][key]
self.tenant_sizes[tenant_id] -= 1
self.total_size -= 1
def invalidate_tenant(self, tenant_id):
# We make a list of keys because we are going to modify the dict.
for key in list(self.tenant_key_map[tenant_id].keys()):
self.invalidate(tenant_id, key)
def invalidate_pattern(self, tenant_id, pattern):
# pattern: a function that takes a key and returns True if it matches.
keys_to_remove = [key for key in self.tenant_key_map[tenant_id] if pattern(key)]
for key in keys_to_remove:
self.invalidate(tenant_id, key)
def _evict(self):
over_quota_tenants = [t for t in self.tenant_sizes if self.tenant_sizes[t] > self.get_quota(t)]
if over_quota_tenants:
# Pick the tenant with the largest overage.
tenant_to_evict = max(over_quota_tenants, key=lambda t: self.tenant_sizes[t] - self.get_quota(t))
entry = self.tenant_lru_tails[tenant_to_evict]
else:
entry = self.global_lru_tail
self._remove_entry(entry)
del self.tenant_key_map[entry.tenant_id][entry.key]
self.tenant_sizes[entry.tenant_id] -= 1
self.total_size -= 1
def _add_to_head(self, entry):
# Global LRU
entry.global_prev = None
entry.global_next = self.global_lru_head
if self.global_lru_head:
self.global_lru_head.global_prev = entry
self.global_lru_head = entry
if not self.global_lru_tail:
self.global_lru_tail = entry
# Tenant LRU
tenant_id = entry.tenant_id
entry.tenant_prev = None
entry.tenant_next = self.tenant_lru_heads.get(tenant_id)
if self.tenant_lru_heads.get(tenant_id):
self.tenant_lru_heads[tenant_id].tenant_prev = entry
self.tenant_lru_heads[tenant_id] = entry
if not self.tenant_lru_tails.get(tenant_id):
self.tenant_lru_tails[tenant_id] = entry
def _remove_entry(self, entry):
# Remove from global LRU
if entry.global_prev:
entry.global_prev.global_next = entry.global_next
else:
self.global_lru_head = entry.global_next
if entry.global_next:
entry.global_next.global_prev = entry.global_prev
else:
self.global_lru_tail = entry.global_prev
# Remove from tenant LRU
tenant_id = entry.tenant_id
if entry.tenant_prev:
entry.tenant_prev.tenant_next = entry.tenant_next
else:
self.tenant_lru_heads[tenant_id] = entry.tenant_next
if entry.tenant_next:
entry.tenant_next.tenant_prev = entry.tenant_prev
else:
self.tenant_lru_tails[tenant_id] = entry.tenant_prev
# Clean up tenant's LRU head/tail if empty
if self.tenant_lru_heads[tenant_id] is None:
del self.tenant_lru_heads[tenant_id]
if self.tenant_lru_tails[tenant_id] is None:
del self.tenant_lru_tails[tenant_id]
def _move_to_head(self, entry):
self._remove_entry(entry)
self._add_to_head(entry)
This is the complete code.
However, note: in _remove_entry, we are accessing self.tenant_lru_heads[tenant_id] and self.tenant_lru_tails[tenant_id] which might have been deleted in the previous step? Actually, we are deleting only after setting to None. But we are using the same tenant_id for both.
Also, note that when we remove an entry, we are updating the head and tail for the tenant. Then we check if the head is None and delete the tenant from the heads dict. Similarly for tails.
But what if the tenant's head is None but the tail is not? That shouldn't happen because if there's at least one entry, head and tail are both set. And when we remove the last entry, both become None.
So it's safe.
We should also handle the case when we try to evict and the cache is empty? But we only call _evict when total_size >= max_total_size and we are about to add a new entry, so the cache is full. But if max_total_size is 0, then we might have a problem. We assume max_total_size > 0.
This is a basic implementation. We might want to add:
code
- A way to change quotas dynamically.
- A way to get the current size for a tenant.
- A way to get the global LRU order for debugging.
But for the purpose of the problem, this should suffice.
Let me know if there are any questions.
I'll design a tenancy-aware cache that provides isolation, fair resource allocation, and flexible invalidation for multi-tenant systems. Here's a comprehensive implementation:
from collections import defaultdict, OrderedDict
from typing import Any, Optional, Pattern
import re
from dataclasses import dataclass, field
import threading
@dataclass
class TenantMetrics:
"""Track per-tenant metrics for fairness"""
current_size: int = 0
hits: int = 0
misses: int = 0
evictions: int = 0
last_access: float = 0.0
@dataclass
class CacheEntry:
"""Individual cache entry with tenant context"""
key: str
value: Any
tenant_id: str
created_at: float
last_accessed: float
access_count: int = 1
ttl: Optional[float] = None # Time-to-live in seconds
class TenancyAwareCache:
"""
A thread-safe, tenancy-aware cache with:
- Tenant isolation (no key collision between tenants)
- Fair eviction policies (per-tenant quotas)
- Flexible invalidation (key, pattern, tenant-wide)
- Metrics collection
"""
def __init__(
self,
max_total_size: int = 10000,
default_tenant_quota: int = 1000,
tenant_quotas: Optional[dict[str, int]] = None,
eviction_policy: str = "lru", # "lru", "fifo", "ttl"
enable_metrics: bool = True
):
self.max_total_size = max_total_size
self.default_tenant_quota = default_tenant_quota
self.tenant_quotas = tenant_quotas or {}
self.eviction_policy = eviction_policy
self.enable_metrics = enable_metrics
# Core storage: {tenant_id: {key: CacheEntry}}
self._data: dict[str, dict[str, CacheEntry]] = defaultdict(dict)
# Access tracking for eviction policies
self._access_orders: dict[str, OrderedDict] = defaultdict(OrderedDict)
# Metrics
self._metrics: dict[str, TenantMetrics] = defaultdict(TenantMetrics) if enable_metrics else {}
# TTL tracking
self._ttl_queue: list[tuple[float, str, str]] = [] # (expiry_time, tenant_id, key)
self._lock = threading.RLock()
self._condition = threading.Condition(self._lock)
# Start TTL cleaner thread
if enable_metrics:
self._start_ttl_cleaner()
def _get_tenant_quota(self, tenant_id: str) -> int:
"""Get quota for tenant (with fallback to default)"""
return self.tenant_quotas.get(tenant_id, self.default_tenant_quota)
def _is_tenant_over_quota(self, tenant_id: str) -> bool:
"""Check if tenant exceeds their quota"""
return len(self._data[tenant_id]) > self._get_tenant_quota(tenant_id)
def _get_total_size(self) -> int:
"""Get total entries across all tenants"""
return sum(len(tenant_data) for tenant_data in self._data.values())
def _construct_key(self, tenant_id: str, key: str) -> str:
"""Construct tenant-scoped key (internal)"""
return f"{tenant_id}:{key}"
def _deconstruct_key(self, scoped_key: str) -> tuple[str, str]:
"""Extract tenant_id and key from scoped key"""
tenant_id, key = scoped_key.split(":", 1)
return tenant_id, key
def get(self, tenant_id: str, key: str) -> Optional[Any]:
"""
Get value for tenant/key.
Returns None if not found or expired.
"""
with self._lock:
# Check TTL first
if not self._is_valid(tenant_id, key):
self._remove(tenant_id, key)
if self.enable_metrics:
self._metrics[tenant_id].misses += 1
return None
entry = self._data[tenant_id].get(key)
if not entry:
if self.enable_metrics:
self._metrics[tenant_id].misses += 1
return None
# Update access metadata
entry.last_accessed = entry.access_count = entry.last_accessed + 1
entry.access_count += 1
# Update LRU tracking
if self.eviction_policy == "lru":
self._update_access_order(tenant_id, key)
if self.enable_metrics:
self._metrics[tenant_id].hits += 1
self._metrics[tenant_id].last_access = entry.last_accessed
return entry.value
def set(
self,
tenant_id: str,
key: str,
value: Any,
ttl: Optional[float] = None
) -> bool:
"""
Set value for tenant/key.
Returns True if set succeeded, False if rejected (quota exceeded).
"""
with self._lock:
# Check quota
current_tenant_size = len(self._data[tenant_id])
tenant_quota = self._get_tenant_quota(tenant_id)
if current_tenant_size >= tenant_quota:
# Try to evict from this tenant first
if not self._evict_from_tenant(tenant_id, 1):
return False
# Check global size
if self._get_total_size() >= self.max_total_size:
self._evict_global(1)
# Create entry
import time
entry = CacheEntry(
key=key,
value=value,
tenant_id=tenant_id,
created_at=time.time(),
last_accessed=time.time(),
ttl=ttl
)
# Store entry
self._data[tenant_id][key] = entry
# Update tracking
if self.eviction_policy == "lru":
self._access_orders[tenant_id][key] = None
self._access_orders[tenant_id].move_to_end(key, last=False)
if ttl:
self._ttl_queue.append((time.time() + ttl, tenant_id, key))
self._ttl_queue.sort(key=lambda x: x[0])
if self.enable_metrics:
self._metrics[tenant_id].current_size = len(self._data[tenant_id])
return True
def invalidate(self, tenant_id: str, key: str) -> bool:
"""Invalidate specific key for tenant"""
with self._lock:
return self._remove(tenant_id, key)
def invalidate_pattern(self, tenant_id: str, pattern: str) -> int:
"""
Invalidate keys matching pattern for tenant.
Returns number of keys invalidated.
"""
with self._lock:
regex = re.compile(pattern)
count = 0
# Collect keys to avoid modifying during iteration
keys_to_remove = [
key for key in self._data[tenant_id].keys()
if regex.match(key)
]
for key in keys_to_remove:
if self._remove(tenant_id, key):
count += 1
return count
def invalidate_tenant(self, tenant_id: str) -> int:
"""
Invalidate all keys for tenant.
Returns number of keys invalidated.
"""
with self._lock:
count = len(self._data[tenant_id])
self._data[tenant_id].clear()
self._access_orders[tenant_id].clear()
if self.enable_metrics:
self._metrics[tenant_id].current_size = 0
self._metrics[tenant_id].evictions += count
# Clean up empty tenant structures
if not self._data[tenant_id]:
del self._data[tenant_id]
if not self._access_orders[tenant_id]:
del self._access_orders[tenant_id]
if tenant_id in self._metrics and not self._data[tenant_id]:
del self._metrics[tenant_id]
return count
def _remove(self, tenant_id: str, key: str) -> bool:
"""Internal remove operation"""
if tenant_id not in self._data or key not in self._data[tenant_id]:
return False
# Remove from data
del self._data[tenant_id][key]
# Remove from access order
if tenant_id in self._access_orders and key in self._access_orders[tenant_id]:
del self._access_orders[tenant_id][key]
if not self._access_orders[tenant_id]:
del self._access_orders[tenant_id]
# Update metrics
if self.enable_metrics:
self._metrics[tenant_id].current_size = len(self._data[tenant_id])
self._metrics[tenant_id].evictions += 1
return True
def _update_access_order(self, tenant_id: str, key: str):
"""Update LRU access order"""
if tenant_id in self._access_orders:
if key in self._access_orders[tenant_id]:
self._access_orders[tenant_id].move_to_end(key, last=False)
else:
self._access_orders[tenant_id][key] = None
self._access_orders[tenant_id].move_to_end(key, last=False)
def _evict_from_tenant(self, tenant_id: str, count: int = 1) -> int:
"""Evict entries from specific tenant"""
evicted = 0
if tenant_id not in self._access_orders:
return 0
keys_to_evict = []
if self.eviction_policy == "lru":
# Evict oldest entries (last in OrderedDict)
for _ in range(min(count, len(self._access_orders[tenant_id]))):
key, _ = self._access_orders[tenant_id].popitem(last=True)
keys_to_evict.append(key)
elif self.eviction_policy == "fifo":
# Evict first inserted (first in OrderedDict)
for _ in range(min(count, len(self._access_orders[tenant_id]))):
key, _ = self._access_orders[tenant_id].popitem(last=False)
keys_to_evict.append(key)
for key in keys_to_evict:
self._remove(tenant_id, key)
evicted += 1
return evicted
def _evict_global(self, count: int = 1) -> int:
"""Global eviction across all tenants (fair share)"""
evicted = 0
all_tenants = list(self._data.keys())
# Fair share: evict roughly equally from each over-quota tenant
over_quota_tenants = [
t for t in all_tenants
if self._is_tenant_over_quota(t)
]
if not over_quota_tenants:
# No over-quota tenants, evict from any tenant
over_quota_tenants = all_tenants
# Calculate fair share per tenant
per_tenant = max(1, count // len(over_quota_tenants))
remaining = count
for tenant_id in over_quota_tenants:
if remaining <= 0:
break
to_evict = min(per_tenant, remaining, len(self._data[tenant_id]))
evicted += self._evict_from_tenant(tenant_id, to_evict)
remaining -= to_evict
return evicted
def _is_valid(self, tenant_id: str, key: str) -> bool:
"""Check if entry exists and hasn't expired"""
if tenant_id not in self._data or key not in self._data[tenant_id]:
return False
entry = self._data[tenant_id][key]
if entry.ttl and (entry.created_at + entry.ttl) < time.time():
return False
return True
def _start_ttl_cleaner(self):
"""Background thread to clean expired TTL entries"""
import time
def cleaner():
while True:
with self._condition:
now = time.time()
# Clean expired entries
while self._ttl_queue and self._ttl_queue[0][0] <= now:
expiry, tenant_id, key = self._ttl_queue.pop(0)
if tenant_id in self._data and key in self._data[tenant_id]:
entry = self._data[tenant_id][key]
if entry.ttl and (entry.created_at + entry.ttl) <= now:
self._remove(tenant_id, key)
# Wait until next expiry or 1 second
timeout = 1.0
if self._ttl_queue:
timeout = max(0.1, self._ttl_queue[0][0] - now)
self._condition.wait(timeout)
thread = threading.Thread(target=cleaner, daemon=True)
thread.start()
def get_metrics(self, tenant_id: Optional[str] = None) -> dict:
"""Get cache metrics"""
with self._lock:
if tenant_id:
metrics = self._metrics.get(tenant_id, TenantMetrics())
return {
"tenant_id": tenant_id,
"size": len(self._data.get(tenant_id, {})),
"quota": self._get_tenant_quota(tenant_id),
"hits": metrics.hits,
"misses": metrics.misses,
"hit_rate": metrics.hits / (metrics.hits + metrics.misses) if (metrics.hits + metrics.misses) > 0 else 0,
"evictions": metrics.evictions
}
else:
# Global metrics
total_hits = sum(m.hits for m in self._metrics.values())
total_misses = sum(m.misses for m in self._metrics.values())
total_evictions = sum(m.evictions for m in self._metrics.values())
return {
"total_entries": self._get_total_size(),
"max_total_size": self.max_total_size,
"tenant_count": len(self._data),
"total_hits": total_hits,
"total_misses": total_misses,
"global_hit_rate": total_hits / (total_hits + total_misses) if (total_hits + total_misses) > 0 else 0,
"total_evictions": total_evictions
}
def clear(self):
"""Clear entire cache"""
with self._lock:
self._data.clear()
self._access_orders.clear()
self._metrics.clear()
self._ttl_queue.clear()