0
0
Redisquery~5 mins

Rate limiter with INCR and EXPIRE in Redis

Choose your learning style9 modes available
Introduction

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.

To limit login attempts from a user to prevent brute force attacks.
To restrict API calls per user or IP address to avoid overload.
To control message sending frequency in a chat application.
To prevent excessive form submissions on a website.
To throttle requests to a backend service during peak times.
Syntax
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.

Examples
This increments the request count for user 123 and sets the count to expire after 60 seconds.
Redis
INCR user:123:requests
EXPIRE user:123:requests 60
Tracks API calls for clientA and resets the count every hour.
Redis
INCR api:clientA:limit
EXPIRE api:clientA:limit 3600
Sample Program

This 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.

Redis
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
OutputSuccess
Important Notes

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.

Summary

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.