Caching
Caching is the highest-leverage performance work available and the hardest to get right, because the two hard problems are naming things and invalidating caches. A cache is a copy that may be wrong; every decision is about how wrong it may be and for how long.
The 60-second answer
Section titled “The 60-second answer”Cache at every layer: browser, CDN, reverse proxy, application and database. Control it with
Cache-Control, validate withETag/If-None-Matchreturning304. Name every entry by a key that includes everything the response depends on, set a TTL, and addVaryfor the headers the response varies by. Server-side caches are usually cache-aside. Invalidate with short TTLs plus explicit deletes or key versioning. Protect the database from stampedes with single-flight locks, TTL jitter and stale-while-revalidate.
The layers
Section titled “The layers”| Layer | TTL | Survives deploy | Controls |
|---|---|---|---|
| Browser private cache | minutes to a year | yes | Cache-Control, ETag |
| CDN / edge | seconds to days | yes | Cache-Control, Vary, purge API |
| Reverse proxy | seconds to hours | yes | Same, plus local config |
| Application in-process | ms to seconds | no | Code; per node, so inconsistent |
| Redis / Memcached | minutes to hours | yes | Application logic |
Cache as close to the user as possible: a CDN hit costs no origin work at all. But only cache data whose staleness is acceptable — a bank balance and a marketing image are not the same problem.
HTTP caching
Section titled “HTTP caching”HTTP/1.1 200 OKCache-Control: public, max-age=60, s-maxage=600, stale-while-revalidate=30ETag: "8f14e45fceea167a5a36dedd4bea2543"Vary: Accept-Encoding, Accept-Language| Directive | Meaning |
|---|---|
max-age=N |
Fresh for N seconds in any cache |
s-maxage=N |
Overrides max-age for shared caches |
no-cache |
May store, must revalidate before use |
no-store |
Must not store at all — use for personal data |
private / public |
Browser only / shared caches may store |
must-revalidate |
Once stale, do not serve without revalidating |
stale-while-revalidate=N |
Serve stale for N seconds while refreshing |
stale-if-error=N |
Serve stale if the origin errors |
immutable |
Never revalidate while fresh; for hashed assets |
no-cache does not mean “do not cache” — it means “revalidate”. no-store forbids storage.
Getting these backwards puts personal data in a CDN.
Conditional requests
Section titled “Conditional requests”GET /styles/app.cssIf-None-Match: "8f14e45f"HTTP/1.1 304 Not ModifiedETag: "8f14e45f"A 304 reuses the client’s copy and saves the body, not the round trip. For large assets that is a
big win; for a small JSON response it can be worse than returning the body.
ETag should be a hash of the representation (strong) or a version marker (weak, W/ prefixed).
Last-Modified works but has one-second resolution and breaks when a file is rewritten within the
same second.
Fingerprinted assets
Section titled “Fingerprinted assets”<link rel="stylesheet" href="/assets/app.8f14e45f.css">Hash in the filename plus public, max-age=31536000, immutable gives an infinite cache with instant
invalidation: the URL changes when the content changes. This is the most valuable caching pattern on
the web, and the reason you never serve un-fingerprinted assets with a long TTL.
Vary and cache keys
Section titled “Vary and cache keys”A cache key is the URL plus whatever Vary lists. Omitting a header that changes the response serves
the wrong bytes; including too many shatters the cache into tiny fragments. Vary: Accept-Encoding
is mandatory when you compress. Vary: Cookie effectively destroys shared caching, because every
session gets its own entry.
Server-side strategies
Section titled “Server-side strategies”Cache-aside (lazy loading) — the default.
def find_user(id) key = "user:v3:#{id}" cached = redis.get(key) return JSON.parse(cached) if cached
user = db.query("SELECT * FROM users WHERE id = $1", id).first return nil unless user
redis.set(key, JSON.generate(user), ex: 300 + rand(30)) # jitter userendRead-through — the cache library loads on miss. Same semantics, less code, less control. Write-through — write cache and database in one path; reads always warm, writes slower. Write-behind — write the cache, flush asynchronously; fastest, and loses data on crash. Refresh-ahead — refresh hot keys before expiry; needs a popularity signal.
Invalidation
Section titled “Invalidation”- TTL. Simple, bounded staleness, no coordination. Most systems should stop here.
- Explicit delete on write.
DEL user:42after the update. A reader that missed before the write can repopulate the stale value after the delete — mitigate with delete-after-commit, a short TTL, or versioned keys. - Key versioning. Store a version key; the data key includes it. Bumping it invalidates everything for that entity atomically.
- Tag / surrogate-key purge. Tag responses with entities and purge by tag at the CDN.
- Pub/sub invalidation. Broadcast deletes to nodes with a local cache. Fire-and-forget: a missed message means staleness until TTL.
The honest position: TTL plus explicit delete; versioning when deletes race; accept a short inconsistency window rather than building distributed cache coherence.
Redis specifics
Section titled “Redis specifics”- Set
maxmemoryand an eviction policy:allkeys-lrutreats everything as evictable,volatile-lruonly keys with a TTL. Without a limit the OS OOM killer decides. - Command execution is single-threaded, so
KEYS *or a hugeSMEMBERSblocks everything. UseSCAN. - Cluster mode shards by hash slot; multi-key operations need one slot (hash tags
{user:42}:profile). - Treat Redis as shared state that can vanish. A cold cache must not take the database down.
Cache stampede and hot keys
Section titled “Cache stampede and hot keys”When a popular key expires, every concurrent request misses and hits the database at once.
def find_with_lock(key, ttl: 300) cached = redis.get(key) return JSON.parse(cached) if cached
if redis.set("#{key}:lock", "1", nx: true, ex: 10) begin value = yield redis.set(key, JSON.generate(value), ex: ttl) value ensure redis.del("#{key}:lock") end else sleep 0.05 retry_cached = redis.get(key) retry_cached ? JSON.parse(retry_cached) : yield endendAlso: TTL jitter so keys created together do not expire together; probabilistic early expiry;
negative caching for misses so a nonexistent id cannot hammer the database; CDN
stale-while-revalidate; and request coalescing per key.
Hot keys need a different answer: replicate the key across shards with a random suffix, or keep a local copy refreshed by pub/sub, so one shard is not the bottleneck.
Follow-up questions
Section titled “Follow-up questions”- What is the difference between
no-cacheandno-store, and where would each be wrong? - How do you invalidate a CDN entry after an admin edit?
- Why is
Vary: Cookiealmost always a mistake for a CDN? - What happens to your database when Redis restarts empty?
- How do you cache a personalised feed without caching per user?
Common traps
Section titled “Common traps”- “
no-cachemeans do not cache.” It means revalidate. - “A cache hit is always faster.” A remote hit costs a round trip (~0.5 ms in-region); a local computation may be faster.
- “Invalidation is easy with TTL.” TTL bounds staleness, it does not remove it. If the product needs immediate consistency, do not cache that read.
- “Just add Redis.” It adds a failure mode, a consistency problem and a dependency.
- “Cache the whole page for everyone.” Personalisation inside a
publicresponse leaks data. - “Set a TTL and forget it.” Without jitter and stampede protection, expiries line up and create periodic outages.