Distributed Locks and Fencing Tokens: The Lock Expires, and the Holder Does Not Know
System Design series · Part 4 Distributed data (7 of 7)
- Replication and Replication Lag: Why Users Cannot Read What They Just Wrote After Read/Write Splitting
- Sharding: Choosing a Shard Key, Moving Data When You Reshard, and What You Lose Across Shards
- Consistent Hashing: Moving Only 1/N When Nodes Change, Virtual Nodes, Rendezvous Hashing, and Deliberately Chosen Keys
- Distributed IDs: UUIDv7, Snowflake, and Segment Allocation, Compared on Order, Size, and What They Leak
- CAP and PACELC: Consistency or Availability During a Partition, Latency or Consistency Otherwise
- Consensus and Raft: Elections, Log Replication, Read Consistency, and Leader Election with etcd
- Distributed Locks and Fencing Tokens: The Lock Expires, and the Holder Does Not Know
System Design series Part 4-7 | Previous: Consensus and Raft | Next: REST, gRPC, and GraphQL | Series map
Read first: Part 3-4 Transactions and Isolation Levels, Part 4-6 Consensus and Raft.
Scenario and problem
Every day at 3 a.m., the talk platform settles the previous day’s registration fees with its speakers: it totals the amounts, calls the bank’s payout API, and writes a settlement record. The service runs as 3 instances, and the requirements are:
- Only one instance settles at a time
- If the instance doing the work crashes or hangs halfway, another one takes over, without waiting for someone to step in by hand
- The same payment is never paid out twice
- Nightly settlementEvery day at 3 a.m., the previous day's registration fees are settled with the speakers: total the amounts, call the bank's payout API, write a settlement record. The service runs as 3 instances.
- Only one at a timeAll three wake up at 3 a.m., but only one of them may settle at a time.
- Someone takes over a crashIf the instance doing the work crashes or hangs halfway, another one must take over automatically, without waiting for someone to step in by hand.
- Never pay the same item twiceIf the stuck instance wakes up later and thinks it is still settling, the same payment goes out twice. As you will see below, a lock alone cannot stop this.
Points 1 and 2 are an ordinary distributed lock. Point 3 is the hard part: as this post shows, a lock alone cannot deliver point 3.
The simplest approach and its limits
synchronized,ReentrantLock: they only lock within one JVM (see Vertical Scaling, Horizontal Scaling, and Stateless Services)- Lock a row with the database’s
SELECT ... FOR UPDATEand run the whole settlement inside that transaction: mutual exclusion works, and when the holder crashes, its connection drops and the lock is released automatically. But the transaction stays open for several minutes, holding a connection and piling up undo log the whole time, and it calls an external API from inside the transaction. If the transaction rolls back after the payout succeeded, the database no longer knows the money has already gone out - Redis
SET lock 1 NX, thenDELwhen done: if the holder crashes, the lock is never released
The standard fix for the last problem is to make the lock expire on its own (a lease). But automatic expiry is exactly where every problem in the rest of this post comes from.
Core mechanism
What a lock has to provide
| Property | Meaning | How to get it |
|---|---|---|
| Mutual exclusion | Only one holder at a time | An atomic “create only if absent” |
| Never stuck forever | If the holder crashes, the lock is eventually released | The lease expires and the lock is released automatically |
| Fault tolerance | If one machine of the lock service fails, the lock is not lost | Replication or consensus |
The first two conflict: since the lock can expire without the holder knowing, “I hold the lock” can turn false at any moment.
Pauses: the holder does not know it has lost the lock
- Instance A gets a 30-second lease from the lock service and gets ready to start settling.
- The lock service replies with success. From this moment on, A believes it holds the lock.
- A hits a Full GC, and the whole JVM stops for 40 seconds, including the watchdog thread that extends the lease.
- The lease expires, and the lock service releases the lock. A is still frozen in GC and knows nothing about it.
- Instance B comes to get the same lock.
- Nobody holds the lock anymore, so the lock service replies with success, and B starts settling.
- B pays speaker 42 and marks the payment as paid. So far everything is fine.
- GC ends, and A carries on from where it stopped. It does not know the lock expired long ago.
- A pays again, and the same money goes out twice. A lock that can expire cannot stop a holder that wakes up after a pause.
Pauses have many causes: GC stop-the-world, a virtual machine being migrated or having its CPU taken away, memory swapped out, packets stuck in a network queue, the system clock jumping.
The intuitive fix is “check once more that you still hold the lock before writing”, but it does not help: the pause can happen after the check and before the write. As long as “check” and “write” are two steps, there is a gap between them.
Libraries such as Redisson have a watchdog that keeps extending the lease while the holder is alive, so that a long job does not let the lock expire. But the watchdog is also a thread in the same JVM: during a GC pause it stops too, so it cannot solve this problem.
Efficiency locks and correctness locks
Martin Kleppmann divides the uses of distributed locks into two kinds:
- Efficiency: avoid doing the same work twice. If two instances occasionally run at the same time, it only wastes resources. For example, keeping several instances from rebuilding the same cache entry at once in Caching in Depth
- Correctness: if two instances run at the same time, the data ends up wrong. For example, payouts or decrementing stock
For an efficiency lock, a simple Redis lock is enough. A correctness lock cannot rely on the lock alone: the protected resource has to be able to reject operations from an expired holder.
Fencing tokens
Every time the lock is acquired, the lock service also issues a monotonically increasing number. The holder sends this number with every operation on the resource, and the resource remembers the largest number it has seen and rejects anything smaller:
sequenceDiagram
participant A as Instance A
participant L as Lock service
participant B as Instance B
participant DB as Settlement data
A->>L: acquire lock
L-->>A: OK, token 33
Note over A: GC pause
Note over L: expires, released
B->>L: acquire lock
L-->>B: OK, token 34
B->>DB: write (token 34)
Note over DB: max token seen = 34
A->>DB: write (token 33)
DB-->>A: rejected, 33 < 34
This protection does not depend on time: however long A pauses, its token is smaller than that of any later holder. The conditions are:
- The token must be issued atomically together with acquiring the lock, and strictly increase with every acquisition
- The resource itself has to be able to check the token. A database can, with a conditional update; most external APIs cannot, so use an idempotency key instead (see In Java)
Where tokens come from: etcd’s revision (the leader key revision in Consensus and Raft), ZooKeeper’s zxid or the number of a sequential node, or Redisson’s fenced lock. Google’s Chubby offered the same idea, the sequencer, long ago.
Redis locks
The correct way to do it with a single Redis:
SET lock:settlement <random value> NX PX 30000NX: create only if it does not exist;PX 30000: expire automatically after 30 seconds- The value must be a random value that differs on every acquisition. On release, delete the lock only if “the value is still mine”; otherwise A, waking up from a pause, deletes B’s lock
- Release with compare-and-delete: from Redis 8.4 on you can use
DELEX key IFEQ <random value>; earlier versions use a Lua script so that the comparison and the deletion are one atomic operation
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
endThe problem with a single Redis is fault tolerance: Redis replication is asynchronous. If the primary crashes after writing the lock but before replicating it to the replica, the replica is promoted to the new primary without the lock, and another client can acquire it again.
Redlock and the controversy around it
Redlock, proposed in the official Redis documentation, uses N (for example 5) independent Redis primaries: the client acquires the lock on every node in turn, and counts it as acquired only if a majority (at least 3) succeed and the time spent is less than the lock’s validity time; the validity time is reduced by the time spent acquiring the lock.
Kleppmann’s 2016 article points out two problems:
- It relies on timing assumptions: network delay, process pauses, and clock error all need upper bounds. The GC pause scenario above applies to Redlock just the same
- It does not produce a fencing token: without an increasing number, the resource has no way to tell which holder an operation came from
Redis’s author, Salvatore Sanfilippo, replied with a post of his own, arguing that the timing assumptions are reasonable in practice. The practical conclusion of the debate: Redlock adds the cost of running 5 independent nodes, yet still needs fencing to guarantee correctness. For an efficiency lock, a single Redis is enough; correctness comes from fencing and idempotency, and Redlock is rarely worth it.
Other implementations
- A lease table in the database (for example ShedLock): a table keyed by the lock name that records
lock_until. Acquiring the lock is one conditionalUPDATEorINSERT, and it is as durable as the database. Use the database’s clock, to avoid clock skew between application servers - Database advisory locks: MySQL’s
GET_LOCK(), PostgreSQL’spg_advisory_lock(). The lock is tied to the database connection and released when the connection drops; but with a connection pool, the connection holding the lock may be returned to the pool and handed to someone else - etcd, ZooKeeper: the lock is built on consensus, so a node failure in the lock service does not lose the lock, and you get a fencing token for free. The cost is one more service to run
Comparing options
| Implementation | When the lock service fails | Fencing token | Depends on | Good for |
|---|---|---|---|---|
Single Redis (SET NX PX) |
Failover may lose the lock | None | Redis | Efficiency locks |
Redisson RLock |
Same as above, the watchdog renews automatically | None | Redis | Efficiency locks |
Redisson RFencedLock |
Same as above | Yes, but stored in Redis | Redis | Paired with a check at the resource |
| Redlock | Works while a majority of nodes is alive | None | 5 independent Redis nodes, timing assumptions | Rarely worth it |
| Database lease table (ShedLock) | Same as the database | None | The database clock | Running a scheduled job only once |
| Database advisory lock | Released when the connection drops | None | The same connection | Short mutual exclusion within one database |
| etcd, ZooKeeper | Works while a majority of nodes is alive | Yes (revision, zxid) | A consensus service | Correctness locks |
In Java
1. Run a scheduled job only once: ShedLock
The settlement job only needs “never two copies at the same time”, and you already have MySQL, so use ShedLock:
CREATE TABLE shedlock (
name VARCHAR(64) NOT NULL,
lock_until TIMESTAMP(3) NOT NULL,
locked_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
locked_by VARCHAR(255) NOT NULL,
PRIMARY KEY (name)
);@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30M")
public class SchedulingConfig {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.usingDbTime() // use the database clock, unaffected by clock skew between application servers
.build());
}
}@Scheduled(cron = "0 0 3 * * *")
@SchedulerLock(name = "speaker-settlement", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
public void settleYesterday() {
settlementService.settle(LocalDate.now().minusDays(1));
}lockAtMostFor: if the holder crashes, the lock is released automatically after at most 30 minutes. It must be longer than the longest normal run of the settlement; otherwise the lock expires before the settlement is done, and another instance starts it overlockAtLeastFor: even if the job finishes in 1 second, the lock is held for at least 1 minute, so that when the instances’ clocks differ slightly, another one does not run the same scheduled time again
ShedLock is an efficiency lock: it has no fencing token. If a settlement runs longer than 30 minutes, or the holder pauses for more than 30 minutes, two instances can still be doing it at the same time. So the payout itself needs the two further layers of protection below.
2. Check the fencing token at the resource
Add a fence_token column to the settlement record:
CREATE TABLE speaker_settlement (
speaker_id BIGINT NOT NULL,
settle_date DATE NOT NULL,
amount DECIMAL(12,2) NOT NULL,
status VARCHAR(16) NOT NULL, -- PENDING, PAYING, PAID
fence_token BIGINT NOT NULL DEFAULT 0,
payout_id VARCHAR(64),
PRIMARY KEY (speaker_id, settle_date)
);Get a token from Redisson’s fenced lock, claim each payout with the token first, and check again when writing back the result:
@Service
public class SettlementService {
private final RedissonClient redisson;
private final JdbcClient jdbc;
private final PayoutGateway payoutGateway;
public SettlementService(RedissonClient redisson, JdbcClient jdbc, PayoutGateway payoutGateway) {
this.redisson = redisson;
this.jdbc = jdbc;
this.payoutGateway = payoutGateway;
}
public void settle(LocalDate date) throws InterruptedException {
RFencedLock lock = redisson.getFencedLock("lock:speaker-settlement:" + date);
Long token = lock.tryLockAndGetToken(0, 30, TimeUnit.MINUTES); // no waiting, released automatically after 30 minutes
if (token == null) {
return; // another instance is doing it
}
try {
for (Settlement s : findUnpaid(date)) {
payOnce(s, token);
}
} finally {
lock.unlock();
}
}
private void payOnce(Settlement s, long token) {
// 1. Claim with the token: fails if already paid, or already claimed by a holder with a larger token
int claimed = jdbc.sql("""
UPDATE speaker_settlement
SET fence_token = :token, status = 'PAYING'
WHERE speaker_id = :speakerId AND settle_date = :date
AND status IN ('PENDING', 'PAYING') AND fence_token <= :token
""")
.param("token", token)
.param("speakerId", s.speakerId())
.param("date", s.settleDate())
.update();
if (claimed == 0) {
return;
}
// 2. The payout API does not know fencing tokens, so use a fixed idempotency key: one settlement pays out only once, however many times it is called
String idempotencyKey = "settlement:" + s.speakerId() + ":" + s.settleDate();
PayoutResult result = payoutGateway.pay(s.speakerId(), s.amount(), idempotencyKey);
// 3. Check the token again when writing back the result
jdbc.sql("""
UPDATE speaker_settlement
SET status = 'PAID', payout_id = :payoutId
WHERE speaker_id = :speakerId AND settle_date = :date AND fence_token = :token
""")
.param("payoutId", result.payoutId())
.param("speakerId", s.speakerId())
.param("date", s.settleDate())
.param("token", token)
.update();
}
private List<Settlement> findUnpaid(LocalDate date) {
return jdbc.sql("""
SELECT speaker_id AS speakerId, settle_date AS settleDate, amount
FROM speaker_settlement
WHERE settle_date = :date AND status IN ('PENDING', 'PAYING')
""")
.param("date", date)
.query(Settlement.class)
.list();
}
}Each of the three layers stops a different case:
| Case | What stops it |
|---|---|
| Two instances start settling at the same time | The lock (efficiency) |
| A wakes up after a pause, and B has already taken over and claimed the payout | The claim fails on fence_token <= :token |
| A pauses after claiming and before paying, B takes over, claims again, and pays, and A also pays when it wakes up | The payout API’s idempotency key: both calls use the same key, so the bank pays only once |
| The holder crashes after paying and before writing back | The status stays at PAYING; the next settlement claims it again and pays with the same idempotency key, getting back the same result |
What really guarantees “never pays twice” is the idempotency key; the fencing token keeps the state in the database from being overwritten by an expired holder. The lock only keeps duplicate work from happening in most cases.
The code above is written from the official documentation of Redisson 4.0, ShedLock, and Spring Framework, and has not been compiled or run.
PayoutGatewaystands for the API of a bank or payment provider; how the idempotency key is passed depends on each provider’s spec.
Pitfalls and gotchas
- The lock is released before the transaction commits: you acquire the lock inside a
@Transactionalmethod and release it infinally. The release happens when the method ends, but the proxy commits the transaction only after the method returns. If another instance acquires the lock in between, it still reads the old data and does the work again. Put the lock outside the transaction: acquire the lock first, then call the transactional method - Deleting someone else’s lock: releasing with a plain
DELdeletes a lock someone else acquired during your pause. Always compare the value - A lease that is too short: the lock expires before the work is done.
lockAtMostForandleaseTimemust be longer than the longest normal run of the work, and you should monitor the actual run time - Thinking the watchdog solves pauses: during a GC pause the watchdog stops too
- Releasing from another thread: Redisson’s
RLock, like Java’sLock, can be released only by the thread that acquired it; releasing it from another thread throwsIllegalMonitorStateException. Watch out for this when you continue the work withCompletableFutureor on a different virtual thread - The token goes backwards after a Redis failover:
RFencedLockkeeps the token in Redis. Asynchronous replication can lose the most recent increments during a failover, so a newly issued token may repeat an old one. For correctness requirements like moving money, the idempotency key at the resource is not optional; for a stronger guarantee, have etcd or the database issue the token - A lock that is too coarse: one global lock makes every speaker’s settlement wait in line. Split it by resource, for example one lock per day or one per speaker
- Many clients competing for the lock at once: every client keeps retrying, and the polling saturates Redis. Set a wait time and backoff, or use a queue instead
- If a database constraint will do, skip the lock: decrement seats with a conditional update (Transactions and Isolation Levels), and prevent duplicates with a unique index. These are atomic inside the database, with no lease that can expire
Security
- Lock keys built from user input: the
courseIdinlock:course:{courseId}is taken straight from the request, so an attacker can acquire locks on other people’s resources and keep legitimate operations from ever getting the lock. Check authorization before acquiring the lock, and build keys only from IDs validated on the server - Using locks for denial of service: an attacker triggers many “acquire a lock, then run for a long time” operations, each lock is held up to the lease limit, and every legitimate user waits in line. Limit how many locks each user can hold at once, and add rate limiting (Abuse Prevention in Part 8)
- Access control on Redis itself: anyone who can connect to Redis can delete any lock directly. Enable ACLs so that each service can access only keys with its own prefix, use TLS for connections, and do not expose Redis publicly
- The scope of idempotency keys: if an idempotency key is built only from strings the user controls, an attacker can send a request with someone else’s key first, so that the victim’s real request is treated as a duplicate and skipped. Idempotency keys must include information the server decides (for example the settlement’s primary key), and be compared only within the same account
- Fencing is defense in depth: when the lock service is misused or misconfigured, the token check and the idempotency key at the resource still block duplicate writes and payouts
When to use it, and when not to
- Efficiency locks (single Redis, ShedLock): avoiding duplicate computation, running a scheduled job only once, work where an occasional duplicate run does no harm
- Correctness: start with the database’s conditional updates and unique indexes; when you must use a lock, add a fencing token, and add an idempotency key to external calls
- Do not use a distributed lock: to protect updates to a single row (leave that to the database), for long flows across several services (use a saga or a state machine, Part 7), or as a work queue
References
- Martin Kleppmann, “How to do distributed locking”, 2016: https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
- Salvatore Sanfilippo, “Is Redlock safe?”, 2016: http://antirez.com/news/101
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017, Chapter 8
- Mike Burrows, “The Chubby lock service for loosely-coupled distributed systems”, OSDI 2006
- Redis Documentation — Distributed Locks with Redis: https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/
- Redis Documentation — SET: https://redis.io/docs/latest/commands/set/
- Redisson — Locks and synchronizers: https://github.com/redisson/redisson/blob/redisson-4.0.0/docs/data-and-services/locks-and-synchronizers.md
- ShedLock: https://github.com/lukas-krecan/shedlock
- Spring Framework Reference — JdbcClient: https://docs.spring.io/spring-framework/reference/data-access/jdbc/core.html
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments