A rate limiter helps control how often a user or system can perform an action. Using Redis commands INCR and EXPIRE makes it simple and fast.
Rate limiter with INCR and EXPIRE in Redis
INCR key EXPIRE key seconds
INCR increases the number stored at key by 1. If the key does not exist, it is set to 0 before incrementing.
EXPIRE sets a time-to-live (TTL) in seconds for the key. After this time, the key is deleted automatically.
INCR user:123:requests EXPIRE user:123:requests 60
INCR api:clientA:limit
EXPIRE api:clientA:limit 3600This design uses Redis to count user requests in a 60-second window. The first request sets the expiration. Each request increments the count. If the count goes above 5, the server blocks further requests until the count resets.
1. Client sends a request. 2. Server runs INCR on key 'user:42:requests'. 3. If the returned count is 1, server sets EXPIRE on the key for 60 seconds. 4. Server checks if count exceeds limit (e.g., 5 requests). 5. If limit exceeded, server rejects request; else, processes it. Data flow: - User request -> Server - Server -> Redis INCR 'user:42:requests' - Redis returns count - Server -> Redis EXPIRE 'user:42:requests' 60 (only if count == 1) - Server decides to allow or block request based on count - Server responds to user
Always set EXPIRE only when the count is 1 to avoid resetting the TTL on every request.
This method works well for simple fixed-window rate limiting but may cause bursts at window edges.
For more precise control, consider sliding window or token bucket algorithms.
Use INCR to count actions and EXPIRE to reset counts automatically.
Set EXPIRE only once when the count starts to avoid TTL reset issues.
This approach is simple, fast, and suitable for many rate limiting needs.