actix-web-ratelimit
A simple and highly customizable rate limiting middleware for actix-web 4.
Features
- actix-web 4 Compatible: Built specifically for actix-web 4
- Simple & Easy to Use: Minimal configuration required
- Expandable Store: easy to create your own store, In-Memory store and Redis store have been provided
- High Performance: Efficient sliding window algorithm
- Customizable: Custom client identification and rate limit exceeded handlers
- Thread Safe: Concurrent request handling with DashMap
Quick Start
Add this to your Cargo.toml:
[]
= "0.1"
# Or, for Redis support
= { = "0.1", = ["redis"] }
Usage
Basic Usage with In-Memory Store
// Configure rate limiting: allow 3 requests per 10-second window
let config = default.max_requests.window_secs;
// Create in-memory store for tracking request timestamps
let store = new;
new
.bind?
.run
.await
Advanced Configuration
let store = new;
let config = default
.max_requests
.window_secs
// Extract client identifier from req. It is IP (realip_remote_addr) by default.
.id
// Custom handler for rate limit exceeded. It returns a 429 response by default.
.exceeded;
new
.bind?
.run
.await
Redis Store
first set feature redis enable:
= { = "0.1", = [ "redis" ] }
then you can use it:
let store = new;
let config = default.max_requests.window_secs;
new
.bind?
.run
.await
Configuration Options
RateLimitConfig
| Method | Description | Default |
|---|---|---|
max_requests(usize) |
Maximum requests per window | 10 |
window_secs(u64) |
Time window in seconds | 100 |
id(fn) |
Client identification function | IP address |
exceeded(fn) |
Rate limit exceeded handler | 429 response |
Storage Backends
MemoryStore
- Pros: Fast, no external dependencies
- Cons: Not distributed, data lost on restart
- Use case: Single instance applications
RedisStore (requires redis feature)
- Pros: Distributed, persistent, scalable
- Cons: Requires Redis server
- Use case: Multi-instance applications
Algorithm
This middleware uses a sliding window algorithm:
- Extract client identifier from request
- Retrieve stored request timestamps for the client
- Remove expired timestamps outside the time window
- Check if remaining request count exceeds the limit
- If not exceeded, record new timestamp and allow request
- If exceeded, call the rate limit handler
Examples
Run the example:
Then test the rate limiting:
# This should work
# Exceed rate limit by making many requests
for; do ; done
[features]
redis: Enables Redis storage backend support
License
This project is licensed under the MIT License.