Database and Cache Double-Write Consistency: Common Solutions and Best Practices
This article examines the data consistency challenges of writing to both databases and caches, outlines four common double‑write strategies, analyzes their pitfalls—especially under high concurrency—and recommends the optimal approach of writing to the database then deleting the cache, while discussing retry mechanisms, scheduled tasks, message queues, and binlog listeners.
Database and cache double‑write consistency is a language‑agnostic issue that becomes severe under high concurrency.
The article first describes the typical cache‑first read flow and the problem when data is updated in the database but the cache becomes stale.
Four common double‑write strategies are presented:
Write cache then write database.
Write database then write cache.
Delete cache then write database.
Write database then delete cache.
Each strategy is analyzed; the cache‑first approach can produce dirty data if the database write fails, while the database‑then‑cache approach can cause stale cache under concurrent writes.
High‑concurrency scenarios are illustrated with request sequences showing how newer data can be overwritten by older data in the cache.
The article recommends the “write database then delete cache” method as the most reliable, though it still may encounter rare inconsistencies.
To mitigate cache‑deletion failures, various retry mechanisms are discussed: synchronous retries, asynchronous retries via thread pools, retry tables with scheduled tasks, message‑queue retries (e.g., RocketMQ), and binlog listeners (e.g., Canal) that delete cache after database changes.
Examples of code snippets are shown using 假数据 , 新数据 , 旧数据 , and 重试机制 to illustrate concepts.
Finally, the article notes that while these solutions improve consistency, they cannot guarantee 100% correctness, and proper monitoring and fallback strategies are essential.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.