Video in progress
What is wrong with this update order in cache-aside?
public void updatePrice(long courseId, BigDecimal price) {
redis.set("course:" + courseId, toJson(new Course(courseId, price)));
courseRepository.updatePrice(courseId, price);
}
Updating the cache and writing to the DB aren't atomic: with two parallel writes, a stale value stays in the cache. Usually you write to the DB first and then delete the cache key (delete, not update), and a short TTL covers the remaining cases.
📖 Answer
There are two problems here.
The first is the order. The cache was updated, then the DB write failed with an exception (a constraint, a timeout). Now the cache holds a price that isn't in the DB, and everyone sees it until the TTL runs out.
Worse than that — parallel writes. A changes the price to 100, B to 120:
A: redis.set(100)
B: redis.set(120)
B: db.update(120)
A: db.update(100) // 100 in the DB, 120 in the cache — inconsistent forever (until the TTL)
In practice I write it like this:
@Transactional
public void updatePrice(long courseId, BigDecimal price) {
courseRepository.updatePrice(courseId, price);
}
@TransactionalEventListener(phase = AFTER_COMMIT)
void onPriceChanged(PriceChanged e) {
redis.delete("course:" + e.courseId()); // the next read takes it from the DB
}
Why delete: deletion is idempotent, and order doesn't matter. Whoever deletes first, the next reader loads the latest value from the DB.
But even this isn't 100%: if a reader has already read the old value from the DB but hasn't yet managed to write it to the cache, and the writer deletes in that window, the old value ends up in the cache. The probability is small, which is why a TTL is still set. If you need a stricter guarantee — invalidation through CDC (from the binlog/WAL) or a "delayed double delete".
Sign up to mark studied questions and save your progress.