Data inconsistency scenarios:

Scenario 1 (Query) :

In the case of high concurrency, thread A’s redis is not matched, so it queries the DB and gets the value 1. At this time, the DB is modified, thread B’s redis is not matched, queries the DB and gets the value 2, but thread B first stores the redis, and then thread A stores the redis. At this time, the redis data is 1, which is dirty data.

Solution:

Through the lock solution, ensure the query DB and store redis operation atomicity, or use optimistic lock, add a version number or time stamp, store redis before checking, but still to ensure the search and save atomicity

Scenario 2 (Update) :

Write db first, delete cache, db may be updated, but not updated in Redis, at this time redis hit the data is the old data, so no.

Scenario 3 (Update) :

Delete the cache first, then write to db. Thread A is an update operation, deletes the cache first, but has not written to the DB yet, when thread B arrives, it is A query operation, finds no data in the cache, checks the DB, but thread A has not finished writing to the DB yet, so thread B finds dirty data.

Solution:

Cache-aside pattern: Cache-Aside pattern One of them is that

Invalid: The application retrieves data from the cache. If the application fails to retrieve data, it retrieves data from the database and puts it in the cache.

Hit: An application retrieves data from the cache and returns it.

Update: Save the data to the database, and then invalidate the cache after success.

The concurrency problem with this strategy is that if there are two requests, one for query A and one for update B, the following situation will occur

(1) The cache is just invalid

(2) request A to query the database, get an old value

(3) Request B to write the new value to the database

(4) Request B to delete the cache

(5) Request A to write the found old value into the cache

In this case, the causes of dirty data are:

Request B’s write operation (3) needs to take less time than request A’s read operation (2) before (5).

But what is the possibility of this situation? Here take read/write separation as an example. Why does read/write separation occur? So the chances of that happening are pretty low.

conclusion

Redis and DB data consistency theory is not possible, if you really have strong data consistency requirements, you should not slow down the storage!!