import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import defaultdict
from typing import Optional, Any
# Simulated global data store (DB)
DB_DATA = {
"user:123:profile": {"name": "Alice", "age": 30},
"user:456:profile": {"name": "Bob", "age": 25},
"product:789": {"name": "Widget", "price": 19.99},
}
class Database:
"""Slow backend database layer."""
def get(self, key: str) -> Optional[Any]:
time.sleep(0.1) # Simulate DB latency
return DB_DATA.get(key)
class CacheLayer:
"""Generic cache layer with TTL, per-key locking for stampede defense, and stale-on-read support."""
def __init__(self, name: str, ttl: int, next_layer):
self.name = name
self.ttl = ttl
self.next_layer = next_layer
self.data: dict[str, Any] = {}
self.expiry: dict[str, float] = {}
# Per-key locks for stampede defense (distributed: use Redlock/Redis)
self._locks = defaultdict(threading.Lock)
def _is_fresh(self, key: str, now: float) -> bool:
return key in self.data and self.expiry.get(key, 0) > now
def get(self, key: str) -> Optional[Any]:
now = time.time()
# Fast path: fresh hit
if self._is_fresh(key, now):
print(f" {self.name}: HIT fresh '{key}'")
return self.data[key]
# Stale? Capture for potential serve-stale
stale_value = self.data.get(key) if key in self.data else None
# Acquire per-key lock (stampede defense)
lock = self._locks[key]
with lock:
# Double-check under lock
if self._is_fresh(key, time.time()):
print(f" {self.name}: HIT fresh '{key}' (double-check)")
return self.data[key]
# Miss/stale: fetch from next layer
print(f" {self.name}: MISS '{key}' -> {self.next_layer.name}")
value = self.next_layer.get(key)
if value is not None:
self._set(key, value)
print(f" {self.name}: BACKFILL '{key}' (TTL={self.ttl}s)")
return value
else:
print(f" {self.name}: MISS everywhere '{key}'")
return None
# Non-lock holders serve stale (if any) to reduce latency
if stale_value is not None:
print(f" {self.name}: SERVE STALE '{key}'")
return stale_value
return None
def _set(self, key: str, value: Any):
self.data[key] = value
self.expiry[key] = time.time() + self.ttl
def set(self, key: str, value: Any):
"""Direct set (e.g., for writes/population)."""
self._set(key, value)
def invalidate(self, key: str):
"""Explicit invalidation (distributed: use pub/sub to all instances)."""
now = time.time()
if key in self.data:
del self.data[key]
del self.expiry[key]
print(f" {self.name}: INVALIDATED '{key}'")
def stats(self):
now = time.time()
hits = sum(1 for k, e in self.expiry.items() if e > now)
total = len(self.expiry)
return f"{self.name}: {hits}/{total} fresh (TTL={self.ttl}s)"
# Build the hierarchy: CDN (long TTL) → Edge → Service → DB
db = Database()
service_cache = CacheLayer("Service", ttl=60, next_layer=db) # App-level cache (e.g., Redis)
edge_cache = CacheLayer("Edge", ttl=600, next_layer=service_cache) # Edge server cache (e.g., Varnish)
cdn_cache = CacheLayer("CDN", ttl=3600, next_layer=edge_cache) # CDN cache (e.g., CloudFront)
# Top-level cache (user-facing)
ROOT_CACHE = cdn_cache
# Invalidator (hits all layers)
def invalidate_all(key: str):
"""Invalidate across hierarchy."""
for layer in [cdn_cache, edge_cache, service_cache]:
layer.invalidate(key)
# Demo: Simulate stampede (100 concurrent requests)
def demo_stampede(key: str, num_requests: int = 100):
print(f"\n=== Stampede Demo: {num_requests} concurrent GET '{key}' ===")
start = time.time()
def req():
return ROOT_CACHE.get(key)
with ThreadPoolExecutor(max_workers=50) as executor:
futures = [executor.submit(req) for _ in range(num_requests)]
for future in as_completed(futures):
future.result() # Wait
elapsed = time.time() - start
print(f"Stampede complete: {num_requests} reqs in {elapsed:.2f}s ({elapsed/num_requests*1000:.1f}ms/req)")
print("\nCache stats:")
print(service_cache.stats())
print(edge_cache.stats())
print(cdn_cache.stats())
# Demo: Normal hits/misses
def demo_normal():
print("\n=== Normal Flow ===")
# Cold miss: populates all layers
print("1. Cold MISS 'user:123:profile':")
ROOT_CACHE.get("user:123:profile")
# Hit CDN
print("\n2. CDN HIT:")
ROOT_CACHE.get("user:123:profile")
# Expire CDN only (simulate short test TTL)
cdn_cache.expiry["user:123:profile"] = time.time() - 1
print("\n3. CDN MISS -> Edge HIT:")
ROOT_CACHE.get("user:123:profile")
# Demo: Invalidation
def demo_invalidation():
print("\n=== Invalidation Demo ===")
# Update DB (simulate)
DB_DATA["user:123:profile"]["age"] = 31
# Invalidate
invalidate_all("user:123:profile")
# Next get repopulates
value = ROOT_CACHE.get("user:123:profile")
print(f"Post-invalidate GET: {value}")
# Run demos
if __name__ == "__main__":
demo_normal()
demo_stampede("product:789", num_requests=100) # Triggers DB once, others wait/serve stale
demo_invalidation()
# Final stats
print("\nFinal stats:")
print(db) # DB has no stats
print(service_cache.stats())
print(edge_cache.stats())
print(cdn_cache.stats())
Key Features Implemented
- Hierarchy:
CDN (3600s TTL) → Edge (600s) → Service (60s) → DB. Misses propagate + backfill upwards.
- Keys: Strings (e.g.,
"user:123:profile" for user-specific caching).
- TTLs: Layer-specific expiration. Checked on every
get.
- Invalidation:
invalidate_all(key) deletes from all caches (extend with pub/sub like Redis Pub/Sub for distributed).
- Stampede Defense:
- Per-key
threading.Lock() prevents thundering herd (only 1 fetches next layer).
- Double-checked locking.
- Serve-stale for non-lock holders (low latency).
- Distributed: Replace with Redis Redlock or etcd leases.
- Production Notes:
- Caches: Use Redis/Memcached (Service/Edge), CloudFront/Fastly (CDN).
- Writes: Use
write-through or invalidate on update.
- Advanced: Stale-while-revalidate (HTTP headers), jittered TTLs, cache warming.
- Metrics: Add hit/miss counters.
Run the script to see output: Cold misses hit DB once, stampedes fetch DB once, invalidations refresh from DB. Total stampede time << naive (no defense).