Implementing Caching Strategies

1. Using Cache-Aside Pattern

StepAction
1App reads from cache
2Miss → query DB
3Populate cache with TTL
4Return value

Example: Lookup with cache-aside

String v = jedis.get(key);
if (v == null) {
    v = db.load(key);
    jedis.setex(key, 300, v);
}
return v;

2. Using Write-Through Pattern

AspectDetail
Write orderApp → cache → DB synchronously
ConsistencyStrong; both updated atomically (app responsibility)
LatencyHigher write latency

3. Using Write-Behind Pattern

AspectDetail
Write orderApp → cache; async flush to DB
TradeoffFast writes, risk of data loss on crash
Use caseCounters, metrics, non-critical writes

4. Implementing TTL-Based Expiration

PatternCommand
Set + TTLSET key v EX 300
Refresh on readGETEX key EX 300
Sliding windowReset TTL on each access

5. Handling Cache Invalidation

StrategyDescription
Delete on writeApp DELs cache key after DB update
TTL-onlyEventual consistency via short TTL
Pub/Sub fanoutBroadcast invalidation to nodes
Client-side trackingRESP3 invalidation messages 6.0+

6. Using Probabilistic Early Expiration

Example: XFetch algorithm

// recompute early with probability ∝ (β × delta × log(rand))
double rnd = Math.log(Math.random());
if (now - lastWrite + beta * recomputeMs * rnd >= expiry) {
    refreshCache();
}
BenefitDescription
Stampede preventionSpreads recomputation in time

7. Implementing Cache Warming

StrategyWhen
Startup loadPre-populate hot keys on boot
Background refreshScheduled job rehydrates top-N items
Pipelined MSETBulk warm via single round-trip

8. Preventing Cache Stampede

TechniqueDescription
Lock + recomputeSET NX lock; only winner rebuilds
Stale-while-revalidateServe old value while refreshing
Probabilistic earlyXFetch algorithm
Request coalescingPer-process singleflight

9. Using Lazy Loading

PropertyDetail
TriggerPopulate only on miss
ProCache contains only what's used
ConFirst request always slow

10. Implementing Cache Key Patterns

PatternExample
Entityuser:42
Compounduser:42:orders
Hashtag (Cluster){user:42}:orders
Versioneduser:42:v3
Namespacedapp:env:type:id

11. Using Cache Tagging

ApproachImplementation
Tag → keysSET of keys per tag
InvalidateSMEMBERS tag → UNLINK keys → DEL tag

12. Implementing Cache Versioning

StrategyDetail
Counter keyINCR app:cache:version for global purge
Prefix keyInclude version in cache key — old keys expire naturally