0
0
Redisquery~5 mins

WATCH for optimistic locking in Redis

Choose your learning style9 modes available
Introduction
WATCH helps prevent conflicts when many people try to change the same data at the same time.
When multiple users try to update the same item in a shopping cart.
When several processes try to change a shared counter or value.
When you want to make sure your update is based on the latest data.
When you want to avoid overwriting changes made by others.
When you want to retry an update if the data changed before you saved.
Syntax
Redis
WATCH key1 [key2 ...]
MULTI
  commands
EXEC
UNWATCH
WATCH marks keys to watch for changes before starting a transaction.
If any watched key changes before EXEC, the transaction is aborted.
Examples
Watch 'mykey' for changes, then increment it inside a transaction.
Redis
WATCH mykey
MULTI
INCR mykey
EXEC
Watch the user's balance before decreasing it by 10.
Redis
WATCH user:123:balance
MULTI
DECRBY user:123:balance 10
EXEC
Watch the shopping cart key before adding an item.
Redis
WATCH cart:456
MULTI
HSET cart:456 item "apple"
EXEC
Sample Program
This example watches the 'counter' key. If no one else changes it, it increments the counter by 1.
Redis
WATCH counter
MULTI
INCR counter
EXEC
OutputSuccess
Important Notes
If the watched key changes before EXEC, EXEC returns null and the transaction does not run.
Use UNWATCH to cancel watching keys if you decide not to run the transaction.
WATCH is useful to avoid lost updates in concurrent environments.
Summary
WATCH helps detect changes to keys before running a transaction.
If watched keys change, the transaction is canceled to avoid conflicts.
Use WATCH with MULTI and EXEC to safely update shared data.