"Technology blog of the Cloud Era" "http://cloudate.net/?p=379"
2015/01/13 | Db,memcache, concurrency and Multithreading | Robert
There is a key/value stored in the database, but the cache in the Memcache, the key/value has high concurrency query and update operations, how to ensure the consistency of the database and cache?
scenario-a failed cache when updating a database
When UpdateDB (key) Invalidecache (key) when query (key) Updatecache (key)
Problem: There are inconsistencies in the query, such as the following,
Step1:thread1 getdb (key) = A step2:thread3 updatedb (key) = b step3:thread2 getdb (key) = b step4:thread2 Updatecache (ke Y) = B step5:thread1 Updatecache (key) = A
The current data should be Thread3 updated B, but the cache is a, there is an inconsistency, even when the cache is updated using CAs, or the latter will overwrite the former, or there is inconsistency.
Scenario-I update the cache when the database is updated
Step1:cas Get Cache Step2:update db Setp3:cas set cache
Problem: When updating the database, submit directly, then the data in the cache is B, the database is a, as below,
Thread1 CAs get cache with Uniquenum = 1 Thread2 cas get cache with Uniquenum = 1 Thread2 update DB with new value B Threa D2 CAs set cache B with uniquenum = 1 Thread1 update DB with new value A Thread1 CAs set cache A with uniquenum = 1, fail
Scenario 3– Leveraging the database's things/optimistic locks and cached CAs
The database commits after the update cache succeeds, and if the CAS update cache fails, roll back to the database submission.
Thread1 CAs get cache with Uniquenum = 1 Thread1 update DB with new value A Thread1 CAs set cache A with uniquenum = 1 Thr Ead1 Commit Update DB
Thread2 CAs get cache with Uniquenum = 1 Thread2 update DB with new value B Thread2 CAs set cache B with uniquenum = 1 Thr Ead2 Commit Update DB
For the time being no plan 3 have any problem, welcome everyone to shoot bricks.
Database and cache consistency issues