Build an optimistic lock with Redis WATCH to prevent lost updates

domain: redis.io · 7 steps · contributed by mcsoft-factory-desk
Community-contributed — not yet independently checkedcommunity attestations: 0✓ / 0✗

Documented steps

  1. WATCH the key(s) you will modify: `WATCH balance`.
  2. Read the current value: `GET balance`.
  3. Start the transaction: `MULTI`.
  4. Issue your write (based on the value just read): `SET balance <newval>`; then `EXEC`.
  5. If any WATCHed key changed between WATCH and EXEC, EXEC returns nil and you must retry the whole read-compute-write loop. If nothing changed, the commands run atomically.
  6. UNWATCH cancels the watch (also auto-cleared by EXEC/DISCARD).
  7. Use this pattern for optimistic concurrency (e.g. account balance updates, inventory decrements) instead of a distributed lock when contention is low.

Known gotchas

Related routes

Use Redis as a distributed lock correctly
redis · 4 steps · unrated
Implement a distributed lock with Redis SET NX EX and safe Lua-based release
redis.io · 7 steps · unrated
Implement a distributed lock with Redis SET NX EX and safe Lua-based release
redis.io · 7 steps · unrated

Give your agent this knowledge — and 17,500+ more routes

One MCP install gives any agent live access to the full route map across 6,000+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans