Redis for LLD: The Right Data Structure, Atomically

Five Redis patterns that cover almost every LLD problem, and why each needs to be atomic.

By SysAdmin ยท Published 2026-11-20

Redis makes every single command atomic. Your bugs live in the gap between two commands.

Part 3 of the LLD Foundations series. If a problem's page lists redis under Recommended, ask for a RedisClient in your constructor (see Part 1):

public class RateLimiterImpl implements RateLimiterContract {
    private final RedisClient redis;

    public RateLimiterImpl(RedisClient redis) {
        this.redis = redis;
    }
}

1. What the client gives you

The RedisClient covers the core commands, grouped by data type:

TypeMethods
Strings / countersget, set, setEx, setNx, incr, incrBy, decr, del, exists, expire, ttl
Lists (queues)lpush, rpush, lpop, rpop, lrange, llen
Setssadd, sismember, smembers, scard
Sorted setszadd, zrange, zrevrange, zscore, zrank, zcard
Hashes (objects)hset, hget, hgetAll, hexists, hdel
Everything elseeval(script, keys, args), publish, keys, type

Anything not in the table, such as ZREMRANGEBYSCORE, ZPOPMIN or SET ... NX PX, goes through eval. That's not a workaround: a Lua script runs atomically on the server, which is exactly what LLD problems need.

โš ๏ธ Trap: keys(pattern) scans the whole keyspace and blocks Redis while it runs. Don't put it on a hot path. Keep an index (a set or sorted set of ids) instead.

2. Why one command is safe and two aren't

Redis executes one command at a time, so incr can never lose an update. But a sequence of commands can interleave with another client's:

// โŒ Two clients can both read "1", and both take the last unit
String left = redis.get("stock:" + sku);
if (Integer.parseInt(left) > 0) {
    redis.decr("stock:" + sku);
}

The fix is always one of these:

  1. A single command that does the check itself. setNx only sets if absent; incr returns the new value, so you check after incrementing.
  2. A Lua script when the logic needs several commands.

3. Pattern 1: counters with expiry (fixed window)

// โŒ If anything fails between the two calls, the key never expires
long n = redis.incr(key);
if (n == 1) redis.expire(key, 60);

As one script, the counter and its expiry are set together:

private static final String INCR_WITH_TTL = """
    local n = redis.call('INCR', KEYS[1])
    if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
    return n
    """;

public boolean allow(String userId) {
    Object r = redis.eval(INCR_WITH_TTL, List.of("rl:" + userId), List.of("60"));
    return ((Number) r).longValue() <= 100;   // 100 requests per 60 s window
}

๐Ÿ’ก Tip: eval returns an Object: a number for integer replies, a String for text, null for nil and a List for arrays. Cast through Number for counts.

4. Pattern 2: sliding windows (sorted set)

A fixed window lets a burst through at the boundary: 100 requests at 0:59 and 100 more at 1:00. A sliding window keeps one timestamped entry per request in a sorted set:

private static final String SLIDING = """
    local now    = tonumber(ARGV[1])
    local window = tonumber(ARGV[2])
    local limit  = tonumber(ARGV[3])
    redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
    if redis.call('ZCARD', KEYS[1]) < limit then
      redis.call('ZADD', KEYS[1], now, ARGV[4])
      redis.call('PEXPIRE', KEYS[1], window)
      return 1
    end
    return 0
    """;

public boolean allow(String userId) {
    long now = System.currentTimeMillis();
    Object r = redis.eval(SLIDING, List.of("sw:" + userId),
            List.of(String.valueOf(now), "60000", "100", now + "-" + UUID.randomUUID()));
    return ((Number) r).longValue() == 1;
}

Removing old entries, counting, and adding the new one must happen in one script. Otherwise two requests can both see 99 and both get in. The member is unique, so two requests in the same millisecond don't overwrite each other.

5. Pattern 3: locks with an owner and a timeout

setNx alone has no expiry: if the holder dies, the lock is held forever. Set the value and the TTL atomically, and release only your own lock:

private static final String ACQUIRE = "return redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2])";
private static final String RELEASE = """
    if redis.call('GET', KEYS[1]) == ARGV[1] then
      return redis.call('DEL', KEYS[1])
    end
    return 0
    """;

public String tryLock(String resource, long ttlMs) {
    String token = UUID.randomUUID().toString();
    Object r = redis.eval(ACQUIRE, List.of("lock:" + resource), List.of(token, String.valueOf(ttlMs)));
    return r == null ? null : token;          // nil means someone else holds it
}

public boolean unlock(String resource, String token) {
    Object r = redis.eval(RELEASE, List.of("lock:" + resource), List.of(token));
    return ((Number) r).longValue() == 1;
}

โš ๏ธ Trap: del("lock:x") without the owner check can delete a lock that expired and was taken by someone else.

6. Pattern 4: queues and priority queues

private static final String POP_MIN = """
    local r = redis.call('ZPOPMIN', KEYS[1])
    if #r == 0 then return nil end
    return r[1]
    """;

public void enqueue(String taskId, int priority) {
    redis.zadd("tasks", priority, taskId);
}

public String dequeue() {
    return (String) redis.eval(POP_MIN, List.of("tasks"), List.of());
}

A zrange followed by a separate del is the classic double-processing bug.

7. Pattern 5: objects as hashes, plus an index

Store each entity as a hash and keep the ids in a set, so you can list them without keys:

public void saveServer(String id, String host, int weight) {
    redis.hset("server:" + id, "host", host);
    redis.hset("server:" + id, "weight", String.valueOf(weight));
    redis.sadd("servers", id);
}

public Map<String, String> loadServer(String id) {
    Map<String, String> h = redis.hgetAll("server:" + id);
    return h.isEmpty() ? null : h;
}

When an object's fields must change together with other keys, for example when moving a task from "running" to "done", do it in one script.

8. Choosing a structure

You needUse
A count, an id, a quotaString with incr
Something that expiressetEx, or EXPIRE / PEXPIRE inside a script
First in, first outList
Ordered by time or prioritySorted set (score = timestamp or priority)
Membership, uniquenessSet
A record with fieldsHash, plus a set of ids
Check and update togetherA Lua script

Takeaways

Try it yourself: Build a Sliding Window Rate Limiter, Build a Priority Task Queue and Build a Circuit Breaker all run against a real Redis.