Backend & Cloud Engineer Guide: Distributed API Gateways & Atomic Redis Rate Limiting
A single misconfigured partner webhook script or credential-stuffing botnet can fire 20,000 requests per second at your API, exhausting PostgreSQL connection pools and starving legitimate enterprise tenants. In-memory per-process rate limiters fail in auto-scaled cloud environments because 20 container instances don't share state, and naive Redis `GET` + `INCR` sequences suffer from race conditions under concurrency. As a Senior Backend Engineer and Cloud Engineer, I implement atomic Redis Lua token-bucket / sliding-window rate limiters, per-tenant quota tiers, and Cloud Armor / AWS WAF edge rules.
1. Atomic Token-Bucket Rate Limiting via a Single Redis Lua Script
Executing the token refill calculation and decrement inside a single Redis `EVALSHA` Lua script guarantees strict atomicity in under 0.3 milliseconds with zero network round-trip race conditions:
TOKEN_BUCKET_LUA = """
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
local data = redis.call("HMGET", key, "tokens", "last_ms")
local tokens = tonumber(data[1])
local last_ms = tonumber(data[2])
if tokens == nil then
tokens = capacity
last_ms = now_ms
else
local elapsed_sec = math.max(0, now_ms - last_ms) / 1000.0
tokens = math.min(capacity, tokens + (elapsed_sec * refill_rate))
last_ms = now_ms
end
if tokens < requested then
local retry_after_ms = math.ceil(((requested - tokens) / refill_rate) * 1000)
return {0, math.floor(tokens), retry_after_ms}
else
tokens = tokens - requested
redis.call("HMSET", key, "tokens", tokens, "last_ms", last_ms)
redis.call("PEXPIRE", key, math.ceil((capacity / refill_rate) * 2000))
return {1, math.floor(tokens), 0}
end
"""
2. Emitting Standard `RateLimit-*` & `Retry-After` Headers
When a client exceeds its burst quota, the API gateway returns `HTTP 429 Too Many Requests` with `Retry-After`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` headers so well-behaved SDKs back off deterministically without hammering the origin.
3. Hire a Senior Backend & Cloud Engineer for API Security & Scale
Protecting public APIs or multi-tenant SaaS backends against traffic spikes and abuse? Explore my Backend Engineer Pillar Guide, review my Cloud Engineer Pillar Guide, or book a 1-Day API Gateway & Rate Limiting Sprint.