Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/upstash_ratelimit/src/lua-scripts/multi.ts>slidingWindowLimitScript

Rate limiting library for serverless runtimes
Latest
variable slidingWindowLimitScript
import { slidingWindowLimitScript } from "https://deno.land/x/upstash_ratelimit@v2.0.5-canary/src/lua-scripts/multi.ts";

type

` local currentKey = KEYS[1] -- identifier including prefixes local previousKey = KEYS[2] -- key of the previous bucket local tokens = tonumber(ARGV[1]) -- tokens per window local now = ARGV[2] -- current timestamp in milliseconds local window = ARGV[3] -- interval in milliseconds local requestId = ARGV[4] -- uuid for this request local incrementBy = tonumber(ARGV[5]) -- custom rate, default is 1 local currentFields = redis.call("HGETALL", currentKey) local requestsInCurrentWindow = 0 for i = 2, #currentFields, 2 do requestsInCurrentWindow = requestsInCurrentWindow + tonumber(currentFields[i]) end local previousFields = redis.call("HGETALL", previousKey) local requestsInPreviousWindow = 0 for i = 2, #previousFields, 2 do requestsInPreviousWindow = requestsInPreviousWindow + tonumber(previousFields[i]) end local percentageInCurrent = ( now % window) / window if requestsInPreviousWindow * (1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then return {currentFields, previousFields, false} end redis.call("HSET", currentKey, requestId, incrementBy) if requestsInCurrentWindow == 0 then -- The first time this key is set, the value will be equal to incrementBy. -- So we only need the expire command once redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second end return {currentFields, previousFields, true} `