Mastering Redis Rate Limiting: 3 Practical Techniques with Java

This article explains three Redis‑based rate‑limiting methods—using SETNX, a ZSET sliding window, and a token‑bucket with List—provides Java code examples, and discusses their advantages, drawbacks, and how to integrate them into backend services.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Redis Rate Limiting: 3 Practical Techniques with Java

When high‑concurrency scenarios grow, rate limiting becomes crucial. Redis provides powerful capabilities, and this article demonstrates three simple implementations.

Method 1: Using Redis SETNX

The SETNX command, combined with an expiration, can act as a distributed lock. By setting a key with a 10‑second TTL and allowing only 20 successful SETNX operations within that window, we achieve basic rate limiting. This approach cannot easily handle sliding windows.

Method 2: Using Redis ZSET (sliding window)

A sliding‑window algorithm can be realized with a sorted set where each request is stored with a unique UUID as the member and the current timestamp as the score. By querying the range of scores within the desired interval, we obtain the request 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 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("访问成功");
}

Method 3: Token Bucket with Redis List

Each request attempts to pop a token from a Redis list. If the list is empty, the request is rejected; otherwise it proceeds. Tokens are replenished periodically by a scheduled task that pushes a UUID into the list.

public Response limitFlow2(Long id) {
    Object result = redisTemplate.opsForList().leftPop("limit_list");
    if (result == null) {
        return Response.ok("当前令牌桶中无令牌");
    }
    return Response.ok(articleDescription2);
}
@Scheduled(fixedDelay = 10_000, initialDelay = 0)
public void setIntervalTimeTask() {
    redisTemplate.opsForList().rightPush("limit_list", UUID.randomUUID().toString());
}

These snippets can be placed in AOP or filter layers to protect endpoints. Beyond rate limiting, Redis also supports other structures such as GeoHash, Bitmap, HyperLogLog, and Bloom filters for 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.

Javaredisrate limitingSliding WindowToken Bucket
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

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.