In modern distributed microservices and public API gateways, rate limiting is not merely an anti-abuse defense—it is a mission-critical reliability primitive. Without robust, low-latency rate limiting, a single rogue client script, DDoS wave, or unexpected traffic spike can saturate database connection pools, exhaust memory, and trigger cascading cluster failures.
However, rate limiting across a horizontally scaled, multi-region architecture is a complex distributed systems problem. Local in-memory limiters fail when requests are distributed across hundreds of backend pods, while naive centralized database counters introduce crippling network latency and concurrency race conditions.
In this engineering deep dive, we evaluate the core rate-limiting algorithms, implement zero-race atomic limiters using Redis and Lua, analyze the Sliding Window Counter pattern, and explore enterprise-scale Envoy Global Rate Limiting.
---1. Core Algorithms: Comparing Mechanics and Edge Cases
Every rate-limiting strategy balances computational efficiency, memory footprint, and burst tolerance:
| Algorithm | Memory Consumption | Burst Tolerance | Boundary Starvation Risk | Best Use Case |
|---|---|---|---|---|
| Fixed Window Counter | Extremely Low (1 integer per key) | Poor (Double limits at boundary) | High | Basic non-critical throttling, daily quotas. |
| Token Bucket | Low (2 integers: tokens & timestamp) | Excellent (Allows burst up to bucket capacity) | None | Public REST APIs, user action rate limiting (Stripe, GitHub). |
| Leaky Bucket | Low to Moderate (Queue length) | Zero (Enforces steady egress rate) | None | Traffic shaping, message queue ingestion smoothing. |
| Sliding Window Log | High (Stores timestamp per request) | Perfect (Infinite granularity) | None | High-security financial transactions, strict login attempts. |
| Sliding Window Counter | Low (2 counters: current & previous) | Very Good (Weighted statistical approximation) | Negligible | High-throughput microservices, edge reverse proxies. |
2. The Token Bucket Algorithm Internals
The Token Bucket algorithm is the industry standard for API rate limiting. Conceptually:
- A bucket holds up to a maximum capacity of
$C$tokens. - Tokens are added to the bucket at a constant refill rate of
$R$tokens per second. - When an incoming request arrives, it attempts to draw
1token. If tokens ≥ 1, the request proceeds. If tokens < 1, the request is rejected withHTTP 429 Too Many Requests.
Crucially, production implementations do not run background timers to refill buckets. Instead, the refill is computed lazily on-demand upon each request arrival based on elapsed time:
# Lazy Token Bucket Refill Computation
elapsed_seconds = current_timestamp - last_refreshed_timestamp
tokens = min(capacity, current_tokens + (elapsed_seconds * refill_rate))
---
3. High-Performance Atomic Redis Lua Implementation
In a distributed environment, executing GET tokens, calculating the refill in application code, and running SET tokens creates a fatal race condition under high concurrency. Two parallel requests will read the same token count and both be erroneously allowed.
By executing the evaluation inside an atomic Redis Lua script, the entire operation runs single-threaded in Redis memory in sub-millisecond time without distributed locking:
-- Redis Token Bucket Lua Script
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2]) -- tokens per millisecond
local now = tonumber(ARGV[3]) -- current timestamp in ms
local requested = tonumber(ARGV[4]) -- tokens to consume (usually 1)
-- Retrieve stored state [tokens, last_updated]
local data = redis.call('HMGET', key, 'tokens', 'last_updated')
local current_tokens = tonumber(data[1])
local last_updated = tonumber(data[2])
if current_tokens == nil then
current_tokens = capacity
last_updated = now
else
local elapsed = math.max(0, now - last_updated)
current_tokens = math.min(capacity, current_tokens + (elapsed * refill_rate))
last_updated = now
end
if current_tokens >= requested then
current_tokens = current_tokens - requested
redis.call('HMSET', key, 'tokens', current_tokens, 'last_updated', last_updated)
-- Set TTL to 2x full refill duration to clean up idle keys
redis.call('PEXPIRE', key, math.ceil((capacity / refill_rate) * 2000))
return {1, math.floor(current_tokens)} -- 1 = Allowed
else
redis.call('HMSET', key, 'tokens', current_tokens, 'last_updated', last_updated)
return {0, math.floor(current_tokens)} -- 0 = Throttled
end
---
4. The Sliding Window Counter Approximation
When tracking high-volume sliding windows (e.g., "1,000 requests per minute"), storing individual timestamps in a Sorted Set (ZSET) wastes significant memory. The Sliding Window Counter provides a sub-1% error approximation by blending the current and previous fixed window counters:
Estimated Requests = (Previous Window Count * (1 - Percentage of Current Window Elapsed)) + Current Window Count
If a client made 100 requests in the previous minute window and has made 30 requests 15 seconds into the current minute window (25% elapsed):
Requests = (100 * (1 - 0.25)) + 30 = 75 + 30 = 105 requests
This smoothly penalizes bursts at boundary edges while requiring only two lightweight counter keys per user in Redis.
---5. Architecture at Scale: Envoy Global gRPC Rate Limiting
At ultra-high scale (millions of RPS), routing every HTTP request through application-level middleware to query Redis incurs unacceptable latency and CPU overhead. Instead, modern cloud-native architectures offload rate limiting to the ingress proxy layer using Envoy's Global Rate Limit Service (RLS).
The Envoy RLS Workflow
- An incoming HTTP request hits the Envoy edge proxy or Kubernetes ingress controller.
- Envoy extracts pre-configured descriptors (e.g.,
[{"generic_key": "api_v1"}, {"remote_address": "198.51.100.4"}]). - Envoy makes an asynchronous, highly optimized gRPC call to a dedicated standalone Rate Limit Service (RLS) over HTTP/2.
- The RLS service executes pipelined checks against Redis clusters and returns
OKorOVER_LIMITwith rate-limit headers. - Envoy either proxies the request to the upstream application pod or immediately returns a
429directly from the edge.
6. Production Best Practices
- Standardized Headers: Always return RFC 6585 and IETF Draft rate-limiting headers so clients can self-throttle:
RateLimit-Limit: 100 RateLimit-Remaining: 42 RateLimit-Reset: 18 - Fail-Open vs Fail-Closed: If your Redis cluster is experiencing network partitioning or degradation, decide explicitly whether to fail-open (allow requests to preserve availability) or fail-closed (deny requests to protect downstream databases). Most consumer web apps should fail-open.
- Tiered Key Hierarchies: Implement multi-layer rate limits: a global IP-level limit to stop brute-force attacks, an authenticated
user_idlimit to enforce subscription tiers, and an endpoint-level limit on expensive operations (e.g. PDF generation, password resets).
By implementing atomic token bucket scripts and offloading global throttling to edge proxies, you ensure predictable performance, eliminate denial-of-service risks, and safeguard backend stability under any traffic condition.