You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by "Baoyuantop (via GitHub)" <gi...@apache.org> on 2025/12/03 03:29:27 UTC

Re: [PR] feat(limit-count): add sliding window support for redis-based policies [apisix]

Baoyuantop commented on code in PR #12756:
URL: https://github.com/apache/apisix/pull/12756#discussion_r2583501795


##########
apisix/plugins/limit-count/limit-count-redis.lua:
##########
@@ -40,12 +40,61 @@ local script = core.string.compress_script([=[
 ]=])
 
 
-function _M.new(plugin_name, limit, window, conf)
+local script_sliding = core.string.compress_script([=[
+    assert(tonumber(ARGV[3]) >= 1, "cost must be at least 1")
+
+    local now = tonumber(ARGV[1])
+    local window = tonumber(ARGV[2])
+    local limit = tonumber(ARGV[3])
+    local cost = tonumber(ARGV[4])
+
+    local window_start = now - window
+
+    -- remove events outside of the window
+    redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, window_start)
+
+    local current = redis.call('ZCARD', KEYS[1])
+
+    if current + cost > limit then
+        local earliest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
+        local reset = 0
+        if #earliest == 2 then
+            reset = earliest[2] + window - now
+            if reset < 0 then
+                reset = 0
+            end
+        end
+        return {-1, reset}
+    end
+
+    for i = 1, cost do
+        redis.call('ZADD', KEYS[1], now, now .. ':' .. i)

Review Comment:
   Hi @sihyeonn, any updates?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org