Publish cache invalidation after the database commits so a failed transaction cannot leave readers with an impossible state.
Spring cache after commit: keep rolled-back writes out of readers
The database decides first
A receipt update can pass validation, write a row and still roll back when a later constraint fails. Updating a shared cache inside that transaction lets another request observe a value the database never committed. An after-commit event moves invalidation to the success side of the boundary. Eviction then makes the next read load durable state. The event handler below is short and deliberately does not contact another service.
Know the remaining gap
After-commit work runs in the same process and can be lost if the process stops between commit and eviction. Give entries a bounded TTL, and use a durable change record when strict cross-node invalidation is required. A transaction-aware cache decorator can defer ordinary put, evict and clear operations until commit, but immediate atomic operations such as putIfAbsent have different timing. Read the behavior of the chosen CacheManager rather than assuming every cache action is deferred.
Test two timelines
First commit a receipt edit and verify that a subsequent reader sees the new stored value. Then force a rollback after the edit and verify no invalidation event ran. Exercise a node restart just after commit: TTL should eventually repair the stale entry, while a durable relay is needed for a tighter freshness guarantee. Transaction events and an outbox relay define those different delivery promises.
Implementation contract
@Component
final class ReceiptCacheInvalidator {
private final CacheManager cacheManager;
ReceiptCacheInvalidator(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void on(ReceiptChanged changed) {
Cache receiptCache = cacheManager.getCache("receipt-view-v3");
if (receiptCache != null) receiptCache.evict(changed.cacheKey());
}
}Cost and verification
An invalidation adds one cache write after each committed edit and the next read pays a cache miss. A durable relay adds storage and retry work, but closes the process-crash gap that an in-memory event cannot close.
Common Mistakes
- Do not populate shared cache state from a transaction that may roll back.
- Do not assume an after-commit in-memory handler is durable across process failure.
- Do not assume every atomic cache operation waits until commit.
Read next
Spring cache eviction: invalidate the same tenant key used by the read, Spring transaction events: run a listener after commit without claiming durability, Spring outbox relay: claim, deliver, and acknowledge one event, Spring null-result caching: decide whether a miss should survive, Spring Redis cache TTL versus idle expiry: GETEX changes the read contract.
