Stage 3 · Build
Caching, Queues & Background Jobs
Cache Patterns
Apply cache-aside, write-through, stale-while-revalidate, key design, and stampede protection.
Cache-Aside
Cache-aside is the most common caching pattern. The application checks the cache first. On a miss, it reads from the database and populates the cache. On writes, it invalidates the cache.
Write-Through
Stale-While-Revalidate
Key Design
Good cache keys are descriptive, unique, and include version information. Use colons as separators. Include the entity type and ID.
- user:123 — simple entity cache
- user:123:profile — specific view of an entity
- user:123:permissions — nested data
- v1:user:123 — versioned key for schema changes
- lock:order:456 — distributed lock
- rate:api:user:123 — rate limiter counter
Cache Stampede
A cache stampede happens when many requests hit a cache miss simultaneously and all try to rebuild the cache. This can overwhelm the database. Use locks or singleflight to prevent it.
Cache Invalidation
There are two hard things in computer science: cache invalidation and naming things. The key insight is to invalidate eagerly on writes rather than relying on TTL alone.
Even with eager invalidation, always set a TTL on cache entries. If invalidation fails (Redis is down, code bug), the TTL ensures stale data expires eventually. This is your defense in depth.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.