Implementing Caching Patterns

1. Cache-Aside Pattern

StepAction
ReadApp checks cache → miss → load from DB → populate cache → return
WriteApp writes DB; invalidates cache (or updates)
ProsCache failures don't break reads (fall back to DB)
ConsStale data window; first read is slow

Example: Cache-Aside (Java + Redis)

public Product get(String id) {
    String cached = redis.get("prod:" + id);
    if (cached != null) return mapper.readValue(cached, Product.class);
    Product p = productRepo.findById(id).orElseThrow();
    redis.setex("prod:" + id, 300, mapper.writeValueAsString(p));
    return p;
}

2. Read-Through Cache Pattern

AspectDetail
MechanismApp reads cache only; cache loads from DB on miss
Cache Owns DB AccessLoader function configured at cache
ProsCleaner app code
ToolsCaffeine LoadingCache, Hazelcast, Ehcache

3. Write-Through Cache Pattern

AspectDetail
MechanismApp writes cache; cache writes synchronously to DB
ProsCache always consistent with DB
ConsWrite latency = cache + DB

4. Write-Behind Cache Pattern

AspectDetail
MechanismApp writes cache; cache async-batches writes to DB
ProsLow write latency; coalesces writes
ConsData loss risk on cache crash; complex consistency

5. Refresh-Ahead Cache Pattern

AspectDetail
MechanismAsync refresh entries before TTL expires (predicted access)
BenefitHides cache miss latency from users
CostWasted refreshes for items not accessed again

6. Distributed Cache Pattern

AspectDetail
MechanismCentralized/sharded cache shared by service instances
ToolsRedis Cluster, Memcached, Hazelcast, Aerospike
ShardingConsistent hashing across nodes
HAReplication; sentinel/failover

7. Near Cache Pattern

AspectDetail
DefinitionLocal in-process cache + remote distributed cache (L1 + L2)
LookupLocal first → remote → origin
InvalidationRemote pubsub broadcasts invalidations
ProsSub-microsecond hits; reduces remote load

8. Cache Invalidation Pattern

StrategyDetail
TTL ExpiryEventually consistent; simplest
Explicit InvalidateDelete key on write
Event-DrivenSubscribe to change events; invalidate
Versioned KeysBump version → old key naturally evicts
Tag-BasedInvalidate group by tag
Warning: "There are only two hard things in CS: cache invalidation and naming things." Plan for stale data; design TTL conservatively.

9. Cache Stampede Prevention Pattern

StrategyDetail
Mutex / SingleflightOne thread loads; others wait/share result
Stale-While-RevalidateServe stale; refresh async
Probabilistic Early ExpiryRefresh with rising probability as TTL nears
Jittered TTLRandomize expiry to avoid synchronized expiry

10. Multi-Level Cache Pattern

TierStorageLatency
L1In-process (Caffeine)~ns
L2Local-machine (Redis sidecar)~µs
L3Distributed (Redis cluster)~ms
L4CDN edge~10ms (geo)
OriginDatabase / service~10-100ms