The user wants a "tenancy-aware cache hierarchy" with specific features:
- Tenancy-aware: Data must be segregated by tenant (e.g.,
tenant_id). Keys should be namespaced.
- Hierarchy: Multiple levels of caching (e.g., L1: Request Scope, L2: In-memory/Distributed like Redis).
- Request Scoping: A cache layer that exists only for the duration of a single request (L1).
- Invalidation Policies: Strategies to remove stale data (TTL, explicit invalidation, tags).
- Miss Analytics: Tracking cache misses to understand performance and hit rates.
Architecture & Design:
- Language: Python is a good choice for readability and pseudo-code clarity, but Go or Java could also work. I'll stick to Python for the implementation example as it's widely understood.
- Components:
CacheKey: A utility class to handle tenant namespacing.
RequestCache (L1): A dictionary-based cache that lives within a context (e.g., contextvars).
DistributedCache (L2): Interface for Redis/Memcached.
CacheManager: Orchestrates the hierarchy (L1 -> L2 -> Source).
Invalidator: Handles policies (TTL, Tags).
Analytics: A sink for miss/hit data.
Detailed Implementation Plan:
- Tenancy: Every key must be prepended with a
tenant_id. I'll enforce this via a KeyBuilder.
- Request Scoping (L1): Use Python's
contextvars to store a dictionary. This ensures that within an async or threaded request, the cache is local and isolated.
- Hierarchy Logic:
- Get: Check L1 -> Check L2 -> Fetch from Source -> Populate L2 -> Populate L1.
- Set: Set L1 -> Set L2.
- Invalidation:
- TTL: Standard time-based expiration (mostly for L2).
- Tags: Store a mapping of
Tag -> Set of Keys. When a tag is invalidated, delete all keys. This is complex but powerful.
- Miss Analytics:
- We need a way to record why a miss happened or simply that it happened.
- I'll create an
AnalyticsCollector interface.
Drafting the Code Structure (Mental or Scratchpad):
- Key Construction:
f"tenant:{tid}:key:{key}"
- L1:
request_local_cache.get(key)
- L2: Mock Redis class
redis_client.get(key)
- Manager:
class CacheManager:
def get(tenant_id, key):
full_key = build_key(tenant_id, key)
if L1.has(full_key): return L1.get()
if L2.has(full_key): return L2.get()
# Miss
analytics.record_miss(tenant_id, key)
value = source.load()
set(tenant_id, key, value)
return value
Refining the Invalidation:
Tag-based invalidation is hard to do atomically in a simple example without external dependencies. I will implement a simplified version or just explain the strategy. For the code, I'll focus on a TagInvalidator that maintains a side-car map.
Refining Miss Analytics:
The prompt asks for "Miss Analytics". This implies metrics. I'll emit an event containing tenant, key, latency, and layer (L1/L2).
Putting it together into a solution:
I will structure the response as a "System Design & Implementation Guide".
- Architecture Overview: Explain the layers.
- Core Components: Classes for Keys, L1, L2, and the Manager.
- Implementation: Python code demonstrating the flow.
- Features Deep Dive: Explain how tenancy, scoping, and analytics work in the code.
Self-Correction during drafting:
Initial thought: Just use a global dict for L1.
Correction: No, "Request Scoping" implies isolation between concurrent requests. Must use contextvars (Python) or ThreadLocal (Java). I will use contextvars for modern Python async support.
Invalidation Policies:
I should support:
- TTL (Time To Live): Standard.
- Explicit Invalidation: Delete by key.
- Tag-based: Invalidate groups (e.g., "user_profile_123").
Final Code Structure:
TenancyScope: Context manager for setting the current tenant.
CacheKey: Helper to build namespaced keys.
RequestLocalCache: L1.
DistributedCache: L2 (Mock).
MetricsCollector: Analytics.
HierarchicalCache: The main facade.
Let's write the code.
This solution engineers a robust, multi-layer caching system in Python. It addresses the specific requirements of Multi-Tenancy (data isolation), Hierarchy (Request-scoped L1 + Distributed L2), Intelligent Invalidation, and Observability (Miss Analytics).
Architecture Overview
- Tenancy Isolation: Every cache key is strictly namespaced (
tenant_id:key). The system refuses to operate without a tenancy context.
- L1 Cache (Request Scoped): Uses
contextvars to create a dictionary that lives only for the duration of a single HTTP request or background task. This eliminates network round-trips for repeated reads within the same transaction.
- L2 Cache (Distributed): Simulated Redis interface. Shared across the application.
- Invalidation Policies: Supports Time-To-Live (TTL) and Tag-Based invalidation (e.g., "invalidate all data related to
user_123").
- Miss Analytics: A specialized sink that captures what is being missed, how long the regeneration took, and which tenant is impacted.
Implementation
import time
import threading
import hashlib
import json
from contextvars import ContextVar
from typing import Any, Optional, Callable, List, Dict
from dataclasses import dataclass, field
from enum import Enum
# ==========================================
# 1. Core Infrastructure & Tenancy Context
# ==========================================
# ContextVar ensures thread-safety and isolation in async/threaded environments
current_tenant: ContextVar[str] = ContextVar('current_tenant')
class TenancyError(Exception):
pass
class CacheMissError(Exception):
pass
# ==========================================
# 2. Analytics & Monitoring (Miss Layer)
# ==========================================
@dataclass
class MissEvent:
tenant_id: str
key: str
latency_ms: float
tags: List[str]
timestamp: float = field(default_factory=time.time)
def to_json(self):
return json.dumps(self.__dict__)
class MissAnalyticsCollector:
"""
Listens for cache misses and records metrics.
In a real system, this would push to Prometheus, Datadog, or an event queue.
"""
def __init__(self):
self._lock = threading.Lock()
self.events = []
def record_miss(self, event: MissEvent):
with self._lock:
self.events.append(event)
# Simulation: Print to console for visibility
print(f"📊 [ANALYTICS] Miss Recorded: Tenant={event.tenant_id}, "
f"Key={event.key}, RegenTime={event.latency_ms:.2f}ms")
# ==========================================
# 3. Invalidation Policies
# ==========================================
class InvalidationPolicy(Enum):
NONE = 0
TTL = 1
TAG_BASED = 2
@dataclass
class CacheEntry:
value: Any
tags: List[str] = field(default_factory=list)
expires_at: Optional[float] = None
# ==========================================
# 4. Storage Layers (L1 & L2)
# ==========================================
class InMemoryStorage:
"""
L2 Simulation: Mimics a shared store like Redis/Memcached.
Supports tag tracking for complex invalidation.
"""
def __init__(self):
self._store: Dict[str, CacheEntry] = {}
self._tag_index: Dict[str, set] = {} # Mapping Tag -> Set of Keys
self._lock = threading.RLock()
def get(self, namespaced_key: str) -> Optional[CacheEntry]:
with self._lock:
entry = self._store.get(namespaced_key)
if entry and entry.expires_at and time.time() > entry.expires_at:
self.delete(namespaced_key)
return None
return entry
def set(self, namespaced_key: str, entry: CacheEntry):
with self._lock:
self._store[namespaced_key] = entry
# Update Tag Index
for tag in entry.tags:
if tag not in self._tag_index:
self._tag_index[tag] = set()
self._tag_index[tag].add(namespaced_key)
def delete(self, namespaced_key: str):
with self._lock:
if namespaced_key in self._store:
# Clean up tags
tags = self._store[namespaced_key].tags
for tag in tags:
if tag in self._tag_index:
self._tag_index[tag].discard(namespaced_key)
del self._store[namespaced_key]
def invalidate_by_tag(self, tag: str):
with self._lock:
keys_to_delete = list(self._tag_index.get(tag, set()))
print(f"🗑️ [L2-INVALIDATE] Tag '{tag}' invalidating {len(keys_to_delete)} keys.")
for key in keys_to_delete:
self.delete(key)
# ==========================================
# 5. The Hierarchical Cache Manager
# ==========================================
class TenancyAwareCacheHierarchy:
def __init__(self, l2_storage: InMemoryStorage, analytics: MissAnalyticsCollector):
self._l2 = l2_storage
self._analytics = analytics
# L1 is a ContextVar: A simple dictionary unique to this request/context
self._request_cache: ContextVar[dict] = ContextVar('request_cache', default=None)
def _get_namespaced_key(self, key: str) -> str:
"""Ensures strict key isolation between tenants."""
try:
tenant = current_tenant.get()
return f"t:{tenant}:k:{key}"
except LookupError:
raise TenancyError("Attempted to access cache without setting Tenancy Context")
def _get_l1(self) -> dict:
"""Retrieves the local request cache or initializes it."""
cache = self._request_cache.get()
if cache is None:
cache = {}
self._request_cache.set(cache)
return cache
# --- Core Operations ---
def get_or_set(self, key: str, loader: Callable[[], Any],
ttl: Optional[int] = None, tags: List[str] = []):
"""
The main interaction method.
Flow: L1 (Request) -> L2 (Distributed) -> Source (Loader)
"""
full_key = self._get_namespaced_key(key)
l1 = self._get_l1()
# 1. Check L1 (Request Scoped)
if full_key in l1:
print(f"✅ [L1-HIT] Key: {key}")
return l1[full_key]
# 2. Check L2 (Distributed)
entry = self._l2.get(full_key)
if entry:
print(f"✅ [L2-HIT] Key: {key}")
# Promote to L1 for future checks in this request
l1[full_key] = entry.value
return entry.value
# 3. Cache Miss -> Load Data
print(f"❌ [MISS] Key: {key}. Loading from source...")
start_time = time.perf_counter()
value = loader() # Execute the expensive operation
end_time = time.perf_counter()
duration_ms = (end_time - start_time) * 1000
# 4. Analytics Hook
event = MissEvent(
tenant_id=current_tenant.get(),
key=key,
latency_ms=duration_ms,
tags=tags
)
self._analytics.record_miss(event)
# 5. Populate L2
expires = time.time() + ttl if ttl else None
new_entry = CacheEntry(value=value, tags=tags, expires_at=expires)
self._l2.set(full_key, new_entry)
# 6. Populate L1
l1[full_key] = value
return value
def invalidate(self, key: str):
"""Invalidates a specific key across all layers."""
full_key = self._get_namespaced_key(key)
# Clear L1
if full_key in self._get_l1():
del self._get_l1()[full_key]
# Clear L2
self._l2.delete(full_key)
print(f"🗑️ [INVALIDATE] Key: {key}")
def invalidate_tag(self, tag: str):
"""
Invalidates a group of keys.
Note: Tag invalidation usually only clears L2 effectively.
L1 is request-scoped and typically short-lived, but we can try to clear it
if we track tags in L1 (omitted here for simplicity as L1 expires after request).
"""
self._l2.invalidate_by_tag(tag)
# ==========================================
# 6. Usage Example
# ==========================================
if __name__ == "__main__":
# Setup
l2_store = InMemoryStorage()
analytics_collector = MissAnalyticsCollector()
cache_system = TenancyAwareCacheHierarchy(l2_store, analytics_collector)
# Mock Loader Function (Simulates Database Call)
def load_user_profile():
print(" ... [DB Query] Fetching user data ...")
time.sleep(0.05) # Simulate 50ms latency
return {"id": 1, "name": "Alice", "role": "Admin"}
# --- Scenario 1: Tenant A Request ---
print("\n--- Tenant A: First Request (Cold Cache) ---")
current_tenant.set("tenant_A") # Set Context
# First Call: Miss in L1, Miss in L2, Hits Loader
data1 = cache_system.get_or_set(
"user:1",
load_user_profile,
ttl=60,
tags=["user_data", "region:us"]
)
# Second Call inside same request context: Hit L1
print("\n--- Tenant A: Same Request (Repeated Read) ---")
data2 = cache_system.get_or_set("user:1", load_user_profile)
# --- Scenario 2: Tenant B Request (Isolation Check) ---
print("\n--- Tenant B: Attempting to access same logical key ---")
current_tenant.set("tenant_B")
# This will MISS because the key is namespaced to tenant_B
data3 = cache_system.get_or_set("user:1", load_user_profile)
# --- Scenario 3: New Request for Tenant A (L2 Hit) ---
print("\n--- Tenant A: New Request (L2 Hit) ---")
# Simulate new request (Context is reset, L1 is empty)
# We set the context again, but L1 (contextvar) is fresh/empty
current_tenant.set("tenant_A")
data4 = cache_system.get_or_set("user:1", load_user_profile)
# --- Scenario 4: Tag Invalidation ---
print("\n--- Tenant A: Tag Invalidation ---")
cache_system.invalidate_tag("user_data")
# Next read forces miss
print("\n--- Tenant A: Read after invalidation ---")
data5 = cache_system.get_or_set("user:1", load_user_profile)
Key Engineering Decisions
-
Request Scoping via contextvars:
We avoid passing a cache object around functions. By using ContextVar, the L1 cache is globally accessible but safely isolated to the specific thread or asyncio task handling the request. This is critical for high-performance middleware.
-
The get_or_set Pattern (Memoization):
We do not provide separate get and set methods as the primary API. Instead, we accept a loader callable. This prevents "cache stampedes" (where multiple threads try to regenerate a value simultaneously) by encapsulating the read-through logic in one atomic operation.
-
Tag-Based Invalidation Strategy:
Maintaining a tag index (tag -> set of keys) allows for efficient group invalidation. When invalidate_tag is called, we look up all keys associated with that tag and purge them. This is essential for complex domain models where a single update might affect multiple cached views.
-
Miss Analytics:
The MissEvent captures the regeneration cost (latency_ms). This is more valuable than simply knowing a miss occurred. It allows operations teams to prioritize optimization efforts on the cache misses that hurt user experience the most.