Building atomic sliding window rate limiters that survive distributed bot attacks.
Implementing sliding-window log algorithms in high-throughput API gateways is an important part of protecting modern applications. APIs handle thousands of requests from browsers, mobile applications, integrations, and automated clients. Without proper rate limiting, excessive traffic can overload backend services, increase infrastructure costs, and expose sensitive endpoints to automated abuse.
Traditional rate limiters often store request counters in application memory. This approach becomes unreliable when an application runs across multiple servers or containers. Redis provides a shared storage layer, while Lua scripts make rate-limit operations atomic, helping distributed systems enforce consistent request limits.
1. Why Distributed Applications Need Rate Limiting
Consider an API deployed across three application servers. Each server has its own request counter and allows 100 requests per minute.
A client distributing requests across all three servers could potentially generate more traffic than the intended limit because each server tracks requests independently.
This creates several security and performance problems:
- Inconsistent request limits across application instances.
- Counter resets after application restarts.
- Race conditions during concurrent requests.
- Increased exposure to automated bot traffic.
- Unnecessary backend resource consumption.
A centralized Redis-based rate limiter solves the shared-counter problem. Every application instance checks the same Redis data, allowing the system to enforce consistent limits.
Rate limiting is particularly useful for login endpoints, payment APIs, password-reset workflows, search services, and other resource-intensive operations.
2. Understanding the Sliding-Window Log Algorithm
The sliding-window log algorithm tracks individual request timestamps within a rolling time period.
For example, an API might allow 100 requests per minute. Whenever a new request arrives, the rate limiter removes expired timestamps, counts the remaining requests, and decides whether the new request should be accepted.
Redis sorted sets provide a convenient way to implement this algorithm.
Each request is stored with its timestamp as the sorted-set score. Redis then performs the following operations:
- Remove timestamps outside the active window.
- Count the remaining requests.
- Reject the request if the limit has been reached.
- Otherwise, record the new request.
- Set an expiration on the Redis key.
Unlike fixed-window counters, sliding windows avoid arbitrary time-boundary resets. This provides more consistent request enforcement.
The main trade-off is memory consumption. A sliding-window log stores individual request entries, so high-throughput systems should evaluate whether a sliding-window counter or token-bucket algorithm would be more efficient.
3. Implementing Atomic Rate Limiting with Redis and Lua
A basic implementation might use separate Redis commands to check a counter and increment it.
However, concurrent requests can execute these operations simultaneously. Multiple clients might read the same counter before any of them updates it, allowing more requests than intended.
Lua scripting addresses this problem by executing the complete rate-limit decision as one atomic Redis operation.
Create a file named sliding_window.lua:
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local member = ARGV[4]
local cutoff = now - window
-- Remove expired requests
redis.call(
"ZREMRANGEBYSCORE",
key,
"-inf",
cutoff
)
-- Count active requests
local count = redis.call("ZCARD", key)
-- Reject requests when the limit is reached
if count >= limit then
return 0
end
-- Record the accepted request
redis.call("ZADD", key, now, member)
-- Automatically expire the Redis key
redis.call("PEXPIRE", key, window)
return 1
The script returns 1 when a request is accepted and 0 when the limit is reached.
Because Redis executes the Lua script atomically, another Redis command cannot interrupt the sequence between checking the request count and recording the accepted request.
For production systems, request members must be unique, timestamps must use consistent units, and Redis Cluster key-slot restrictions must be considered.
4. Testing the Implementation with Docker and Redis CLI
A local Docker environment makes it possible to reproduce and test the rate limiter without connecting to a production API.
Step 1: Start a Redis container.
docker run -d \
--name redis-rate-limit-lab \
-p 6379:6379 \
redis:7
Check whether Redis is responding:
docker exec redis-rate-limit-lab redis-cli PING
Expected output:
PONG
Step 2: Copy the Lua script into the container.
docker cp sliding_window.lua \
redis-rate-limit-lab:/tmp/sliding_window.lua
Step 3: Execute a rate-limit test.
The following Linux shell example allows five requests within a 60-second window.
for i in $(seq 1 7); do
NOW=$(date +%s%3N)
docker exec redis-rate-limit-lab redis-cli \
--eval /tmp/sliding_window.lua rl:demo , \
"$NOW" 60000 5 "request-$i"
done
Expected behavior, assuming all seven requests arrive within the same window:
1
1
1
1
1
0
0
Here, 1 represents an accepted request and 0 represents a rejected request.
Step 4: Inspect stored requests.
docker exec redis-rate-limit-lab redis-cli \
ZCARD rl:demo
Inspect the request timestamps:
docker exec redis-rate-limit-lab redis-cli \
ZRANGE rl:demo 0 -1 WITHSCORES
The sorted set should contain five accepted requests.
Step 5: Clean up the testing environment.
docker rm -f redis-rate-limit-lab
These commands provide a basic functional reproduction. A separate concurrency test and performance benchmark are necessary before considering the implementation production-ready.
5. Production Security and Scalability Best Practices
Redis-based rate limiting is useful, but deploying it at scale requires careful configuration.
Memory management: Sliding-window logs store individual request records. High-volume APIs may benefit from token-bucket or sliding-window counter implementations.
Trusted client identity: Never blindly trust client-controlled X-Forwarded-For headers. Configure known reverse proxies and use authenticated account or API-key identities wherever possible.
Redis Cluster compatibility: Scripts accessing multiple keys must respect Redis Cluster's key-slot requirements. Related keys can use hash tags to keep them in the same slot.
Failure handling: Decide whether the application should fail open or fail closed when Redis becomes unavailable. Sensitive authentication and payment endpoints may require stricter controls.
HTTP response handling: Return HTTP 429 Too Many Requests when a client exceeds its configured limit. A Retry-After header can communicate when another request may be attempted.
Monitoring: Track rejected requests, Redis latency, memory consumption, error rates, and unusual traffic patterns. Monitor aggregate behavior instead of relying only on individual IP addresses.
Security testing: Test concurrent requests, distributed traffic patterns, proxy misconfigurations, and rate-limit bypass scenarios in an authorized environment.
A strong rate-limiting strategy combines shared counters, atomic operations, trusted identity extraction, and continuous monitoring. Redis and Lua provide a practical foundation for building these controls across distributed API infrastructure.
Secure APIs Before Traffic Becomes a Threat
Distributed rate limiting helps maintain API availability, control automated abuse, and protect backend resources. Combining Redis-based enforcement with continuous application security testing creates a stronger foundation for modern web applications.
Explore automated DAST scanner solutions and website security testing resources.
Hack My Website helps developers focus on identifying vulnerabilities and strengthening application security before attackers exploit weaknesses.
Top comments (0)