Three Simple Redis Rate‑Limiting Techniques You Can Implement Today
This article explains three practical Redis‑based rate‑limiting methods—using SETNX, ZSET sliding windows, and a token‑bucket algorithm with List—complete with Java code examples and a discussion of their advantages and drawbacks.
Method 1: Rate limiting with Redis SETNX
By leveraging Redis' SETNX command together with an expiration time, you can ensure that only a fixed number of requests are allowed within a given time window. For example, setting an expiry of 10 seconds and allowing 20 successful SETNX calls implements a 20‑request‑per‑10‑seconds limit. The main drawback is that this approach cannot easily slide the window (e.g., from 2‑11 seconds) and requires maintaining multiple keys for overlapping intervals.
Method 2: Sliding window using Redis ZSET
A sliding‑window rate limiter can be built with a sorted set (ZSET). Each incoming request adds a unique value (e.g., a UUID) with the current timestamp as the score. By querying the ZSET for members whose scores fall within the desired time range, you can count the number of requests in that interval.
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 implementation provides a true sliding window but the ZSET size grows over time.
Method 3: Token‑bucket algorithm with Redis List
The token‑bucket approach stores tokens in a Redis list. When a request arrives, the service attempts to LEFTPOP a token; if none are available, the request is rejected. Tokens are replenished periodically by a scheduled task that RIGHTPUSH unique identifiers into the list.
// Consume 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());
}All three methods are straightforward to integrate into an AOP interceptor or servlet filter to protect your APIs.
Beyond rate limiting, Redis offers many other capabilities such as caching, distributed locks, GeoHash, BitMap, HyperLogLog, and Bloom filters (available from Redis 4.0 onward).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
