Mastering Redis Distributed Locks: From Basics to Redlock and Advanced Strategies

This article explores the fundamentals and advanced techniques of implementing reliable, high‑performance distributed locks with Redis, covering lock acquisition, waiting and retry strategies, expiration, renewal, safe release, the Redlock algorithm, and practical performance optimizations for backend systems.

IT Services Circle
IT Services Circle
IT Services Circle
Mastering Redis Distributed Locks: From Basics to Redlock and Advanced Strategies

Now almost all back‑ends are distributed systems, and data consistency is a core challenge; locks are indispensable, from synchronized or ReentrantLock in monoliths to distributed locks in multi‑node environments.

Distributed locks and distributed transactions are the two "roadblocks" in distributed systems. Interview questions often focus on SETNX and expiration, but deeper issues such as waiting, timeout, and renewal are frequently overlooked.

1. Lock Acquisition

Any middleware that supports exclusive operations can implement a distributed lock, e.g., ZooKeeper, Nacos, or MySQL SELECT ... FOR UPDATE, but Redis is the most common choice due to its high performance and rich commands.

Redis provides the atomic SET ... EX ... NX command, which creates a simple lock: SET lock_key unique_value EX 30 NX Lock : SETNX lock_key any_value (or SET ... NX) – success returns 1.

Release : DEL lock_key.

1
1

1.1 Waiting and Retry

When SETNX fails, clients should not return immediately. Two main waiting strategies:

1.1.1 Spin Lock

Sleep a short interval and retry until success or total timeout is reached. Simple but wastes CPU and Redis queries.

1.1.2 Event Listening

Use Redis Pub/Sub or Keyspace Notifications to subscribe to the DEL event of the lock key and retry only when the lock is released.

2
2

1.1.2 How to Retry Safely?

Use a globally unique ID (UUID) as the lock value. On retry, check the current value with GET to decide whether the previous attempt succeeded, failed, or the lock is owned by another client.

Query lock existence. Validate lock ownership. Handle lock held by others.

1.2 Expiration and Renewal

Without an expiration, a crashed client would leave a dead lock. The lock must be set with a TTL atomically using SET ... EX ... NX. SET lock_key unique_value EX 30 NX Choosing the TTL depends on business latency; a common practice is to measure the 99.9th percentile execution time and add a safety buffer.

Typical TTL values are 10–30 seconds for most business operations.

1.2.3 Renewal (Watchdog)

A background thread periodically extends the TTL (e.g., EXPIRE lock_key 60) while the lock is still held.

1.2.4 Renewal Failure Strategies

If renewal repeatedly fails, the safest approach is to abort the business logic immediately; a more aggressive approach continues execution at the risk of inconsistency.

2. Lock Release

Releasing must be atomic: check that the stored value matches the client’s UUID before deleting. The usual way is a Lua script:

if redis.call("get", KEYS[1]) == ARGV[1] then
  return redis.call("del", KEYS[1])
else
  return 0
end
11
11

3. Advanced Schemes

3.1 Redlock

Redlock runs the lock command on N independent Redis instances and requires a majority (e.g., 3 of 5) to succeed within the lock’s effective time.

Lock acquisition steps:

Record current timestamp.

Try SET ... EX ... NX on each instance with a short network timeout.

If a majority succeed and total time < TTL‑elapsed, the lock is considered acquired.

Release: run the Lua “check‑and‑delete” script on all instances.

12
12

3.2 Performance Optimizations

3.2.1 Singleflight

Within a single service instance, only one goroutine (or thread) attempts to acquire the lock; others wait for the result, drastically reducing Redis traffic.

14
14

3.2.2 Local Hand‑off

After a thread finishes its work but before releasing the lock, it can hand the lock token to another waiting thread in the same process, avoiding an extra DEL / SETNX round‑trip.

15
15

3.2.3 When to Drop the Lock Altogether

Many use‑cases (e.g., inventory deduction) can be solved with optimistic DB locking or consistent hashing, eliminating the need for a distributed lock.

4. Summary

From the simple SETNX model to renewal, atomic release, Redlock, and various performance tricks, distributed locks revolve around reliability and performance. Understanding the trade‑offs and knowing alternatives such as optimistic locking or consistent hashing is more valuable than memorising command syntax.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentRedlock
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.