python
import time
from collections import defaultdict, OrderedDict
from typing import Dict, Optional, Any, Tuple
from dataclasses import dataclass
from threading import Lock
@dataclass
class TenantQuota:
max_bytes: int = 100 * 1024 * 1024 # Default 100MB
max_keys: int = 100_000 # Default 100k keys
class TenantCache:
"""
Per-tenant cache isolation strategy with:
- Key scoping via tenant-prefixed keys.
- Hard/soft quotas per tenant (bytes + key count).
- Fair eviction: Per-tenant LRU for intra-tenant eviction.
Global eviction prioritizes over-quota tenants by usage ratio.
Thread-safe. Approximates size as len(key) + len(value) + 32 bytes overhead.
"""
def __init__(self, global_max_bytes: int = 10 * 1024 * 1024 * 1024): # 10GB global
self.global_max_bytes = global_max_bytes
self._lock = Lock()
# Global cache: key -> Entry
self._cache: Dict[str, 'CacheEntry'] = {}
# Per-tenant stats
self._tenant_stats: Dict[str, TenantStats] = {}
self._quotas: Dict[str, TenantQuota] = {}
# Per-tenant LRU: tenant_id -> OrderedDict (MRU first, LRU last)
self._tenant_lrus: Dict[str, OrderedDict] = defaultdict(OrderedDict)
# Global usage tracking
self._global_bytes = 0
self._global_keys = 0
def register_tenant(self, tenant_id: str, quota: Optional[TenantQuota] = None):
"""Register a tenant with optional custom quota."""
with self._lock:
if tenant_id not in self._quotas:
self._quotas[tenant_id] = quota or TenantQuota()
self._tenant_stats[tenant_id] = TenantStats()
def _scoped_key(self, tenant_id: str, key: str) -> str:
"""Key scoping: tenant:{tenant_id}:{hash(key):8}:{key} to prevent collisions and bound length."""
key_hash = hash(key) & 0xFFFFFFFF # 32-bit hash for prefix
return f"tenant:{tenant_id}:{key_hash:08x}:{key}"
def _unscoped_key(self, scoped_key: str) -> Tuple[str, str]:
"""Extract tenant_id and original key from scoped key."""
parts = scoped_key.split(':', 3)
if len(parts) != 4 or not parts[0] == 'tenant':
raise ValueError("Invalid scoped key")
tenant_id, _, key_hash, orig_key = parts
return tenant_id, orig_key
def get(self, tenant_id: str, key: str) -> Optional[Any]:
"""Get value for tenant-scoped key. Updates LRU."""
scoped_key = self._scoped_key(tenant_id, key)
with self._lock:
if scoped_key not in self._cache:
return None
entry = self._cache[scoped_key]
self._promote_lru(tenant_id, scoped_key)
return entry.value
def put(self, tenant_id: str, key: str, value: Any, ttl_seconds: Optional[int] = None):
"""Put with quota check and eviction.
- First, enforce tenant quota (evict own LRU if needed).
- Then, check global limit (fair multi-tenant eviction if needed).
"""
if tenant_id not in self._quotas:
raise ValueError(f"Tenant {tenant_id} not registered")
scoped_key = self._scoped_key(tenant_id, key)
size = self._entry_size(scoped_key, value)
with self._lock:
# Step 1: Enforce tenant quota (soft eviction from own tenant)
self._enforce_tenant_quota(tenant_id, size)
# Remove old entry if exists
old_entry = self._cache.get(scoped_key)
if old_entry:
self._remove_entry(old_entry)
# Step 2: Enforce global limit (fair eviction)
while self._global_bytes + size > self.global_max_bytes:
if not self._fair_global_eviction():
raise MemoryError("Global cache full; cannot evict fairly")
# Insert new entry
entry = CacheEntry(scoped_key, value, size, ttl_seconds)
self._cache[scoped_key] = entry
self._tenant_lrus[tenant_id][scoped_key] = entry # MRU
self._update_tenant_stats(tenant_id, +size, +1)
self._global_bytes += size
self._global_keys += 1
def _enforce_tenant_quota(self, tenant_id: str, required_size: int):
"""Evict from this tenant's LRU until space available."""
quota = self._quotas[tenant_id]
stats = self._tenant_stats[tenant_id]
while (stats.bytes + required_size > quota.max_bytes or
stats.keys + 1 > quota.max_keys):
if not self._evict_tenant_lru(tenant_id):
break # Cannot free more space
def _fair_global_eviction(self) -> bool:
"""Evict one entry from the 'unfairest' tenant (highest usage_ratio = bytes/quota).
Prioritizes:
1. Over-quota tenants (ratio >1).
2. Highest ratio.
Falls back to global LRU from highest-ratio tenants.
Returns True if evicted.
"""
# Find over-quota tenants, sorted by usage_ratio desc
over_quota = []
under_quota = []
for tenant_id, stats in self._tenant_stats.items():
if tenant_id not in self._quotas:
continue
quota = self._quotas[tenant_id]
ratio = stats.bytes / max(quota.max_bytes, 1)
if ratio > 1:
over_quota.append((ratio, tenant_id))
elif self._tenant_lrus[tenant_id]:
under_quota.append((ratio, tenant_id))
candidates = sorted(over_quota + under_quota, reverse=True)
for _, tenant_id in candidates[:10]: # Limit scan for perf
if self._evict_tenant_lru(tenant_id):
return True
return False
def _evict_tenant_lru(self, tenant_id: str) -> bool:
"""Evict least-recently-used entry from tenant's LRU queue."""
lru = self._tenant_lrus[tenant_id]
if not lru:
return False
victim_scoped_key = next(iter(lru)) # LRU is first in OrderedDict
victim_entry = lru.popitem(last=False)[1] # Remove LRU
self._remove_entry(victim_entry)
return True
def _promote_lru(self, tenant_id: str, scoped_key: str):
"""Move to MRU in tenant's LRU."""
lru = self._tenant_lrus[tenant_id]
if scoped_key in lru:
lru.move_to_end(scoped_key)
def _remove_entry(self, entry: 'CacheEntry'):
"""Remove entry and update stats. Checks TTL."""
if entry.scoped_key in self._cache:
del self._cache[entry.scoped_key]
tenant_id, _ = self._unscoped_key(entry.scoped_key)
self._update_tenant_stats(tenant_id, -entry.size, -1)
self._global_bytes -= entry.size
self._global_keys -= 1
def _update_tenant_stats(self, tenant_id: str, delta_bytes: int, delta_keys: int):
stats = self._tenant_stats[tenant_id]
stats.bytes += delta_bytes
stats.keys += delta_keys
stats.bytes = max(0, stats.bytes) # Clamp
stats.keys = max(0, stats.keys)
def _entry_size(self, scoped_key: str, value: Any) -> int:
# Approximate: key + serialized value + overhead
val_size = len(str(value).encode('utf-8')) if value else 0
return len(scoped_key.encode('utf-8')) + val_size + 32
@dataclass
class CacheEntry:
scoped_key: str
value: Any
size: int
created_at: float = None
ttl_seconds: Optional[int] = None
def __post_init__(self):
self.created_at = time.time()
@dataclass
class TenantStats:
bytes: int = 0
keys: int = 0
# Example Usage
if __name__ == "__main__":
cache = TenantCache(global_max_bytes=1_000_000) # 1MB for demo
cache.register_tenant("tenantA", TenantQuota(max_bytes=500_000))
cache.register_tenant("tenantB", TenantQuota(max_bytes=300_000))
# Fill caches
for i in range(100):
cache.put("tenantA", f"key{i}", f"value{i}" * 1000)
cache.put("tenantB", f"key{i}", f"value{i}" * 500)
print(f"TenantA stats: {cache._tenant_stats['tenantA']}")
print(f"TenantB stats: {cache._tenant_stats['tenantB']}")
print(f"Global bytes: {cache._global_bytes}")
This strategy balances isolation, fairness, and efficiency. Test with load generators to tune quotas!