When data changes, should you update or delete the cache key, and write the DB or delete the cache first?
Short answer
By default delete the key instead of updating it, in this order: write the DB, commit, then delete the cache. Deleting is idempotent, so ordering can't go wrong; deleting the cache before the DB write lets a reader load the old value back.
3 points to say:
- Delete, don't update: two writers updating the cache can arrive out of order, leaving an old value until the TTL ends.
- Write DB → commit → delete; in Spring use
@TransactionalEventListener(AFTER_COMMIT), never delete inside the@Transactionalmethod. - Delayed double delete cleans up the rare slow-reader race; TTL is always the last safety net.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.