You clear the cache on every update. Why does old data return?
Question
A shop caches prices with the code below. On a miss, read_price loads the price from the database and caches it. update_price saves the new price and deletes the cache entry.
Product 42 costs 10. An editor changes it to 12. Sometimes the page keeps showing 10 long after the update.
Find the order of events that causes this. Then change the design so a slow read can never put an old price back.
def read_price(product_id): price = cache.get(product_id) if price is None: price = db.load_price(product_id) # can be slow cache.set(product_id, price) return price def update_price(product_id, new_price): db.save_price(product_id, new_price) cache.delete(product_id)
Show hints (3)
- "FIND THE GAP"
read_priceloads the price, then writes it to the cache. What if all ofupdate_priceruns between those two lines? - "WHAT TO COMPARE"
Give each price a version that goes up on every update. When a read fills the cache, it sends the version it loaded. What should the cache compare it with?
- "WHERE IT LIVES"
Store the version apart from the value, so a delete can't erase it. Drop any fill with an older version, in one atomic step.
Show checked explanation
A slow read loaded 10. Meanwhile an update saved 12 and deleted the entry. Then the slow read wrote 10 back. Fix: give each price a version. The cache keeps the current version per key and drops older fills, comparing and writing in one atomic step.
class VersionedCache: def __init__(self): self.entries = {} # key -> (version, value) self.current = {} # key -> current version; survives deletes def invalidate(self, key, new_version): self.current[key] = new_version self.entries.pop(key, None) def fill(self, key, version, value): # one atomic step in a real cache if version < self.current.get(key, version): # no version yet: accept return False self.entries[key] = (version, value) return True cache = VersionedCache() cache.invalidate(42, 8) # update: 12 saved as version 8 print(cache.fill(42, 7, 10), cache.entries) # slow read from version 7 print(cache.fill(42, 8, 12), cache.entries) # new read from version 8
False {}
True {42: (8, 12)}Code run on CPython 3.12 against every order of two reads and one update. Checked by an editor other than the author.
Walkthrough
This is a race condition: the result depends on the timing of two requests. This order breaks the code:
| step | what happens | database | cache |
|---|---|---|---|
| 1 | Read A misses, loads 10, then pauses | 10 (v7) | empty |
| 2 | Update saves 12 and deletes the entry | 12 (v8) | empty |
| 3 | A wakes up and writes 10 | 12 (v8) | 10 |
From step 3 on, every reader gets 10. The delete came too early to help.
The fix is a check at fill time, when a read writes into the cache. Each price row in the database gets a version that goes up on every update:
- A read loads the price and its version in one query.
- An update saves 12 as version 8 and tells the cache: version 8 is current, drop the entry.
- The cache rejects a fill whose version is older than the current one.
A's fill has version 7, so it is rejected and the cache stays empty. The next read fills it with 12 at version 8. A key with no version yet has had no update, so its fill is accepted.
Two details make this safe. The version is stored apart from the value, so the delete can't erase it. And the compare and the write are one atomic step, so no update can run between them.
Common mistakes
- Making the read faster. The bug is the order of events, not the speed. Any pause, retry or slow network still opens the gap.
- Relying on the TTL (expiry time). It starts at the fill, not the read. Read at second 0, update at 1, fill at 2, 30-second TTL: the old price is served until second 32.
- Letting the version disappear. If it lives only inside the cached entry, the delete removes it and a late fill wins. A cache restart or eviction during a slow read does the same.
- Keying the cache by product id alone when the price also depends on currency or customer group. Buyers then get each other's prices. The key needs everything the price depends on.
Follow-up questions
- "What if the database and the cache are separate servers?" The cache must still compare and write in one step. Redis can do this with Lua. But the database commit and the call that sets the new version are two steps. If that call is lost, the cache keeps the old price. Retry it, and keep a TTL as a last limit.
- "How would you test this?" Force the order instead of using sleeps: A loads, the update runs, A fills. The cache must be empty. Then try every order and assert that no old version is ever cached.
- "What does A return after its fill is rejected?" A can still return 10 to its caller. It started before the update finished, and 10 was correct when it read. Just don't cache it. If the caller needs the newest price, read again, but limit the retries: the price may keep changing.
What a strong answer covers
Draws the order of events that brings the old price back. Explains why the delete and the TTL don't stop it. Proposes a versioned fill, checked atomically, with the version kept apart from the value.
Open in interactive practice deck →