Mastering Rate Limiting with Redis: 3 Practical Implementations

This article explains three Redis‑based rate‑limiting techniques—using SETNX, sorted sets, and a token‑bucket with lists—providing code examples, discussing their advantages and drawbacks, and showing how to integrate them into Java Spring applications to protect high‑concurrency services.

Programmer DD
Programmer DD
Programmer DD
Mastering Rate Limiting with Redis: 3 Practical Implementations

Facing increasing high‑concurrency scenarios, rate limiting becomes crucial. Redis offers powerful capabilities, and this article demonstrates three simple Redis‑based implementations.

Method 1: Using Redis SETNX

Redis distributed lock relies on SETNX with an expiration. By setting a key with SETNX and an expire time, we can ensure only N requests are allowed within a time window. For example, limiting 20 requests in 10 seconds can be achieved by setting the key to expire after 10 seconds. The drawback is that it cannot handle sliding windows such as 2‑11 seconds.

Method 2: Using Redis Sorted Set (ZSET)

The sliding‑window problem can be solved with a ZSET where each request is stored with a unique value (e.g., UUID) and a score equal to the current timestamp. The ZSET range query retrieves the number of requests within the desired interval. The following code shows how to add a request and check the count.

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("每分钟最多只能访问5次");
        }
    }
    redisTemplate.opsForZSet().add("limit", UUID.randomUUID().toString(), currentTime);
    return Response.ok("访问成功");
}

This approach provides a sliding‑window effect but the ZSET size grows over time.

Method 3: Using Redis List as a Token Bucket

The token‑bucket algorithm controls input and output rates. A Redis List can store tokens; each request pops a token with LEFTPOP. If no token is available, the request is rejected. Tokens are replenished periodically using a scheduled task that pushes a UUID into the list.

// Output token
public Response limitFlow2(Long id) {
    Object result = redisTemplate.opsForList().leftPop("limit_list");
    if (result == null) {
        return Response.ok("当前令牌桶中无令牌");
    }
    return Response.ok(articleDescription2);
}

// Refill tokens every 10 seconds
@Scheduled(fixedDelay = 10_000, initialDelay = 0)
public void setIntervalTimeTask() {
    redisTemplate.opsForList().rightPush("limit_list", UUID.randomUUID().toString());
}

These implementations can be integrated into AOP or filters to protect APIs.

Redis is not limited to caching; its diverse 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.

BackendJavaredisSpring Bootrate limitingSliding WindowToken Bucket
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.