How to Build Safe Distributed Locks with Redis and Redisson

This article explains why simple SETNX/EXPIRE commands can cause deadlocks, shows how to achieve atomic lock operations with Lua scripts or the Redis SET command, and demonstrates how to use the Redisson library for re‑entrant, auto‑renewing distributed locks in Java.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Build Safe Distributed Locks with Redis and Redisson

Preface

In everyday development we often need to lock resources, such as decrementing product inventory. The naive approach of reading the stock, checking it, and then decreasing it is not atomic and can cause overselling under concurrency. In a monolithic system a local lock may suffice, but a distributed system requires a distributed lock.

Solution

Using SETNX and EXPIRE

SETNX key value
EXPIRE key seconds
DEL key
if (setnx("item_1_lock",1)) {
    expire("item_1_lock",30);
    try {
        // business logic
    } catch {
        // handle error
    } finally {
        del("item_1_lock");
    }
}

This method can work but is risky because SETNX and EXPIRE are not atomic; if an error occurs after SETNX succeeds, the lock may never expire, leading to a deadlock.

Atomicity with Lua script

if (redis.call('setnx', KEYS[1], ARGV[1]) < 1) then
    return 0;
end;
redis.call('expire', KEYS[1], tonumber(ARGV[2]));
return 1;

Running SETNX and EXPIRE in a Lua script guarantees that both commands succeed or both fail, eliminating the deadlock risk.

SET command (Redis 2.6.12+)

SET key value NX EX 30
DEL key
if (set("item_1_lock",1,"NX","EX",30)) {
    try {
        // business logic
    } catch {
        // handle error
    } finally {
        del("item_1_lock");
    }
}

From Redis 2.6.12 onward the SET command can combine the lock acquisition and expiration atomically.

Getting Started with Redisson

Redisson provides a re‑entrant lock with automatic lease renewal. By adding the Redisson dependency you can use its high‑level API instead of writing raw Redis commands.

Install Redisson

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.13.2</version>
</dependency>
implementation 'org.redisson:redisson:3.13.2'

Simple Example

RedissonClient redissonClient = Redisson.create();
RLock lock = redissonClient.getLock("lock");
boolean res = lock.lock();
if (res) {
    try {
        // business logic
    } finally {
        lock.unlock();
    }
}

Lock Implementation Details (selected snippets)

private void lock(long leaseTime, TimeUnit unit, boolean interruptibly) throws InterruptedException {
    long threadId = Thread.currentThread().getId();
    Long ttl = tryAcquire(leaseTime, unit, threadId);
    if (ttl == null) return;
    // subscription handling omitted for brevity
    // repeat acquisition while needed
}

protected RFuture<Boolean> unlockInnerAsync(long threadId) {
    return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
        "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then return nil; " +
        "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
        "if (counter > 0) then redis.call('pexpire', KEYS[1], ARGV[2]); return 0; " +
        "else redis.call('del', KEYS[1]); redis.call('publish', KEYS[2], ARGV[1]); return 1; end;",
        Arrays.asList(getName(), getChannelName()), internalLockLeaseTime, getLockName(threadId));
}

Conclusion

Using Redis for distributed locking solves many concurrency problems but still has pitfalls such as non‑atomic operations and accidental lock deletion. Choose the appropriate technique (Lua script, SET with NX/EX, or Redisson) based on system scale and requirements, and remember that database‑level safeguards are also essential.

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.

redisdistributed-lockredissonLua Scriptsetnx
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.