Building a Resilient Cache Tier
As Sherlock, I'll deduce the blueprint for a cache tier that's not just fast, but resilient—immune to stampedes, hygienic in its TTLs, and strategically filled. We'll cover fill strategies, stampede prevention, and TTL hygiene, with architectural patterns, code examples (in Go for universality, adaptable to any lang), and trade-offs. This assumes a distributed system with a backend (e.g., DB) and a cache like Redis or an in-memory store (e.g., Ristretto/Caffeine).
1. Core Principles of Resilience
- Availability > Freshness: Serve stale data over failures.
- Decouple Read/Write: Cache hits bypass backend; misses are protected.
- Observe & Adapt: Metrics for hit ratio (>90% target), latency p99 (<50ms), eviction rate (<5%).
- Stack: Redis (distributed, TTL-native) + local L1 (e.g., BigCache) for hybrid warmth.
Client → Load Balancer → App (Cache-Aside Logic) → Redis (L2) → DB
↓ Local Cache (L1, ~10s TTL)
2. Fill Strategies
Choose based on read/write ratio and consistency needs. Cache-Aside (Lazy Loading) is the resilient default.
a. Cache-Aside (Most Resilient)
- App checks cache → Miss → Fetch from backend → Store in cache → Return.
- Pros: Simple, backend-only on misses. Resilient to cache outages.
- Cons: First miss latency; potential stampede (next section).
// Go example with Redis (github.com/redis/go-redis/v9)
func GetUser(ctx context.Context, id string) (*User, error) {
key := fmt.Sprintf("user:%s", id)
// L1: Local cache (e.g., sync.Map or Ristretto)
if u, ok := localCache.Get(key); ok {
return u.(*User), nil
}
// L2: Redis
val, err := rdb.Get(ctx, key).Result()
if err == nil {
u := unmarshalUser(val)
localCache.Put(key, u, 10*time.Second) // L1 TTL
return u, nil
}
// Miss: Backend fill
u, err := db.GetUser(ctx, id)
if err != nil {
return nil, err // Fail-fast, no cache poison
}
// Multi-level write
rdb.Set(ctx, key, marshalUser(u), 5*time.Minute)
localCache.Put(key, u, 10*time.Second)
return u, nil
}
b. Read-Through (Proxy)
- Cache lib (e.g., Redis with Redigo) auto-fills on miss.
- Pros: Transparent to app.
- Cons: Cache becomes SPOF; use for read-heavy.
c. Write-Through/Write-Behind
- Write-Through: Write cache + backend synchronously.
- Write-Behind (Async): Write cache, async backend (e.g., Kafka).
- Use for write-heavy; resilient with idempotent async queues.
Recommendation: Cache-Aside + Write-Behind for resilience.
3. Stampede Prevention (Thundering Herd Killer)
When 1k reqs hit a cold key simultaneously, backend melts. Prevent with probabilistic renewal, locking, and stale serving.
a. Probabilistic Early Expiration (TTL Jitter)
- Expire keys early randomly before TTL ends → Background refresh.
- Formula: TTL = baseTTL * (1 - jitter), jitter ~ Uniform(0, 0.2).
// Set with jitter
func setWithJitter(ctx context.Context, key string, val []byte, baseTTL time.Duration) {
jitter := time.Duration(rand.Float64()*0.2) * baseTTL
ttl := baseTTL - jitter
rdb.Set(ctx, key, val, ttl)
}
b. Stale-While-Revalidate (SWR) – Netflix Pattern
- Serve stale + async refresh in background.
- HTTP-inspired:
Cache-Control: max-age=300, stale-while-revalidate=60.
func GetWithSWR(ctx context.Context, key string) (*User, error) {
val, err := rdb.Get(ctx, key).Result()
if err != nil {
return fetchAndCache(ctx, key) // Cold fill
}
u := unmarshalUser(val)
// Async refresh if "stale"
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if fresh, err := fetchAndCache(ctx, key); err == nil {
// Promote fresh
}
}()
return u, nil
}
c. Single-Flight Locking (Semaphore)
- Use Redis Lua or app-level mutex (e.g.,
sync.Mutex + key hash).
- Only one filler per key; others wait or get stale.
// Redis Lua for distributed lock
lua := `
if redis.call('get', KEYS[1]) == ARGV[1] then
return 1 -- Locked by us
end
if redis.call('set', KEYS[1], ARGV[1], 'NX', 'EX', 10) then
redis.call('set', KEYS[2], ARGV[2]) -- Cache fill
return 2 -- We filled
end
return 0 -- Waiter
`
d. Circuit Breaker + Rate Limit
- Use Hystrix/ Resilience4j: If backend error rate >20%, fallback to stale.
- Per-key rate limit (Redis + token bucket).
Stack Prevention Priority: SWR > Jitter > Locking.
4. TTL Hygiene (Freshness Without Waste)
Bad TTLs = Stale data or OOM evictions. Hygiene = dynamic + lazy.
a. Tiered TTLs
- Hot keys: Short TTL (1min), high traffic.
- Cold keys: Long TTL (1hr) + lazy refresh.
- Use Redis
EXPIRE + PERSIST for immortal hot keys.
// Dynamic TTL based on metrics
func ttlForKey(key string, hitRate float64) time.Duration {
if hitRate > 0.95 { return 1 * time.Hour } // Immortal-ish
if hitRate > 0.8 { return 10 * time.Minute }
return 1 * time.Minute
}
b. Lazy Expiration + Grace Period
- Don't expire on read; background scan (Redis
SCAN + EXPIRE).
- Grace: On TTL hit, serve + extend 2x.
c. Invalidation (Pub/Sub)
- Backend events → Redis
PUBLISH → Invalidate keys.
- Tag-based:
user:* → DEL pattern (use SCAN).
// Invalidation handler
func onUserUpdate(userID string) {
pattern := fmt.Sprintf("user:%s:*", userID)
keys, _ := rdb.Keys(ctx, pattern).Result()
if len(keys) > 0 {
rdb.Del(ctx, keys...)
}
}
d. Cache Warming
- Startup: Pre-fill hot keys from DB snapshot.
- Background: Periodic
SCAN + refresh low-hit keys.
Hygiene Metrics:
| Metric | Target | Action |
|---|
| Hit Ratio | >90% | Increase TTL/hot keys |
| Eviction Rate | <5% | Scale cache / LRU tuning |
| Stale Ratio | <10% | Tighten jitter/SWR |
Deployment & Monitoring
- Redis Cluster: Sharding, Sentinel for HA.
- Local L1: Prevents Redis chatter.
- Tools: Prometheus (hit ratio), Grafana dashboards,
redis-cli --stat.
- Edge Cases:
| Scenario | Defense |
|---|
| Cache Outage | Fallback to DB (circuit breaker) |
| DB Outage | Stale-only mode |
| Hot Key Storm | Per-key quotas |
This tier scales to 1M+ RPS. Test with Locust: Simulate 10k concurrent misses. Questions on impl? The evidence is in the code—let's iterate. 🕵️