Backend Development 6 min read

Redis Distributed Lock: Basic Implementation, Expiration, Safety Measures, and Lua Atomicity

This article explains how to implement a Redis distributed lock, covering the basic SETNX approach, adding expiration, handling lock release errors with renewal and unique identifiers, achieving atomicity via Lua scripts, and discussing the inherent challenges of network delay, process pause, and clock drift in distributed systems.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Redis Distributed Lock: Basic Implementation, Expiration, Safety Measures, and Lua Atomicity

Redis Distributed Lock

Technology evolves to solve problems, and distributed locks are a classic example of using Redis to coordinate resource access across multiple machines.

Simplest Version

The most basic way to acquire a lock is to use Redis' SETNX command, which sets a key only if it does not already exist.

setnx key value

If the key does not exist, Redis creates it with the given value; otherwise the command returns 0.

Expiration Time

When the machine that holds the lock crashes, the lock could remain forever. A common safeguard is to set an expiration time so the lock is released automatically after a period.

setnx key value nx ex 100

The time unit is seconds.

What If the Wrong Lock Is Released?

Two problems can arise:

The task has not finished but the lock expires, allowing another process to acquire it.

A process mistakenly releases a lock that belongs to another process.

Solutions:

Lock renewal – periodically extend the expiration while the task is running.

Unique lock identifier – store a UUID (or other unique value) as the lock value so only the owner can release it.

Optimized design (illustrated in the image below):

Lua for Atomicity

When deleting a lock, a race condition can occur if the lock has been reassigned. Using a Lua script ensures the check‑and‑delete operation is atomic.

Example Lua script (shown in the image):

Final Defense – NPC

In distributed systems, the biggest enemy is NPC, an acronym for Network Delay, Process Pause, and Clock Drift.

Network Delay – latency that cannot be fully eliminated even with TCP guarantees.

Process Pause – pauses caused by garbage collection, cloud‑server migration, or other factors, which can last from milliseconds to minutes.

Clock Drift – unsynchronized hardware clocks that may jump forward or backward, even when synchronized via NTP.

These three issues are unavoidable, meaning there is no perfectly safe distributed lock; solutions must be chosen based on business requirements.

If the master node fails, Redis (being an AP system) may not have replicated the lock to replicas. The official RedLock algorithm can be used to require a majority of nodes to hold the key before considering the lock acquired.

RedLock adds safety at the cost of additional complexity, and sometimes a simpler approach is sufficient.

Backend Technical Community Invitation

Build a high‑quality technical exchange community. Developers, recruiters, and anyone interested in sharing job referrals are welcome to join and help each other grow.

Source: juejin.cn/post/7255902957035323450

Please keep discussions focused on technical exchange, job referrals, and industry topics.

Advertisements and private solicitations are prohibited; beware of scams.

backend developmentConcurrencyRedisDistributed LockluaRedlock
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login 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.