Bird
Raised Fist0
Redisquery~10 mins

WATCH for optimistic locking in Redis - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - WATCH for optimistic locking
Start Transaction
↓
WATCH key(s)
↓
Read current value(s)
↓
MULTI - start commands queue
↓
Queue commands
↓
EXEC - try to commit
↓
Success
↓
Retry or Abort
WATCH monitors keys for changes before transaction; if keys change, EXEC aborts to prevent conflicts.
Execution Sample
Redis
WATCH balance
val = GET balance
MULTI
SET balance val-10
EXEC
This sequence watches 'balance', reads it, queues a decrement, then tries to commit if no changes.
Execution Table
StepCommandActionKey State BeforeKey State AfterResult
1WATCH balanceStart watching 'balance'balance=100balance=100OK
2GET balanceRead current valuebalance=100balance=100100
3MULTIStart transaction queuebalance=100balance=100OK
4SET balance 90Queue command to set balance to 90balance=100balance=100QUEUED
5EXECTry to commit transactionbalance=100balance=90[OK]
6EndTransaction completebalance=90balance=90Success
💡 EXEC commits because 'balance' was not changed after WATCH; transaction succeeds.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
balance1001009090
transaction_statenonenonecommittedcommitted
Key Moments - 2 Insights
Why does EXEC fail if the watched key changes before EXEC?
Because WATCH detects the key change and causes EXEC to return NULL, aborting the transaction to avoid conflicts (see execution_table step 5).
What happens if you don't call MULTI after WATCH?
Commands run immediately without transaction; WATCH has no effect without MULTI/EXEC (no queuing or atomic commit).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'balance' after step 2?
A90
B100
CNULL
D110
💡 Hint
Check 'Key State Before' and 'Result' columns at step 2 in execution_table.
At which step does the transaction actually commit the changes?
AStep 3 (MULTI)
BStep 4 (SET command queued)
CStep 5 (EXEC)
DStep 1 (WATCH)
💡 Hint
Look for when 'transaction_state' changes to 'committed' in variable_tracker and 'Result' in execution_table.
If another client changes 'balance' after WATCH but before EXEC, what will EXEC return?
ANULL - transaction aborted
BOK - transaction committed
CError - syntax error
DQUEUED - commands queued
💡 Hint
Recall the behavior described in key_moments about EXEC aborting if watched keys change.
Concept Snapshot
WATCH key(s) monitors keys for changes.
MULTI starts a transaction queue.
Commands are queued until EXEC.
EXEC commits if keys unchanged; else aborts.
Use WATCH to avoid race conditions in Redis.
Full Transcript
In Redis, WATCH is used for optimistic locking by monitoring keys for changes before a transaction. First, WATCH is called on keys to monitor. Then the current values are read. MULTI starts queuing commands. Commands like SET are queued but not executed yet. EXEC tries to commit all queued commands atomically. If any watched key changed after WATCH, EXEC aborts and returns NULL to avoid conflicts. Otherwise, EXEC commits changes. This prevents race conditions when multiple clients modify the same keys concurrently.

Practice

(1/5)
1. What is the main purpose of the WATCH command in Redis optimistic locking?
easy
A. To monitor keys for changes before executing a transaction
B. To lock keys permanently for exclusive access
C. To delete keys automatically after a timeout
D. To create backups of keys before modification

Solution

  1. Step 1: Understand the role of WATCH in Redis

    WATCH is used to monitor keys for any changes before a transaction starts.
  2. Step 2: Identify what happens if keys change

    If any watched key changes before EXEC, the transaction is canceled to avoid conflicts.
  3. Final Answer:

    To monitor keys for changes before executing a transaction -> Option A
  4. Quick Check:

    WATCH detects key changes before transaction [OK]
Hint: WATCH checks keys before transaction to avoid conflicts [OK]
Common Mistakes:
  • Thinking WATCH locks keys permanently
  • Assuming WATCH deletes keys
  • Believing WATCH creates backups
2. Which of the following is the correct sequence of Redis commands to safely update a key counter using optimistic locking?
easy
A. MULTI, WATCH counter, INCR counter, EXEC
B. WATCH counter, MULTI, INCR counter, EXEC
C. WATCH counter, INCR counter, MULTI, EXEC
D. INCR counter, WATCH counter, MULTI, EXEC

Solution

  1. Step 1: Identify correct order for optimistic locking

    You must first WATCH the key to monitor changes, then start MULTI for transaction.
  2. Step 2: Confirm command order

    The correct order is WATCH counter, then MULTI, then commands like INCR, finally EXEC.
  3. Final Answer:

    WATCH counter, MULTI, INCR counter, EXEC -> Option B
  4. Quick Check:

    WATCH before MULTI for optimistic locking [OK]
Hint: Always WATCH before MULTI to start transaction safely [OK]
Common Mistakes:
  • Starting MULTI before WATCH
  • Running commands before MULTI
  • Not using EXEC at the end
3. Consider this Redis transaction sequence:
WATCH balance
MULTI
INCR balance
EXEC

If another client modifies balance after WATCH but before EXEC, what will be the result of EXEC?
medium
A. EXEC will fail and return null
B. EXEC will succeed and increment balance
C. EXEC will throw a syntax error
D. EXEC will retry automatically

Solution

  1. Step 1: Understand WATCH behavior on key change

    If a watched key changes before EXEC, the transaction is aborted to prevent conflicts.
  2. Step 2: Identify EXEC result when aborting

    When aborted, EXEC returns null (or nil) indicating the transaction did not run.
  3. Final Answer:

    EXEC will fail and return null -> Option A
  4. Quick Check:

    Key changed after WATCH causes EXEC to return null [OK]
Hint: If watched key changes, EXEC returns null, no update done [OK]
Common Mistakes:
  • Assuming EXEC still increments key
  • Expecting syntax error on EXEC
  • Thinking EXEC retries automatically
4. You wrote this Redis code:
WATCH stock
MULTI
DECR stock
EXEC

But sometimes the stock count is not decremented even though no errors occur. What is the most likely cause?
medium
A. EXEC command was missing
B. The DECR command syntax is incorrect
C. The stock key was modified by another client after WATCH
D. WATCH does not support DECR command

Solution

  1. Step 1: Analyze why stock is not decremented

    If another client changes the watched key after WATCH, EXEC aborts the transaction silently.
  2. Step 2: Confirm command correctness

    DECR syntax is correct and EXEC is present, so no syntax errors.
  3. Final Answer:

    The stock key was modified by another client after WATCH -> Option C
  4. Quick Check:

    Concurrent key change aborts transaction silently [OK]
Hint: Concurrent changes abort EXEC silently, no decrement done [OK]
Common Mistakes:
  • Blaming DECR syntax
  • Forgetting EXEC command
  • Thinking WATCH blocks commands
5. You want to safely increment a shared counter only if it is less than 10 using Redis optimistic locking. Which code snippet correctly implements this logic?
hard
A. WATCH counter if val < 10: val = GET counter MULTI INCR counter EXEC
B. MULTI WATCH counter val = GET counter if val < 10: INCR counter EXEC
C. WATCH counter MULTI val = GET counter if val < 10: INCR counter EXEC
D. WATCH counter val = GET counter MULTI if val < 10: INCR counter EXEC

Solution

  1. Step 1: Understand optimistic locking with conditional logic

    You must WATCH the key, then GET its value before starting MULTI to ensure value is current.
  2. Step 2: Confirm correct command order

    WATCH first, then GET value, then MULTI, then conditionally INCR, finally EXEC.
  3. Final Answer:

    WATCH counter val = GET counter MULTI if val < 10: INCR counter EXEC -> Option D
  4. Quick Check:

    GET before MULTI after WATCH ensures correct conditional update [OK]
Hint: GET value after WATCH but before MULTI for safe conditional update [OK]
Common Mistakes:
  • Starting MULTI before GET
  • Getting value after MULTI
  • Not watching key before GET
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard