Quick answer: Caching stores the result of expensive work (database queries, API calls, rendered pages) in fast memory so the next request is served instantly. The most common pattern is cache-aside: check the cache β on a miss, load from the database β store in the cache with a TTL. Redis is the most popular cache because it is an in-memory key-value store with expiry, data structures and sub-millisecond reads. The hard part is invalidation: decide how data becomes stale and how you refresh it.
Where caching happens
Layer | Example | Good for |
|---|---|---|
Browser | Cache-Control headers | Static assets, images |
CDN | Cloudflare, CloudFront, Azure Front Door | Static files, public pages, global users |
Application memory | In-process memory cache | Small, rarely changing config |
Distributed cache | Redis, Memcached | Shared data across many servers |
Database | Buffer pool, materialized views | Heavy aggregations |
Caching patterns
1. Cache-aside (lazy loading) β most common
async function getProduct(id) {
const key = `product:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // hit
const product = await db.products.findById(id); // miss
await redis.set(key, JSON.stringify(product), 'EX', 600); // 10 min TTL
return product;
}
async function updateProduct(id, data) {
await db.products.update(id, data);
await redis.del(`product:${id}`); // invalidate
}2. Write-through
Write to the cache and database together. Cache is always fresh, but writes are slower.
3. Write-behind (write-back)
Write to the cache first; persist to the database asynchronously. Very fast but risks data loss β use carefully.
4. Read-through
The cache library itself loads missing data from the database.
Invalidation strategies
- TTL (time to live): simplest; accept slightly stale data for a defined time.
- Delete on write: remove the key when data changes (shown above).
- Versioned keys:
product:42:v7β bump the version to invalidate. - Event-based: publish a change event; subscribers clear caches.
Never cache per-user sensitive data under shared keys, and never cache authorization decisions longer than permissions can change. Include the user or tenant ID in keys where data is personal.
Common problems and fixes
Problem | What happens | Fix |
|---|---|---|
Cache stampede | A popular key expires; thousands of requests hit the DB at once | Locking/single-flight, early refresh, random TTL jitter |
Cache penetration | Requests for keys that don't exist always hit the DB | Cache "not found" briefly, bloom filter, validation |
Stale data | Users see old values | Delete on write, shorter TTL |
Memory full | Evictions or errors | Set maxmemory and an eviction policy (e.g. allkeys-lru), TTL on all keys |
Redis beyond simple caching
- Strings with expiry β cache values, OTP codes.
- Hashes β objects such as sessions.
- Sorted sets β leaderboards, rankings.
- INCR + EXPIRE β rate limiting.
- Lists / Streams β queues and event processing.
- Pub/Sub β real-time notifications and cache invalidation.
# Simple rate limit: max 100 requests per minute per user
INCR rate:user:42
EXPIRE rate:user:42 60 NXHTTP caching headers
Cache-Control: public, max-age=31536000, immutable # hashed static files
Cache-Control: private, no-cache # user pages, revalidate
ETag: "abc123" # conditional requestsWhat to cache (and not)
- β Read-heavy, rarely changing data: product catalogs, settings, lookups, rendered fragments.
- β Expensive aggregations: dashboards, reports.
- β Third-party API responses with rate limits.
- β Rapidly changing balances or stock counts where accuracy is critical.
- β Data that is cheap to compute already.
Summary
- Cache-aside with TTL is the default pattern.
- Invalidate on write; add jitter to TTLs.
- Protect against stampede and penetration.
- Use Redis data structures for sessions, rate limits and leaderboards.
- Measure hit ratio β a cache that never hits is just complexity.