NOTE
3.2 Redis Concurrency Competition
Two clients reading and updating the same value can race. These notes use concurrent price increments to examine unexpected update results.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is a Race Condition?
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 Resolve Race Conditions
Redis is single-threaded, so in theory there are no race conditions 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.
3. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub