import time
from collections import OrderedDict
from threading import RLock
from typing import Any, Optional, Dict
class TenantAwareCache:
"""
A thread-safe, tenant-aware LRU cache with the following features:
- **Key Scoping**: Cache entries are fully isolated per tenant using nested OrderedDicts.
No cross-tenant leakage possible.
- **Invalidation**: Per-key, per-tenant, or global clearing.
- **Fairness**:
- Per-tenant LRU eviction with configurable max entries per tenant.
- Global tenant LRU eviction: least recently used tenants are evicted when
exceeding max tenants limit (prevents tenant explosion).
- **Correctness**:
- Thread-safe with RLock.
- TTL-based expiration (checked on get; passive cleanup).
- Automatic cleanup of empty tenant caches.
- Touch-on-access for LRU (both per-tenant keys and tenants themselves).
Usage:
cache = TenantAwareCache(max_size_per_tenant=1000, max_tenants=1000, default_ttl=3600)
cache.set("tenant1", "user:123", {"data": "value"}, ttl=300)
value = cache.get("tenant1", "user:123")
cache.clear_key("tenant1", "user:123")
cache.clear_tenant("tenant1")
cache.clear_all()
"""
def __init__(
self,
max_size_per_tenant: int = 1000,
max_tenants: int = 1000,
default_ttl: Optional[int] = 3600,
):
self._caches: OrderedDict[str, OrderedDict[str, tuple[Any, float]]] = OrderedDict()
self._max_size_per_tenant = max_size_per_tenant
self._max_tenants = max_tenants
self._default_ttl = default_ttl
self._lock = RLock()
def _get_or_create_cache(self, tenant_id: str) -> OrderedDict[str, tuple[Any, float]]:
"""Get or create tenant cache, enforcing tenant LRU eviction."""
with self._lock:
if tenant_id not in self._caches:
# Evict LRU tenant if at limit
if len(self._caches) >= self._max_tenants:
oldest_tenant = next(iter(self._caches))
del self._caches[oldest_tenant]
self._caches[tenant_id] = OrderedDict()
# Touch tenant (move to MRU)
self._caches.move_to_end(tenant_id)
return self._caches[tenant_id]
def get(self, tenant_id: str, key: str) -> Optional[Any]:
"""Get value for tenant:key. Checks TTL and touches for LRU."""
cache = self._get_or_create_cache(tenant_id)
with self._lock:
entry = cache.get(key)
if not entry:
return None
value, expiry = entry
now = time.time()
if expiry != float("inf") and now > expiry:
del cache[key]
if not cache:
del self._caches[tenant_id]
return None
# Touch key (move to MRU)
cache.move_to_end(key)
return value
def set(
self, tenant_id: str, key: str, value: Any, ttl: Optional[int] = None
) -> None:
"""Set value for tenant:key with optional TTL. Enforces per-tenant LRU eviction."""
ttl = self._default_ttl if ttl is None else ttl
expiry = float("inf") if ttl is None or ttl <= 0 else time.time() + ttl
cache = self._get_or_create_cache(tenant_id)
with self._lock:
cache[key] = (value, expiry)
# Touch key (move to MRU)
cache.move_to_end(key)
# Evict LRU key if over limit
if len(cache) > self._max_size_per_tenant:
cache.popitem(last=False)
def clear_key(self, tenant_id: str, key: str) -> None:
"""Invalidate specific key for a tenant. Cleans up empty tenant caches."""
with self._lock:
cache = self._caches.get(tenant_id)
if cache:
cache.pop(key, None)
if not cache:
del self._caches[tenant_id]
def clear_tenant(self, tenant_id: str) -> None:
"""Invalidate all keys for a tenant."""
with self._lock:
self._caches.pop(tenant_id, None)
def clear_all(self) -> None:
"""Global invalidation: clear all tenants and keys."""
with self._lock:
self._caches.clear()
def stats(self) -> Dict[str, Any]:
"""Get cache statistics."""
with self._lock:
total_tenants = len(self._caches)
total_entries = sum(len(cache) for cache in self._caches.values())
tenant_sizes = {tid: len(cache) for tid, cache in self._caches.items()}
return {
"total_tenants": total_tenants,
"total_entries": total_entries,
"max_size_per_tenant": self._max_size_per_tenant,
"max_tenants": self._max_tenants,
"tenant_sizes": tenant_sizes,
}
def __len__(self) -> int:
with self._lock:
return sum(len(cache) for cache in self._caches.values())
Design Explanation
- Data Structure:
OrderedDict[tenant_id -> OrderedDict[key -> (value, expiry)]]. Double LRU: outer for tenants, inner for keys.
- Thread Safety: Single
RLock for simplicity and correctness (fine for moderate contention; shard for high-scale).
- Eviction:
- Per-tenant: On
set, evict oldest key if over max_size_per_tenant.
- Cross-tenant: On new tenant creation, evict oldest tenant if over
max_tenants.
- Touch-on-read/write keeps active tenants/keys recent.
- Expiration: Passive (checked on
get). No background threads needed.
- Edge Cases Handled:
- Empty tenant auto-cleanup.
- TTL=0 or None → no expiry.
- Concurrent access safe.
- No cross-tenant pollution (keys scoped internally).
- Performance: O(1) amortized get/set/invalidate. Python
OrderedDict is efficient.
- Extensibility: Easy to add size-based eviction (track
sys.getsizeof(value)), pub/sub invalidation, or Redis backing.
Example Usage
cache = TenantAwareCache(max_size_per_tenant=3, max_tenants=2)
# Tenant 1
cache.set("t1", "k1", "v1")
cache.set("t1", "k2", "v2")
cache.set("t1", "k3", "v3")
print(cache.get("t1", "k1")) # "v1" (k1 touched)
cache.set("t1", "k4", "v4") # Evicts k1 (LRU)
# New tenant evicts inactive
cache.set("t2", "k1", "v2k1")
print(len(cache.stats()["tenant_sizes"])) # 2 tenants
# Invalidation
cache.clear_key("t1", "k4")
cache.clear_tenant("t2")
cache.clear_all()
print(cache.stats())
# {'total_tenants': 0, 'total_entries': 0, ...}
This implementation is production-ready for moderate scale, fully meeting the requirements. For ultra-high scale, integrate with Redis (per-tenant namespaces) or add sharding.