📖 Scenario: You are managing a simple inventory system where multiple users can update the stock count of a product. To avoid conflicts when two users try to update the stock at the same time, you will use Redis's WATCH command for optimistic locking.
🎯 Goal: Build a Redis transaction that safely updates the stock count of a product using WATCH to detect changes and retry if the stock was modified by another user.
📋 What You'll Learn
Create a Redis key product_stock with initial stock value 10
Use WATCH on the product_stock key before starting the transaction
Get the current stock value and check if it is enough to reduce by 3
Use MULTI and EXEC to decrement the stock by 3 atomically
If the transaction fails due to concurrent modification, retry the operation
💡 Why This Matters
🌍 Real World
Optimistic locking with WATCH is useful in inventory systems, booking systems, or any application where multiple users update shared data concurrently.
💼 Career
Understanding Redis transactions and optimistic locking is important for backend developers working with caching, real-time data, and distributed systems.
Progress0 / 4 steps
1
Set initial stock value
Create a Redis key called product_stock and set its value to 10 using the SET command.
Redis
Hint
Use the SET command to create the key with the initial stock.
2
Watch the stock key
Use the WATCH command on the product_stock key to monitor it for changes before starting the transaction.
Redis
Hint
Use WATCH product_stock to watch the key.
3
Get the current stock value
Use GET product_stock to retrieve the current stock value (executed immediately). In a real application or client script, check here if the value is at least 3 before proceeding to the transaction.
Redis
Hint
Use GET product_stock before MULTI to read and check the value client-side.
4
Start transaction, decrement, and execute
Start the transaction with MULTI, decrement the stock atomically with DECRBY product_stock 3, and execute with EXEC. If EXEC returns (nil), the WATCH was triggered by a concurrent change—retry the entire operation from WATCH.
Redis
Hint
Add MULTI, then DECRBY product_stock 3, followed by EXEC.
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
Step 1: Understand the role of WATCH in Redis
WATCH is used to monitor keys for any changes before a transaction starts.
Step 2: Identify what happens if keys change
If any watched key changes before EXEC, the transaction is canceled to avoid conflicts.
Final Answer:
To monitor keys for changes before executing a transaction -> Option A
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
Step 1: Identify correct order for optimistic locking
You must first WATCH the key to monitor changes, then start MULTI for transaction.
Step 2: Confirm command order
The correct order is WATCH counter, then MULTI, then commands like INCR, finally EXEC.
Final Answer:
WATCH counter, MULTI, INCR counter, EXEC -> Option B
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
Step 1: Understand WATCH behavior on key change
If a watched key changes before EXEC, the transaction is aborted to prevent conflicts.
Step 2: Identify EXEC result when aborting
When aborted, EXEC returns null (or nil) indicating the transaction did not run.
Final Answer:
EXEC will fail and return null -> Option A
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
Step 1: Analyze why stock is not decremented
If another client changes the watched key after WATCH, EXEC aborts the transaction silently.
Step 2: Confirm command correctness
DECR syntax is correct and EXEC is present, so no syntax errors.
Final Answer:
The stock key was modified by another client after WATCH -> Option C
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
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.
Step 2: Confirm correct command order
WATCH first, then GET value, then MULTI, then conditionally INCR, finally EXEC.
Final Answer:
WATCH counter
val = GET counter
MULTI
if val < 10:
INCR counter
EXEC -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.