What If a Redis Lock Expires While the Old Client Is Still Running?

The most dangerous moment for a Redis distributed lock is rarely failing to acquire it. It is when the lock has already expired while the old holder is still running.

Client A acquires a lock with a 10-second TTL, then stalls for 15 seconds mid-execution because of a GC pause, network congestion, or a slow downstream API. Once the lease expires, Client B acquires the lock and gets to work. Then A wakes back up, and now both clients are modifying the same resource. Even if your lock and unlock commands are written completely right, that window still exists.

Once you see this clearly, the safety boundary of a Redis lock is much easier to draw: it can coordinate concurrent callers, but on its own it cannot guarantee that a shared resource only accepts operations from the current holder.

Three details a basic Redis lock has to get right first

The crudest implementation grabs a key with SETNX and removes it with DEL when the work is done. That gives you mutual exclusion, but it easily leaves orphaned locks behind: if the client crashes right after acquiring the lock, DEL never runs.

Adding an expiration avoids holding the lock forever, but you cannot split SETNX and EXPIRE into two separate commands. If the client crashes after the first command succeeds and before the second runs, the lock still has no lease. Redis’s SET command options let you combine “write only if absent” and “set expiration” into a single atomic operation:

1
SET order:123 7f5d... NX PX 30000

The value cannot just be a constant like 1 either. Each acquisition needs its own unique random token; otherwise, if A’s lock expires and B acquires a new one, A’s late DEL will wipe out B’s lock.

Releasing the lock also needs to check the token and delete the key atomically. The standard approach is a Lua script:

1
2
3
4
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0

At this point, a lock on a single Redis instance meets the baseline requirements: atomic acquisition, a built-in lease, a unique token per holder, and owner-only release. That is also the single-instance baseline described in Redis’s official documentation.

Still, all of this only guarantees that the lock record inside Redis isn’t mismanaged. Whether an old client can still modify the underlying shared resource is a separate problem.

Expiration turns a lock into a lease

A local mutex is normally released actively by the thread holding it. A distributed lock with a TTL behaves more like a lease: the client holds permission to act for a fixed window, and once time is up, the lock service lets someone else take over.

The problem is that Redis knows the key has expired, but it has no way to stop business code that is already running:

1
2
3
4
5
6
7
Client A: acquires lock token=A, TTL 10s
↓
Pauses for 15s mid-execution
↓ Redis: A's lock expires
Client B: acquires token=B
↓
Client A resumes and keeps writing to the shared resource

A unique token and Lua-based unlock prevent A from deleting B’s lock, but they do nothing to stop A’s code from writing to a database, touching a file, or calling a downstream service. Having A re-check Redis right before writing isn’t enough either, because A can still pause right after that check, and by the time it resumes, the lock has already changed hands.

This is why “just give the TTL plenty of headroom” only lowers the odds. You can estimate normal task duration, but you can rarely put a reliable upper bound on process pauses, network delays, and dependency timeouts.

What auto-renewal helps with, and what it doesn’t

Another approach is to renew the lease periodically while the task is running. Redisson’s watchdog uses this idea: when no explicit lease time is specified, it keeps extending the lock’s TTL for as long as the holding client is still healthy and working.

This helps a lot with legitimate long-running tasks. If a job occasionally stretches from 10 seconds to 30, you don’t have to set an absurdly large TTL up front, and you won’t drop the lock simply because normal execution took longer than usual.

Still, the renewal thread itself runs inside the client process. If the process hits a long pause, loses connectivity to Redis, or fails to run the renewal before the lease expires, the lock still lapses. When the client recovers, it can still keep running the stale task. A watchdog improves lease management; it does not turn a lease into a never-expiring local mutex.

Primary-replica failover opens a second way to lose a lock

The window above happens on the client side. When Redis runs with primary-replica replication and automatic failover, the lock record itself can vanish during a switchover.

Suppose A writes the lock on the primary, and the primary crashes before that command replicates to a replica. The replica gets promoted to primary without the key, so B can immediately acquire the same lock. Both A and B now believe they hold exclusive access.

This is a direct consequence of asynchronous replication. Redis’s own distributed lock documentation explicitly flags this as a case where a primary-plus-replica setup cannot guarantee mutual exclusion. Replication confirmation commands like WAIT can reduce the chance of unsynced data, but Redis’s documentation is clear that WAIT does not turn asynchronous replication into strongly consistent replication.

So whenever someone asks “is a Redis lock safe?”, you have to specify the deployment topology. A single instance, primary-replica with failover, and Redlock across multiple independent nodes do not offer the same set of guarantees.

Redlock targets node failure, but the debate hasn’t gone away

Instead of relying on one primary and its asynchronous replicas, Redlock writes the lock across multiple independent Redis primary nodes. With five nodes, for example, the client must get successful replies from at least three within the lock’s validity time. If it fails to reach a majority, or if the total elapsed time already exceeds the validity window, acquisition fails. On release, the client attempts to clean up all nodes.

The design aims to keep the lock service available when a minority of Redis nodes go down, while avoiding the single-failover lock loss problem. Even so, it is still a time-bounded lease. Its correctness depends on network delays, process pauses, and clock drift remaining small relative to the TTL.

That is the heart of Martin Kleppmann’s critique of Redlock: if the lock is responsible for correctness, a client that pauses past lease expiration can still write to the resource, and Redlock provides no monotonically increasing fencing token that would let the resource reject a late-arriving old holder. In his response, Redis creator Salvatore Sanfilippo argued that Redlock works under explicit timing and clock assumptions, and offered a different take on random tokens and resource-side checks.

Reducing that debate to “Redlock is completely safe” or “Redlock is unusable” misses the point. The better questions are: can your workload tolerate occasional duplicate execution, does your infrastructure satisfy the timing assumptions the algorithm relies on, and does the resource layer have a second line of defense if the lock fails?

To protect data, checking the lock isn’t enough

If duplicate execution just means doing the same computation twice, a Redis lock works well as an efficiency optimization. An occasional lock failure wastes some compute, not data integrity. In those cases, a single-instance lock is usually plenty, and much simpler to build and operate.

If a failed lock means overselling inventory, corrupting balances, or overwriting data, you cannot leave correctness solely to a lease. The resource layer needs a way to reject expired holders, and a fencing token is a common way to do that.

Each time the lock service grants a lock, it also returns a strictly increasing number:

1
2
3
4
Client A acquires token=33, then hits a long pause
Client B acquires token=34 and writes to the resource
Client A resumes and sends a write carrying token=33
The resource sees 33 < 34 (already processed) and rejects the request

A random UUID cannot do this. It can tell Redis whether a key still belongs to the current client, but it carries no ordering. When the resource sees two UUIDs, it has no idea which request is stale.

Fencing tokens come with a clear constraint, though: the database or service being protected has to store and validate that number. For third-party APIs you can’t modify, plain file writes, or stores without conditional updates, a fencing token is hard to apply directly. In those cases, you usually have to close the gap with unique constraints, version-checked conditional updates, transactions, idempotency keys, or a business state machine, rather than adding more tricks to the lock itself.

Switching to ZooKeeper doesn’t eliminate resource-side protection

ZooKeeper locks are typically built on ephemeral sequential nodes. It gives you ordered coordination state, and when a client session expires, its ephemeral node gets cleaned up automatically. Those properties make it a better fit for coordination than Redis’s asynchronous primary-replica failover.

Even so, session expiration does not kill the client process. If a client pauses for too long or gets partitioned, ZooKeeper deletes its node and hands the lock to the next client in line; once the old client wakes up, it can still touch the resource. So correctness-critical writes still need a fencing token or an equivalent resource-side guard. Swapping out the lock service changes the failure model, but it doesn’t make late requests disappear.

How I decide whether to use a Redis lock now

The first question I ask is whether this lock is for efficiency or for correctness. If it’s just cutting down duplicate work, a single-instance Redis lease is usually simple and effective. If a single duplicate execution corrupts data, the lock is only a front-door throttle to smooth out concurrency spikes, and the database and downstream services still need their own constraints.

On the implementation side, I no longer hand-roll locks out of raw SETNX and DEL. I pick a well-maintained client library and verify its token generation, atomic unlock, renewal behavior, failover semantics, and failure strategy. Monitoring can’t stop at “did lock acquisition succeed?” either. You also want to track hold duration, renewal failures, wait times, and whether tasks are still running after their lock expires.

A Redis lock will block most everyday concurrency. Once a lease lapses, though, the old client gets no command telling its code to stop immediately. Whenever data correctness matters, the final check has to live on the resource actually being modified.


References: Redis Distributed Locks Documentation, Redis WAIT Command, Redisson Watchdog Configuration, Martin Kleppmann’s Analysis of Redlock, Salvatore Sanfilippo’s Response, ZooKeeper Lock Recipe