0
0
Redisquery~30 mins

WATCH for optimistic locking in Redis - Mini Project: Build & Apply

Choose your learning style9 modes available
Using WATCH for Optimistic Locking in Redis
๐Ÿ“– 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
Need a 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
Need a 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
Need a 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
Need a hint?

Add MULTI, then DECRBY product_stock 3, followed by EXEC.