Backend Engineer: Adaptive Distributed Token-Bucket Rate Limiting & HTTP 429 Throttling in Data Ingestion Pipelines
When a distributed fleet of 20 ingestion workers queries partner catalog APIs or public e-commerce endpoints, per-process in-memory rate limiters cannot coordinate global request velocity across containers. As soon as aggregate traffic crosses the upstream host's burst threshold, the server responds with HTTP 429 Too Many Requests (or 503 Slow Down). As a Backend Engineer, I coordinate cluster-wide request pacing using atomic Redis Lua token buckets with dynamic penalty cooldowns that automatically slow down the entire fleet the instant any single worker observes a `429`.
1. Atomic Redis Lua Token Bucket with Global Cooldown Penalty
Our Redis Lua script tracks both the per-domain token bucket (`tokens`, `last_refill_ms`) and a shared `cooldown_until_ms` timestamp. If any worker receives an `HTTP 429` or `Retry-After` header from a target host, it updates `cooldown_until_ms` in Redis so all 20 workers immediately pause requests to that domain until the penalty window expires:
-- adaptive_rate_limit.lua
-- KEYS[1] = bucket key (e.g. "ratelimit:domain:api.supplier.com")
-- ARGV[1] = now_ms, ARGV[2] = capacity, ARGV[3] = refill_per_sec
local state = redis.call("HMGET", KEYS[1], "tokens", "last_ms", "cooldown_until_ms")
local now_ms = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local refill_rate = tonumber(ARGV[3])
local cooldown_until = tonumber(state[3] or "0")
if now_ms < cooldown_until then
return {0, cooldown_until - now_ms}
end
local tokens = tonumber(state[1])
local last_ms = tonumber(state[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))
end
if tokens >= 1.0 then
tokens = tokens - 1.0
redis.call("HMSET", KEYS[1], "tokens", tokens, "last_ms", now_ms)
redis.call("EXPIRE", KEYS[1], 3600)
return {1, 0}
else
local wait_ms = math.ceil(((1.0 - tokens) / refill_rate) * 1000.0)
return {0, wait_ms}
end
2. Combining Proactive Token Buckets with Reactive Jitter Backoff
Proactive Redis token buckets prevent 99% of rate-limit violations before requests leave your VPC, while our decorrelated jitter backoff & DLQ pipeline and bounded asyncio queue workers handle unexpected upstream capacity drops gracefully.
Need a Backend Engineer to build distributed Redis rate limiters and resilient data ingestion pipelines? Book a 1-Day Engineering Sprint.