Redis › Transactions
How does the WATCH command enable optimistic locking within a Redis transaction?
IntermediateAnswer
WATCH lets you monitor one or more keys for changes made by other clients before your transaction executes, and if any watched key is modified between calling WATCH and calling EXEC, the entire transaction is automatically aborted, letting your application detect the conflict and retry the operation safely rather than working with stale data.
WATCH account:1:balance
val = GET account:1:balance
MULTI
SET account:1:balance <new_value>
EXECReal-world example An inventory management system watches a product's stock count before decrementing it, so if another customer's purchase changes the stock count first, the transaction safely aborts and the application retries with the updated value.