Awesome-claude-code caching-strategies-knowledge

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.

install
source · Clone the upstream repo
git clone https://github.com/dykyi-roman/awesome-claude-code
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/dykyi-roman/awesome-claude-code "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/caching-strategies-knowledge" ~/.claude/skills/dykyi-roman-awesome-claude-code-caching-strategies-knowledge && rm -rf "$T"
manifest: skills/caching-strategies-knowledge/SKILL.md
source content

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

StrategyHow It WorksConsistencyPerformanceUse Case
Cache-AsideApp reads cache first, fetches from DB on miss, writes to cacheEventualRead-heavyGeneral purpose, most common
Read-ThroughCache itself fetches from DB on missEventualRead-heavyTransparent caching layer
Write-ThroughApp writes to cache and DB synchronouslyStrongWrite-heavy (slower writes)Consistency-critical data
Write-BehindApp writes to cache, cache writes to DB asynchronouslyEventualWrite-heavy (fast writes)High write throughput
Write-AroundApp writes directly to DB, cache populated on readEventualInfrequent-read dataWrite-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

ApproachDescriptionConsistencyComplexity
TTL (Time-To-Live)Cache expires after fixed durationEventual (stale window)Low
Event-DrivenInvalidate on domain eventNear real-timeMedium
Versioned KeysInclude version in cache keyImmediate (new key)Medium
Tag-BasedGroup related keys by tag, purge by tagImmediateHigh
Write-ThroughUpdate cache on writeImmediateMedium
ManualExplicit invalidation in codeDepends on disciplineLow

TTL Selection Guide

Data TypeTTLReasoning
Static config1-24 hoursRarely changes
User profile5-15 minutesModerate change frequency
Session data30 minutesLinked to session timeout
Product catalog1-5 minutesModerate updates
Search results30-60 secondsFrequent updates
Real-time data5-15 secondsHigh change frequency
Counters/statsNo 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    │
└─────────────────────────────────────────────────┘
LevelStorageLatencyCapacityScope
L1In-process (APCu, static)< 1μsSmall (MB)Per-process
L2Distributed (Redis)1-5msLarge (GB)Shared
L3CDN / HTTP Cache5-50msVery largeGlobal
OriginDatabase10-100msUnlimitedSource of truth

Redis Data Structures for Caching

StructureWhen to UseExample
StringSimple key-value, serialized objectsUser session, JSON blob
HashObject with fields, partial readsUser profile (name, email, role)
Sorted SetRanked data, leaderboards, time-seriesTop products, recent activity
ListQueues, recent items, feedsRecent notifications
SetUnique collections, tagsUser permissions, online users
HyperLogLogCardinality estimationUnique visitors count

Strategy Selection by Workload

WorkloadStrategyWhy
Read-heavy, tolerance for staleCache-Aside + TTLSimple, effective
Read-heavy, consistency neededCache-Aside + event invalidationFresh data
Write-heavy, read-after-writeWrite-ThroughImmediate consistency
Write-heavy, async OKWrite-BehindBest write performance
Mixed, complex invalidationTag-based + event-drivenGranular control
API responsesHTTP Cache (CDN) + L2Reduce 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

MethodHow It WorksComplexityBest For
Locking (Mutex)One process recomputes, others waitMediumMost cases
Probabilistic Early Expiry (XFetch)Recompute before TTL with probabilityMediumHigh concurrency
Stale-While-RevalidateServe stale, refresh asyncMediumLatency-critical
External refreshCron/worker refreshes before expiryLowPredictable access

Distributed Cache Coherence

StrategyConsistencyLatencyComplexity
TTL onlyEventual (stale window)NoneLow
Pub/Sub invalidationNear-real-time~1-5msMedium
Write-through all nodesStrongHighHigh
Version-based (ETag)Strong (on read)Per-read checkMedium

Write-Back vs Write-Through

AspectWrite-ThroughWrite-Back
Write latencyHigher (sync)Lower (cache only)
Data safetySafeRisk of loss
ConsistencyStrongEventual
DB loadPer-writeBatched
Use caseFinancial, ordersAnalytics, 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