search
HomeDatabaseMysql TutorialHow to solve the dual-write problem between Redis and MySQL

Write in front

Strictly speaking, any non-atomic operation cannot guarantee consistency unless blocking reads and writes are used to achieve strong consistency. Therefore, the goal we pursue in the cache architecture is eventual consistency.
Caching improves performance by sacrificing strong consistency.

This is determined by the CAP theory. The applicable scenario for the cache system is the non-strong consistency scenario, which belongs to the AP in CAP.

The following three cache read and write strategies have their own advantages and disadvantages, and there is no best one.

Three read-write cache strategies

Cache-Aside Pattern (bypass cache mode)

Cache-Aside Pattern, that is, bypass cache mode, is proposed for Solve the data inconsistency problem between cache and database as much as possible.

Read: Read data from the cache and return directly after reading. If it cannot be read, load it from the database, write it to the cache, and then return the response.
Write: When updating, first update the database and then delete the cache.

Read-Through/Write-Through (read-write penetration)

In the Read/Write Through Pattern, the server regards the cache as the main data storage, reads data from it and writes the data in. The responsibility of the Cache service is to read and write DB data, thereby reducing the burden on the application.

Because the distributed cache Redis we often use does not provide the cache function of writing data to DB, it is not used much.

Write: Check the cache first. If it does not exist in the cache, update the DB directly. If it exists in the cache, the cache will be updated first, and then the cache service will update the DB by itself (Update cache and DB simultaneously).

Read: Read data from the cache and return directly after reading it. If it cannot be read, load it from DB first, write it to cache and then return the response.

Write Behind Pattern (Asynchronous Cache Write)

Write Behind Pattern is very similar to Read/Write Through Pattern. Both are handled by the cache service to read and write cache and DB.

However, there are big differences between the two: Read/Write Through updates the cache and DB synchronously, while Write Behind Caching only updates the cache and does not directly update the DB, but instead Update DB in asynchronous batch mode.

Obviously, this method brings greater challenges to data consistency. For example, if the cache data may not be updated asynchronously to the DB, the cache service may hang, which will cause A greater disaster.

This strategy is also very rare in our daily development process, but it does not mean that it has few application scenarios. For example, the asynchronous writing of messages in the message queue to disk and MySQL's InnoDB Buffer Pool mechanism all use this kind of strategy.

Write Behind Pattern The write performance of DB is very high, which is very suitable for some scenarios where the data changes frequently and the data consistency requirements are not so high, such as the number of views and likes.

Analysis of bypass cache mode

Some questions about Cache Aside Pattern

The bypass cache mode is the one we use most in daily life. Based on the bypass cache mode introduced above, we may have the following questions.

Why the write operation deletes the cache instead of updating the cache

Answer: Thread A initiates a write operation first, and updates it first database. Thread B initiates another write operation, and updates the database in the second step. Due to network and other reasons, thread B updates the cache first, and thread A updates the cache.

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.

In fact, it is possible to update the cache when writing operations are required, but we need to add a lock/distributed lock to ensure that there are no thread safety issues when updating the cache.

In the process of writing data, why do we need to update the DB first and then delete the cache?

Answer: For example, request 1 is a write operation. If First delete cache A, request 2 is a read operation, first read cache A, find that the cache has been deleted (deleted by request 1), and then read the database, but at this time request 1 has not had time to update the data in time, then request 2 What is read is old data, and request 2 will also put the old data read into the cache, causing data inconsistency.

In fact, it is also possible to delete the cache first and then update the database. For example, if you adopt the delayed double delete strategy
sleep for 1 second and then eliminate the cache again, you can delete all data within 1 second. The cached dirty data caused by this is deleted again. It doesn’t have to be 1 second, it depends on your business, However, this approach is not recommended, because many factors may happen in this 1 second, and its uncertainty is too great.

In the process of writing data, is it okay to update the DB first and then delete the cache?

Answer: In theory, data inconsistency may still occur, but the probability is very small.

Assume that there will be two requests, one requesting A to perform a query operation, and one requesting B to perform an update operation, then the following situation will occur

(1) The cache just expired
(2) Request A to query the database and get an old value
(3) Request B to write the new value into the database
(4) Request B to delete the cache
(5) Request A to write the old value found to the cache ok. If the above situation occurs, dirty data will indeed occur.

However, the probability of this happening is not high

There is a congenital condition for the above situation to occur, that is, the database writing operation in step (3) is smaller than that in step ( The read database operation of 2) takes less time, so it is possible to make step (4) precede step (5).

However, if you think about it carefully, the read operation of the database is much faster than the write operation (otherwise, why do we do the separation of reading and writing? The meaning of doing the separation of reading and writing is because the reading operation is faster and consumes less resources) , so step (3) takes less time than step (2), and this situation is difficult to occur.

Are there any other reasons for the inconsistency?

Answer: If the cache deletion fails, it will cause inconsistency

How to solve it?
Use Canal to subscribe to the binlog of the database and obtain the data that needs to be operated. Start another program to obtain the information from this subscription program and delete the cache.

Defects of Cache Aside Pattern

Defect 1: The first requested data must not be in the cache

Solution: hot data can be put in advance in cache.

Defect 2: Frequent write operations will cause the data in the cache to be frequently deleted, which will affect the cache hit rate.

Strong consistency scenario between database and cache data: When updating the DB, the cache is also updated, but we need to add a lock/distributed lock to ensure that there are no thread safety issues when updating the cache. Scenarios in which the database and cache data are inconsistent can be temporarily allowed: when updating the DB, the cache is also updated, but a relatively short expiration time is added to the cache. This ensures that even if the data is inconsistent, the impact will be relatively small.

The above is the detailed content of How to solve the dual-write problem between Redis and MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools