Three Practical Redis Rate‑Limiting Techniques with Code Samples

This article explains three Redis‑based rate‑limiting approaches—using SETNX for simple counters, ZSET for sliding‑window limits, and a token‑bucket algorithm with List—providing Java code examples and discussing their advantages and drawbacks.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Three Practical Redis Rate‑Limiting Techniques with Code Samples

First method: Redis SETNX

By leveraging Redis' SETNX command together with an expiration time, we can ensure that only a fixed number of requests are allowed within a given time window. For example, setting an expiration of 10 seconds and allowing up to 20 requests achieves basic rate limiting, though it cannot handle sliding windows such as 2‑11 seconds.

Second method: Redis ZSET (sliding window)

The sliding‑window algorithm can be implemented with Redis' sorted‑set (ZSET). Each request is added to a ZSET with a unique value (e.g., a UUID) and a score equal to the current timestamp. By querying the range of scores between now‑interval and now, we obtain the number of requests in the last interval seconds. This approach provides precise sliding‑window limits but causes the ZSET to grow over time.

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("Each minute can be accessed at most 5 times");
        }
    }
    redisTemplate.opsForZSet().add("limit", UUID.randomUUID().toString(), currentTime);
    return Response.ok("Access successful");
}

Third method: Redis token‑bucket with List

The token‑bucket algorithm controls the input rate by storing tokens in a Redis List. When a request arrives, a token is popped from the left; if a token is obtained, the request proceeds, otherwise it is rejected. Tokens are replenished periodically using a scheduled Java task that pushes a new UUID token to the right of the list.

public Response limitFlow2(Long id) {
    Object result = redisTemplate.opsForList().leftPop("limit_list");
    if (result == null) {
        return Response.ok("No token available in the bucket");
    }
    return Response.ok(articleDescription2);
}

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

All three implementations are relatively straightforward and can be integrated into Spring AOP or servlet filters to protect APIs. Beyond rate limiting, Redis offers many other data structures and features such as GeoHash, BitMap, HyperLogLog, and Bloom filters (available from Redis 4.0 onward).

JavaRedisRate LimitingToken Bucket
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.