Correct distributed lock with Redis (token, TTL, Lua release)

Backend Live Coding November 13, 2026 python

The TTL prevents an "eternal" lock if the process dies.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# ======================================================================
# Q: How do you implement a distributed lock with Redis correctly?
#
# The TTL prevents an "eternal" lock if the process dies. The token prevents me
# from deleting a lock that someone else acquired after mine expired. redis-py
# has a ready-made r.lock(name, timeout=...). For critical correctness I prefer
# PostgreSQL advisory locks or database constraints.
# ======================================================================

token = uuid.uuid4().hex
if r.set('lock:erp-sync', token, nx=True, px=60_000):     # only if it does not exist, with a TTL
    try:
        run_sync()
    finally:
        # release only if the lock is still mine (atomic with Lua)
        r.eval("if redis.call('get', KEYS[1]) == ARGV[1] then "
               "return redis.call('del', KEYS[1]) else return 0 end", 1, 'lock:erp-sync', token)