Video in progress
In this code, in what situation does a stale value stay between the cache and the DB for a long time?
public Product get(long id) {
Product p = cache.get(id);
if (p == null) {
p = repo.findById(id).orElseThrow();
cache.put(id, p); // TTL 1 hour
}
return p;
}
@Transactional
public void updatePrice(long id, BigDecimal price) {
cache.evict(id);
repo.updatePrice(id, price);
}
There's a race between two requests: a reader fetched the old value from the DB, meanwhile the writer updated the DB and evicted the cache, and then the reader put the old value into the cache. Now the stale value stays until the TTL expires.
📖 Answer
There are two problems here.
The first is obvious: evict is called before the transaction commits. The sequence:
- Writer:
cache.evict(id). - Reader: the cache is empty, reads from the DB — the transaction isn't committed yet, the old price.
- Reader: puts the old price in the cache.
- Writer: commit.
The result is the old price for 1 hour. The fix: evict after the commit.
@Transactional
public void updatePrice(long id, BigDecimal price) {
repo.updatePrice(id, price);
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { cache.evict(id); }
});
}
Or through @TransactionalEventListener(phase = AFTER_COMMIT).
The second is subtler and remains even when you evict after the commit: a reader fetched the old value from the DB, then stalled (a GC pause), meanwhile the writer updated and evicted, and then the reader wrote the old value. The probability is small, but it does happen under load.
Against it:
- a short TTL — even if it goes wrong, it doesn't live long;
- a "delayed second eviction": evict after the commit, then evict once more 1–2 seconds later;
- writing with a version: store a
versionfield in the value and don't allow writing an older one than what's in the cache (with a Lua script).
For critical data like the price or stock level, at order time look at the DB, not the cache.
Sign up to mark studied questions and save your progress.