How to solve the double write consistency of Redis


1. Update strategy

The default update strategy of Redis and MySQL is the bypass cache strategy, and the bypass cache strategy has a write strategy and a read strategy

Write strategy: When updating, update the database first, then update the cache

Read strategy: When reading data, if it hits the cache, it returns directly; if it misses the cache, it queries the database, builds a cache, and then returns the data


2. Problem scenario

When updating data, according to the default strategy, the database will be updated first, and then the cache will be deleted

However, under concurrent conditions, other threads read the old value of the data again, and it happens that the data is accessed for the first time, and the cache is not built, so the above deleted cache is rebuilt, resulting in the old value in the cache , the new value in the database.

This leads to inconsistencies between the data in the database and the cache. The detailed process can be seen in the figure below

insert image description here


3. Solutions

Solution 1: Redis sets a short expiration time for the key. Even if the data is inconsistent, the data will expire soon. The disadvantage is that it will affect the cache hit rate

Solution 2: Adopt a delayed double-delete strategy.

(1) Eliminate the cache first
(2) Update the database again
(3) After sleeping for a corresponding period of time, clear the cache again

Its principle is: write requests to delete the cache first, if there is a read request at this time, an old cache will be built, and the rest of the corresponding time in step (3) is to ensure that the old cache is established. The cache is cleared, and the next read operation will go directly to the database to read the new value.

Its shortcomings are also obvious. The sleep time is not very easy to grasp, so this strategy is not recommended.

Guess you like

Origin blog.csdn.net/giveupgivedown/article/details/130567916
Recommended