What is WATCH and optimistic locking in Redis?
Answer
WATCH key [key ...] implements optimistic locking in Redis. After calling WATCH, if any watched key is modified by another client before EXEC is called, the transaction is aborted — EXEC returns nil instead of executing the queued commands. The typical pattern is: (1) WATCH a key, (2) read its value, (3) start MULTI, (4) queue write commands based on the read value, (5) EXEC — if it returns nil, retry from step 1. This implements a check-and-set (CAS) operation, enabling race-free read-modify-write cycles without pessimistic locking. Use WATCH for low-contention scenarios like updating a user's balance based on its current value. Under high contention (many concurrent retries), Lua scripting is more efficient as it runs atomically without needing retries.
Previous
How do MULTI and EXEC work in Redis transactions?
Next
What is Lua scripting in Redis and when should you use it?
More Redis Questions
View all →- Intermediate What is Redis Cluster and how does it shard data?
- Intermediate What is the difference between Redis Sentinel and Redis Cluster?
- Intermediate How do MULTI and EXEC work in Redis transactions?
- Intermediate What is Lua scripting in Redis and when should you use it?
- Intermediate What are Redis eviction policies?