Three Practical Redis Rate‑Limiting Techniques: setnx, ZSet Sliding Window, and Token Bucket

This article explains three Redis‑based rate‑limiting methods—using SETNX for simple counters, leveraging ZSET for a sliding‑window algorithm, and implementing a token‑bucket scheme with LISTs—complete with Java code examples and discussion of their advantages and drawbacks.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Three Practical Redis Rate‑Limiting Techniques: setnx, ZSet Sliding Window, and Token Bucket
Facing increasing high‑concurrency scenarios, rate limiting becomes crucial. Redis offers powerful capabilities, and here we demonstrate three simple implementations.

1. Rate limiting with Redis SETNX

When using Redis for distributed locks, the SETNX command combined with EXPIRE (CAS) is common. For rate limiting, we can use SETNX to allow only N requests within a time window. For example, to allow 20 requests in 10 seconds, we set SETNX with an expiration of 10 seconds and stop when the count reaches 20. This approach is straightforward but cannot slide the window (e.g., cannot count requests from 2‑11 seconds when measuring 1‑10 seconds).

2. Sliding‑window rate limiting with Redis ZSET

The sliding‑window problem can be solved by storing each request in a sorted set ( ZSET) where the member is a unique UUID and the score is the current timestamp. By querying the range of scores within the desired interval, we obtain the number of requests in that period.

public Response limitFlow() {
    Long currentTime = new Date().getTime();
    System.out.println(currentTime);
    if (redisTemplate.hasKey("limit")) {
        Integer count = redisTemplate.opsForZSet()
            .rangeByScore("limit", currentTime - intervalTime, currentTime)
            .size(); // intervalTime is the rate‑limit period
        System.out.println(count);
        if (count != null && count > 5) {
            return Response.ok("Each minute can be accessed at most 5 times");
        }
    }
    redisTemplate.opsForZSet().add("limit", UUID.randomUUID().toString(), currentTime);
    return Response.ok("Access successful");
}

This code achieves the sliding‑window effect, ensuring no more than M requests in N seconds, but the ZSET grows over time.

3. Token‑bucket rate limiting with Redis LIST

The token‑bucket algorithm can be implemented using a Redis LIST. Tokens are pushed into the list at a fixed rate (e.g., every 10 seconds) via a scheduled task, each token being a unique UUID. When a request arrives, we try to LEFTPOP a token; if none is available, the request is rejected.

public Response limitFlow2(Long id) {
    Object result = redisTemplate.opsForList().leftPop("limit_list");
    if (result == null) {
        return Response.ok("No token left in the bucket");
    }
    return Response.ok(articleDescription2);
}
@Scheduled(fixedDelay = 10_000, initialDelay = 0)
public void setIntervalTimeTask() {
    redisTemplate.opsForList().rightPush("limit_list", UUID.randomUUID().toString());
}

These implementations are easy to integrate into AOP or servlet filters to protect APIs.

Redis is not only a cache; its rich data structures (String, Hash, List, Set, ZSET, GeoHash, Bitmap, HyperLogLog, Bloom filter) enable many advanced use cases.

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.

Backendrate limitingZSetToken Bucketsetnx
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.