NOTE

3.2 Redis Concurrency Competition

The Redis concurrency-competition problem and solutions using atomic commands, mutexes, optimistic locking, and Lua scripts.

Redis / CacheCreated Updated 1 min readhistorical

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.

  1. Connection 1 reads price as 10.
  2. Connection 2 reads price as 10.
  3. Connection 1 adds 10 to price, obtaining 20, and writes it back.
  4. 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: first get, then set, 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
  1. Connection 1 watches price at 10.
  2. Connection 2 watches price at 10.
  3. Connection 1 adds 10 to price, obtaining 20, writes it back, and executes successfully in the transaction.
  4. Connection 2 adds 10 to price, obtaining 20, and writes it back. Because step 3 modified price, it finds that price is 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

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub