If credentials or tokens are verified at the edge, Token Buckets & Redis Lua, pair an in-memory local limiter (token bucket) for sub-millisecond burst protection with a Redis Lua sliding-window or token-bucket store for global tenant quotas, and always return HTTP 429 with `Retry-After`.
TL;DR30-second simplified summary▾
Core Mechanics: Rate limiting decouples incoming demand from system capacity by enforcing an admission budget keyed by tenant_id, api_key, or ip:route before expensive auth or database work runs.
Visual & Structural Flow: Depicts Two-Tier Local Token Bucket + Redis Lua Global Rate Limiter (API Client -> Gateway L1 Bucket -> Redis Lua (L2) -> Origin Service); Local Token-Lease Batching + Async Redis Sync (Client (500k RPS) -> Edge Gateway -> Regional Redis).
Trade-Offs & Production: Choose the algorithm based on memory per key, burst tolerance, and exactness. To eliminate cross-region RTT and Redis hot-key contention at 500,000 RPS, regional Envoy gateways enforce local in-memory Token Buckets and asynchronously batch-sync quota leases.
Failure Modes & Application: Explore distributed rate limiter architectures, token bucket designs, and retry-storm prevention.
What is Rate Limiting.
Why this matters: The mechanism: understand how Rate Limiting works from first principles.
Rate limiting decouples incoming demand from system capacity by enforcing an admission budget keyed by tenant_id, api_key, or ip:route before expensive auth or database work runs.
Token Bucket allows controlled bursts up to capacity while capping sustained rate at tokens/sec in memory. Leaky Bucket smooths bursts into a constant egress rate. Sliding Window Counter eliminates the 2x boundary-burst spike of Fixed Windows in space.
Two-Tier Local Token Bucket + Redis Lua Global Rate Limiter
Hybrid local + Redis Lua rate limiting protects origin pools in <1 ms without a single point of failure.
Why we need Rate Limiting (Race Conditions & Boundary Stampedes).
Why this matters: The problem: see what breaks without Rate Limiting under real concurrency or scale.
Think of Why we need Rate Limiting (Race Conditions & Boundary Stampedes) as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: The problem: see what breaks without Rate Limiting under real concurrency or scale.
Without rate limiting, a single buggy retry loop or scraper saturates DB pools and causes 503 outages for all tenants. Implementing it naively introduces two classic bugs: (1) separate Redis GET then INCR commands create read-modify-write race conditions that over-admit concurrent bursts; (2) Fixed Window Counters allow 2x quota (1,000 req at 12:00:59 + 1,000 req at 12:01:01).
Why we need Rate Limiting (Race Conditions & Boundary Stampedes)
- Problem
- How to implement Rate Limiting Algorithms, Token Buckets & Redis Lua without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- If credentials or tokens are verified at the edge, token Buckets & Redis Lua, pair an in-memory local limiter (token bucket) for sub-millisecond burst protection with a Redis Lua sliding-window or token-bucket store for global tenant quotas, and always return HTTP 429 with
Retry-After. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Rate Limiting Algorithms, Token Buckets & Redis Lua experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Weighted Cost Budgets
Charge cost = 1 for GET /items/{id} and cost = 25 for POST /search/export against the same tenant bucket so heavy routes cannot starve cheap ones.
IETF RateLimit Headers + `429`
Always return 429 Too Many Requests (never 500/503) with Retry-After, RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset.
Where Rate Limiting applies (and where Healthchecks Must Bypass).
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Where Rate Limiting applies (and where Healthchecks Must Bypass) as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Apply rate limits to public APIs, login/OTP endpoints, and expensive LLM/export routes; exempt internal healthchecks and metrics scrapes.
| Choice | What it buys | What it costs |
|---|---|---|
| Good Candidate: Public APIs, Login/OTP & Multi-Tenant Quotas | Prevents brute-force attacks, scraping, and noisy-neighbor DB pool exhaustion. | Requires keying authenticated routes on `tenant_id`/`api_key_hash` rather than shared carrier NAT IPs. |
| Avoid: `/healthz`, Readiness & Prometheus Scrape Paths | Keep probe endpoints unthrottled so Kubernetes never triggers false-positive pod restarts under load. | Throttling `/healthz` turns a traffic spike into a cascading pod-eviction outage. |
| Avoid: Pure Downstream Slowness Bottlenecks | Use adaptive concurrency limits (Vegas/Gradient2) or backpressure when downstream latency degrades regardless of RPS. | Static RPS limits cannot adapt when DB queries slow from 5 ms to 500 ms. |
How Atomic Token Buckets & Redis Lua are implemented.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Think of How Atomic Token Buckets & Redis Lua are implemented as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Operational control: configure bounds, failure handling, and safe production defaults.
Use Redis TIME inside Lua scripts (avoiding gateway wall-clock skew), attach PEXPIRE TTLs to every key so one-off IPs never leak RAM, and deploy new limits in shadow/dry-run mode (enforce: false) before blocking traffic.
-- Atomic Redis Token Bucket (KEYS[1]=key, ARGV[1]=cap, ARGV[2]=rate_per_sec, ARGV[3]=cost)
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(data[1]) or tonumber(ARGV[1])
local last = tonumber(data[2]) or now
tokens = math.min(tonumber(ARGV[1]), tokens + math.max(0, now - last) * tonumber(ARGV[2]))
local allowed = 0
if tokens >= tonumber(ARGV[3]) then
tokens = tokens - tonumber(ARGV[3])
allowed = 1
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil((tonumber(ARGV[1]) / tonumber(ARGV[2])) * 1000) + 1000)
return {allowed, math.floor(tokens)}
Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Choose the algorithm based on memory per key, burst tolerance, and exactness.
Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter
- Race condition drops limits
- Redis round-trip per check
- Thundering retry storm
- Single-RTT atomic Lua script
- Retry-After jittered backoff
- Per-tenant quota isolation
| Choice | What it buys | What it costs |
|---|---|---|
| Token Bucket (Redis Hash / Local) | $O(1)$ memory (2 numbers), allows controlled bursts up to $B$, zero boundary spikes. | Requires atomic Lua script for distributed accuracy. |
| Sliding Window Counter | $O(1)$ memory and smooths 2x fixed-window boundary spikes via weighted overlap. | Approximate interpolation across the previous window. |
| Sliding Window Log (Redis `ZSET`) | 100% exact to the millisecond with zero boundary approximation. | Stores $O(N)$ timestamps per key—explodes RAM for high-rate tenants. |
Production example: Multi-Region Gateway with Token-Lease Batching.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Production example: Multi-Region Gateway with Token-Lease Batching as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Production architecture: see how the components compose end to end under real load.
To eliminate cross-region RTT and Redis hot-key contention at 500,000 RPS, regional Envoy gateways enforce local in-memory Token Buckets and asynchronously batch-sync quota leases (INCRBY 50) with a regional Redis/Valkey shard every 50–100 ms.
Local Token-Lease Batching + Async Redis Sync
Batching 50-token leases cuts Redis QPS by 50x and keeps normal API checks at sub-millisecond local latency.
Problems solved by Rate Limiting & System Design Deep Dives.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of Problems solved by Rate Limiting & System Design Deep Dives as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Applied problems: connect these internals to concrete system design and debugging scenarios.
Explore distributed rate limiter architectures, token bucket designs, and retry-storm prevention.
Practice: Make the trade-off yourself.
Why are separate Redis `GET` and `SET`/`INCR` commands unsafe for enforcing API rate limits across concurrent gateway pods?