Implementing Caching Strategies

1. Configuring Cache Storage

StorageLatencyCapacity
In-process LRU< 1µsMBs
Local disk1-5 msGBs
Redis1-2 ms10s GBs
Memcached1-2 ms10s GBs
CDN edge10-30 ms (first), instant repeatPBs

2. Setting Cache TTL Values (time-to-live)

ContentTTL
Static assets1 year + cache-bust
Public API list1-5 min
User profile30s - 5min
Search results10-60s
Real-time data0 (no cache)

3. Using Cache Key Patterns

Example: Composite cache key

key = method + ":" + path + "?" + sorted(query) +
      "|user=" + user_id + "|locale=" + accept_lang +
      "|enc=" + accept_encoding
hash = sha1(key)
Include in KeyWhy
MethodGET vs HEAD differ
Path + sorted queryParam order shouldn't matter
Vary headersPer encoding/language
Auth scopePer-user / public split

4. Implementing Cache Invalidation

MethodGranularity
TTL expiryCoarse, time-based
Explicit purge by keySingle entry
Tag-based purgeAll "user:42" entries
Surrogate-Key headerFastly/Varnish style
Versioned keyBump version → cache miss

5. Configuring Cache Bypass Rules

Bypass IfReason
Authorization header presentPer-user response
Cookie setPersonalized
Cache-Control: no-cacheClient opt-out
Admin/debug headerForce origin fetch
Non-GET methodMutations not cached

6. Setting Up Conditional Caching

Example: ETag conditional GET

GET /resource HTTP/1.1
If-None-Match: "v3-abc123"

HTTP/1.1 304 Not Modified
ETag: "v3-abc123"
Cache-Control: max-age=300

7. Using Cache Warming Strategies

StrategyUse
Pre-fetch on deployAvoid cold start
Background refreshRe-fetch before TTL expires
Popular keys listTop-N analytics-driven
stale-while-revalidateServe stale + async refresh

8. Implementing Cache Partitioning

Partition ByReason
TenantIsolation, easy purge
RegionData residency
Content typeDifferent eviction policies
Cache zoneHot vs cold tiers

9. Configuring Cache Size Limits

LimitStrategy
Max bytesLRU eviction
Max itemsBounded count
Per-entry max sizeReject huge responses
Eviction policyLRU, LFU, TinyLFU, ARC

10. Setting Up Cache Hit Ratio Monitoring

MetricTarget
Hit ratio> 80% for cacheable
Byte hit ratio> 90% (large objects)
Eviction rateLow & stable
Origin offload% requests not hitting backend