MySQL and Redis Dual-Write Consistency: Cache-Aside, Delayed Double Delete, and the Binlog Endgame
MySQL and Redis Dual-Write Consistency: From Cache-Aside to Binlog Fallback, Explained in Full
Author: Rain的Java大神之路 Tags: Backend, Interview, Java
There is stock in the online database, but the cache shows no stock. This kind of "occasionally inconsistent" mystery is most likely caused by MySQL and Redis dual-write consistency. It is also nearly a guaranteed backend interview question. Many people memorize answers, but few can actually explain it. This article explains the problem principle, mainstream solutions, production-grade code, pitfalls, and selection strategies in full. It is suitable for frontline developers who have been tormented by this problem, and also for students preparing for interviews.
1. First figure out: where does the inconsistency come from?
Many students immediately agonize over "delete cache first or update database first". That direction is actually off. You must first understand the root of the inconsistency.
MySQL is about ACID, Redis pursues extreme performance. Two independent storage systems, two engines, are naturally not on the same page. There is no atomic distributed commit across storage: after the database transaction commits, the Redis deletion does not necessarily succeed; after Redis deletes, the database update may also roll back. As long as concurrency exists and network exists, the window of inconsistency always exists.
Break it down further, inconsistency has three sources:
| Root | Explanation |
|---|---|
| Concurrency race | Read/write timing crosses, old values are written back into the cache |
| Operation failure | DB update succeeds, cache operation fails, or the reverse |
| Primary-replica lag | After writing to the primary, reading from the replica, the replica's old data is written back into the cache |
Corresponding to production, these are three classic failure scenes:
| Failure scene | Process | Result |
|---|---|---|
| DB write succeeds, cache deletion fails | Thread A updates DB -> Redis deletion fails -> Thread B reads old cache | Dirty data persists |
| Delete cache first, DB update fails | Thread A deletes Redis -> DB write fails and rolls back -> cache empty, DB old | Old value reseeded, long-term dirty |
| Concurrent read/write out of order | Thread A deletes cache + writes DB, Thread B reads old DB value and writes cache | Redis stores old value |
The most typical race condition timeline looks like this:
Time T1: Read request A cache miss, queries DB and gets old value V1 Time T2: Write request B updates DB to V2, then deletes the cache Time T3: Read request A slowly writes V1 back into the cache Result: DB is V2, cache is V1, dirty data lives until TTL expires
This window is usually only a few milliseconds to tens of milliseconds, but under high concurrency it is not unusual to hit it several times a day. So the core of solution design is one sentence: compress the window as much as possible, and make failures have a fallback.
Set the goal correctly: do not promise absolute strong consistency. If you force distributed transactions or global locks, throughput collapses, and the cache loses its meaning. The common practice at big companies is: accept a very short inconsistency window, use an eventual consistency solution to compress the window until the business cannot feel it, and use TTL as the final fallback for all anomalies.
One sentence to set the tone: the database is the truth, Redis is only a shadow. Write operations are only responsible for invalidating the shadow, not redrawing it.
Now that the root cause is clear, do not rush to prescribe medicine. There are several seemingly natural solutions that are accidents if used.
2. First remove landmines: these three solutions must not be used naked
| Wrong solution | Fatal problem |
|---|---|
| Update Redis first, then update MySQL | Redis succeeds, MySQL fails -> cache has it, database does not -> permanent inconsistency |
| Update MySQL first, then update Redis | Concurrent writes cause the database order and cache order to cross, write overwrite leaves old values |
| Add distributed locks to all reads and writes | Throughput collapses, Redis cache loses its meaning |
The second one is the most subtle. Draw a timeline and it shows its true shape:
This leads to the first frequently asked follow-up question of this topic.
Why "delete the cache" instead of "update the cache"?
Three reasons, say them in order in an interview:
- Concurrent writes can overwrite each other. The order in which two write threads update the database and the order in which they update the cache may cross, and a later write's old value overwrites an earlier write's new value.
- Recomputation cost is high. Cache values are often aggregates from multiple-table JOINs. Every write to the database would trigger a full recomputation, wasting CPU and write performance.
- Deletion naturally fits lazy loading. After deletion, the next read goes back to the source to rebuild. If no one reads it, it does not occupy memory. Also,
DELis idempotent; repeated execution or out-of-order execution is not a problem.
Key point: the cache is derived data. Write operations only invalidate it; rebuilding is left to read requests. The less state you maintain, the lower the probability of errors.
Landmines cleared, the protagonist arrives.
3. Main solution: Cache-Aside, update database first, then delete cache
This is the Cache Aside Pattern known in the industry, used in Facebook's classic paper as well. More than 90% of internet businesses can blindly choose it.
The process is two sentences:
- Read: read Redis first; if hit, return directly; if miss, read MySQL, write back to Redis (must include expiration time).
- Write: update MySQL first, then delete the corresponding key in Redis.
Why is it reliable? Extreme timeline analysis
The only dirty-data window of "update database then delete cache" requires three conditions to hold simultaneously:
- The cache happens to expire, read thread A queries DB and gets the old value, but has not yet written it back.
- Write thread B completes the DB update and deletes the cache.
- Thread A slowly writes the old value back into the cache.
In other words, the time from "querying the database to writing back" for a read request must be greater than the total time of "writing the database + deleting the cache". In real business, reads are usually faster than writes, so this condition is extremely harsh, the probability is extremely low. Combined with TTL as a fallback, it can basically be ignored. This "reason why the probability is extremely low" is itself an interview bonus point, worth remembering separately.
Basic version code
@Service
public class UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserMapper userMapper;
private static final String USER_KEY = "user:info:";
/** Read: query cache first, on miss query DB and write back, be sure to include TTL */
public User getUser(Long userId) {
String key = USER_KEY + userId;
User user = (User) redisTemplate.opsForValue().get(key);
if (user != null) {
return user;
}
user = userMapper.selectById(userId);
if (user != null) {
// Expiration is the fallback: if all compensation mechanisms fail, it relies on this to converge automatically
redisTemplate.opsForValue().set(key, user, 30, TimeUnit.MINUTES);
}
return user;
}
/** Write: update the database first, then delete the cache (delete, not update) */
@Transactional(rollbackFor = Exception.class)
public void updateUser(User user) {
userMapper.updateById(user);
redisTemplate.delete(USER_KEY + user.getId());
}
}
But do not be happy too early: there is a transaction-boundary trap here
The basic version above actually has a hidden danger: redisTemplate.delete() is written inside the @Transactional method body, which means the deletion happens before the transaction commits. I have personally overturned a car on this point. Two ways it overturns:
- After deleting the cache, the transaction later rolls back: the cache is empty, the DB has not changed, and a read request reseeds the old value.
- A read request squeezes in between the cache deletion and the transaction commit: it reads an uncommitted old value and writes it back into the cache.
Technical highlight: cache deletion must be bound to after the transaction commits. Use
TransactionSynchronizationManagerto register a synchronization, or use@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)to send an event. The two writing styles are equivalent; the latter is event-driven and more decoupled.
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private StringRedisTemplate redisTemplate;
@Transactional(rollbackFor = Exception.class)
public void updateUser(User user) {
// 1. Only touch the database
userMapper.updateById(user);
// 2. Register a transaction synchronization: delete cache only after commit succeeds
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() {
@Override
public void afterCommit() {
redisTemplate.delete("user:info:" + user.getId());
}
}
);
}
}
Even so, Cache-Aside still has two residual risks. In an interview you must proactively mention them, otherwise you will be questioned until you collapse:
- Risk 1: extreme concurrent write-back - the extreme timeline above; low probability but not zero.
- Risk 2: the second step deletion fails - the DB commit succeeds,
redisTemplate.delete()hits a network hiccup or Redis is temporarily unavailable, and the cache stays on the old value for a long time.
These two risks correspond to the hardening solutions in the next two sections. First, risk 1.
4. Hardening 1: Delayed Double Delete, a backstab for concurrent write-back
Some people may ask: since updating the database first and then deleting the cache is correct, would deleting the cache first and then updating the database work? The answer is: even worse. Look at this accident scene:
A read request happens to squeeze between "delete cache" and "update DB", writing the old value back into the cache, and it stays dirty until the next update. Delayed Double Delete is a patch for this process: delete once before updating, and delete again after a delay after updating. It is specifically for clearing the old value written back by concurrent reads during the window.
Production-grade code
@Service
public class StockService {
@Autowired
private StockMapper stockMapper;
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private ThreadPoolTaskExecutor delayDeleteExecutor; // custom thread pool, do not use the default pool
@Autowired
private RocketMQTemplate rocketMQTemplate;
// Delay time goes to the config center, can be adjusted without restart
@Value("${cache.delay-delete-time:500}")
private long delayDeleteTime;
@Transactional(rollbackFor = Exception.class)
public void updateStock(Long skuId, Integer newStock) {
String key = "stock:" + skuId;
// ① First deletion: invalidate the cache first
redisTemplate.delete(key);
// ② Update the database
stockMapper.updateStock(skuId, newStock);
// ③ Asynchronous delayed second deletion - never sleep synchronously in the business thread
delayDeleteExecutor.execute(() -> {
try {
Thread.sleep(delayDeleteTime);
redisTemplate.delete(key);
} catch (Exception e) {
// ④ If the second deletion still fails, send to MQ as fallback; do not pin hopes on one delete
rocketMQTemplate.convertAndSend("cache-delete-retry", key);
}
});
}
}
Technical highlight: the deletion action leaves the transaction boundary but the database commit succeeds first; the async thread pool isolates it so the main path is not slowed down; a second deletion failure goes to MQ compensation. All three layers are indispensable. In addition, if the infrastructure supports it, using MQ delayed messages instead of
Thread.sleepis more elegant.
How to determine the delay time? This is a frequent follow-up question
Absolutely do not make it up. Empirical formula:
Delay time Δ > primary-replica sync delay + the time for one read request from "querying DB to writing back"
In practice, there are three levels of approaches:
- Stress-test baseline: stress-test the database average query time, set it to 2
3 times that; or use the interface P99 response time as the baseline and leave margin. Primary-replica delay is usually 150ms, at peak it can be several hundred milliseconds; one read write-back is tens of milliseconds, so 500ms~1s is a common safe value. - Config center dynamic adjustment: put the delay time in the config center (like
cache.delay-delete-timein the example), adjust it any time without restarting the service. - Dynamic calculation: a more rigorous approach is to evaluate the primary-replica delay in real time using the offset difference from
INFO replication.
The boundary of Delayed Double Delete: it is a patch, not the final state
Let me speak some honest words. Delayed Double Delete has three hard shortcomings:
- The sleep time cannot be estimated precisely - set too short and the window is not covered; set too long and the cache stays dirty longer.
- In a read-write split architecture, it cannot cover everything - the second deletion cannot delete old data that other service instances read from replicas and wrote.
- Every write request occupies one extra async thread, which is not a small number under high concurrency.
So my positioning is clear: Delayed Double Delete is suitable as transitional hardening when concurrency conflicts are obvious but you do not want to introduce MQ/Canal, or as an auxiliary method for read-write split scenarios. It is not the main solution.
What about risk 2 - deletion failure? This is the number one source of dirty data in production.
5. Hardening 2: deletion failure must be retryable
The scenario is specific: the DB commit succeeds, redisTemplate.delete() hits a network hiccup, Redis is temporarily unavailable, or the interface times out. The deletion does not execute, and the cache stays on the old value for a long time. Writing just one line of delete is not enough; deletion failure must be compensable.
Option A: MQ async retry
MQ naturally supports retry. If a consumer goes down, it can consume again, and eventual consistency is guaranteed. In production, it is recommended to configure the full trio of message persistence + producer acknowledgement + consumer manual ACK.
// When deletion fails, send a retry message; the message body carries a unique ID for idempotency
public void deleteCacheWithRetry(String cacheKey) {
try {
Boolean deleted = redisTemplate.delete(cacheKey);
if (!Boolean.TRUE.equals(deleted)) {
sendDeleteMessage(cacheKey);
}
} catch (Exception e) {
// Exceptions also send a message, guaranteeing "eventually deleted"
sendDeleteMessage(cacheKey);
}
}
private void sendDeleteMessage(String cacheKey) {
CacheDeleteMessage message = new CacheDeleteMessage(
UUID.randomUUID().toString(), cacheKey);
rabbitTemplate.convertAndSend("cache-exchange", "cache.delete", message);
}
@Component
public class CacheDeleteConsumer {
@Autowired
private StringRedisTemplate redisTemplate;
@RabbitListener(queues = "cache-delete-queue")
public void handleDeleteMessage(CacheDeleteMessage message) {
// 1. Idempotency check: process each message only once
String idempotentKey = "cache:delete:idempotent:" + message.getMessageId();
if (Boolean.TRUE.equals(redisTemplate.hasKey(idempotentKey))) {
return;
}
try {
// 2. Delete the cache (delete is naturally idempotent)
redisTemplate.delete(message.getCacheKey());
// 3. Mark as processed, automatically cleaned after 24 hours
redisTemplate.opsForValue().set(idempotentKey, "1", 24, TimeUnit.HOURS);
} catch (Exception e) {
// 4. Throw exception to trigger MQ automatic retry (e.g., configured 3 retries),
// after retries reach the limit, enter the dead-letter queue and alert for manual intervention
throw new RuntimeException("Cache deletion failed: " + message.getCacheKey(), e);
}
}
}
Option B: local retry table + scheduled task (interview bonus answer)
If you do not want to introduce MQ just to delete cache, or if the requirement is "deletion tasks absolutely cannot be lost", use a local retry table. The essence: put the deletion task table and the business SQL in the same transaction - either both succeed or both roll back, the task is never lost.
@Transactional(rollbackFor = Exception.class)
public void updateUser(User user) {
String cacheKey = "user:info:" + user.getId();
// 1. Update the database
userMapper.updateById(user);
// 2. Write the deletion task table in the same transaction - the task and the business SQL live and die together
CacheEvictTask task = new CacheEvictTask();
task.setCacheKey(cacheKey);
task.setStatus(0); // 0 pending
task.setRetryCount(0);
cacheEvictTaskMapper.insert(task);
// 3. Try deletion after the transaction commits
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() {
@Override
public void afterCommit() {
redisEvictService.evict(cacheKey, task.getId());
}
}
);
}
@Component
public class CacheEvictRetryJob {
@Autowired
private CacheEvictTaskMapper taskMapper;
@Autowired
private StringRedisTemplate redisTemplate;
// Periodically scan failed tasks and compensate the deletion
@Scheduled(fixedDelay = 5000)
public void retryEvict() {
List<CacheEvictTask> tasks = taskMapper.selectFailedTasks();
for (CacheEvictTask task : tasks) {
try {
redisTemplate.delete(task.getCacheKey());
taskMapper.updateStatus(task.getId(), 1); // mark complete
} catch (Exception e) {
taskMapper.incrRetryCount(task.getId());
// retry count exceeds threshold -> alert, manual intervention
}
}
}
}
How to choose between the two methods?
| Compensation method | Characteristics | Applicable scenarios |
|---|---|---|
| Local immediate retry | Simplest, covers transient hiccups | Bottom layer for all scenarios |
| MQ async retry | Natural retry + dead letter + peak shaving | Teams that already have MQ infrastructure |
| Local retry table + scheduled task | Same transaction as business, tasks never lost | Do not want to introduce MQ, or require tasks not to be lost |
| Canal binlog fallback | Zero business intrusion, detailed in next section | Medium and large systems |
If you do not even want to write retry code in the business path, use the ultimate form.
6. Ultimate form: Canal subscribes to Binlog, zero intrusion into business code
All previous solutions share one point: business code must personally manage the "delete cache" matter. But business code "writes the database then sends a message/deletes cache" is always two steps, and if either step fails, inconsistency occurs. Binlog is the database's own behavior - as long as the database write succeeds, the change is definitely in the binlog. This is the fundamental difference from embedded dual-write in business code.
The architecture looks like this:
Business code only writes MySQL. Canal pretends to be a replica, pulls and parses the binlog, delivers to MQ, and consumers delete the cache. Deletion failures are automatically retried by MQ, and eventually enter the dead-letter queue for manual intervention. A similar tool is Debezium, with the same idea.
Consumer code (including idempotency + retry + dead letter)
@Component
@RocketMQMessageListener(
topic = "binlog-cache-invalidation",
consumerGroup = "cache-evict-group"
)
public class CanalBinlogConsumer implements RocketMQListener<CanalMessage> {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public void onMessage(CanalMessage message) {
// Only process DML, filter DDL
if (Boolean.TRUE.equals(message.getIsDdl())) {
return;
}
message.getData().forEach(row -> {
Object idVal = row.get("id");
if (idVal == null) return;
String cacheKey = "product:" + idVal;
try {
// Invalidate cache (Delete) rather than update cache (Put):
// Delete is naturally idempotent, repeated consumption and out-of-order messages are not a problem
stringRedisTemplate.delete(cacheKey);
} catch (Exception e) {
// Throw exception to trigger MQ ladder retry (1s, 5s, 10s...)
// after reaching the limit, enter dead-letter queue + alert, manual intervention
throw new RuntimeException("Evict failed: " + cacheKey, e);
}
});
}
}
The three technical highlights of this architecture, just name them in an interview:
- Partition by primary key hash to preserve order: configure
canal.mq.partitionHash = shop_db.t_product:idon the Canal side, so consecutive modifications to the same row are routed to the same MQ queue, avoiding out-of-order consumption causing old values to overwrite new values; you can also carry a version number in the message for double insurance.- Invalidation is better than update:
delete(key)is much more idempotent thanset(key, val), and repeated message delivery is safe.- Zero business intrusion: operations directly changing the database, scheduled tasks batch-updating data, other services directly connecting to the DB - all these writes that "bypass the application layer" can be captured by binlog. This is something manual dual-write can never do.
Two engineering details that must be noted
Detail 1: consumption idempotency. MQ is "at least once" delivery, so duplicate messages are inevitable. Deleting the cache is itself idempotent, so it does not matter. But if what you do in the consumer is "refresh the cache" rather than "delete", you must deduplicate with a unique message ID. The recommended combination is Bloom filter for fast deduplication + Redis for precise verification, with tiny memory overhead to block duplicate consumption:
@Override
public void onMessage(MessageExt msg) {
String msgId = msg.getMsgId();
// Bloom filter gives a probabilistic dedup first, Redis precise second confirmation
if (bloomFilterManager.mightContain("consumed", msgId)
&& Boolean.TRUE.equals(redisTemplate.hasKey("msg_consumed:" + msgId))) {
return;
}
BinlogEvent event = JSON.parseObject(msg.getBody(), BinlogEvent.class);
redisTemplate.delete(event.getCacheKey());
// Double mark to prevent duplicate consumption
bloomFilterManager.put("consumed", msgId);
redisTemplate.opsForValue().set("msg_consumed:" + msgId, "1", 2, TimeUnit.HOURS);
}
Detail 2: position persistence. Canal's binlog position / GTID must be persisted, so that after the sync service restarts or reconnects, it can continue from the persisted position without losing changes.
Supporting play for multi-level cache
If you use a multi-level structure of local cache (Caffeine) + Redis, there is an additional blind spot: one node deletes Redis, but the local caches in other nodes' JVMs still hold old values. The solution is to start another consumer group in broadcast mode, where every application instance subscribes to the same topic and each clears its own local cache. The recommended consumption order is "clear local first, then delete remote" to compress the dirty-data window as much as possible. For sharded databases and tables, the same applies: Canal listens to the binlog of all shards, combined with a unified cache key naming convention, and the business is unaware.
If you do not want to depend on Canal Server, you can also connect directly with the native client:
CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress("127.0.0.1", 11111), "example", "", "");
connector.connect();
connector.subscribe(".*\\..*");
connector.rollback();
while (true) {
Message message = connector.getWithoutAck(100);
long batchId = message.getId();
if (batchId == -1 || message.getEntries().isEmpty()) {
Thread.sleep(1000);
continue;
}
for (CanalEntry.Entry entry : message.getEntries()) {
if (entry.getEntryType() != CanalEntry.EntryType.ROWDATA) continue;
CanalEntry.RowChange rowChange =
CanalEntry.RowChange.parseFrom(entry.getStoreValue());
// Only care about UPDATE / DELETE
if (rowChange.getEventType() == CanalEntry.EventType.UPDATE
|| rowChange.getEventType() == CanalEntry.EventType.DELETE) {
String tableName = entry.getHeader().getTableName();
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
String id = getPrimaryKey(rowData); // parse row data to get primary key
redisTemplate.delete(tableName + ":info:" + id);
}
}
}
connector.ack(batchId); // acknowledge consumption, advance position
}
Of course, this solution has a cost: architecture complexity rises, and there is a sync delay from hundreds of milliseconds to seconds. It is only suitable for eventual consistency scenarios. Introducing Canal for a small system is overkill.
At this point the article is more than half done. Everyone who can read this far is a tough person. Follow to not get lost. This "high-concurrency must-ask interview question" series will later break down flash-sale overselling and MQ message loss.
The write path is done. The read path also hides dangers.
7. The read side should not run naked either
Dual-write consistency is not only about writes. If several details on the read side are not done, the previous efforts will be discounted.
1. TTL is the last line of defense and must be set. Even if all compensation mechanisms fail, the expiration time can make dirty data converge automatically. In production, it is generally set to 15 minutes to 2 hours, and add a random offset to the TTL to prevent a large number of keys expiring at the same time causing a cache avalanche.
2. Prevent cache breakdown: mutex lock rebuild + double check. The moment a hot key expires, a large number of requests will pass through to the DB at the same time. Use a mutex lock to let only one request go back to the source (singleflight idea), and other requests wait for the result:
public User getUserSafe(Long id) {
String key = "user:" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user != null) {
return user;
}
// Cache miss: mutex lock lets only one request go back to source
RLock lock = redissonClient.getLock(key + ":rebuild");
if (lock.tryLock(2, 5, TimeUnit.SECONDS)) {
try {
// Double check: look again after acquiring the lock to avoid repeated source reads
user = (User) redisTemplate.opsForValue().get(key);
if (user == null) {
user = userMapper.selectById(id);
if (user != null) {
redisTemplate.opsForValue().set(key, user, 30, TimeUnit.MINUTES);
} else {
// Cache empty values too, with short TTL, to prevent penetration
redisTemplate.opsForValue().set(key, "", 1, TimeUnit.MINUTES);
}
}
} finally {
lock.unlock();
}
}
return user;
}
A budget-limited version can use SETNX (setIfAbsent) to implement a lightweight mutex lock; remember to set an expiration time to prevent deadlock. Another small trick: after deleting the cache, hang a short empty-value marker for a few seconds, which can also block the breakdown traffic at the moment of deletion.
3. Prevent penetration: Bloom filter + cache empty values. Querying data that does not exist will hit the DB every time. Put a Bloom filter in front to intercept, and use short-TTL empty values to catch anything that slips through.
4. Use logical expiration for extreme hot spots. Do not set a physical expiration time. Store a logical expiration time in the value. When a read finds it expired, asynchronously start a thread to rebuild the cache, and the current request returns the old value first - trade a short inconsistency for availability.
5. Large key deletion should not block the main thread. When batch cleaning, use SCAN for progressive traversal, never KEYS *; for large key deletion use UNLINK for asynchronous release (Redis 4.0+).
6. Degradation strategy. When Redis is entirely unavailable, read the database directly to ensure business availability - the system must not go down just because the cache went down.
What if the business says: I cannot tolerate even one second of old data?
8. If the boss insists on strong consistency: put the cost on the table first
For truly strong-consistency scenarios (account balance, inventory deduction, payment status, flash-sale core data), my attitude is: honestly put the cost on the table, then give options.
Option 1: use distributed read-write locks, trade throughput for consistency. Read locks are shared (read-read not mutually exclusive), write locks are exclusive (block all reads and writes), serializing "DB update + delete cache":
@Service
public class StockService {
@Resource
private RedissonClient redisson;
@Resource
private StringRedisTemplate redisTemplate;
@Resource
private StockMapper stockMapper;
/** Read: acquire read lock, read-read shared, read-write mutually exclusive */
public Stock getStock(Long productId) {
RReadWriteLock rwLock = redisson.getReadWriteLock("lock:stock:" + productId);
RLock readLock = rwLock.readLock();
readLock.lock();
try {
String json = redisTemplate.opsForValue().get("stock:" + productId);
if (StringUtils.isNotBlank(json)) {
return JSON.parseObject(json, Stock.class);
}
Stock stock = stockMapper.selectById(productId);
if (stock != null) {
redisTemplate.opsForValue().set("stock:" + productId,
JSON.toJSONString(stock), 30, TimeUnit.MINUTES);
}
return stock;
} finally {
readLock.unlock();
}
}
/** Write: acquire write lock, DB + delete cache serialized */
public void deductStock(Long productId, int qty) {
RReadWriteLock rwLock = redisson.getReadWriteLock("lock:stock:" + productId);
RLock writeLock = rwLock.writeLock();
writeLock.lock();
try {
stockMapper.deduct(productId, qty);
redisTemplate.delete("stock:" + productId);
} finally {
writeLock.unlock();
}
}
}
Underlying principle bonus point: Redisson's write lock uses a Hash structure to store
UUID:ThreadId -> reentry count, and on release uses a Lua script to verify identity to prevent deleting someone else's lock; the read lock maintains a separate Timeout Key for each thread to achieve precise renewal; the watchdog mechanism automatically renews to 30 seconds every 10 seconds by default, preventing the lock from expiring before the business finishes.
But note: read-write locks should only be used for very few keys like inventory and balance, not the whole site. QPS will really be cut in half.
Option 2: change the play according to the scenario.
| Scenario | Solution |
|---|---|
| Strong-consistency reads | Read the database directly, do not use cache |
| High write concurrency | Distributed lock serialization |
| Inventory deduction | Redis Lua atomic deduction + database final settlement |
| Money-related | Database transaction + idempotency + reconciliation |
| Hot data | Local cache + Redis + DB multi-level fallback |
| Flash-sale peak shaving | Redis pre-deduct inventory + MQ async settlement, sacrifice strong consistency for availability, rely on reconciliation |
There is also a pragmatic approach: treat Redis as a read-only cache with an extremely short TTL (e.g., 1 second), authoritative data always in MySQL, and writes go directly to the DB. Real consistency is guaranteed by database transactions; Redis is only a performance layer and does not participate in the core logic of consistency.
Answering a frequent follow-up in passing: can Seata distributed transactions be used? Yes, but not recommended; performance loss is large. More importantly - Redis does not support transaction rollback at all. Dual-write consistency is essentially an eventual consistency problem, not a distributed transaction problem. Saying this sentence directly earns bonus points.
Also complete the other two textbook solutions for completeness, so the interview shows a complete knowledge graph:
- Write-Through: write requests write both cache and DB synchronously, the cache layer guarantees synchronization. Strong consistency but poor write performance, suitable for write-light, strong-consistency scenarios.
- Write-Behind: only write the cache, the cache asynchronously batches writes to the DB. Extremely high performance but may lose data, suitable for statistical scenarios like like counts and view counts where loss is acceptable.
All difficulties are laid out. Use a table to wrap up.
9. High-frequency difficulty quick-reference table
First, separately mention the most easily overlooked corner - primary-replica lag: after writing to the primary, immediately reading from the replica; the replica has not synced yet, and the old value is reseeded into the cache. There are four solutions: reads within a short window after writes force the primary; write marker method (on write, SETEX a flag; on read, if the flag exists, connect directly to the primary); wait for the replica's GTID position to catch up before reading; or add a delayed double delete.
| Difficulty | Accident | Solution |
|---|---|---|
| Concurrent read/write out-of-order write-back | Old value reseeded, cache dirty for a long time | Update DB then delete cache; delayed double delete; binlog path deletes after commit |
| Cache deletion fails | DB new, cache old, dirty data persists | Local retry -> MQ retry -> local retry table -> Canal fallback, layer by layer |
| Transaction boundary misalignment | Transaction rolls back but cache is empty | AFTER_COMMIT event / transaction synchronization, delete only after commit |
| Primary-replica lag dirty read | Source read from replica gets old value | Force read primary / write marker / wait for GTID position / delayed double delete |
| Delay time hard to estimate | Too short does not cover the window, too long makes dirt last longer | Use P99 as baseline with margin; config center dynamic adjustment; fundamental solution is binlog path |
| Cache breakdown | Hot key expires and punches through DB | Mutex rebuild + double check; logical expiration + async refresh |
| Cache penetration | Querying nonexistent data hits DB directly | Bloom filter in front + cache empty values (short TTL) |
| Cache avalanche | Large number of keys expire at the same time | Add random offset to TTL; multi-level cache |
| Message out of order | Two modifications to the same row consumed out of order | Partition by primary key hash + version number; delete-only is naturally immune |
| Duplicate consumption | MQ at-least-once delivery | Deletion is naturally idempotent; refresh scenarios use message ID + Bloom filter + Redis dedup |
| Canal disconnect loses position | Changes lost after restart | Persist binlog position / GTID, continue after reconnect |
| Large key deletion blocks | KEYS *, large key deletion blocks the main thread |
SCAN progressive traversal + UNLINK async release |
| Multi-instance local cache blind spot | One node deletes Redis, other nodes' local cache still old | MQ broadcast consumer group, each instance clears local cache |
| Sharded DB/table sync | Changes spread across multiple databases | Canal listens to all shards' binlog + unified key conventions |
| Concept confusion | Answering penetration/avalanche as consistency | Consistency is about "new vs old", penetration is about "exists or not", discuss separately |
Final step: how to choose a solution according to your business.
10. Selection guide: do not choose one of three, combine according to business
Production environments rarely bet on only one solution. First look at the evolution logic:
Full solution comparison table
| Solution | Consistency | Performance | Complexity | Applicable scenarios |
|---|---|---|---|---|
| Update cache first then update DB | Very poor | High | Low | Completely not recommended |
| Delete cache first then update DB | Average | High | Low | Requires delayed double delete |
| Cache-Aside (update DB then delete cache) | Eventual consistency | High | Low | First choice for 90% of businesses |
| Delayed double delete | Stronger | Medium | Medium | Read-write split, slightly higher consistency requirements |
| MQ async deletion | Eventual consistency | High | Medium | High concurrency + can tolerate hundreds of ms delay |
| Canal + Binlog | Eventual consistency (more stable) | High | High | Big company medium-large systems, complete decoupling |
| Write-Through | Strong consistency | Low | Medium | Write-light + strong consistency requirement |
| Write-Behind | Weak consistency | Extremely high | High | Statistical data where loss is acceptable |
| Redisson read-write lock | Strong consistency | Low | Medium | Very few keys like financial amounts, flash-sale inventory |
Selection decision tree
Match by business level
| Business level | Recommended combination |
|---|---|
| Ordinary business (user info, content, user profiles) | Update MySQL -> delete Redis after transaction commit -> TTL fallback |
| Higher reliability requirements | Write deletion task table in same transaction -> delete cache after transaction -> scheduled retry fallback |
| Complex systems / middle platform | Canal listens to Binlog -> MQ async deletion |
| Strong consistency (balance, inventory, payment, purchase qualification) | No cache / read-write lock serialization / Redis Lua atomic deduction + reconciliation |
For core paths like inventory and money, a common landing route is the combination of "update DB first then delete cache + delayed double delete for concurrent write-back + Binlog/MQ for deletion failure"; for non-core configuration and list data, Cache-Aside with a reasonable TTL is enough, not worth introducing Canal.
After launch, watch four metrics
Solution implementation is not the end; monitoring is: cache hit rate, cache deletion failure rate, MQ message backlog, Canal sync delay. Add a scheduled reconciliation task (Batch Repair) as the final manual fallback, and the system is closed-loop.
11. Interview bonus: how to answer this question beautifully
Finally, a few practical tips.
Answer rhythm: follow the order "set the tone -> draw a diagram -> decouple -> code -> difficulty table", and in 40 seconds of opening you can hold the rhythm in your hand. One sentence to set the tone:
"Dual-write cannot achieve absolute strong consistency; forcing distributed locks ruins performance. In production we only pursue eventual consistency. The standard play is: Cache Aside + delete-only instead of update + failures are compensable."
Frequent follow-up prediction:
- Q: How to determine the delayed double delete time? A: Greater than "primary-replica sync + one read write-back" time, use interface P99 as the baseline with margin, empirical value 500ms~1s, put in config center for dynamic adjustment.
- Q: The cache is a multi-table aggregate result, but binlog changed only one of the tables. What to do? A: Maintain a mapping of "table -> cache key set"; or simply let aggregate cache rely only on short TTL and do not proactively delete - do not reverse-query all associated keys for one field, the gain is not worth the loss.
- Q: Why is deleting cache better than updating cache? A: Concurrent overwrite, recomputation cost, lazy loading idempotency - triple hit, full version in section 3.
Two closing golden sentences, memorize whichever you like:
"I do not pursue strong consistency for dual-write. I use 'update DB first, delete cache after commit' to compress the inconsistency window to a minimum, use binlog to catch deletion failure, and use TTL to fall back for all anomalies; if strong consistency is really needed, I separately add read-write locks and first explain the throughput cost."
Or the sixteen-character version: DB first, then delete; failures retryable; eventually consistent; fallback alertable.
Cheat-sheet memory: update DB -> commit -> delete -> failure goes to binlog -> all with TTL -> hot spots add a lock. Memorize these six steps and this question is stable.
In closing
Review the article's key points:
- The root of inconsistency is two independent storage systems without atomic commit, plus concurrency races and primary-replica lag.
- The main solution is Cache-Aside: update DB first, delete cache after transaction commit, delete rather than update.
- Delayed double delete patches concurrent write-back; MQ retry / local retry table patches deletion failure; Canal + Binlog is the ultimate zero-intrusion fallback.
- On the read side, equip TTL, mutex locks, empty-value caching; strong-consistency scenarios use read-write locks or no cache at all.
- There is no silver bullet. Choose according to the business's tolerance for inconsistency; all caches must carry TTL.
The implementation advice is also simple: ordinary business starts with Cache-Aside + TTL, and once stable, harden layer by layer according to data level. Do not go full-stack from the start - over-engineering is as harmful as no design.
What dual-write consistency really tests is not Redis, but your engineering sense that "in distributed systems there is no silver bullet, but there must be a way out."
Let's talk about something specific: which dual-write consistency solution do you use online? How many milliseconds is your delayed double delete sleep, and what pits have you stepped in? Leave a comment, I will reply one by one. If you found this useful, like, share, and forward to support me. Your support is my greatest motivation to keep breaking down high-frequency questions.