NOTE
3.2 Redis Concurrency Competition
The Redis concurrency-competition problem and solutions using atomic commands, mutexes, optimistic locking, and Lua scripts.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is the Concurrency Competition Problem?
Suppose the initial value of price is 10, and two connections both need to perform a +10 operation on it. The correct result should be 30.
- Connection 1 reads
priceas 10. - Connection 2 reads
priceas 10. - Connection 1 adds 10 to
price, obtaining 20, and writes it back. - Connection 2 adds 10 to
price, obtaining 20, and writes it back. As above, the final result is 20 instead of 30. The reason is that the update operation is split into two steps here: firstget, thenset, rather than being atomic.
2. How to Solve the Concurrency Competition Problem
Redis is single-threaded, so in theory there is no concurrency competition unless multiple operations at the application layer are not atomic.
2.1. Atomic Commands
incr and decr are atomic commands.
2.2. Add a Mutex
A distributed lock can be used.
2.3. Optimistic Locking
Use Redis’s watch command and transactions.
watch price
get price $price
$price = $price + 10
multi
set price $price
exec
- Connection 1 watches
priceat 10. - Connection 2 watches
priceat 10. - Connection 1 adds 10 to
price, obtaining 20, writes it back, and executes successfully in the transaction. - Connection 2 adds 10 to
price, obtaining 20, and writes it back. Because step 3 modifiedprice, it finds thatpriceis no longer 10 when modifying it, so the transaction fails.
2.4. Lua Script
Redis can guarantee the atomicity of Lua-script execution.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub