Backend Development 22 min read

Comprehensive Guide to Redis Distributed Locks, Redlock, and Redisson Implementation

This article provides an in-depth tutorial on using Redis for distributed locking, covering when locks are needed, core properties, basic SETNX usage, timeout handling, lock renewal with watchdogs, Redlock algorithm debates, and practical Redisson integration with Java code examples.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Comprehensive Guide to Redis Distributed Locks, Redlock, and Redisson Implementation

Distributed locks are essential for ensuring that only one process accesses a shared resource at a time in high‑concurrency environments. This guide starts by asking common questions such as when a lock is required, where to place lock/unlock code, how to avoid unreleased locks, and how to set appropriate timeouts.

Basic Redis lock primitives : The classic approach uses SETNX (or SET if Not eXists ) to acquire a lock and DEL to release it. Example:

> SETNX lock:168 1
(integer) 1   # lock acquired

> SETNX lock:168 2
(integer) 0   # lock acquisition failed

After the critical section the lock is released with DEL lock:168 .

Problems with naïve implementations include node crashes, business‑logic exceptions, and the risk of releasing a lock owned by another client. To solve this, a unique identifier (value) is stored with the lock and verified before deletion, typically via a Lua script to keep the check‑and‑delete operation atomic:

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

Timeout handling : Setting a fixed expiration (e.g., EXPIRE lock:168 60 ) can cause premature release if the business logic runs longer. The solution is to use the atomic SET key value NX PX ttl command (available since Redis 2.6) which sets the value and expiration in one step.

Watchdog (auto‑renewal) : Redisson implements a watchdog that automatically extends the lock’s TTL while the owning thread is alive. The default watchdog interval is one‑third of lockWatchdogTimeout (default 30 s). If a lock is acquired without an explicit lease time, the watchdog periodically runs a Lua script like:

if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then
    redis.call('pexpire', KEYS[1], ARGV[1]);
    return 1;
end
return 0;

Re‑entrant locks : Redisson achieves re‑entrancy by storing a hash where the field is the client UUID and the value is the lock count. Incrementing the count on each re‑entry and decrementing on each unlock ensures the lock is only fully released when the count reaches zero.

Redlock algorithm : To mitigate master‑slave failover issues, the Redlock algorithm acquires the lock on a majority of independent Redis instances. The article outlines the five‑step procedure (time measurement, acquiring on N nodes, checking majority, adjusting TTL, and releasing on all nodes). It also presents the criticism by Martin Kleppmann and the counter‑argument by the Redis author, highlighting concerns about clock synchronization, network latency, and the lack of a fencing token.

Redisson integration : The guide shows how to add the redisson-spring-boot-starter and redisson-spring-data-25 dependencies, configure Spring Boot properties for Redis, and obtain beans such as RedissonClient , RedissonRxClient , and RedisTemplate . Sample Java code demonstrates acquiring a lock, executing business logic inside a try block, and releasing the lock in a finally block to guarantee release even on exceptions.

Additional practical tips include avoiding overly long lock TTLs (which can block the system for hours after a crash), using the watchdog correctly (only when no explicit lease time is set), and configuring lockWatchdogTimeout to a sensible value.

In summary, the article walks through the entire lifecycle of a Redis‑based distributed lock—from basic commands to advanced patterns like re‑entrancy, auto‑renewal, and multi‑node Redlock—providing code snippets, Lua scripts, and best‑practice recommendations for robust concurrency control in backend systems.

JavaConcurrencyRedisDistributed LockRedissonRedlock
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

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.