Caching Strategies Knowledge Base
Quick reference for caching patterns, invalidation strategies, and Redis implementation guidelines. Focuses on caching theory and Redis patterns — for Cache-Aside code generation, see create-cache-aside.
Caching Strategies
| Strategy |
How It Works |
Consistency |
Performance |
Use Case |
| Cache-Aside |
App reads cache first, fetches from DB on miss, writes to cache |
Eventual |
Read-heavy |
General purpose, most common |
| Read-Through |
Cache itself fetches from DB on miss |
Eventual |
Read-heavy |
Transparent caching layer |
| Write-Through |
App writes to cache and DB synchronously |
Strong |
Write-heavy (slower writes) |
Consistency-critical data |
| Write-Behind |
App writes to cache, cache writes to DB asynchronously |
Eventual |
Write-heavy (fast writes) |
High write throughput |
| Write-Around |
App writes directly to DB, cache populated on read |
Eventual |
Infrequent-read data |
Write-once, read-later |
Strategy Flow Diagrams
Cache-Aside (Lazy Loading):
Read: App → Cache (hit?) → yes → return
→ no → DB → write to Cache → return
Write: App → DB → invalidate Cache
Read-Through:
Read: App → Cache (hit?) → yes → return
→ no → Cache fetches from DB → return
Write: App → DB → invalidate Cache
Write-Through:
Read: App → Cache (hit?) → yes → return
→ no → DB → return
Write: App → Cache → Cache writes to DB (sync)
Write-Behind (Write-Back):
Read: App → Cache (hit?) → yes → return
→ no → DB → return
Write: App → Cache → Cache writes to DB (async, batched)
Cache Invalidation Approaches
| Approach |
Description |
Consistency |
Complexity |
| TTL (Time-To-Live) |
Cache expires after fixed duration |
Eventual (stale window) |
Low |
| Event-Driven |
Invalidate on domain event |
Near real-time |
Medium |
| Versioned Keys |
Include version in cache key |
Immediate (new key) |
Medium |
| Tag-Based |
Group related keys by tag, purge by tag |
Immediate |
High |
| Write-Through |
Update cache on write |
Immediate |
Medium |
| Manual |
Explicit invalidation in code |
Depends on discipline |
Low |
TTL Selection Guide
| Data Type |
TTL |
Reasoning |
| Static config |
1-24 hours |
Rarely changes |
| User profile |
5-15 minutes |
Moderate change frequency |
| Session data |
30 minutes |
Linked to session timeout |
| Product catalog |
1-5 minutes |
Moderate updates |
| Search results |
30-60 seconds |
Frequent updates |
| Real-time data |
5-15 seconds |
High change frequency |
| Counters/stats |
No TTL (event-driven) |
Update on write |
Multi-Level Caching
┌─────────────────────────────────────────────────┐
│ MULTI-LEVEL CACHE │
│ │
│ Request → L1 (In-Process) hit → return │
│ miss ↓ │
│ L2 (Redis/Memcached) hit → populate L1 │
│ miss ↓ │
│ L3 (CDN/HTTP Cache) hit → populate L2 │
│ miss ↓ │
│ Database → populate L2 → populate L1 │
└─────────────────────────────────────────────────┘
| Level |
Storage |
Latency |
Capacity |
Scope |
| L1 |
In-process (APCu, static) |
< 1μs |
Small (MB) |
Per-process |
| L2 |
Distributed (Redis) |
1-5ms |
Large (GB) |
Shared |
| L3 |
CDN / HTTP Cache |
5-50ms |
Very large |
Global |
| Origin |
Database |
10-100ms |
Unlimited |
Source of truth |
Redis Data Structures for Caching
| Structure |
When to Use |
Example |
| String |
Simple key-value, serialized objects |
User session, JSON blob |
| Hash |
Object with fields, partial reads |
User profile (name, email, role) |
| Sorted Set |
Ranked data, leaderboards, time-series |
Top products, recent activity |
| List |
Queues, recent items, feeds |
Recent notifications |
| Set |
Unique collections, tags |
User permissions, online users |
| HyperLogLog |
Cardinality estimation |
Unique visitors count |
Strategy Selection by Workload
| Workload |
Strategy |
Why |
| Read-heavy, tolerance for stale |
Cache-Aside + TTL |
Simple, effective |
| Read-heavy, consistency needed |
Cache-Aside + event invalidation |
Fresh data |
| Write-heavy, read-after-write |
Write-Through |
Immediate consistency |
| Write-heavy, async OK |
Write-Behind |
Best write performance |
| Mixed, complex invalidation |
Tag-based + event-driven |
Granular control |
| API responses |
HTTP Cache (CDN) + L2 |
Reduce server load |
Detection Patterns
# Cache usage
Grep: "Cache|Redis|Memcached|APCu|apc_" --glob "**/*.php"
Grep: "CacheInterface|CacheItemPoolInterface|SimpleCacheInterface" --glob "**/*.php"
# Cache-Aside pattern
Grep: "->get\(.*\).*->set\(" --glob "**/*.php"
Grep: "cache->has|cache->get|cache->set" --glob "**/*.php"
# TTL configuration
Grep: "ttl|expire|setex|SETEX|TTL" --glob "**/*.php"
Grep: "CACHE_TTL|CACHE_LIFETIME" --glob "**/.env*"
# Cache invalidation
Grep: "->delete\(|->invalidate\(|->clear\(|->flush\(" --glob "**/*.php"
Grep: "invalidateTag|invalidateTags|clearByTag" --glob "**/*.php"
# Redis patterns
Grep: "Predis|PhpRedis|Redis::|new Redis" --glob "**/*.php"
Grep: "REDIS_HOST|REDIS_URL" --glob "**/.env*"
# Multi-level caching
Grep: "ChainCache|StackedCache|MultiLevelCache" --glob "**/*.php"
Grep: "apcu_fetch|apcu_store" --glob "**/*.php"
Advanced Patterns
Cache Stampede Prevention
| Method |
How It Works |
Complexity |
Best For |
| Locking (Mutex) |
One process recomputes, others wait |
Medium |
Most cases |
| Probabilistic Early Expiry (XFetch) |
Recompute before TTL with probability |
Medium |
High concurrency |
| Stale-While-Revalidate |
Serve stale, refresh async |
Medium |
Latency-critical |
| External refresh |
Cron/worker refreshes before expiry |
Low |
Predictable access |
Distributed Cache Coherence
| Strategy |
Consistency |
Latency |
Complexity |
| TTL only |
Eventual (stale window) |
None |
Low |
| Pub/Sub invalidation |
Near-real-time |
~1-5ms |
Medium |
| Write-through all nodes |
Strong |
High |
High |
| Version-based (ETag) |
Strong (on read) |
Per-read check |
Medium |
Write-Back vs Write-Through
| Aspect |
Write-Through |
Write-Back |
| Write latency |
Higher (sync) |
Lower (cache only) |
| Data safety |
Safe |
Risk of loss |
| Consistency |
Strong |
Eventual |
| DB load |
Per-write |
Batched |
| Use case |
Financial, orders |
Analytics, counters |
References
For detailed information, load these reference files:
references/strategies.md — Detailed strategy analysis, cache warming, stampede prevention, distributed consistency
references/redis-patterns.md — Eviction policies, data structure guide, cluster/sentinel, Lua scripting, PHP patterns
references/advanced-patterns.md — Cache stampede prevention (locking, XFetch, stale-while-revalidate), cache warming strategies, write-back vs write-through comparison, distributed cache coherence, key design patterns
1---2name: caching-strategies-knowledge3description: Caching Strategies knowledge base. Provides caching patterns (Cache-Aside, Read-Through, Write-Through, Write-Behind), invalidation approaches, multi-level caching, and Redis data structures for caching audits and generation.4---56# Caching Strategies Knowledge Base78Quick reference for caching patterns, invalidation strategies, and Redis implementation guidelines. Focuses on caching theory and Redis patterns — for Cache-Aside code generation, see `create-cache-aside`.910## Caching Strategies1112| Strategy | How It Works | Consistency | Performance | Use Case |13|----------|-------------|-------------|-------------|----------|14| Cache-Aside | App reads cache first, fetches from DB on miss, writes to cache | Eventual | Read-heavy | General purpose, most common |15| Read-Through | Cache itself fetches from DB on miss | Eventual | Read-heavy | Transparent caching layer |16| Write-Through | App writes to cache and DB synchronously | Strong | Write-heavy (slower writes) | Consistency-critical data |17| Write-Behind | App writes to cache, cache writes to DB asynchronously | Eventual | Write-heavy (fast writes) | High write throughput |18| Write-Around | App writes directly to DB, cache populated on read | Eventual | Infrequent-read data | Write-once, read-later |1920### Strategy Flow Diagrams2122```23Cache-Aside (Lazy Loading):24 Read: App → Cache (hit?) → yes → return25 → no → DB → write to Cache → return26 Write: App → DB → invalidate Cache2728Read-Through:29 Read: App → Cache (hit?) → yes → return30 → no → Cache fetches from DB → return31 Write: App → DB → invalidate Cache3233Write-Through:34 Read: App → Cache (hit?) → yes → return35 → no → DB → return36 Write: App → Cache → Cache writes to DB (sync)3738Write-Behind (Write-Back):39 Read: App → Cache (hit?) → yes → return40 → no → DB → return41 Write: App → Cache → Cache writes to DB (async, batched)42```4344## Cache Invalidation Approaches4546| Approach | Description | Consistency | Complexity |47|----------|-------------|-------------|------------|48| TTL (Time-To-Live) | Cache expires after fixed duration | Eventual (stale window) | Low |49| Event-Driven | Invalidate on domain event | Near real-time | Medium |50| Versioned Keys | Include version in cache key | Immediate (new key) | Medium |51| Tag-Based | Group related keys by tag, purge by tag | Immediate | High |52| Write-Through | Update cache on write | Immediate | Medium |53| Manual | Explicit invalidation in code | Depends on discipline | Low |5455### TTL Selection Guide5657| Data Type | TTL | Reasoning |58|-----------|-----|-----------|59| Static config | 1-24 hours | Rarely changes |60| User profile | 5-15 minutes | Moderate change frequency |61| Session data | 30 minutes | Linked to session timeout |62| Product catalog | 1-5 minutes | Moderate updates |63| Search results | 30-60 seconds | Frequent updates |64| Real-time data | 5-15 seconds | High change frequency |65| Counters/stats | No TTL (event-driven) | Update on write |6667## Multi-Level Caching6869```70┌─────────────────────────────────────────────────┐71│ MULTI-LEVEL CACHE │72│ │73│ Request → L1 (In-Process) hit → return │74│ miss ↓ │75│ L2 (Redis/Memcached) hit → populate L1 │76│ miss ↓ │77│ L3 (CDN/HTTP Cache) hit → populate L2 │78│ miss ↓ │79│ Database → populate L2 → populate L1 │80└─────────────────────────────────────────────────┘81```8283| Level | Storage | Latency | Capacity | Scope |84|-------|---------|---------|----------|-------|85| L1 | In-process (APCu, static) | < 1μs | Small (MB) | Per-process |86| L2 | Distributed (Redis) | 1-5ms | Large (GB) | Shared |87| L3 | CDN / HTTP Cache | 5-50ms | Very large | Global |88| Origin | Database | 10-100ms | Unlimited | Source of truth |8990## Redis Data Structures for Caching9192| Structure | When to Use | Example |93|-----------|------------|---------|94| String | Simple key-value, serialized objects | User session, JSON blob |95| Hash | Object with fields, partial reads | User profile (name, email, role) |96| Sorted Set | Ranked data, leaderboards, time-series | Top products, recent activity |97| List | Queues, recent items, feeds | Recent notifications |98| Set | Unique collections, tags | User permissions, online users |99| HyperLogLog | Cardinality estimation | Unique visitors count |100101## Strategy Selection by Workload102103| Workload | Strategy | Why |104|----------|----------|-----|105| Read-heavy, tolerance for stale | Cache-Aside + TTL | Simple, effective |106| Read-heavy, consistency needed | Cache-Aside + event invalidation | Fresh data |107| Write-heavy, read-after-write | Write-Through | Immediate consistency |108| Write-heavy, async OK | Write-Behind | Best write performance |109| Mixed, complex invalidation | Tag-based + event-driven | Granular control |110| API responses | HTTP Cache (CDN) + L2 | Reduce server load |111112## Detection Patterns113114```bash115# Cache usage116Grep: "Cache|Redis|Memcached|APCu|apc_" --glob "**/*.php"117Grep: "CacheInterface|CacheItemPoolInterface|SimpleCacheInterface" --glob "**/*.php"118119# Cache-Aside pattern120Grep: "->get\(.*\).*->set\(" --glob "**/*.php"121Grep: "cache->has|cache->get|cache->set" --glob "**/*.php"122123# TTL configuration124Grep: "ttl|expire|setex|SETEX|TTL" --glob "**/*.php"125Grep: "CACHE_TTL|CACHE_LIFETIME" --glob "**/.env*"126127# Cache invalidation128Grep: "->delete\(|->invalidate\(|->clear\(|->flush\(" --glob "**/*.php"129Grep: "invalidateTag|invalidateTags|clearByTag" --glob "**/*.php"130131# Redis patterns132Grep: "Predis|PhpRedis|Redis::|new Redis" --glob "**/*.php"133Grep: "REDIS_HOST|REDIS_URL" --glob "**/.env*"134135# Multi-level caching136Grep: "ChainCache|StackedCache|MultiLevelCache" --glob "**/*.php"137Grep: "apcu_fetch|apcu_store" --glob "**/*.php"138```139140## Advanced Patterns141142### Cache Stampede Prevention143144| Method | How It Works | Complexity | Best For |145|--------|-------------|------------|----------|146| Locking (Mutex) | One process recomputes, others wait | Medium | Most cases |147| Probabilistic Early Expiry (XFetch) | Recompute before TTL with probability | Medium | High concurrency |148| Stale-While-Revalidate | Serve stale, refresh async | Medium | Latency-critical |149| External refresh | Cron/worker refreshes before expiry | Low | Predictable access |150151### Distributed Cache Coherence152153| Strategy | Consistency | Latency | Complexity |154|----------|-------------|---------|------------|155| TTL only | Eventual (stale window) | None | Low |156| Pub/Sub invalidation | Near-real-time | ~1-5ms | Medium |157| Write-through all nodes | Strong | High | High |158| Version-based (ETag) | Strong (on read) | Per-read check | Medium |159160### Write-Back vs Write-Through161162| Aspect | Write-Through | Write-Back |163|--------|---------------|------------|164| Write latency | Higher (sync) | Lower (cache only) |165| Data safety | Safe | Risk of loss |166| Consistency | Strong | Eventual |167| DB load | Per-write | Batched |168| Use case | Financial, orders | Analytics, counters |169170## References171172For detailed information, load these reference files:173174- `references/strategies.md` — Detailed strategy analysis, cache warming, stampede prevention, distributed consistency175- `references/redis-patterns.md` — Eviction policies, data structure guide, cluster/sentinel, Lua scripting, PHP patterns176- `references/advanced-patterns.md` — Cache stampede prevention (locking, XFetch, stale-while-revalidate), cache warming strategies, write-back vs write-through comparison, distributed cache coherence, key design patterns