Skip to content

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.

Cache at every layer: browser, CDN, reverse proxy, application and database. Control it with Cache-Control, validate with ETag/If-None-Match returning 304. Name every entry by a key that includes everything the response depends on, set a TTL, and add Vary for 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.

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/1.1 200 OK
Cache-Control: public, max-age=60, s-maxage=600, stale-while-revalidate=30
ETag: "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.

GET /styles/app.css
If-None-Match: "8f14e45f"
HTTP/1.1 304 Not Modified
ETag: "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.

<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.

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.

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
user
end

Read-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.

  1. TTL. Simple, bounded staleness, no coordination. Most systems should stop here.
  2. Explicit delete on write. DEL user:42 after 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.
  3. Key versioning. Store a version key; the data key includes it. Bumping it invalidates everything for that entity atomically.
  4. Tag / surrogate-key purge. Tag responses with entities and purge by tag at the CDN.
  5. 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.

  • Set maxmemory and an eviction policy: allkeys-lru treats everything as evictable, volatile-lru only keys with a TTL. Without a limit the OS OOM killer decides.
  • Command execution is single-threaded, so KEYS * or a huge SMEMBERS blocks everything. Use SCAN.
  • 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.

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
end
end

Also: 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.

  1. What is the difference between no-cache and no-store, and where would each be wrong?
  2. How do you invalidate a CDN entry after an admin edit?
  3. Why is Vary: Cookie almost always a mistake for a CDN?
  4. What happens to your database when Redis restarts empty?
  5. How do you cache a personalised feed without caching per user?
  • “no-cache means 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 public response leaks data.
  • “Set a TTL and forget it.” Without jitter and stampede protection, expiries line up and create periodic outages.