0
0
RedisHow-ToBeginner · 3 min read

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
EXEC
💻

Example

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 WATCH before MULTI will not monitor keys.
  • If a watched key changes, EXEC returns null and the transaction is aborted.
  • Always check the result of EXEC to 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

CommandDescription
WATCH key1 [key2 ...]Monitor keys for changes before a transaction
MULTIStart a transaction block
EXECExecute all commands in the transaction if keys unchanged
DISCARDCancel 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.