Sliding Window with Sorted Sets in Redis
Implement an accurate distributed sliding window rate limiter using Redis sorted sets, with atomic operations and automatic expiry of old entries.
Sliding Window with Sorted Sets in Redis is a free API Rate Limiting & Scalability Patterns lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the API Rate Limiting & Scalability Patterns learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
From Theory to Production
You understand the sliding window log and counter conceptually. Now build one that works across many servers using Redis sorted sets, the most common production technique for accurate distributed rate limiting.
Why Sorted Sets
A Redis sorted set (ZSET) stores members ranked by a numeric score. By using the request timestamp as the score, we get an ordered log of recent requests we can trim and count efficiently.
One Key Per Client
Each client gets a key like rl:user123. Every incoming request adds a member to that client's sorted set, scored by the current timestamp in milliseconds.
ZADD rl:user123 1700000000123 1700000000123Trimming the Window
Before counting, remove entries older than the window. If the window is 60 seconds, delete everything with a score below now - 60000. This keeps only the requests inside the current sliding window.
ZREMRANGEBYSCORE rl:user123 0 (now-60000)Counting Requests
After trimming, the cardinality of the set is the number of requests in the window. Compare it against the limit to allow or deny.
ZCARD rl:user123Atomicity Matters
Doing trim, add, and count as separate commands creates a race condition under concurrency. Wrap them in a single Lua script so Redis executes them atomically per client.
The Lua Script
A Lua script run with EVAL performs all steps in one atomic operation, returning whether the request is allowed. No two requests can interleave mid-check.
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[2], ARGV[2])
return 1
end
return 0Setting Expiry
Always set a TTL on the key (a bit longer than the window) so abandoned clients do not leak memory. Idle keys expire automatically.
EXPIRE rl:user123 120Accuracy vs Memory
This approach is highly accurate because it tracks every request timestamp, but memory grows with request volume per window. For very high-traffic clients, the sliding window counter approximation uses far less memory.
Handling Many Nodes
Because all API nodes talk to the same Redis, the limit is enforced globally regardless of which node handles a request. Use a Redis cluster or replica setup for availability, mindful that replication lag can slightly relax limits.
Failure Modes
Decide what happens if Redis is unreachable: fail open (allow traffic, risk overload) or fail closed (block traffic, risk outage). Most public APIs fail open with a local fallback limiter.
Quick Check
Test your understanding of the Redis sliding window.
Recap
You built a distributed sliding window:
- Store request timestamps in a Redis sorted set, one key per client.
- Trim old entries with
ZREMRANGEBYSCORE, count withZCARD. - Wrap trim/count/add in a Lua script for atomicity.
- Set a TTL to free memory, and decide fail-open vs fail-closed for Redis outages.
Frequently asked questions
Is the “Sliding Window with Sorted Sets in Redis” lesson free?
Yes — the full text of “Sliding Window with Sorted Sets in Redis” is free to read here on the web, and the API Rate Limiting & Scalability Patterns course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the API Rate Limiting & Scalability Patterns course, upgrade to CoddyKit PRO.
What will I learn in “Sliding Window with Sorted Sets in Redis”?
Implement an accurate distributed sliding window rate limiter using Redis sorted sets, with atomic operations and automatic expiry of old entries. You practise API Rate Limiting & Scalability Patterns with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start API Rate Limiting & Scalability Patterns?
No prior experience is required. API Rate Limiting & Scalability Patterns on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sliding Window with Sorted Sets in Redis” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this API Rate Limiting & Scalability Patterns lesson?
Yes. Every API Rate Limiting & Scalability Patterns lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Sliding Window Log Implementation
- Sliding Window Counter Strategy
- Algorithm Comparison and Trade-offs
- Sliding Window with Sorted Sets in Redis