Cache-aside served the old price for hours because a reader refilled the cache mid-update
Sellers changed prices and some product pages kept showing the old price until the one-day TTL expired. The update deleted the cache key, then wrote the database, and a concurrent reader refilled the cache in between. Timeline, reproduction and the three fixes we combined.
Sellers on our marketplace can change prices at any time. Support received a complaint from a seller who had lowered a price for a sale: the product page still showed the old, higher price six hours later, but the checkout charged the new one. Customers were confused, and some abandoned the purchase.
It did not happen every time. We counted price-change events against cached prices with a script that compared Redis with the database for every product changed in the last day:
checked 18,412 recently updated products
mismatched cache entries: 37 (0.20%)
oldest mismatch: 21h 12m since update
About one in five hundred price changes left a stale value in the cache, and stale values lived until the TTL expired, which was 24 hours.
The code
Reads used cache-aside: try the cache, fall back to the database, then fill the cache.
def get_product(product_id: int) -> dict:
key = f"product:{product_id}"
cached = redis.get(key)
if cached:
return json.loads(cached)
product = db.fetch_product(product_id) # SELECT ... FROM products
redis.set(key, json.dumps(product), ex=86400)
return product
Writes invalidated the cache:
def update_price(product_id: int, price: int) -> None:
redis.delete(f"product:{product_id}") # 1. invalidate
db.execute("UPDATE products SET price = %s WHERE id = %s", (price, product_id)) # 2. write
db.commit()
The comment on the delete said "invalidate first so nobody reads the old price". That ordering is the bug.
The race, step by step
Consider a product page being viewed often (as sale items are) while the seller updates the price:
| Time | Writer (update_price) | Reader (get_product) | Cache | Database |
|---|---|---|---|---|
| t1 | delete key | empty | price 2499 | |
| t2 | cache miss | empty | 2499 | |
| t3 | read DB: 2499 | empty | 2499 | |
| t4 | UPDATE, COMMIT | empty | 1999 | |
| t5 | set key = 2499 | 2499 | 1999 |
The reader started after the delete and read the database before the writer committed. It then wrote that old value to the cache after the writer had finished. The cache now holds the old price, and nothing will remove it until the TTL expires. The writer's delete had already happened; there is no second invalidation.
The window is the time between the reader's database read (t3) and its cache write (t5), overlapping the writer's update (t4). On a busy product with many concurrent readers, that overlap happens regularly.
Why "write first, then delete" is better but not perfect
Reversing the order, update the database then delete the key, closes most of the window: after the delete, any reader goes to the database and sees the committed new value. But a narrower race remains:
| Time | Writer | Reader | Cache | Database |
|---|---|---|---|---|
| t1 | cache miss (key just expired) | empty | 2499 | |
| t2 | read DB: 2499 | empty | 2499 | |
| t3 | UPDATE, COMMIT | empty | 1999 | |
| t4 | delete key | empty | 1999 | |
| t5 | set key = 2499 | 2499 | 1999 |
This requires the reader's database read to happen before the commit and its cache write to happen after
the delete. That is rare, because a cache write right after a database read is usually much faster than an
update plus commit, but under GC pauses or network jitter it can still occur. The general lesson is that
cache-aside with plain SET cannot be made perfectly consistent with ordering alone.
Environment
| Item | Value |
|---|---|
| Cache | Redis 7.2, single primary with replica |
| Database | PostgreSQL 16 |
| App | Python 3.12 web workers, about 30k product reads per second at peak |
| TTL | 24 hours |
| Stale rate | about 0.2% of price changes |
We combined three changes: correct ordering, a guard against stale fills, and a TTL that bounds the damage.
1. Write the database, then delete the cache
def update_price(product_id: int, price: int) -> None:
with db.transaction():
db.execute("UPDATE products SET price = %s, version = version + 1 WHERE id = %s",
(price, product_id))
redis.delete(f"product:{product_id}") # after commit
The delete runs after the commit. If the delete fails (Redis unavailable), we log and enqueue a retry; the TTL is the last line of defence.
2. Version the value so a stale fill cannot overwrite a fresh one
We added a version column to products, incremented on every update. The cached value carries the
version it was read at, and the cache write only succeeds if it would not replace a newer version. A small
Lua script makes the compare-and-set atomic in Redis:
-- KEYS[1] = cache key, ARGV[1] = version, ARGV[2] = payload, ARGV[3] = ttl seconds
local current = redis.call('HGET', KEYS[1], 'v')
if current and tonumber(current) >= tonumber(ARGV[1]) then
return 0
end
redis.call('HSET', KEYS[1], 'v', ARGV[1], 'data', ARGV[2])
redis.call('EXPIRE', KEYS[1], ARGV[3])
return 1
On its own this does not help after a delete, because an empty key has no version to compare against. So on update, instead of deleting, we write a tombstone with the new version and no data:
def update_price(product_id: int, price: int) -> None:
with db.transaction():
new_version = db.fetchval(
"UPDATE products SET price = %s, version = version + 1 WHERE id = %s RETURNING version",
(price, product_id))
redis.hset(f"product:{product_id}", mapping={"v": new_version, "data": ""})
redis.expire(f"product:{product_id}", 300)
A reader that finds a tombstone treats it as a miss and loads from the database. When a slow reader that loaded the old row (version 7) tries to fill the cache, the script sees version 8 already present and refuses. Only a reader that loaded version 8 or later can fill it.
3. Shorter TTL as a backstop
We lowered the product TTL from 24 hours to 10 minutes. With the first two fixes, stale entries should not occur at all; if a bug elsewhere ever leaves one, it now lives minutes, not a day. The hit rate barely changed (from 98.9 percent to 98.4 percent), because popular products are re-read constantly and refill quickly.
Things we considered and rejected
- Delete twice (before and after the write, sometimes with a delay). This narrows the window further, but it is a timing heuristic, and it doubles invalidation traffic.
- Write-through (the writer sets the new value in the cache). This has its own race when two writers update the same product concurrently, and the cache can end up holding the older write. With versions it works, but the tombstone approach gave us the same guarantee with less code.
- Change data capture (invalidate from the database's change stream). The strongest option, and the direction we may take as the number of writers grows, but more infrastructure than this problem needed.
1. A deterministic reproduction. We wrote a test that forces the interleaving with events, so it fails reliably on the old code instead of occasionally:
def test_slow_reader_cannot_restore_old_price(redis, db, product):
reader_read_db = threading.Event()
writer_done = threading.Event()
def slow_reader():
row = db.fetch_product(product.id) # reads old version
reader_read_db.set()
writer_done.wait()
cache_fill(product.id, row) # tries to write old version
t = threading.Thread(target=slow_reader); t.start()
reader_read_db.wait()
update_price(product.id, 1999)
writer_done.set(); t.join()
assert get_product(product.id)["price"] == 1999
The old code returned 2499. The new code returns 1999.
2. Production comparison. The same mismatch script now runs every 15 minutes. Over three weeks it has reported zero mismatches older than the update propagation time (under one second).
3. Load. The Lua script adds one round trip per cache fill, which only happens on misses. Redis CPU went up by about 2 percent, and p99 product read latency did not change measurably.
4. Security and business implications. A stale price shown on the page while checkout charges another is a consumer protection issue in some jurisdictions. Checkout always reads the price from the database, and it now also shows a clear message if the price changed since the page was loaded, so the customer never pays an amount they were not shown.
Takeaways
- Deleting the cache before writing the database lets concurrent readers refill it with the old value.
- Write the database first, then invalidate. That closes most, but not all, of the window.
- Version cached values and refuse fills older than what is there. Use a tombstone on update so there is always a version to compare against.
- Keep TTLs short enough that any remaining bug has bounded impact.
References: Redis EVAL and Lua scripting, Redis HSET, PostgreSQL UPDATE RETURNING.
Add a label
Embed this post
<iframe src="https://hibug.me/cache-aside-race-stale-after-update" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I work on performance and capacity for a marketplace with heavy read traffic and sharp daily peaks. My days are split between caches, Redis, document stores, connection pools and the load tests that tell us whether any of it will hold. Most of the problems I write about looked like scaling issues and turned out to be something smaller: a cache that refilled itself with stale data, a single command that froze Redis, a pool drained by one leaked connection, a load test that measured its own generator instead of the system. I try hard to measure before changing anything, so each post includes how we gathered numbers, what they showed and how we confirmed the fix under realistic load. I also include the optimisations that made things worse, because those taught me the most.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.