Self-Hosted Distributed Rate Limiting and API Throttling with Redis and Envoy
Quick Summary (TL;DR)
- Distributed rate limiting requires a shared, atomic counter store—Redis is the de facto standard.
- Envoy enforces limits at the edge via the
envoy.filters.http.ratelimitfilter talking to a Rate Limit Service (RLS) backed by Redis.- Token bucket is best for bursty APIs; sliding window is best for precise, abuse-resistant quotas.
- Use Lua scripts in Redis for atomicity, and consistent hashing to scale across Redis shards.
- Always define a fail-open vs. fail-closed policy and monitor 429 rates, Redis latency, and RLS health.
Rate limiting is one of those problems that looks trivial on a whiteboard—“just count requests”—and becomes genuinely hard the moment you have more than one server. This guide walks you through building a production-grade, self-hosted rate limiting system using Envoy as the enforcement point and Redis as the distributed counter store.
Introduction to Distributed Rate Limiting
A single-instance rate limiter is easy: keep a counter in memory. But the moment you run three Envoy replicas behind a load balancer, each replica sees only a third of the traffic. A “100 requests per minute” limit enforced locally becomes an effective 300 rpm cluster-wide—and worse, it’s inconsistent because traffic distribution is uneven.
Distributed rate limiting solves this by moving the counter to a centralized, low-latency store that all instances consult. Redis is ideal: it offers sub-millisecond operations, atomic primitives (INCR, EXPIRE), Lua scripting for compound operations, and sorted sets for time-based windows.
The trade-off is that you’ve introduced a network hop and a new failure domain. This guide addresses both.
Understanding Rate Limiting Algorithms
Two families dominate production systems. Understanding their behavior under burst traffic is the single most important design decision you’ll make.
Token Bucket Algorithm
Imagine a bucket that holds up to capacity tokens. Tokens refill at a steady rate (e.g., 10/sec). Each request consumes one token; if the bucket is empty, the request is rejected (or queued).
Key property: it permits bursts up to the bucket capacity while enforcing a long-term average rate. A bucket of 100 tokens refilling at 10/sec lets a client fire 100 requests instantly, then throttles to 10/sec.
In Redis, you store {tokens, last_refill_timestamp} per key and compute refill lazily on each request—no background job needed.
Sliding Window Algorithm
A fixed window (“1000 requests per minute, reset at :00”) has a notorious flaw: a client can send 1000 requests at 0:59 and another 1000 at 1:00, effectively doubling the rate at the boundary.
A sliding window fixes this by tracking individual request timestamps (or bucketed counts) over a rolling interval. The most common implementation is a sliding window log using a Redis sorted set: each request is a member scored by its timestamp; you ZREMRANGEBYSCORE to evict old entries and ZCARD to count the remainder.
A memory-efficient variant is the sliding window counter, which interpolates between two adjacent fixed windows—cheaper but approximate.
Choosing the Right Algorithm
| Criterion | Token Bucket | Sliding Window |
|---|---|---|
| Burst handling | Allows bursts up to capacity | Strict—no boundary bursts |
| Precision | Approximate average rate | Exact over rolling interval |
| Memory per key | O(1) | O(requests in window) |
| Redis data structure | Hash | Sorted set |
| Best for | Public APIs, user-facing traffic | Security quotas, billing, abuse prevention |
| Complexity | Low | Medium |
Rule of thumb: use token bucket for fairness and user experience; use sliding window where the limit is a hard contractual or security boundary.
Architecture Overview: Envoy and Redis
flowchart LR
C[Client] --> LB[Load Balancer]
LB --> E1[Envoy Instance 1]
LB --> E2[Envoy Instance 2]
LB --> E3[Envoy Instance N]
E1 --> RLS[Rate Limit Service gRPC]
E2 --> RLS
E3 --> RLS
RLS --> R[(Redis Cluster)]
RLS -. fallback .-> LC[Local Cache]
E1 --> U[Upstream Service]
E2 --> U
E3 --> U
The flow: Envoy’s HTTP rate limit filter extracts a descriptor (e.g., remote_address, api_key, or a header) and sends it to the RLS over gRPC. The RLS executes a Lua script against Redis, which atomically updates the counter and returns allow/deny. Envoy then enforces the decision—returning HTTP 429 with x-envoy-ratelimited when denied.
You can use the reference Envoy ratelimit service or write a thin custom RLS in Go. Both speak the same gRPC protocol.
Envoy Rate Limit Filter Configuration
Here’s a minimal but production-ready listener config:
http_filters:
- name: envoy.filters.http.ratelimit
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimit
domain: api-gateway
failure_mode_deny: false # fail open
timeout: 50ms
rate_limit_service:
transport_api_version: V3
grpc_service:
envoy_grpc:
cluster_name: ratelimit_cluster
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
And the per-route descriptors:
route_config:
virtual_hosts:
- name: api
domains: ["*"]
routes:
- match: { prefix: "/api" }
route: { cluster: backend }
typed_per_filter_config:
envoy.filters.http.ratelimit:
"@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimitPerRoute
rate_limits:
- actions:
- request_headers:
header_name: "x-api-key"
descriptor_key: "api_key"
The descriptor_key becomes the identifier the RLS uses to look up limits in its YAML config:
descriptors:
- key: api_key
value: "free-tier"
rate_limit:
unit: minute
requests_per_unit: 60
Redis as a Distributed Counter Store
Two non-negotiables for correctness:
- Atomicity. Read-modify-write in application code races under concurrency. Use Lua scripts (
EVAL) so the entire check-and-update runs server-side in one atomic step. - TTL hygiene. Every key must expire, or you’ll leak memory. Set TTLs to
window + bufferso idle clients are garbage collected automatically.
Size your Redis for the key cardinality: one key per (descriptor, client). At 100k active clients with a 1-minute window, that’s 100k keys—trivial for Redis. At 10M, plan for sharding (see consistent hashing below).
Implementing Token Bucket with Redis and Envoy
The RLS handler calls this Lua script per request:
-- KEYS[1] = bucket key, ARGV: capacity, refill_rate, now_ms, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local bucket = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(bucket[1]) or capacity
local ts = tonumber(bucket[2]) or now
local delta = math.max(0, now - ts) / 1000.0
tokens = math.min(capacity, tokens + delta * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) + 60)
return allowed and 1 or 0
The EXPIRE is set to the time it takes to refill a full bucket plus a buffer—once a client is fully replenished, the key carries no information and can vanish.
Implementing Sliding Window with Redis and Envoy
For a precise rolling window, use a sorted set keyed by client:
-- KEYS[1] = window key, ARGV: limit, window_ms, now_ms, member_id
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
local count = redis.call('ZCARD', KEYS[1])
if count < limit then
redis.call('ZADD', KEYS[1], now, ARGV[4])
redis.call('PEXPIRE', KEYS[1], window)
return 1
end
redis.call('PEXPIRE', KEYS[1], window)
return 0
Pass a unique member_id (e.g., now .. ':' .. request_id) so concurrent requests at the same millisecond don’t collide. This costs ~50 bytes per request in the window—budget accordingly.
Consistent Hashing for Scalable Rate Limiting
When one Redis node can’t hold your key space, shard it. Naive hash(key) % N remaps nearly every key when you add a node—resetting everyone’s counters. Consistent hashing places both keys and nodes on a ring, so adding a node only remaps ~1/N of keys.
flowchart TD
K1[Client Key A] --> H{Hash Ring}
K2[Client Key B] --> H
K3[Client Key C] --> H
H --> R1[(Redis Node 1)]
H --> R2[(Redis Node 2)]
H --> R3[(Redis Node 3)]
In practice, use Redis Cluster (which handles slot-based sharding) or a client-side library like twemproxy/envoy-redis-proxy with hash policies. The RLS must use the same hash function as the routing layer, or it will query the wrong shard.
Handling Failures and Edge Cases
| Failure | Recommended handling |
|---|---|
| Redis timeout | failure_mode_deny: false → fail open (allow) |
| RLS unreachable | Local in-memory fallback with conservative limit |
| Clock skew across RLS pods | Use Redis TIME command, not local clocks |
| Hot key (one abusive client) | Per-key local pre-filter before hitting Redis |
| Thundering herd on key expiry | Add jitter to TTLs |
The fail-open vs. fail-closed decision is a business call. Fail-open keeps your API available during a Redis outage but exposes you to abuse; fail-closed protects the backend but turns a cache outage into a full outage. Most teams choose fail-open for read APIs and fail-closed for auth/payment endpoints.
Testing and Monitoring Your Rate Limiter
Load test with hey or wrk to confirm limits fire at the right threshold:
hey -n 500 -c 50 -H "x-api-key: free-tier" https://api.example.com/v1/search
Expect ~60 successes and ~440 429s for a 60/min limit.
Monitor these metrics:
envoy_http_ratelimit_over_limit— 429 rate per route- RLS gRPC latency p99 (alert if > 20ms)
- Redis
latency_percentiles_usecandevicted_keys - RLS
should_rate_limitdecision ratio (a sudden 100% deny signals a bug)
Comparison of Rate Limiting Strategies
| Strategy | Location | Accuracy | Latency | Use case |
|---|---|---|---|---|
| In-memory (per Envoy) | Envoy local | Low (per-instance) | <1ms | Coarse protection |
| Token bucket (Redis) | RLS + Redis | High (average) | 1–5ms | Public APIs |
| Sliding window (Redis) | RLS + Redis | Very high | 2–8ms | Security quotas |
| Fixed window | RLS + Redis | Medium | 1–3ms | Cheap internal limits |
| Leaky bucket (queue) | RLS + queue | High | Higher | Smoothing bursts |
Conclusion and Best Practices
Distributed rate limiting is a solved problem if you respect the fundamentals: centralize state in Redis, keep every operation atomic via Lua, and choose the algorithm that matches your traffic shape.
Checklist before you ship:
- ✅ Lua scripts for every check-and-update—no read-then-write races
- ✅ TTLs on every key, with jitter
- ✅ Explicit fail-open/fail-closed policy per route
- ✅ Consistent hashing when you shard Redis
- ✅ Dashboards for 429 rate, RLS latency, and Redis health
- ✅ Load tests that verify the limit under concurrency
Get these right, and your gateway will absorb abuse gracefully while keeping legitimate traffic fast.
FAQ
What is the difference between rate limiting and throttling? Rate limiting sets a hard limit on the number of requests allowed in a time window, rejecting excess requests. Throttling slows down or queues requests to keep them within limits, often to smooth traffic spikes without outright rejection.
Why use Redis for distributed rate limiting? Redis provides a centralized, high-performance store with atomic operations and Lua scripting, making it ideal for shared counters and timestamps across multiple Envoy instances. TTL support and sorted sets simplify token bucket and sliding window implementations.
How does Envoy integrate with Redis for rate limiting? Envoy’s rate limit filter calls an external rate limit service (RLS) that uses Redis as its backend. The RLS receives descriptors over gRPC, executes Lua scripts against Redis, and returns allow/deny decisions that Envoy enforces with HTTP 429.
What is consistent hashing and why does it matter? Consistent hashing distributes keys across multiple Redis instances while minimizing remapping when instances are added or removed. This keeps rate limiting state consistent during scaling and avoids hotspots.
How do I handle Redis failures? Implement a fallback strategy: fail open (allow requests) or fail closed (deny requests) depending on your security posture. Add circuit breakers, local caching, and a conservative in-memory fallback to reduce dependency on Redis during outages.