How to Use WATCH in Redis for Transaction Control
Use the
WATCH command in Redis to monitor one or more keys for changes before starting a transaction with MULTI. If any watched key changes before EXEC, the transaction is aborted to avoid conflicts.Syntax
The WATCH command monitors one or more keys. If any of these keys change before the transaction executes, the transaction will be aborted.
After WATCH, use MULTI to start the transaction, then queue commands, and finally call EXEC to execute them atomically.
redis
WATCH key1 [key2 ...]
MULTI
// commands
EXECExample
This example shows how to watch a key, start a transaction, modify the key, and execute the transaction only if the key was not changed by others.
redis
WATCH mykey MULTI INCR mykey EXEC
Output
1
Common Pitfalls
- Not calling
WATCHbeforeMULTIwill not monitor keys. - If a watched key changes,
EXECreturnsnulland the transaction is aborted. - Always check the result of
EXECto confirm if the transaction succeeded.
redis
WATCH mykey MULTI INCR mykey EXEC // If another client changes 'mykey' before EXEC, the result is null // Correct usage: WATCH mykey MULTI INCR mykey EXEC // if EXEC returns null then retry transaction
Quick Reference
| Command | Description |
|---|---|
| WATCH key1 [key2 ...] | Monitor keys for changes before a transaction |
| MULTI | Start a transaction block |
| EXEC | Execute all commands in the transaction if keys unchanged |
| DISCARD | Cancel the transaction and unwatch keys |
Key Takeaways
Use WATCH to monitor keys before starting a transaction with MULTI.
If any watched key changes before EXEC, the transaction aborts and EXEC returns null.
Always check EXEC's result to know if the transaction succeeded or needs retry.
WATCH helps avoid race conditions by ensuring atomic updates.
Use DISCARD to cancel a transaction and unwatch keys if needed.