The user wants an implementation of a cache hierarchy: CDN -> Edge -> Service -> DB.
Key components requested:
- Cache Layers: CDN, Edge, Service, DB.
- Features:
- Keys and TTLs (Time To Live).
- Invalidation strategies.
- Stampede defense (Thundering Herd problem).
1. Architecture Overview:
- DB: The source of truth. Slow.
- Service Cache (L1): In-memory (local) cache inside the application instance. Very fast, but limited size and inconsistent across instances.
- Edge Cache (L2): Shared distributed cache (e.g., Redis). Consistent across instances, slightly slower network hop.
- CDN (L3): Geographically distributed, close to the user. Usually for static assets, but can cache API responses.
2. Language/Stack:
I'll use Python with a class based structure to simulate the flow. I'll use asyncio because I/O operations (network/db) are best represented asynchronously. I won't use actual external services (like Nginx or Cloudflare code), but I will write the logic that controls them or simulates them in a cohesive demo.
3. Key Components Implementation Details:
-
Data Structures:
CacheItem: Needs value and expires_at.
-
Stampede Defense:
- Problem: 1000 requests come in for key "X" which is missing. All 1000 hit the DB.
- Solution: Mutex/Locking or "Request Coalescing" (singleflight).
- Implementation: A lock per key. If a request is in flight for a key, other waiters subscribe to the result.
-
Invalidation:
- TTL: Standard expiration.
- Explicit Purge: Ability to delete a key.
- Cache Hierarchy Bypass:
Cache-Control: no-cache headers (simulated).
4. Step-by-Step Implementation Plan:
- Step 1: The Database (Mock).
- Step 2: The Cache Strategy (The Logic).
- Need a
get and set interface.
- Need to handle TTLs.
- Step 3: Stampede Defense (SingleFlight).
- This is crucial. I'll implement a
SingleFlight class.
- Step 4: The Hierarchy Layers.
LocalCache (Python dict with TTL).
RedisCache (Simulated shared dict with TTL).
CDN (Simulated edge storage).
- Step 5: The Orchestrator / Service.
-
This brings it all together. The logic: Request -> CDN -> Edge -> Service -> DB.
-
Actually, usually the "Service" is the application. The hierarchy is Client -> CDN -> Load Balancer -> Service App -> Redis -> DB.
-
Correction: The prompt says "CDN->edge->service->DB". This implies:
- CDN (Infrastructure level).
- Edge (Maybe a Gateway or distributed Redis).
- Service (Local memory/L1).
- DB.
Let's model it as: Request hits
Service. Service checks Local (L1) -> Distributed (L2/Edge) -> DB. The "CDN" part is usually outside the code, but I can model the headers or the decision logic to check/stale the CDN.
-
Refined Hierarchy Model:
- Layer 1 (Service/Local): LRU Cache in memory.
- Layer 2 (Edge/Redis): Shared distributed cache.
- Layer 3 (CDN): Conceptual, usually handled by headers, but I'll wrap the response to simulate CDN caching headers.
- Layer 4 (DB): The generator.
5. Drafting the Code (Mental or Scratchpad):
-
SingleFlight:
class SingleFlight:
def __init__(self):
self.flights = {} # key -> Future/Event
async def do(self, key, func):
if key in self.flights:
await self.flights[key].wait()
return result_from_flight
self.flights[key] = Event()
try:
res = await func()
store_result
return res
finally:
del self.flights[key]
Actually, a simpler Python implementation uses asyncio.Lock per key.
-
TTL: Use time.time().
-
Invalidation:
- Time-based (TTL).
- Tag-based (optional, but complex to implement from scratch. I'll stick to key-based invalidation for simplicity).
6. Refining the Architecture for the Output:
I will create a complete Python script that simulates this hierarchy.
- Classes:
Database: Simulates latency and data storage.
CacheLayer: A generic class handling TTL storage.
SingleFlight: The stampede defense mechanism.
CacheHierarchy: The controller that coordinates L1 (Service), L2 (Edge), and DB interactions.
7. Specific Scenarios to Demonstrate:
- Cache Miss: Fetch from DB, populate L1 and L2.
- Cache Hit (L1): Fast return.
- Invalidation: Purge key, next request hits DB.
- Stampede: Spawn 10 concurrent requests for the same missing key, verify DB is only hit once.
8. Code Construction (Iterative Refinement):
-
Stampede Logic: If I use asyncio.Lock, it blocks execution. If 10 requests come in, they all try to acquire the lock. One wins, fetches data, releases lock. The other 9 acquire the lock, check if data is now present (it is), and return.
- Better Stampede Logic (Async): When the lock is released, they should re-check the cache immediately. Yes.
-
TTL Strategy:
- L1 (Service): Short TTL (e.g., 60s).
- L2 (Edge/Redis): Medium TTL (e.g., 1hr).
- CDN: Long TTL (e.g., 1 day), handled by stale-while-revalidate or manual purge. I will implement "Stale-while-revalidate" logic in the Service layer to show how to keep the CDN/Edge fresh without blocking the user.
9. Formatting the Output:
I will provide a single, copy-pasteable Python script (using asyncio) that models this system. I will add comments explaining the specific parts (Keys, TTL, Invalidation, Stampede).
Self-Correction during drafting:
The user asked for "CDN -> Edge -> Service -> DB".
In a typical microservice topology:
Request -> CDN (Nginx/Cloudflare) -> API Gateway (Edge) -> Service (K8s Pod) -> DB.
However, caches are usually checked in reverse:
- CDN checks its cache.
- If miss, hits Gateway.
- Gateway checks its cache.
- If miss, hits Service.
- Service checks Local Cache.
- If miss, hits DB.
I will implement the Service perspective which manages the Local Cache (L1), calls the Edge Cache (L2), and falls back to the DB, while generating headers for the CDN (L3).
Key Feature Checklist:
Let's write the code.
Structure:
MockDB: Simulates heavy IO.
CacheStore: A helper class to manage dictionary + TTL + cleanup.
CacheService: The main logic.
local_cache: L1.
edge_cache: L2.
locks: For stampede defense.
demo(): Shows the flow.
Refining the Stampede Defense logic:
Simply using a global lock for the whole cache is bad. We need a lock per key.
Map: key -> Lock.
When request comes for key_A:
- Check Cache.
- If miss, acquire
lock_A.
- Check Cache again (maybe another thread filled it while we waited for lock).
- If still miss, fetch from DB.
- Fill Cache.
- Release
lock_A.
This is the standard "Double-Checked Locking" applied to caching to solve the Thundering Herd.
Let's assemble.
This implementation models a robust caching architecture in Python. It simulates the full request lifecycle from a Service (which checks local memory), to an Edge cache (Redis/Distributed), and finally the Database.
It explicitly addresses Cache Stampede (Thundering Herd) using a locking mechanism (Mutex) and demonstrates TTL layering and Invalidation.
Architecture Overview
- L1: Service Cache (In-Memory): Fastest. Short TTL. Private to the instance.
- L2: Edge Cache (Distributed/Redis): Slower than L1, but shared. Medium TTL.
- L3: Database: Source of Truth. Slowest.
Python Implementation
import time
import asyncio
import random
from collections import defaultdict
from dataclasses import dataclass
from typing import Optional, Dict, Any
# ==========================================
# 1. Data Structures & Configuration
# ==========================================
@dataclass
class CacheEntry:
value: Any
expires_at: float
class Database:
"""
Simulates the Source of Truth (L3).
High latency (200ms) to demonstrate the need for caching.
"""
def __init__(self):
self.data = {"user:1": "Alice", "user:2": "Bob", "product:100": "Gaming Laptop"}
async def get(self, key: str) -> Optional[str]:
print(f" [DB] Querying database for '{key}'...")
await asyncio.sleep(0.2) # Simulate network/disk IO latency
return self.data.get(key)
async def update(self, key: str, value: str):
print(f" [DB] Updating database record '{key}'...")
await asyncio.sleep(0.1)
self.data[key] = value
# ==========================================
# 2. Cache Hierarchy Layers
# ==========================================
class CacheLayer:
"""
Generic Cache Layer implementation.
Handles TTL expiration and basic get/set.
"""
def __init__(self, name: str, ttl_seconds: int):
self.name = name
self.ttl = ttl_seconds
self.store: Dict[str, CacheEntry] = {}
def get(self, key: str) -> Optional[Any]:
entry = self.store.get(key)
if not entry:
return None
if time.time() > entry.expires_at:
print(f" [{self.name}] TTL Expired for key '{key}'")
del self.store[key]
return None
print(f" [{self.name}] HIT for key '{key}'")
return entry.value
def set(self, key: str, value: Any):
expires = time.time() + self.ttl
self.store[key] = CacheEntry(value=value, expires_at=expires)
print(f" [{self.name}] SET key '{key}' (TTL: {self.ttl}s)")
def invalidate(self, key: str):
if key in self.store:
del self.store[key]
print(f" [{self.name}] Invalidated key '{key}'")
# ==========================================
# 3. Stampede Defense (The Logic Core)
# ==========================================
class CacheHierarchyService:
"""
Orchestrates L1 -> L2 -> DB lookups.
Implements Stampede Defense using Asyncio Locks.
"""
def __init__(self, db: Database):
self.db = db
# Define Layers with cascading TTLs
# L1 (Service): Very short TTL (e.g. 5s)
# L2 (Edge): Medium TTL (e.g. 60s)
self.l1_service = CacheLayer("L1-Service", ttl_seconds=5)
self.l2_edge = CacheLayer("L2-Edge", ttl_seconds=20)
# Stampede Defense: Key-specific locks
# Prevents 100 requests from hitting the DB simultaneously for the same key
self.locks = defaultdict(asyncio.Lock)
async def get_data(self, key: str) -> Optional[Any]:
print(f"\n> Request incoming for '{key}'")
# 1. Check L1 (Service Local Memory)
val = self.l1_service.get(key)
if val is not None:
return val
# 2. Check L2 (Edge/Redis)
val = self.l2_edge.get(key)
if val is not None:
# Populate L1 on the way back (Read-Through)
self.l1_service.set(key, val)
return val
# 3. STAMPEDE DEFENSE
# If we reach here, data is missing in both cache layers.
# We acquire a lock for this specific key.
print(f" [Lock] Acquiring lock for '{key}' to prevent stampede...")
async with self.locks[key]:
# CRITICAL: Double-Check Pattern
# While we were waiting for the lock, another coroutine might have fetched the data.
# We check L2 again to avoid redundant DB calls.
val = self.l2_edge.get(key)
if val is not None:
print(f" [Lock] Data was populated by another request. Using it.")
self.l1_service.set(key, val)
return val
# 4. Fetch from DB (The expensive operation)
print(f" [Lock] Cache Miss confirmed. Fetching from Source...")
db_val = await self.db.get(key)
if db_val is not None:
# Populate caches (Write-Through / Look-Aside)
self.l2_edge.set(key, db_val)
self.l1_service.set(key, db_val)
return db_val
async def update_data(self, key: str, new_value: str):
"""
Handles Write-Through / Invalidation
"""
print(f"\n> Update request for '{key}'")
# 1. Update Source of Truth
await self.db.update(key, new_value)
# 2. Invalidate Caches (Write-Through or Invalidate)
# Here we use Invalidation to force next read to get fresh data
self.l1_service.invalidate(key)
self.l2_edge.invalidate(key)
print(f" [System] Caches invalidated for '{key}'. Next read will hit DB.")
# ==========================================
# 4. Simulation & Scenarios
# ==========================================
async def simulate_concurrency(service: CacheHierarchyService):
"""
Simulates a Thundering Herd: 5 concurrent requests for the same missing key.
Without locks, this would trigger 5 DB queries.
With locks, it triggers 1 DB query.
"""
print("\n--- SCENARIO: Thundering Herd (5 concurrent requests) ---")
# Ensure key is not in cache to start
service.l1_service.invalidate("user:1")
service.l2_edge.invalidate("user:1")
# Fire 5 requests at the exact same time
tasks = [service.get_data("user:1") for _ in range(5)]
await asyncio.gather(*tasks)
async def simulate_ttl_expiration(service: CacheHierarchyService):
print("\n--- SCENARIO: TTL Expiration & Hierarchy ---")
# First request (Cold Start)
await service.get_data("product:100") # Miss L1, Miss L2, Hit DB
# Second request (Warm)
await service.get_data("product:100") # Hit L1
print("\n [Time Warp] Waiting 6 seconds (L1 expires, L2 valid)...")
await asyncio.sleep(6)
# Third request
# L1 is expired, but L2 should still be valid.
await service.get_data("product:100")
async def simulate_invalidation(service: CacheHierarchyService):
print("\n--- SCENARIO: Data Mutation & Invalidation ---")
# Get initial value
await service.get_data("user:2")
# Update value via service
await service.update_data("user:2", "Robert")
# Fetch again
val = await service.get_data("user:2")
print(f" Result after invalidation: {val}")
# ==========================================
# 5. Main Entry Point
# ==========================================
async def main():
db = Database()
service = CacheHierarchyService(db)
await simulate_concurrency(service)
await simulate_ttl_expiration(service)
await simulate_invalidation(service)
if __name__ == "__main__":
asyncio.run(main())
Key Concepts Explained
1. The Hierarchy & TTL Strategy
We use a cascading TTL strategy. The code implements L1-Service (short TTL) and L2-Edge (longer TTL).
- Request Flow: Client -> Service (L1) -> Edge (L2) -> DB.
- Why? If L1 expires (e.g., 5s), there is a high probability L2 is still warm (e.g., 60s). This prevents hitting the database for every single request when local caches expire.
2. Stampede Defense (Thundering Herd)
Imagine a celebrity tweet causes 1,000 requests/second for user:1, and the cache just expired.
- The Problem: Without protection, 1,000 threads/processes see a cache miss and hammer the database simultaneously, causing a timeout avalanche.
- The Solution (
async with self.locks[key]):
- The first request acquires the lock.
- The other 999 requests wait at the lock.
- The first request fetches from DB and populates the cache.
- The lock releases.
- The remaining 999 requests resume.
- Double-Checked Locking: Inside the lock block, we check the cache again. Since Request #1 filled it, the others see a "Hit" on L2 and skip the DB call entirely.
3. Invalidation
When data changes (update_data), we cannot leave stale data in the cache.
- Strategy: We invalidate (delete) the key from both L1 and L2 immediately after writing to the DB.
- Safety: This ensures the next read request (even if it happens milliseconds later) is forced to fetch the fresh value from the DB.
Sample Output
When you run this code, observe the "Thundering Herd" section. You will see the DB queried only once, despite 5 concurrent requests.
--- SCENARIO: Thundering Herd (5 concurrent requests) ---
> Request incoming for 'user:1'
> Request incoming for 'user:1'
... (5 requests enter)
[Lock] Acquiring lock for 'user:1' to prevent stampede...
[Lock] Cache Miss confirmed. Fetching from Source...
[DB] Querying database for 'user:1'...
[L2-Edge] SET key 'user:1' (TTL: 20s)
[L1-Service] SET key 'user:1' (TTL: 5s)
... (Lock releases)
[Lock] Data was populated by another request. Using it. (Repeated 4 times)