


How to ensure double-write consistency between Redis and MySQL? (Meituan Ermian)
前言
四月份的时候,有位朋友去美团面试,他说被问到Redis与MySQL双写一致性如何保证? 这道题其实就是在问缓存和数据库在双写场景下,一致性是如何保证的?本文将跟大家一起来探讨如何回答这个问题。
谈谈一致性
一致性就是数据保持一致,在分布式系统中,可以理解为多个节点中数据的值是一致的。
- Strong consistency: This consistency level is most in line with user intuition. Whatever it requires the system to write will be read out. The user experience is good, but it is difficult to implement. It often has a great impact on the performance of the system
- Weak consistency: This consistency level restricts the system from being able to read the written value immediately after the write is successful, nor does it guarantee that the written value can be read immediately. Promise how long it will take for the data to be consistent, but we will try our best to ensure that the data can reach a consistent state after a certain time level (such as the second level)
- Eventual Consistency: Final Consistency It is a special case of weak consistency. The system will ensure that a data consistency state can be achieved within a certain period of time. The reason why final consistency is mentioned separately here is because it is a very respected consistency model in weak consistency, and it is also a model that is highly respected in the industry for data consistency in large distributed systems
Three classic caching modes
Caching can improve performance and relieve database pressure, but using cache can also lead to data inconsistency problems. How do we generally use cache? There are three classic caching patterns:
- Cache-Aside Pattern
- Read-Through/Write through
- Write behind
Cache -Aside Pattern
Cache-Aside Pattern, that is, Bypass cache mode, is proposed to solve the problem of data inconsistency between the cache and the database as much as possible.
Cache-Aside read process
The read request process of Cache-Aside Pattern is as follows:
- When reading, read the cache first. If the cache hits, the data will be returned directly.
- If the cache does not hit, read the database, retrieve the data from the database, put it into the cache, and return the response at the same time.
Cache-Aside write process
The write request process of Cache-Aside Pattern is as follows:
When updating, first update the database and then delete the cache .
Read-Through/Write-Through (read-write penetration)
In Read/Write Through mode, the server uses the cache as the main data storage. The interaction between the application and the database cache is completed through the Abstract Cache Layer.
Read-Through
The brief process of Read-Through is as follows
- Read from cache If the data cannot be read, it will be returned directly. If it cannot be read, it will be loaded from the database, written to the cache, and then the response will be returned.
- Is this brief process very similar to
? In fact, Read-Through is just an extra layer of Cache-Provider, and the process is as follows:
Read-Through is actually just
has a layer of encapsulation on top, which will make the program code more concise and reduce the load on the data source. Write-Through
Write-ThroughIn mode, when a write request occurs, the data source and cached data are also completed by the Cache Abstraction Layer The update process is as follows: Write behind (asynchronous cache writing)
followed by Read-Through/Write-ThroughThere are similarities. Cache Provider is responsible for reading and writing cache and database. There is a big difference between them: Read/Write Through
updates the cache and data synchronously, while Write Behind only updates the cache and does not directly update the database, through Batch asynchronous way to update the database.
In this method, the consistency between the cache and the database is not strong.
. But it is suitable for frequent writing scenarios. MySQL's InnoDB Buffer Pool mechanism uses this mode. When operating the cache, should I delete the cache or update the cache?
In general business scenarios, we use the
Cache-Aside mode.
Some friends may ask, Cache-AsideWhen writing a request, why delete the cache instead of updating the cache? When we operate the cache, should we delete the cache or update the cache? Let’s look at an example first: At this time, the cache saves A's data (old data), and the database saves B's data (new data). The data is inconsistent, and dirty data appears. . If deletes the cache instead of updating the cache, this dirty data problem will not occur. Updating the cache has two disadvantages compared to deleting the cache: Suppose there are two requests, A and B, requesting A to do the update operation and requesting B to do the query and read operation. Jiang Zi has a problem La, The cache and database data are inconsistent. The cache stores old data, and the database stores new data. Therefore, Some friends may say that it is not necessary to operate the database first, just use the Cache Delayed Double Delete strategy? What is delayed double deletion? How long does it usually take to sleep for a while? Are they all 1 second? This sleep time = the time it takes to read business logic data is several hundred milliseconds. In order to ensure that the read request ends, the write request can delete cached dirty data that may be brought by the read request. Whether it is delayed double deletion or Cache-Aside first operates the database and then deletes the cache, If the second step of deleting the cache fails, the deletion failure will result in dirty data~ If the deletion fails, delete it a few more times to ensure that the cache deletion is successful~So you can introduce Delete cache Retry mechanism The retry deletion cache mechanism is okay, but it will cause a lot of business code intrusion. In fact, you can also eliminate key asynchronously through the binlog of the database. Taking mysql as an example, you can use Alibaba's canal to collect binlog logs and send them to the MQ queue, and then confirm and process the update message through the ACK mechanism, delete the cache, and ensure data Cache consistency
In the case of double writing, should the database be operated first or the cache first?
Cache-Aside
In the cache mode, some friends still have questions. When writing a request, why operate the database first? Why not operate the cache first?
Cache-Aside
cache mode chooses to operate the database first instead of the cache first. Cache Delayed Double Delete
Delete cache retry mechanism
Read the biglog Asynchronous cache deletion
The above is the detailed content of How to ensure double-write consistency between Redis and MySQL? (Meituan Ermian). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...
