Distributed Rate Limiting using Redis Sliding Windows
Fixed-window rate limiting has a fatal flaw. Here is how to implement a precise sliding window using Redis Sorted Sets.
Fixed window rate limiting (e.g. 100 requests per minute) is easy, but vulnerable to bursts. If a user sends 100 requests at 12:00:59 and 100 requests at 12:01:01, they processed 200 requests in 2 seconds.
Sliding Window with Redis ZSETs: Instead of a simple counter, store each request's timestamp in a Redis Sorted Set (ZSET).
- Remove all elements from the set older than 1 minute (
ZREMRANGEBYSCORE). - Count the remaining elements in the set (
ZCARD). - If the count exceeds the limit, reject the request.
- If not, add the current timestamp to the set (
ZADD).
This ensures that at any given rolling 60-second window, the limit is strictly enforced. It is O(N) where N is the number of requests in the window, which is highly performant in Redis.
Tags
Related Blogs
Beyond JWTs: Designing a Stateful, High-Performance Session Architecture
Stateless JWTs are great until you need to instantly revoke a compromised session. Here's how to build a stateful, Redis-backed authentication system that handles 50k+ concurrent users with sub-millisecond validation.
Handling Stripe Webhooks Resiliently with Idempotency Keys
Webhooks fail. Webhooks retry. Webhooks arrive out of order. If your payment architecture isn't idempotent, you will inevitably double-charge users or double-provision resources.
Migrating from TanStack Start to Next.js App Router: An Architecture Post-Mortem
A deep dive into why we moved our entire CMS away from Vite SSR and TanStack Router, the performance implications of Server Components, and the hydration traps we had to fix.