
Distributed Multi-Rule Rate Limiting & Duplicate Prevention with Redis ZSet & Lua
This article demonstrates how to implement distributed multi-rule rate limiting and duplicate submission prevention using Redis sorted sets and atomic Lua scripts, covering annotation design, key generation, concurrency handling, and two Lua implementation strategies with retry logic for timestamp collisions.
Reading font
Introduction
Most Redis rate-limiting tutorials only cover single-rule scenarios (e.g., 1 request per minute or 10 requests per hour). In a distributed system, an API often needs to satisfy multiple rules simultaneously — for example, 1 verification code per minute and 10 per hour — while also preventing duplicate submissions from malicious bursts.
Problems to Solve
How to enforce multiple rate-limiting rules on one endpoint (e.g., 1 request/minute, 10 requests/hour).
How to protect APIs from malicious high-frequency attacks.
How to limit access counts within a specified time window.
Initial Approach: String Counter with Fixed Window
Key design: RedisKey = prefix:className:methodName, RedisValue = access count with a TTL equal to the rule window.
Intercept logic:
On first access, set RedisKey with RedisValue=1 and the window TTL.
On subsequent accesses, read the value; if it exceeds the limit, reject; otherwise increment.
Concurrency Issue at Boundary
Assume the rule is 1000 requests per minute and the current count is 999. Under high concurrency, many threads read 999 simultaneously, all pass the check, then each increments — resulting in >1000 actual requests.
Solution: ensure atomicity via locking or Lua scripts.
Boundary-Case Problem (Fixed Window Edge)
At the exact moment a window expires, a burst of requests can slip through because the counter resets. The article illustrates this with a timeline diagram (omitted here) showing requests at T=59s and T=61s both passing when the limit is 1/minute.
Improved Solution: Redis ZSet (Sorted Set) with Lua
Using a sorted set where score = timestamp and member = unique request identifier enables precise sliding-window counting via ZCOUNT.
Target Annotation Design
@RateLimiter(
rules = {
@RateRule(count = 10, time = 60, timeUnit = TimeUnit.SECONDS), // 10 req / 60s
@RateRule(count = 20, time = 120, timeUnit = TimeUnit.SECONDS) // 20 req / 120s
},
preventDuplicate = true // 5s duplicate prevention (1 req / 5s)
)Annotation Definitions
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RateLimiter {
String key() default RedisKeyConstants.RATE_LIMIT_CACHE_PREFIX;
LimitTypeEnum limitType() default LimitTypeEnum.IP;
ResultCode message() default ResultCode.REQUEST_MORE_ERROR;
RateRule[] rules() default {};
boolean preventDuplicate() default false;
RateRule preventDuplicateRule() default @RateRule(count = 1, time = 5);
}@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RateRule {
long count() default 10;
long time() default 60;
TimeUnit timeUnit() default TimeUnit.SECONDS;
}Key Generation
Composite key:
prefix : identifier (IP/userId/global) : className-methodName.
public String getCombineKey(RateLimiter rateLimiter, JoinPoint joinPoint) {
StringBuffer key = new StringBuffer(rateLimiter.key());
switch (rateLimiter.limitType()) {
case IP:
key.append(IpUtil.getIpAddr(...)).append(":");
break;
case USER_ID:
SysUserDetails user = SecurityUtil.getUser();
if (user != null) key.append(user.getUserId()).append(":");
break;
case GLOBAL:
break;
}
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
key.append(method.getDeclaringClass().getSimpleName())
.append("-").append(method.getName());
return key.toString();
}Lua Script Implementation (Atomic Check-and-Add)
Two variants are provided; both iterate over the rule pairs passed in ARGV (count, windowMs, count, windowMs, ...), use ZCOUNT to get requests in the sliding window, reject if any rule is exceeded, then add the current request and trim old entries.
Variant A: UUID as Member
-- KEYS[1] = composite key
-- KEYS[2] = UUID (distributed unique)
-- KEYS[3] = currentTime (ms)
-- ARGV = [count1, windowMs1, count2, windowMs2, ...]
local key = KEYS[1]
local uuid = KEYS[2]
local currentTime = tonumber(KEYS[3])
local expireTime = -1
for i = 1, #ARGV, 2 do
local rateRuleCount = tonumber(ARGV[i])
local rateRuleTime = tonumber(ARGV[i+1])
local count = redis.call('ZCOUNT', key, currentTime - rateRuleTime, currentTime)
if tonumber(count) >= rateRuleCount then return true end
if rateRuleTime > expireTime then expireTime = rateRuleTime end
end
redis.call('ZADD', key, currentTime, uuid)
redis.call('PEXPIRE', key, expireTime)
redis.call('ZREMRANGEBYSCORE', key, 0, currentTime - expireTime)
return falseVariant B: Timestamp as Member (with Collision Retry)
Uses the current timestamp as the member value. If multiple requests arrive in the same millisecond, ZADD would deduplicate them (since scores are equal and members are equal), causing under-counting. The script retries up to 5 times with incremented timestamp, then adds a random offset.
-- KEYS[1] = composite key
-- KEYS[2] = currentTime (ms)
-- ARGV = [count1, windowMs1, count2, windowMs2, ...]
local key = KEYS[1]
local currentTime = KEYS[2]
local expireTime = -1
for i = 1, #ARGV, 2 do
local rateRuleCount = tonumber(ARGV[i])
local rateRuleTime = tonumber(ARGV[i+1])
local count = redis.call('ZCOUNT', key, currentTime - rateRuleTime, currentTime)
if tonumber(count) >= rateRuleCount then return true end
if rateRuleTime > expireTime then expireTime = rateRuleTime end
end
redis.call('PEXPIRE', key, expireTime)
redis.call('ZREMRANGEBYSCORE', key, 0, currentTime - expireTime)
local maxRetries = 5
local retries = 0
while true do
local result = redis.call('ZADD', key, currentTime, currentTime)
if result == 1 then break end
retries = retries + 1
if retries >= maxRetries then
local random_value = math.random(1, 1000)
currentTime = currentTime + random_value
else
currentTime = currentTime + 1
end
end
return falseAOP Aspect Interception
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private RedisScript<Boolean> limitScript;
@Before(value = "@annotation(rateLimiter)")
public void boBefore(JoinPoint joinPoint, RateLimiter rateLimiter) {
String key = getCombineKey(rateLimiter, joinPoint);
try {
Boolean flag = redisTemplate.execute(limitScript,
ListUtil.of(key, String.valueOf(System.currentTimeMillis())),
(Object[]) getRules(rateLimiter));
if (Boolean.TRUE.equals(flag)) {
log.error("ip: '{}' 拦截到一个请求 RedisKey: '{}'",
IpUtil.getIpAddr(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest()),
key);
throw new ServiceException(rateLimiter.message());
}
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
}Rule Argument Construction
private Long[] getRules(RateLimiter rateLimiter) {
int capacity = rateLimiter.rules().length << 1;
Long[] args = new Long[rateLimiter.preventDuplicate() ? capacity + 2 : capacity];
int index = 0;
if (rateLimiter.preventDuplicate()) {
RateRule preventRateRule = rateLimiter.preventDuplicateRule();
args[index++] = preventRateRule.count();
args[index++] = preventRateRule.timeUnit().toMillis(preventRateRule.time());
}
RateRule[] rules = rateLimiter.rules();
for (RateRule rule : rules) {
args[index++] = rule.count();
args[index++] = rule.timeUnit().toMillis(rule.time());
}
return args;
}Source code reference: https://gitee.com/y_project/RuoYi-Vue/blob/master/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java
For questions about attribution, corrections or content rights, please contactand we will review it promptly.