🔴 Redis Intermediate

What is WATCH and optimistic locking in Redis?

Answer

WATCH key [key ...] implements optimistic locking in Redis. After calling WATCH, if any watched key is modified by another client before EXEC is called, the transaction is aborted — EXEC returns nil instead of executing the queued commands. The typical pattern is: (1) WATCH a key, (2) read its value, (3) start MULTI, (4) queue write commands based on the read value, (5) EXEC — if it returns nil, retry from step 1. This implements a check-and-set (CAS) operation, enabling race-free read-modify-write cycles without pessimistic locking. Use WATCH for low-contention scenarios like updating a user's balance based on its current value. Under high contention (many concurrent retries), Lua scripting is more efficient as it runs atomically without needing retries.