Building Production API Rate Limiters: Token Bucket & Redis
Rate Limiting is a critical defense mechanism for production APIs, protecting downstream microservices from traffic spikes, denial-of-service (DoS) attacks, and resource exhaustion. Implementing rate limiting across a distributed cluster requires storing state in a high-speed, centralized store like Redis.
This guide covers the core rate limiting algorithms—Token Bucket, Leaky Bucket, Fixed Window, and Sliding Window Log—and demonstrates how to build a production-grade, race-condition-free rate limiter in Redis using atomic Lua scripting.
Rate Limiting Algorithms: Token Bucket vs. Sliding Window
Choosing a rate limiting algorithm depends on your tolerance for burst traffic and memory overhead.
Token Bucket allows bursts of traffic up to a bucket capacity while refilling tokens at a constant rate. Sliding Window Log records exact timestamp logs per user, offering perfect accuracy at the cost of higher memory. Sliding Window Counter approximates logs by combining token counts from the current and previous window periods.
Quick reference
- Use Lua scripts in Redis to execute token calculations atomically, avoiding race conditions under concurrent requests.
- Include standard RFC rate limit response headers (
X-RateLimit-Limit,X-RateLimit-Remaining) so client SDKs can back off gracefully. - Token Bucket handles bursty traffic well, while Leaky Bucket smooths out requests at a constant egress rate.
Remember this
Atomic Lua scripts in Redis provide sub-millisecond, race-condition-free rate limiting across distributed API clusters.
Avoiding Race Conditions & Memory Churn
In a distributed cluster with multiple API gateways, naive read-then-write code causes race conditions where concurrent requests pass limit thresholds simultaneously.
Using atomic Redis Lua scripts or Redis Sorted Sets (ZSETs) for Sliding Window logs ensures thread-safe execution across all gateway instances.
Quick reference
- Set key TTL expiration times on Redis rate limit keys to automatically clean up inactive user sessions.
- Distribute rate limit key hashes evenly across Redis Cluster shards.
- Compare with Rate Limiting Algorithms Guide and NGINX Gateway Guide.
Remember this
Redis Lua scripts eliminate read-modify-write race conditions, ensuring rate limits are enforced strictly in production.
API Gateway Placement & Decision Matrix
Place rate limiters at the API Gateway layer (such as NGINX, Envoy, or Kong) before requests reach internal microservices.
For related guides, see our articles on Load Balancing L4 vs L7 and API Security Best Practices.
Quick reference
- Enforce IP-based rate limiting for unauthenticated public endpoints and Token/User-based limiting for logged-in sessions.
- Return HTTP 429 Too Many Requests status codes with explicit
Retry-Afterheaders. - Implement circuit breakers to fail open if the central Redis rate limiting cluster becomes unreachable.
- Compare with Load Balancing Layer 4 vs Layer 7 and NGINX Gateway Configuration.
Remember this
Enforce rate limits at the API Gateway boundary to shield downstream services from overload and malicious traffic.
Key takeaway
Building rate limiters with Redis and Token Bucket algorithms protects your microservices while delivering predictable performance and smooth handling of bursty traffic.
Related Articles
Explore this topic