Cache Consistency Between MySQL and Redis: Design Patterns and Best Practices
This article explains the relationship between MySQL and Redis, discusses why cache consistency is challenging, and details four cache update design patterns—delete‑then‑update, update‑then‑invalidate (Cache‑Aside), read/write‑through, and write‑behind—illustrating each with flow diagrams and practical considerations.
MySQL is a persistent relational database that guarantees data reliability, while Redis is an in‑memory cache used to improve data access performance.
Ensuring that the data stored in MySQL and Redis stays consistent (the cache‑consistency problem) is a classic challenge because updates must be applied to two independent systems, which can lead to timing gaps, especially under concurrent read/write workloads.
Cache inconsistency typically occurs when data changes: the database and cache cannot be updated atomically, so a short window exists where one reflects the new state and the other does not.
Four common cache‑update design patterns are described below:
Delete cache then update database – The cache is removed first, then the database is updated. This approach is prone to long periods of stale (dirty) data under concurrency and is generally discouraged.
Update database then invalidate cache (Cache‑Aside pattern) – The database is updated first, followed by cache invalidation. This method may still produce brief inconsistency but is widely used because it limits the window of stale data.
Update cache only, let the cache synchronously update the database (Read/Write‑Through pattern) – Business logic writes to the cache, which immediately propagates the change to the database. This yields strong consistency with low latency but requires cache‑side modifications.
Update cache only, let the cache asynchronously update the database (Write‑Behind pattern) – Writes go to the cache, and the cache later batches updates to the database. It offers excellent read/write performance but sacrifices strong consistency and can lose data if the cache fails before flushing.
Each pattern is illustrated with flow diagrams:
In summary, each cache‑update strategy has trade‑offs; none is perfect. System designers should choose the pattern that best fits their business scenario, balancing consistency requirements, performance, and implementation complexity.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.