SteelReed

Search

Search posts, questions…

Caching & RedisQuestion 13 / 24

Middle

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.

AFTER_COMMITa few hundred ms laterWrite the DBCommitDEL keyDEL againNext read loads fresh value

3 points to say:

  1. Delete, don't update: two writers updating the cache can arrive out of order, leaving an old value until the TTL ends.
  2. Write DB → commit → delete; in Spring use @TransactionalEventListener(AFTER_COMMIT), never delete inside the @Transactional method.
  3. 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.