Each API key gets a per-route budget of requests. The gateway asks a shared limiter before it forwards a request. Over budget, the client gets a 429 with a time to retry.
Why · 2 requests
one customer script sent 40k requests a minute to /v1/orders last Tuesday and took orders down for everyone
the on-call engineer · incident review
we need limits per API key, not per IP. half our partner traffic comes from one NAT address
the API owners · Slack
Example plan · 6 tasks · Go
Outcome
No key can send more than its route budget, on any gateway replica.
Order matters. After auth, so the key is known. Before the proxy, so upstream never sees a limited request.
One Lua script refills the bucket and takes a token atomically.
Sketch · internal/ratelimit/take.lua
Refill, then take, in one step
-- KEYS[1] = bucket key; ARGV = rate, burst, now_ms, cost
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local rate, burst = tonumber(ARGV[1]), tonumber(ARGV[2])
local now, cost = tonumber(ARGV[3]), tonumber(ARGV[4])
local tokens, ts = tonumber(b[1]) or burst, tonumber(b[2]) or now
tokens = math.min(burst, tokens + (now - ts) / 1000 * rate)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(burst / rate * 1000))
return { ok and 1 or 0, math.floor(tokens) }
Refill. Tokens grow with the time since the last call, up to the burst.
Atomic. Redis runs the whole script at once, so two replicas never spend the same token.
Expiry. An idle bucket expires, so memory follows the active keys.
An empty bucket answers 429 with Retry-After and never calls upstream.
Sequence · step through it
GET /v1/orders with key k_42
The client sends a request with its key.
The gateway asks the limiter for one token. The limiter runs one script in Redis.
Tokens remain, so the gateway forwards the request and reports what is left.
Later the bucket is empty. The gateway answers 429 with Retry-After and does not call upstream.
What to notice: step 4 never reaches upstream. The limit protects the services, not only the bill.
If Redis does not answer in 50 ms, what does the gateway do?
Then task 3 fails closed, and its test expects a 503 when Redis times out.
How and where
Retry-After rounds the refill time up to whole seconds.
Sketch · gateway/middleware/ratelimit.go
The limited branch
if !d.Allowed {
secs := int(math.Ceil(d.RetryAfter.Seconds()))
w.Header().Set("Retry-After", strconv.Itoa(secs))
w.WriteHeader(http.StatusTooManyRequests)
return // next never runs
}
w.Header().Set("RateLimit-Remaining", strconv.Itoa(d.Remaining))
next.ServeHTTP(w, r)
Round up. A refill in 1.2 s gives 2, so a client that waits never comes back early.
Return first. The handler stops here, so upstream never sees the request.
Operators see allowed and limited counts for each route.
Metric
Labels
Answers
gateway_ratelimit_decisions_total
route, outcome
Which routes hit their limit, and how often
gateway_ratelimit_take_seconds
route
How much time the Redis call adds
Design
Decisions
Two choices are settled. Two more are open, on the claims they change: D3 on claim 1 and D4 on claim 2.
D1
Where the counters live
Decided
Choice: token buckets in Redis, one Lua script per request. Why: the gateway runs 6 replicas. A counter inside one process sees about a sixth of a key's traffic, so each key would get six budgets.
Options considered (3)
Option
Gives
Costs
Redis token bucket · chosen
One budget per key across all replicas
One Redis round trip per request, about 0.4 ms in the same zone
In-process counters
No network call
Six budgets per key; the limit drifts each time replicas scale
Vendor gateway plugin
No code to own
Locks the gateway version; no per-route config
D2
How the limiter counts
Decided
Choice: a token bucket. Why: it allows a short burst up to the bucket size, then holds the average rate. A fixed window lets a key send two budgets across a window edge.
Options considered (3)
Option
Gives
Costs
Token bucket · chosen
Bursts up to the bucket size; a smooth average
Two numbers per key: tokens and last refill time
Fixed window
One counter per key per window
Double budget at each window edge
Sliding log
Exact counts
One entry per request; memory grows with traffic
Design
Interfaces
The gateway depends on one small interface, so tests can swap Redis for a fake.
Limiter
Sketch · internal/ratelimit/limiter.go
The Limiter interface
type Limiter interface {
// Take removes cost tokens from key's bucket, if it holds that many.
Take(ctx context.Context, key string, cost int) (Decision, error)
}
type Decision struct {
Allowed bool
Remaining int
RetryAfter time.Duration
}
Every file the plan adds, changes or removes, grouped by block. Press Code on a row to read that file's code. Pick a row to see its block on the map.
Rate limiter and Redis
internal/ratelimit/limiter.goLimiter, Decision, the Redis client
internal/ratelimit/take.luarefill and take in one atomic step
internal/ratelimit/limiter_test.goruns against a real Redis in a container
Gateway
gateway/middleware/ratelimit.goasks the limiter, writes 429 and headers
gateway/router.gomounts the middleware before the proxy
gateway/middleware/ipblock.goreplaced by per-key limits
Config and metrics
config/routes.yamladds rate and burst per route
gateway/metrics/ratelimit.goallowed and limited counters per route
Build
Tasks
Six tasks. Tasks 1 and 2 have no dependencies, so two agents can start them at once. Each card ends with its key change: the few sections of code that carry it.
Task graph · pick a task
Tasks, their order, and what each one touches
Pick a task to see the blocks and files it touches.
What to notice: an arrow points from a task to a task that waits for it. A dashed box waits; a filled box is done.
1
Token bucket in Redis
Take tokens atomically, so two replicas can never spend the same token.
Tier
2
Files
internal/ratelimit/limiter.go
internal/ratelimit/take.lua
internal/ratelimit/limiter_test.go
Interface
Take(ctx, key, cost) (Decision, error)
Test first
TestTakeIsAtomicUnderConcurrency: 200 goroutines take from a bucket of 100; exactly 100 succeed.
Verify
go test ./internal/ratelimit/ -race
Budget
30 min
Key change
Sketch · internal/ratelimit/limiter_test.go
Exactly 100 of 200 takes succeed
func TestTakeIsAtomicUnderConcurrency(t *testing.T) {
l := newTestLimiter(t, fixedClock) // real Redis in a container
var ok atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 200; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if d, _ := l.Take(ctx, "k_42:orders", 1); d.Allowed { ok.Add(1) }
}()
}
wg.Wait()
if got := ok.Load(); got != 100 { t.Fatalf("allowed %d, want 100", got) }
}
Fixed clock. No refill during the test, so the bucket holds exactly 100 tokens.
Exact count. 101 means two replicas spent one token.
2
Per-route limits in config
Load rate and burst per route, and reject a config with a missing value.
Tier
1
Files
config/routes.yaml
internal/ratelimit/limiter.go
Test first
TestRouteWithoutBurstIsRejected: loading fails and names the route.