0% completed
Invalidation Strategies
On This Page
Part 1: Two Copies of One Fact
Part 2: Strategy 1, Let It Expire
Part 3: Strategy 2, Delete on Write
Part 4: Delete After the Commit, Not Before
Part 5: Strategies 3 and 4, Write-Through and Write-Behind
Part 6: Strategy 5, Event-Driven Invalidation
Part 7: Choosing a Strategy
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways
Software engineers often repeat a line attributed to Phil Karlton. It says, "There are only two hard things in computer science: cache invalidation and naming things."
Engineers still repeat it because the problem is real. A cache holds a second copy of the data, and the database can change the first copy at any moment without telling the cache. This lesson compares five ways for the cache to find out, and how long each one lets the cache serve a wrong value.
Part 1: Two Copies of One Fact
The running example is the online store from the previous lesson, which caches its product pages for about 10 minutes. Three different writers change product data in the store's database:
- The product service handles sellers' edits.
- A nightly job imports supplier prices.
- An admin tool writes to the database directly.
All numbers in this lesson are made-up examples.
The database is the source of truth, which means its copy is correct by definition. The cache holds a second copy. When one of the three writers changes a price in the database, the cached copy becomes stale: it no longer matches the source of truth. Invalidation is the work of making the cache stop serving a stale value.
There are only three ways to do it:
- Let the entry expire, so the cache removes it on its own.
- Delete the entry, so the next read misses and loads the new value from the database.
- Update the entry, by writing the new value into the cache.
Every strategy in this lesson is built from these three. Parts 2 to 6 cover the five strategies in order, and Part 7 compares them side by side.
Part 2: Strategy 1, Let It Expire
The simplest strategy uses only the first way. As the previous lesson explained, a TTL, or time to live, is how long a cache keeps an entry before it removes it. With TTL alone, a price change shows up within about 10 minutes, no matter which of the three writers made it. Nothing has to run when the price changes.
That last point matters most. Expiry is self-healing. A lost message, a crashed writer, or a bug nobody has found yet can leave a wrong value in the cache, and expiry still removes it within one TTL.
The cost is a trade-off between freshness and load. A short TTL gives fresher data but more database reads. A long TTL gives fewer reads but older data. For this reason, keep a TTL on every entry as a backstop, the mechanism that still limits the damage when the main one fails, even when another strategy does the main work.
Part 3: Strategy 2, Delete on Write
Most products want changes to show up faster than one TTL. To get that, the writer acts on the cache right after it writes to the database. It can update the entry or delete it. Deleting is safer, and the reason is the order in which operations arrive. The diagram below shows two writers changing one price at almost the same moment.
Step 1: Both writers change the database. Writer A sets the price to 35 dollars, then writer B sets it to 30. The database ends at 30.
Step 2: The cache operations arrive in the other order. A network delay holds up writer A, so writer B's cache operation lands first.
Step 3: Compare the results. With updates, writer A's late update leaves the cache at 35, which stays wrong until the entry expires. With deletes, the cache ends empty in either order, and the next read loads 30 from the database.
Notice why delete wins. Two deletes give the same result in any order, and two updates do not. A delete is not faster, and it can still fail, so this order safety is its only advantage.
Delete still leaves one rare gap. A slow reader can load the old price from the database just before a write, then store it in the cache just after the writer's delete. The old price is then back in the cache, and the TTL limits how long it stays there. Each delete also causes a miss, and on a very popular key that miss can start the stampede from Stampede, Thundering Herd, Dogpile.
Part 4: Delete After the Commit, Not Before
Part 3 said the writer deletes the entry after it writes to the database. The exact moment of that delete matters, because database writes usually happen inside a transaction. A transaction is a group of database writes that take effect together, at the moment the transaction commits.
A common bug is to delete the cache entry inside the transaction, before the commit. The diagram below shows a writer and a reader inside that gap.
Step 1: The writer deletes the cache entry. The new price of 30 dollars is written but not yet committed.
Step 2: A reader misses. The database still returns the committed price of 40 dollars.
Step 3: The reader stores 40 dollars in the cache.
Step 4: The writer commits 30 dollars. No second delete is coming, so the cache stays stale until the TTL ends.
Notice that the cache is not part of the database transaction. The delete takes effect at once, while the new value is still hidden from other readers. Under heavy reads, even a short gap is hit often, so delete after the commit, not before.
The same problem can return in a second way. A replica is a copy of the database that receives each change a little later than the main database. If readers refill the cache from a replica that lags behind, they can load the old value and put it back, even after a correct delete.
Part 5: Strategies 3 and 4, Write-Through and Write-Behind
Parts 3 and 4 kept the write path the same and changed what the writer does to the cache afterward. The next two strategies change where the write itself goes. A third pattern, write-around, completes the set.
- Write-through. A write goes to the cache and the database together, and the writer is told it succeeded only after both are done. Readers see the new value at once, but writes are slower, and the cache fills with values that nobody may read. When the application does both writes itself, it is a form of updating, so the ordering problem from Part 3 still applies.
- Write-behind. A write goes to the cache at once, and to the database shortly after, often in batches. Writes are fast, but until the cache sends the write on to the database, the cache holds the only copy. If the cache fails in that time, the write is lost.
- Write-around. A write goes only to the database. The cache fills again on the next read, after a delete or the TTL removes the old entry. Delete on write from Part 3 uses this path.
In the store, write-behind suits a view counter, because losing a few views does little harm. It does not suit stock levels, where a lost write could sell an item the store no longer has.
Part 6: Strategy 5, Event-Driven Invalidation
Every strategy since Part 3 needs the writer's code to take part. In the store, only the product service deletes the cache entry after each commit. The nightly import and the admin tool do not, so their price changes wait for the 10-minute TTL.
The fifth strategy removes that need. A change stream is a feed of every committed change in a database, read from a log the database already keeps. In event-driven invalidation, a small program called a consumer reads this feed and deletes the cache keys that each change affects. The diagram below compares the two paths.
Notice the bottom line of each path: application code catches 1 of the 3 writers, and the change stream catches all 3. This gives two advantages:
- The writer no longer has to take part. The import, the admin tool, and even a one-time migration all invalidate correctly, because every change passes through the log.
- It always fires after the commit. The log holds only committed changes, so the gap from Part 4 cannot open.
It also has three costs:
- A short delay. It is slower than a delete in the write path, often by well under a second, and the delay grows if the consumer falls behind.
- One more system. The consumer is a program the team has to run and watch.
- Key mapping. The consumer must map each changed row to every key it affects, such as the product page, a category page, and search results.
The TTL stays, in case the consumer stops.
Part 7: Choosing a Strategy
The table below compares the five strategies, assuming each one keeps a TTL.
| Strategy | How the cache learns of a change | Worst case for a reader | Main risk |
|---|---|---|---|
| TTL only | It does not, and the entry expires | About one TTL old | The TTL is the delay |
| Delete on write | The writer deletes after commit | A rare race, ended by the TTL | Writers that skip the delete |
| Write-through | The writer updates both copies | Wrong until the TTL, if updates arrive out of order | Writers that skip it |
| Write-behind | The cache takes the write first | The database is behind, not the cache | Lost writes if the cache fails |
| Change stream | A consumer reads committed changes | Behind by the consumer's delay | Consumer lag, missed keys |
For the store, a sound choice is the change stream for prices, because two of its three writers never call the cache. The 10-minute TTL stays as the backstop.
Part 8: Using This in an Interview
The question is often short: "How does the cache stay fresh?" Start from the staleness the product accepts, then name the strategy and its worst case.
"Prices can be a few seconds stale, but not 10 minutes. So a consumer reads the change stream and deletes the affected keys after each commit. That catches the import job and the admin tool. I delete instead of updating, because deletes are safe in any order. Every entry keeps its 10-minute TTL, so a stopped consumer leaves prices at most 10 minutes stale."
Expect two follow-up questions. "What if the consumer falls behind?" Alert on its lag, and say the TTL is the ceiling. "Why not write-through?" It catches only the writers that use it, and updates can land out of order.
Common Mistakes
Mistake 1: Dropping the TTL because writes invalidate. Then any missed delete lasts until someone notices, because nothing else removes the wrong value.
Mistake 2: Updating the cache instead of deleting. Two updates in the wrong order leave a wrong value until the entry expires.
Mistake 3: Deleting before the commit. A reader can refill the cache with the old value during the gap.
Mistake 4: Using write-behind for data you cannot lose. A cache failure before the write reaches the database loses it for good.
Key Takeaways
- Expiry is the self-healing strategy. It needs nothing at write time, so every entry keeps a TTL as the backstop.
- Delete, do not update. Two deletes give the same result in any order, and two updates do not.
- Invalidate after the commit. A delete before the commit lets a reader put the old value back.
- The change stream catches every writer. It fires only after commit, at the cost of a short delay and one more system.
- In a system design interview, start from the staleness the product accepts, then name the strategy, its worst case, and the TTL behind it.
The next lesson, Cache Consistency Trade-offs, turns "how stale" into a number and asks when that number is acceptable.
Reading Progress
0%
On This Page
Part 1: Two Copies of One Fact
Part 2: Strategy 1, Let It Expire
Part 3: Strategy 2, Delete on Write
Part 4: Delete After the Commit, Not Before
Part 5: Strategies 3 and 4, Write-Through and Write-Behind
Part 6: Strategy 5, Event-Driven Invalidation
Part 7: Choosing a Strategy
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways