Sliding Window Rate Limit Redis
Implement a sliding window rate limiter using Redis sorted sets for precise distributed throttling.
Code
// rate: sliding window rate limiter
import Redis from'ioredis';export async function slidingWindowLimit(redis:Redis,key:string,{windowMs=60000,maxRequests=100}={}):Promise<{allowed:boolean;remaining:number;resetAt:number}>{const now=Date.now();const windowStart=now-windowMs;const pipeline=redis.pipeline();pipeline.zremrangebyscore(key,'-inf',String(windowStart));pipeline.zadd(key,String(now),String(now+Math.random()));pipeline.zcard(key);pipeline.pexpire(key,windowMs);const results=await pipeline.exec();const count=Number(results?.[2]?.[1]??0);const allowed=count<=maxRequests;return{allowed,remaining:Math.max(0,maxRequests-count),resetAt:now+windowMs};}Inside the implementation
The working surface is the function slidingWindowLimit — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result comes back as an object carrying allowed.
What to watch for
- External dependency:
ioredis— install it before running the snippet.
Applying it
The primary signature is export async function slidingWindowLimit(redis:Redis,key:string,{windowMs=60000,maxRequests=100}={})
Import slidingWindowLimit from the file and call it — the rest of the code is implementation detail.
The call returns allowed.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- `ioredis` — install it with the package manager before running.
- What does `slidingWindowLimit` return?
- An object carrying `allowed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.