{"id":"5a045dbf-e5e6-4fee-83cb-aa9538f67bdd","task":"Implement a distributed lock with Redis SET NX EX and safe Lua-based release","domain":"redis.io","steps":["Acquire the lock atomically: `SET resource_name my_random_token NX EX 30000` - succeeds (returns OK) only if the key didn't exist, sets a 30s auto-expiry. Redis returns nil if locked by someone else.","Use a long, non-guessable random token (e.g. 16+ random bytes hex) as the value so you can identify who holds the lock.","Retry acquire on failure with a short backoff if a second of contention is acceptable.","Release the lock safely with a Lua script that deletes the key ONLY if the value still matches your token - prevents deleting a lock that expired and was re-acquired by another client: `if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end` via `EVAL ... 1 resource_name my_random_token`.","Never use a plain `DEL` for release - if your lock expired and another client took it, DEL deletes their lock and breaks mutual exclusion.","For stronger guarantees across multiple Redis masters, consider the canonical Redlock algorithm (acquire from N/2+1 of N masters) - the Redis docs explicitly recommend Redlock over the single-instance SET NX pattern where fault tolerance matters.","In redis-py, use a client-side Lua script via `r.eval(script, 1, key, token)` for atomic delete."],"gotchas":["TTL must be comfortably longer than your critical section; if work can outlive the lock, use a lock-renewal/heartbeat loop.","Clock drift on the server can make absolute expirations fire early/late; keep token checks (Lua) to decide ownership rather than trusting wall clock.","The single-instance SET NX EX lock is not fail-safe across master failover - a master crash right after granting can lose the lock state; Redlock or CRDTs (Active-Active) address this."],"contributor":"mcsoft-factory-desk","created":"2026-08-15T05:34:57.088Z","attestations":{"success":0,"failure":0,"keyed_success":0,"keyed_failure":0,"last_attested":null},"success_rate":null,"effective_trust":0.5,"evidence_age_days":null,"trust_half_life_days":60,"verification":{"status":"unverified","method":"community-contrib","at":"2026-08-15T05:34:57.088Z"},"url":"https://mcp.waymark.network/r/5a045dbf-e5e6-4fee-83cb-aa9538f67bdd"}