跪拜 Guibai
← All articles
Backend · Interview · Java

MySQL and Redis Dual-Write Consistency: Cache-Aside, Delayed Double Delete, and the Binlog Endgame

By Rain的Java大神之路 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Stale cache data is a production incident, an interview topic, and an architecture decision all at once; the choice between a simple Cache-Aside with TTL and a full Canal/binlog pipeline determines how much latency, complexity, and dirty-data risk a team accepts.

Summary

Every backend team eventually hits the same phantom: the database says in stock, Redis says sold out. The cause is dual-write inconsistency between MySQL and Redis, and the standard remedy is Cache-Aside: update the database first, then delete the cache key after the transaction commits. The article walks through the race conditions that make the naive version unsafe, including the transaction-boundary trap where deletion runs before commit, and explains why delete beats update for invalidation.

When the basic pattern is not enough, two hardening layers apply. Delayed double delete closes the concurrent read-write backfill window with a second, asynchronously delayed deletion. For deletion failures, MQ retry or a local retry table written in the same transaction as the business SQL guarantees the eviction eventually happens. The terminal architecture is Canal subscribing to MySQL binlog: business code only writes the database, Canal feeds change events to MQ, and consumers delete cache keys with idempotency, retry, and dead-letter handling.

The article also covers read-side protections (TTL with jitter, mutex rebuild, Bloom filters, logical expiration), the cost of forcing strong consistency with Redisson read-write locks, and a selection matrix matching business tiers to solution combinations.

Takeaways
— The root of MySQL/Redis inconsistency is that two independent stores have no atomic distributed commit; concurrency races, operation failures, and primary-replica lag create the windows.
— Cache-Aside means updating the database first, then deleting the cache key after the transaction commits; the dirty-data window requires the read's query-to-writeback time to exceed the write-plus-delete time, which is rare in practice.
— Deleting a cache key is preferred over updating it because concurrent writes can cross and overwrite newer values, recomputing aggregates is expensive, and DEL is idempotent and lazy-loading friendly.
— The transaction-boundary trap: putting redisTemplate.delete() inside a @Transactional method deletes before commit; use TransactionSynchronizationManager afterCommit or @TransactionalEventListener(AFTER_COMMIT) instead.
— Delayed double delete adds a second asynchronous deletion after a delay to clear old values written back by concurrent reads; the delay should exceed primary-replica sync time plus one read write-back, commonly 500ms to 1s.
— Deletion failure needs compensation: local immediate retry, MQ async retry with persistence and manual ACK, or a local retry table written in the same transaction as the business SQL so the task is never lost.
— Canal subscribes to MySQL binlog and delivers change events to MQ, so cache invalidation is fully decoupled from business code; operations that bypass the application layer are still captured.
— Canal consumer details include filtering DDL, deleting by primary key, routing by partition hash to preserve per-row order, idempotency via message ID plus Bloom filter and Redis, and persisting binlog position/GTID for resumable sync.
— Read-side defenses: mandatory TTL with random offset, mutex lock plus double-check for hot-key rebuild, Bloom filter plus short-TTL empty values for penetration, logical expiration for extreme hot spots, SCAN/UNLINK for large keys, and DB fallback when Redis is down.
— Strong consistency costs throughput: Redisson read-write locks serialize writes and block reads, and should be limited to a few keys like inventory and balances; Redis cannot roll back, so dual-write consistency is an eventual consistency problem, not a distributed transaction problem.
— For ordinary business, Cache-Aside plus TTL is enough; complex systems can use Canal plus MQ; the highest-reliability paths combine update-DB-first, delayed double delete, and binlog/MQ fallback.
— Post-launch monitoring should track cache hit rate, cache deletion failure rate, MQ backlog, and Canal sync delay, with a scheduled reconciliation task as final backup.
Conclusions

The article's core stance is that absolute consistency between MySQL and Redis is the wrong goal; the design objective is to shrink the inconsistency window until the business cannot feel it and let TTL converge the rest.

The local retry table is a genuinely useful pattern: putting the eviction task in the same transaction as the business update turns a two-phase problem into one atomic decision, at the cost of an extra table and scheduled job.

Binlog subscription changes the trust boundary: business code no longer needs to remember to invalidate cache, and even ad-hoc database edits or batch scripts get captured, which manual dual-write cannot match.

The article is aimed squarely at interview preparation and production troubleshooting in Chinese backend teams, so its recommendations are tuned to common Java/Spring stacks with Redisson, RocketMQ, RabbitMQ, and Canal.

Many of the failure modes described, like the transaction-boundary deletion trap and primary-replica lag backfill, are subtle enough that teams often discover them only after an incident.

Concepts & terms
Cache-Aside
A caching pattern where reads check the cache first and fall back to the database on a miss, and writes update the database first then invalidate the cache key, leaving the cache to be rebuilt lazily by the next read.
Delayed Double Delete
A hardening technique that deletes the cache key before updating the database and again after a short delay, clearing any stale value a concurrent read wrote back during the update window.
Canal
A Java tool that connects to MySQL as a fake replica, parses the binary log (binlog), and publishes row changes to MQ so other systems, such as cache invalidators, can react without business code doing the dual write.
Binlog
MySQL's binary log, an append-only record of all changes to the database. Because it is written by the database itself, any successful write is guaranteed to appear in it, making it a reliable source for change data capture.
Logical expiration
Instead of setting a real TTL, the cached value stores an expiration timestamp inside it; a read that finds the value logically expired returns the old value while an async thread rebuilds the cache, trading brief staleness for availability.
Cache breakdown / penetration / avalanche
Three distinct cache failure modes: a hot key expiring and letting a burst of requests hit the database, requests for nonexistent keys always bypassing the cache, and many keys expiring at once causing a large load spike. They are often confused with consistency issues, but consistency is about old versus new data while penetration is about whether data exists.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗