Caching trades freshness for speed: you serve a stored answer instead of computing it again. Done well, it removes most load from databases and APIs. Done badly, it serves stale or wrong data, or collapses under a stampede when it expires.
Where to cache
| Layer | What | Example |
|---|---|---|
| Browser | Static assets, some API responses | Cache-Control headers |
| CDN | Pages and assets for everyone | Cached HTML for logged-out pages |
| Application memory | Small, hot, per-instance data | Feature flags, config |
| Shared cache (Redis, Memcached) | Data shared across instances | Product details, session data |
| Database | Query results, materialized views | Precomputed reports |
The closer to the user, the faster, and the harder to invalidate. For HTTP-level caching, see HTTP caching headers and caching for content sites.
Cache-aside (lazy loading)
The most common pattern: read from the cache; on a miss, load from the source and store it.
async function getProduct(id: string) {
const key = `product:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const product = await db.products.findById(id);
await redis.set(key, JSON.stringify(product), 'EX', 300); // 5-minute TTL
return product;
}
Simple, and the cache only holds what is used. The first request after expiry pays the full cost.
Write-through and write-behind
- Write-through: update the cache whenever you write to the database. Reads are always warm; writes are slower.
- Write-behind: write to the cache and flush to the database later. Fast writes, risk of data loss; rarely appropriate for business data.
Invalidation
"There are only two hard things in computer science: cache invalidation and naming things." Practical approaches:
- Short TTLs for data that may change: correctness within the TTL.
- Delete on write: when a product changes, delete
product:<id>; the next read reloads. - Versioned keys: include a version in the key (
product:42:v7) so old entries are simply never read again. - Event-driven purge: publish changes and purge CDN or cache entries on publish.
Preventing cache stampedes
When a popular key expires, hundreds of requests miss at once and all hit the database. Defences:
- Request coalescing: only one request rebuilds the value; others wait for it.
- Stale-while-revalidate: serve the stale value while one request refreshes it in the background.
- Jittered TTLs: add randomness so keys do not all expire together.
- Early refresh: refresh shortly before expiry for very hot keys.
What not to cache
- Personalized data in shared caches without the user in the key.
- Data where staleness is dangerous (balances, inventory at checkout) unless TTLs are tiny and checked at the critical step.
- Huge objects that evict everything else.
Metrics that show a cache is working
| Metric | Healthy | Worry when |
|---|---|---|
| Hit rate | High and stable for hot data | Drops after a deploy (key format changed?) |
| Evictions | Low for data you expect to stay | High: cache too small |
| Latency of cache calls | ~1 ms | Rising: network or a slow command |
| Origin load | Low relative to traffic | Spikes when the cache restarts |
See Redis monitoring for the cache side and Redis OOM command not allowed for when memory runs out.
Measuring the effect
Compare p95 latency and database load before and after. In traces, a cache hit shows as a ~1 ms Redis span instead of a database span; VitalRix APM shows both, so you can see the share of requests served from cache and how much time it saves.
A worked example
A product API took 120 ms per request, 90 ms of it in three database queries. Cache-aside with a 5-minute TTL and delete-on-write brought the hit rate to 97% and p95 to 14 ms. A week later, a homepage feature made one key extremely hot; when it expired, about 400 requests missed at once and briefly overloaded the database. Adding request coalescing (one rebuild per key, others wait) and a little TTL jitter removed the spikes.
Cache key design
- Include everything that changes the result: IDs, locale, currency, user segment.
- Version the key format (
v2:product:42) so changes in serialization never read old data. - Keep keys short and readable; you will search for them during incidents.
- Never put secrets in keys; they show up in monitoring and logs.
Checklist
- Decide which data tolerates staleness, and for how long.
- Choose the pattern (cache-aside for most reads).
- Set TTLs with jitter.
- Invalidate on write for data users expect to update immediately.
- Protect hot keys from stampedes.
- Monitor hit rate, evictions and origin load.
What TTL should I use?
As long as users can tolerate stale data for that item. Seconds to minutes for frequently changing data; hours for rarely changing reference data, with delete-on-write.
Redis or in-memory cache?
In-memory is fastest but per instance and lost on restart. Redis is shared across instances and survives app restarts.
How do I avoid serving stale prices?
Cache for display with a short TTL, and always re-check the price from the source of truth at checkout.
Try VitalRix free
Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.