Redis › Transactions

How does the WATCH command enable optimistic locking within a Redis transaction?

Intermediate

Answer

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>
EXEC
Real-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.

Common follow-ups: What does EXEC return if a watched key was modified before it ran?;How many keys can be watched at the same time?