You do not have a caching problem. You have a copy problem.
Caching strategies are not products you install. They are contracts for a copy of your data: who fills it, who updates it, and what a request does when the copy is missing. The pattern name on the whiteboard does not decide whether that copy stays honest. Those three answers do.
Here is the short answer. Use cache-aside for reads because it fails soft. Add write-through only on paths where a reader must see its own write immediately. Use write-behind only when you can lose the last few seconds of writes. Then protect every hot key against a stampede before launch, not after the first database spike. The six decisions that make a system distributed put this choice in context: caching is one component contract inside a larger design, not a strategy you bolt on at the end.
What Are Caching Strategies, Really?
A caching strategy is a rule for three separate decisions: who fills the cache on a miss, whether a write touches the cache, and what happens when the cache is absent.
Teams collapse those three into one word and then argue about the word. That is why the same team can call its design cache-aside
while one service writes through the cache, another deletes on write, and a nightly job bypasses both. The label survives. The contract does not.
Start with the read path. On every read, your service either finds the value (a hit) or does not (a miss). The hit ratio tells you whether the cache earns its place. AWS's guidance on caching is blunt about this: caching helps when results of calls to the dependency can be used across multiple requests or operations
. If every request needs a unique result, the cache adds a network hop and saves nothing.
Then accept the price. Cached data necessarily grows inconsistent with the source over time, so caching can only be successful if both the service and its clients compensate accordingly.
That sentence comes from the Amazon Builders' Library, and it is the most important line in this article. You are not adding speed to a consistent system. You are choosing a stale-read window and teaching your product to live inside it. What staleness does to your users is the next decision after this one.
The failure path is the third decision, and the one most designs skip. A cache is not a database. It can be empty, evicted, partitioned, or gone. Your service needs an answer for each case that is not query the database once per request and hope
.
How Does Cache-Aside Work, and Why Is It the Default?
Cache-aside means the application checks the cache first, loads from the store on a miss, writes the value back into the cache, and returns it.
The pattern is effectively lazy loading. AWS describes the read path in exactly those terms: ask the cache, miss, ask the data store, write the result into the cache. The application owns every step. The cache owns nothing.
value = cache.get(key)
if value is None:
value = store.read(key)
cache.set(key, value, ttl)
return value
The write path is where teams get it wrong. Azure's Cache-Aside guidance is precise: When an application updates information, it writes the change to the data store and then invalidates the corresponding item in the cache.
Delete, do not update. And delete after the store write, never before.
The order matters because of a race. Suppose you delete the key first, then write the database. A reader arrives between those two steps, misses, reads the old row, and writes the old value back into the cache. Now the cache holds a value older than the database, and it will keep serving it until the TTL expires. Azure spells out the same failure: Update the data store *before* removing the item from the cache.
Even with the right order, a read that started before your write can finish after it and repopulate the stale value. Facebook chose deletion over update for a related reason: We choose to delete cached data instead of updating it because deletes are idempotent.
Two deletes in a row leave the same state. Two out-of-order updates do not.
Cache-aside is the default because it degrades well. AWS lists the advantage plainly: when a node fails and a new empty node replaces it, your application continues to function, though with increased latency
. The cache is optional by construction. If it disappears, your service gets slower and your database gets busier, but the request path still exists.
The cost is the miss penalty. AWS counts three trips
for each miss: cache lookup, database read, cache write. On a cold cache, every request pays that. And Azure states the honest limit: The Cache-Aside pattern doesn't guarantee consistency between the data store and the cache.
You get a bounded staleness window, not a consistent copy.
That is the trade you want for product pages, user profiles, permission lookups, and any read-heavy path where a few seconds of staleness does not change a decision. It is the wrong trade for a balance, a stock level you are about to decrement, or a value a user just changed and expects to see.
Why Does Write-Through Feel Safer Than It Is?
Write-through updates the cache and the data store in the same write operation, and the caller waits for both to succeed.
Azure's caching guidance gives the clearest definition: Update the data store and the cache as part of the same write operation, and return the write response only after both updates succeed.
The ElastiCache guide says the same thing from the cache side: The write-through strategy adds data or updates data in the cache whenever data is written to the database.
The appeal is obvious. A reader that follows a successful write sees the new value in the cache immediately. Azure limits write-through to read-heavy access paths that need read-after-write freshness
, which is a narrower use case than most teams assume.
The catch is that write-through does not make your data consistent. It makes the writes that pass through it consistent. Every write path that skips the cache breaks the guarantee silently. A nightly batch job, an admin console running SQL, a second service that owns the same table, a migration script: each one can leave the cache holding a value the database no longer has.
AWS's guide claims Data in the cache is never stale.
Read that as a statement about a closed system. The moment a writer exists outside the cache's write path, the claim is false, and nothing in the cache tells you so.
The second cost is latency and amplification. Every write involves two trips
: one to the cache, one to the database. You also pay for cache churn, because Most data is never read
. You fill a fast tier with rows that nobody will request, and you evict rows that somebody would have.
A failure-ordering question sits underneath all of this. If the database write succeeds and the cache write fails, does the caller get an error? If yes, you have turned a cache outage into a write outage. If no, you have a cache that is silently behind, which is the state you added write-through to avoid. Most teams answer log it and continue
, then discover that the guarantee they designed for only holds on the happy path.
Use write-through when the read-after-write requirement is real and the write rate is low. A user editing their own profile is the classic case. A counter incrementing thousands of times per second is not.
What Do Write-Behind and Write-Around Trade Away?
Write-behind writes to the cache first and persists to the data store asynchronously, so the caller waits only for the cache.
Oracle's Coherence documentation defines it well: modified cache entries are asynchronously written to the data source after a configured delay
. The delay can be seconds or much longer. Writes batch, the database sees fewer statements, and the application stops paying the store's latency on every update.
The bill arrives in durability. Oracle states the consequence without softening it: write-behind effectively makes the cache the system-of-record (until the write-behind queue has been written to disk)
. If the cache dies before the flush, the write is gone. That is acceptable for a view counter and unacceptable for an order. Write-behind also reorders updates, so your schema and your business rules must tolerate out-of-order writes. The delivery guarantees a queue gives you become part of the cache design, because the write-behind queue is now a queue with all the usual failure modes.
Write-around is the quiet option: skip the cache on write, let the next read fill it. You avoid cache churn on data you write once and rarely read, such as logs, archives, or large documents. The cost is that the first read after a write always misses. For write-once data, that is a fine trade.
People often list read-through beside these, but it answers a different question. In read-through, the cache itself loads from the store on a miss; in cache-aside, your application does. That is a code organisation choice, not a freshness or durability choice. Do not let it into the same comparison table as write-behind. The two sit on different axes.
Why Is Invalidation the Hard Part?
Invalidation is hard because a TTL is a guess and an event is a promise, and most systems need both.
Start with what a TTL actually does. Redis does not delete a key at the instant its timer ends. Redis keys are expired in two ways: a passive way and an active way.
A passive expiry happens when a client touches the key. An active expiry samples keys in the background. Between those two, an expired key can sit in memory, invisible to reads but still occupying space. Build correctness on the read behaviour, never on the exact second of deletion.
A TTL also gives you a worst-case staleness bound, not a freshness guarantee. If your product can tolerate ten minutes of stale data, a ten-minute TTL is honest. If it cannot, a TTL is the wrong tool, and you need invalidation on write.
The practical default is a versioned key plus delete-on-write plus a TTL as a backstop. The version prefix lets you invalidate a whole family of entries by changing one number, which is faster and safer than scanning for keys. The delete handles the common case. The TTL handles the writes that slipped past your delete: the batch job, the failed message, the deploy that changed the serialisation format.
Long TTLs need a second mechanism for downstream trouble. AWS uses two: a soft TTL and a hard TTL. The client refreshes when the soft TTL expires. If the downstream service is unavailable, the client keeps serving the existing copy until the hard TTL. That converts a dependency outage into a stale-read window instead of an error page. You can see the same idea in HTTP: RFC 5861 defines stale-while-revalidate and stale-if-error so a shared cache can serve a stale response while it refreshes, or when the origin fails.
Cache the misses too. AWS recommends a negative cache with its own, shorter TTL. Without one, every request for a deleted or nonexistent row hits the database, which is a cache miss you created on purpose. The negative entry costs a little memory and removes a reliable way to overload your store.
What Is a Cache Stampede, and Why Does It Look Like an Outage?
A cache stampede happens when many requests miss the same key at the same moment and all recompute the same value, so one expiry becomes a burst of duplicate work.
The VLDB paper on probabilistic early expiration gives the canonical description: When a frequently-accessed cache item expires, multiple requests to that item can trigger a cache miss and start regenerating that same item at the same time. This phenomenon, known as cache stampede, severely limits the performance of databases and web servers.
Do the arithmetic. Suppose one product key serves 2,000 reads per second, and rebuilding it takes 200 milliseconds. At the instant the key expires, roughly 400 requests arrive inside the rebuild window, and every one of them misses. All 400 run the same query. Your database handles the handful of misses a healthy cache produces, not 400 identical reads in a fifth of a second.
The damage compounds. A cache stampede is often referred to as a cascading failure because several concurrent re-computations will increase the time of each individual recomputation by bogging down the system.
A slower rebuild widens the window. A wider window admits more requests. More requests slow the rebuild further. That is a feedback loop, and it is why the incident looks like a capacity problem when it is really a concurrency problem.
Facebook measured the effect on its memcache deployment. On keys susceptible to thundering herds, the peak database query rate without leases was 17K/s. With leases, it was 1.3K/s. Same traffic, same cache, one mechanism that stopped duplicate rebuilds. The paper describes the underlying condition directly: A thundering herd happens when a specific key undergoes heavy read and write activity.
Notice what that definition implies. A stampede needs a hot key, a miss, and concurrency. You can remove any one of the three, and each removal is a different design move.
How Do You Stop a Stampede?
Stop a stampede by collapsing duplicate work, serving a stale copy while one request refreshes, or spreading expiry so keys do not all die together. Apply them in that order.
Collapse duplicate work first. Request coalescing, also called single-flight, lets one request rebuild the value while the others wait for it. AWS describes the mechanism as ensuring only one pending request is out for uncached resources.
An in-process map of in-flight keys is a few lines and removes the duplicate work inside each server. It does not coordinate across servers, so twenty instances can still send twenty rebuilds. That is the right first move because it is cheap and local.
Serve something stale. If the old value is still usable, return it while one request refreshes. This is the soft-TTL idea again, and HTTP has a standard version: stale-while-revalidate. A stale response with a known age usually beats a timeout, and it removes the thundering herd entirely for that key. The limit is product tolerance, not infrastructure. A price can be a minute old. An account balance cannot.
Add jitter to TTLs. If ten thousand keys all expire on the hour, you get a wave of misses even with no hot key. Randomise each TTL by a few percent, and the wave spreads. Redis's guide to the thundering herd recommends this, and it is the same reasoning behind jittered retries. Jitter is cheap and effective for a large key set. It does nothing for a single hot key, because that key has one expiry and one herd. Do not confuse the two problems.
Use probabilistic early expiration for hot keys. Instead of waiting for expiry, each request makes a small random decision to refresh early, with the probability rising as the deadline approaches. The XFetch paper formalises this, and Rails ships a simpler version as race_condition_ttl: it Specifies the number of seconds during which an expired value can be reused while a new value is being generated.
The first process to notice refreshes; the others reuse the old value during the window. You get one rebuild without a lock.
Use a distributed lock only when you must. A per-key lock in Redis or memcached stops cross-server duplicate work, and nginx offers the same idea inside a cache: proxy_cache_lock allows only one request at a time ... to populate a new cache element
. But a lock adds a new failure mode: the holder crashes, the lock expires, and every waiter races to become the new holder. Treat this as an efficiency lock. Martin Kleppmann's distinction is the right frame: a lock taken for efficiency costs you a duplicate computation when it fails, while a lock taken for correctness can corrupt state. A stampede lock is the first kind. Do not build your consistency on it.
The order matters because the cheap fixes cover most of the damage. Coalescing plus stale serving handles the hot-key case. Jitter handles the many-keys case. The distributed lock is the expensive last resort for a key so hot that even one rebuild per server is too many.
What Else Breaks When the Cache Does?
Four things break around a stampede: a cold cache, a hot key, eviction, and the fallback you wrote for the outage.
Cold start. A deploy, a cache flush, or a new autoscaled instance begins with an empty cache. Every instance then rebuilds the same popular keys at once. Coalescing helps inside a process, and cache warming helps across the fleet: preload the top keys before the instance takes traffic. AWS names cold starts as a first-order risk, not a deployment detail.
Hot keys. One key can exceed what a single cache node can serve, no matter how much memory the cluster has. A bigger cache does not fix this; the key still lands on one node. Why a bigger cache does not fix a hot key is the scaling version of the same argument. The fixes are local caching with an invalidation channel, key splitting, or a read replica for that key. Redis client-side caching exists for exactly this: keep a local copy and let the server push invalidation messages when the value changes.
Eviction. When memory fills, the eviction policy decides what dies. Redis's noeviction policy is honest and brutal: Keys are not evicted but the server will return an error when you try to execute commands that cache new data.
A cache that rejects writes is a cache that has become a failing dependency. LRU is also approximate: The Redis LRU algorithm uses an approximation of the least recently used keys rather than calculating them exactly.
If a hot key gets evicted under memory pressure, you get a stampede with no expiry involved.
The fallback itself. This is the one that turns a cache incident into a database incident. When the cache is down, the obvious fallback is to read the database on every request. Do that during an outage and you send your full production read load to a store that handles a fraction of it. AWS warns that The cache fleet can often be less available
than the service it protects, and that the fallback can cause an atypical spike in traffic to the downstream service
. Cap the fallback rate, shed load, or serve stale. Test with the cache disabled before you need to. The availability budget the cache sits inside is the wider version of this trade.
Cache penetration belongs here too. Requests for keys that do not exist never hit a cached value, so every one reaches the database. A negative cache with a short TTL closes the hole. Without it, an attacker or a broken client can drive load with keys that will never exist.
Which Caching Strategy Should You Choose?
Choose in this order: prove the cache is worth having, default to cache-aside, add write-through only where freshness is a requirement, and design the failure path before launch.
- Measure the hit ratio you expect. If the same result does not serve multiple requests, skip the cache. A cache with a low hit rate is a network hop with extra failure modes.
- Start with cache-aside, delete on write, and a TTL. This is the default because it fails soft and because it needs no special cache features. Version the keys if you need family-level invalidation.
- Add write-through only on the paths that need read-after-write freshness. Keep the set small. Every additional write path is another place where the guarantee can break.
- Choose write-behind only with a durable queue and an explicit loss budget. If you cannot describe which writes you are willing to lose, you are not ready for it.
- Before launch, add coalescing, stale serving, and negative caching. Then run a load test with the cache turned off. The test tells you whether your fallback is a plan or a hope.
The pattern you pick matters less than the contract you write down. Who owns the truth? How stale may a copy be? What does a request do when the copy is missing, and who is allowed to rebuild it? A cache that answers those three questions is an asset. A cache that does not is a dependency you forgot you had, and it will introduce itself at the worst possible moment.
The system design procedure puts this contract in the same sequence as your consistency model, your failure domains, and your capacity plan. Caching is not a layer you add at the end of that sequence. It is one of the places where the sequence becomes visible.
Related Reading
How to Design a Distributed System: Six Decisions in Order
You design a distributed system by making six decisions in order — where state lives, how many copies exist, how those
Strong vs Eventual Consistency: What Your Users Actually Notice
You have probably shipped this bug.
Queues vs Streams: When Should You Use Each?
You have something writing records in one service and something else needing them in another.