Mastering Distributed Locks: Design, Scenarios, and Redis Implementation

This article explains what distributed locks are, outlines their essential characteristics and common use cases, compares implementation approaches such as database, Redis, and Zookeeper, and provides step‑by‑step designs—including basic and advanced Redis‑based locks—to handle high‑concurrency inventory reduction safely.

dbaplus Community
dbaplus Community
dbaplus Community
Mastering Distributed Locks: Design, Scenarios, and Redis Implementation

What Is a Distributed Lock?

In computer science, a lock (or mutex) is a synchronization mechanism that restricts concurrent access to a shared resource. A distributed lock extends this concept to a multi‑service environment, ensuring ordered and exclusive operations on shared data across different machines.

Key Characteristics of Distributed Locks

Mutual Exclusion : Only one client thread can access the resource at any given time.

Deadlock Prevention : Locks are automatically released after a timeout, avoiding permanent blockage.

High Availability : The lock acquisition mechanism must be reliable and performant.

Optional Features : Blocking vs. immediate return, re‑entrancy, fairness, etc.

Typical Scenarios Solved by Distributed Locks

Multiple users modifying the same data (e.g., order‑deduction, flash sales, ticket booking).

Repeated requests causing duplicate records when responses are delayed.

Distributed coordination where only one node should perform a task at a time.

Implementation Approaches

Database‑based locks – simple but limited by performance (generally not recommended).

Redis‑based locks – fast, suitable for high‑performance needs (AP in CAP).

Zookeeper‑based locks – reliable (CP in CAP) but slower than Redis.

Other options include etcd and Consul.

Designing a High‑Concurrency Distributed Lock with Redis

Scenario: 100 items in stock are sold via a flash‑sale interface; the system must prevent overselling.

1. Without a Lock

Concurrent requests cause multiple orders to succeed even when only one item remains, as shown in the following diagram and test results.

2. Basic Redis Lock (Initial Version)

The lock must provide mutual exclusion, dead‑lock avoidance (via expiration), and high availability (using Redis Cluster). The implementation writes a lock flag to Redis before accessing inventory and deletes it afterward. An expiration time cleans up stale locks, and the lock holder’s identifier prevents accidental deletion.

Key Java code:

String hash = redisCluster.scriptLoad(script, key);
Object result = redisCluster.evalsha(hash, keys, args);

Result screenshots demonstrate successful lock acquisition and correct inventory decrement.

3. Advanced Redis Lock

To meet production requirements, the lock must support atomic operations, renewal, blocking acquisition, and re‑entrancy. Lua scripts provide atomicity and reduce network overhead.

Atomic Operations : Use Redis Lua scripts to combine multiple commands.

Renewal : Asynchronously extend the lock’s TTL or call a renewal method.

Blocking Acquisition : Loop with a timeout until the lock becomes available.

Re‑entrancy : Store a hash where the key is the lock name and the field contains client info; increment a counter on each re‑entry.

Example Lua script for lock and re‑entry (illustrated in the diagram):

Relevant Redis commands: EXISTS key – check if a key exists. HSET key field value – set a hash field. PEXPIRE key milliseconds – set key TTL in ms. HEXISTS key field – test if a hash field exists. HINCRBY key field increment – increment a hash field. PTTL key – get remaining TTL.

Unlocking logic checks the thread identifier, decrements the re‑entry count, and deletes the lock when the count reaches zero.

Conclusion

The article covered distributed‑lock characteristics, common use cases, and three mainstream implementation methods, then detailed a Redis‑based lock design from a simple version to an enterprise‑grade solution. While Redis offers high performance, it does not guarantee absolute consistency; alternatives such as Zookeeper or segment‑based inventory locks may be needed for stricter reliability requirements.

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 Developmenthigh concurrencySynchronization
dbaplus Community
Written by

dbaplus Community

Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.

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.