Redis-Based Rate Limiting with INCR
What You'll Learn
You'll learn how to implement a simple, high-performance distributed rate limiter using Redis's atomic INCR command for fixed-window counters.
The Core Idea
Redis provides atomic operations that make distributed rate limiting straightforward. The INCR command increments a counter and returns the new value in a single, atomic step—no race conditions even under heavy concurrent load.
Here's how it works for a fixed time window:
- Key construction: Create a key combining the user ID and current time window (e.g.,
ratelimit:user123:2024-01-15:14:00) - Atomic increment: Use
INCRto increment the counter for that key - Check limit: If the returned value exceeds your threshold, reject the request
- Set expiration: Use
EXPIREto automatically clean up the key after the window passes
Why Redis?
Think of Redis as a lightning-fast, shared scoreboard that multiple servers can read and update simultaneously. Because INCR is atomic, even if 1,000 requests arrive at the exact same millisecond from different application servers, Redis processes them one-by-one internally, ensuring accurate counts.
The Implementation Pattern
Key: "ratelimit:user123:minute:1705329600"
INCR → returns current count
If count == 1, set EXPIRE 60 seconds
If count > limit, reject request
The window boundary is typically calculated as floor(current_timestamp / window_size) * window_size, ensuring all servers agree on which window they're in.
Trade-offs
This approach is simple and fast (~1-2ms latency), but has a "burst" problem at window boundaries: a user could make 100 requests at 14:59:59 and another 100 at 15:00:01, bypassing the limit briefly.
Key Takeaway: Redis INCR provides a simple, atomic foundation for distributed rate limiting with fixed windows—perfect for high-throughput scenarios where microsecond precision matters and occasional boundary bursts are acceptable.