Redis Multi-Rule Rate Limiting: Sliding Window, Lua Atomicity & Duplicate Prevention
This article demonstrates how to implement distributed multi-rule rate limiting and duplicate submission prevention in Redis using sorted sets and Lua scripts for atomic operations, covering annotation-based configuration, sliding window algorithms, concurrency handling, and boundary condition solutions with complete Java and Lua code examples.
Reading font

Problem Statement
Most Redis rate-limiting tutorials only cover a single rule (e.g., 1 request per minute or 10 requests per hour). In a distributed system, an interface may need to satisfy multiple rules simultaneously (e.g., 1 request per minute and 10 requests per hour) while also preventing duplicate submissions within a short window.
Approach 1: String-Based Fixed Window Counter
Design
RedisKey = prefix:className:methodName RedisValue = access count
Algorithm
On first access, set RedisKey with RedisValue=1 and the rule's TTL.
On subsequent accesses, fetch the current count; if it exceeds the limit, reject; otherwise increment.
Concurrency Issue at Boundary
Assume the limit is 1000 requests per minute and the current count is 999. Multiple concurrent threads read 999, all pass the check, then each increments, causing the actual count to exceed 1000.
Solution : Ensure atomicity via Lua scripting or distributed locks.
Critical-Window Edge Case
A request arriving exactly at the window boundary (e.g., at 59.9s and 60.1s) may be counted in two adjacent windows, effectively allowing double the limit. The article illustrates this with a diagram (see image below).
Approach 2: Sorted Set (Zset) Sliding Window with Lua
Data Structure
RedisKey = prefix:ip/userId:className-methodName RedisScore = request timestamp (milliseconds)
RedisValue = unique identifier (UUID or timestamp with retry)
Lua Script Logic
Parameters passed to the script: KEYS[1] = combined key KEYS[2] = unique value (UUID) KEYS[3] = current time in milliseconds ARGV = flat array of [count, windowMs, count, windowMs, ...] for each rule
-- 1. Get parameters
local key = KEYS[1]
local uuid = KEYS[2]
local currentTime = tonumber(KEYS[3])
-- 2. Determine max TTL from rules
local expireTime = -1
-- 3. Iterate over rules (step 2)
for i = 1, #ARGV, 2 do
local rateRuleCount = tonumber(ARGV[i])
local rateRuleTime = tonumber(ARGV[i + 1])
-- 3.1 Count requests in sliding window
local count = redis.call('ZCOUNT', key, currentTime - rateRuleTime, currentTime)
-- 3.2 If any rule exceeded, return true (limited)
if tonumber(count) >= rateRuleCount then
return true
end
-- 3.3 Track max window for TTL
if rateRuleTime > expireTime then
expireTime = rateRuleTime
end
end
-- 4. Add current request
redis.call('ZADD', key, currentTime, uuid)
-- 5. Set key TTL to max window
redis.call('PEXPIRE', key, expireTime)
-- 6. Remove expired entries
redis.call('ZREMRANGEBYSCORE', key, 0, currentTime - expireTime)
return falseHandling Same-Millisecond Collisions (Alternative Value Strategy)
Instead of UUID, use the timestamp as the value. If ZADD returns 0 (member already exists), retry with incremented timestamp up to 5 times, then add a random offset.
local maxRetries = 5
local retries = 0
while true do
local result = redis.call('ZADD', key, currentTime, currentTime)
if result == 1 then
break
else
retries = retries + 1
if retries >= maxRetries then
local random_value = math.random(1, 1000)
currentTime = currentTime + random_value
else
currentTime = currentTime + 1
end
end
endAnnotation-Driven Configuration
@RateLimiter
@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);
}@RateRule
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RateRule {
long count() default 10;
long time() default 60;
TimeUnit timeUnit() default TimeUnit.SECONDS;
}Usage Example
@RateLimiter(
rules = {
@RateRule(count = 10, time = 60, timeUnit = TimeUnit.SECONDS),
@RateRule(count = 20, time = 120, timeUnit = TimeUnit.SECONDS)
},
preventDuplicate = true
)AOP Interceptor Implementation
Key Generation
public String getCombineKey(RateLimiter rateLimiter, JoinPoint joinPoint) {
StringBuffer key = new StringBuffer(rateLimiter.key());
switch (rateLimiter.limitType()) {
case IP:
key.append(IpUtil.getIpAddr(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest())).append(":");
break;
case USER_ID:
SysUserDetails user = SecurityUtil.getUser();
if (!ObjectUtils.isEmpty(user)) key.append(user.getUserId()).append(":");
break;
case GLOBAL:
break;
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Class<?> targetClass = method.getDeclaringClass();
key.append(targetClass.getSimpleName()).append("-").append(method.getName());
return key.toString();
}Advice Method
@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();
}
}Building ARGV Array
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());
}
for (RateRule rule : rateLimiter.rules()) {
args[index++] = rule.count();
args[index++] = rule.timeUnit().toMillis(rule.time());
}
return args;
}Key Takeaways
String-based fixed window is simple but suffers from boundary double-counting and requires atomic increments.
Zset with timestamps as scores enables precise sliding-window counting via ZCOUNT.
Lua scripting guarantees atomic check-and-add across multiple rules.
Unique values (UUID or timestamp-with-retry) prevent member collisions in the sorted set.
Annotation + AOP provides a clean, reusable integration point for Spring applications.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.