Understanding Distributed Locks and Redis RedLock Implementation
This article explains the concept of distributed locks, illustrates real‑world scenarios such as concurrent ATM transactions, and details how to implement reliable distributed locking with Redis using TTL keys, SETNX, Lua scripts, lock renewal, high‑availability considerations, and the RedLock algorithm.
Distributed locks are synchronization mechanisms used in distributed systems to ensure mutual exclusion when multiple nodes or processes share resources, preventing interference and guaranteeing consistency.
For example, two independent ATM machines updating the same account must acquire a lock before modifying the balance, then release it after the operation.
Implementing a distributed lock with Redis
3.1 Key with TTL
Create a key with an expiration time (TTL) so the lock is automatically released if the client crashes.
get -> not exists, acquire success -> set -> ttl -> delWhen the client releases the lock, it deletes the key.
3.2 SETNX
Using the TTL‑key approach requires separate GET and SET operations, which are not atomic. Redis provides the SETNX command to set a key only if it does not exist, optionally with an expiration.
set key value px milliseconds nx3.3 SETNX + Lua
To avoid race conditions when releasing a lock, the client must compare the stored value (ensuring uniqueness) before deleting. This atomic check‑and‑delete can be done with a Lua script:
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end3.4 Lock Renewal
If the business operation takes longer than the original TTL, the lock may expire prematurely. A common solution is to run a watchdog process that periodically extends the TTL of the lock until the operation completes.
3.5 High‑Availability Issues
In a single‑node Redis deployment, a failure makes the lock unavailable. Adding replicas does not solve the problem because replication is asynchronous; a master crash before replication can cause two clients to hold the same lock.
Scenario: ATM‑A acquires the lock from the master, the master crashes before syncing to the slave, the slave is promoted, and ATM‑B acquires the lock while ATM‑A is still processing, leading to safety violations.
4. Redis Module – RedLock
RedLock is a Redis‑based distributed lock algorithm designed to avoid single‑point failures by using N (odd, ≥3) independent Redis master nodes without replication.
Clients attempt to acquire the same key/value on all N instances; if they succeed on at least N/2 + 1 nodes, the lock is considered acquired.
4.1 Acquiring the lock
The lock is obtained when a majority of nodes grant it, preventing multiple clients from simultaneously holding the lock.
4.2 Releasing the lock
Clients must send a release command to every Redis node, even if some nodes did not grant the lock initially.
4.3 Delayed restart
After a node crashes, it should not be restarted immediately; waiting longer than the lock validity time ensures any locks it participated in have expired, avoiding interference after restart.
4.4 Advantages
Effectively prevents single‑point failures.
4.5 Disadvantages
Requires maintaining multiple Redis master instances, which can be cumbersome.
Strongly dependent on synchronized clocks; clock drift can compromise lock safety.
Node crashes and restarts can still affect lock safety depending on Redis persistence settings.
For further details, refer to the official Redis documentation and the RedLock GitHub repository.
Aikesheng Open Source Community
The Aikesheng Open Source Community provides stable, enterprise‑grade MySQL open‑source tools and services, releases a premium open‑source component each year (1024), and continuously operates and maintains them.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.