Book a 30-min callBook a call

Caching strategies: cache-aside, write-through, write-back, TTLs and invalidation

Cache-aside, read-through, write-through and write-back compared, with TTL jitter, invalidation, stampede protection, eviction and HTTP caching headers.

An app box reading from a small store with a clock, a dashed arrow on a miss going on to a database cylinder, and an arrow filling the store back.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
15 min read

Questions people ask

How long should a TTL be?

As long as the data may be stale for the people reading it, and no longer. Start from that tolerance, shorten it for data that changes often, and add random jitter of around ten percent so keys written together do not expire together. Keep a TTL even when you invalidate on write, as a bound on any invalidation bug.

Should I delete or update the stored value when the data changes?

Delete it, after the database transaction commits. Deletes are idempotent, so retries and duplicates are harmless, and the next reader loads the current row. Updating the cached value from the writer risks two concurrent writes landing in the wrong order.

What is a thundering herd?

Many requests missing on the same key at once, usually right after a popular key expires, and all rebuilding it from the database. Prevent it with request coalescing, a short lock so one caller rebuilds, serving the old value while refreshing, or probabilistic early expiration.

Should I use LRU or LFU eviction in Redis?

Start with allkeys-lru, which the Redis documentation calls a good default when some keys are read far more than others. Try allkeys-lfu if one-off scans or batch reads keep pushing hot keys out. Compare the hit ratio and evicted keys in INFO stats before and after.

Building something like this?