API Rate Limits Plan
Plan · API platform

Rate limits for the public API

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.
Scope
Gateway middleware, a Redis token bucket, per-route limits, 429 headers, metrics.
Not in scope
Per-user billing tiers and a self-service limits page.
Progress
of tasks done, ready to start.

Map · the whole system

Where a request goes, today and after this plan

Config service Rate limiter Redis buckets Client API gateway IP blocklist Upstream services Metrics 1 2 3 4 5 6
  1. A client calls the API with its key.
  2. New: the gateway asks the limiter for one token for this key and route.
  3. New: the limiter runs one Lua script, take.lua, in Redis. It refills the bucket and takes a token in one atomic step.
  4. New: the config service sends each route's budget to the limiter.
  5. Allowed requests go upstream. Today they pass the IP blocklist first; this plan removes it.
  6. The gateway counts allowed and limited requests.

Pick a block to see which tasks touch it.

What to notice: the limiter is shared. Every gateway replica asks the same Redis buckets, so a key cannot get six budgets from six replicas.

What changes

    Design

    What changes

    Three claims tell the whole change. Open “How and where” under a claim for the calls and the code that make it true.

    Each key gets one budget per route, shared by every replica.

    RouteRateBurstA key can send in one minute
    GET /v1/orders50/s1003,100 (100 at once, then 50 a second)
    POST /v1/payments5/s10310

    Do internal service keys skip the limiter?

    Then task 2 also loads an allowlist of internal keys, and the middleware checks it first.

    How and where

    The gateway asks the limiter before the proxy runs.

    Calls · one request

    What runs for GET /v1/orders

    What to notice: the limiter runs before the proxy, so a limited request costs one Redis call and nothing upstream.
    Where

    router.go:30 · mount RateLimit after auth

    Diff · gateway/router.go

    The middleware joins the chain

    @@ -27,5 +27,6 @@
     func routes(r *Router, l ratelimit.Limiter, rt RouteTable) {
         r.Use(auth.Middleware)
         r.Use(ipblock.Middleware)
    +    r.Use(middleware.RateLimit(l, rt))
         r.Handle("/", proxy)
     }
    1. 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) }
    1. Refill. Tokens grow with the time since the last call, up to the burst.
    2. Atomic. Redis runs the whole script at once, so two replicas never spend the same token.
    3. 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

    Client Gateway Limiter Redis Upstream GET /v1/orders Take(k_42:orders, 1) EVALSHA take.lua ok, 41 left forward 200 · RateLimit-Remaining: 41 empty, refill in 1.2 s 429 · Retry-After: 2 not called
    1. The client sends a request with its key.
    2. The gateway asks the limiter for one token. The limiter runs one script in Redis.
    3. Tokens remain, so the gateway forwards the request and reports what is left.
    4. 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)
    1. Round up. A refill in 1.2 s gives 2, so a client that waits never comes back early.
    2. Return first. The handler stops here, so upstream never sees the request.

    Operators see allowed and limited counts for each route.

    MetricLabelsAnswers
    gateway_ratelimit_decisions_totalroute, outcomeWhich routes hit their limit, and how often
    gateway_ratelimit_take_secondsrouteHow 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)
    OptionGivesCosts
    Redis token bucket · chosenOne budget per key across all replicasOne Redis round trip per request, about 0.4 ms in the same zone
    In-process countersNo network callSix budgets per key; the limit drifts each time replicas scale
    Vendor gateway pluginNo code to ownLocks 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)
    OptionGivesCosts
    Token bucket · chosenBursts up to the bucket size; a smooth averageTwo numbers per key: tokens and last refill time
    Fixed windowOne counter per key per windowDouble budget at each window edge
    Sliding logExact countsOne 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
    }

    Route limits

    Sketch · config/routes.yaml

    Per-route limits

    routes:
      - match: GET /v1/orders
        rate: 50/s      # refill rate
        burst: 100      # bucket size
      - match: POST /v1/payments
        rate: 5/s
        burst: 10

    Response headers

    HeaderSent onValue
    RateLimit-Remainingevery responsetokens left after this request
    Retry-After429 onlywhole seconds until one token refills, rounded up
    Build

    Files and code

    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. 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) }
      }
      1. Fixed clock. No refill during the test, so the bucket holds exactly 100 tokens.
      2. Exact count. 101 means two replicas spent one token.
    2. 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.
      Verify
      go test ./config/ ./internal/ratelimit/
      Budget
      30 min
      Key change

      Diff · config/routes.yaml

      Each route gets a rate and a burst

      @@ -4,4 +4,8 @@ routes:
         - match: GET /v1/orders
           upstream: orders
      +    rate: 50/s      # refill rate
      +    burst: 100      # bucket size
         - match: POST /v1/payments
           upstream: payments
      +    rate: 5/s
      +    burst: 10

      Sketch · internal/ratelimit/limiter.go

      A route without a burst stops the load

      func LoadRoutes(cfg []RouteConfig) (RouteTable, error) {
          rt := RouteTable{}
          for _, r := range cfg {
              if r.Rate == 0 || r.Burst == 0 {
                  return nil, fmt.Errorf("route %q: rate and burst are required", r.Match)
              }
              rt[r.Match] = Route{Rate: r.Rate, Burst: r.Burst}
          }
          return rt, nil
      }
      1. Fail at load. A bad config stops the deploy, not a live request.
    3. 3

      Limiter middleware in the gateway

      Ask the limiter before the proxy runs. Fail open if Redis does not answer in 50 ms.

      Tier
      2
      Files
      • gateway/middleware/ratelimit.go
      • gateway/router.go
      Interface
      func RateLimit(l ratelimit.Limiter, routes RouteTable) func(http.Handler) http.Handler
      Test first
      TestLimitedRequestNeverReachesUpstream: with an empty bucket, the upstream fake sees 0 calls.
      Verify
      go test ./gateway/... -run RateLimit
      Budget
      30 min
      Key change

      Sketch · gateway/middleware/ratelimit.go

      Ask the limiter; fail open after 50 ms

      func RateLimit(l ratelimit.Limiter, routes RouteTable) func(http.Handler) http.Handler {
          return func(next http.Handler) http.Handler {
              return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                  rt := routes.Match(r)
                  ctx, cancel := context.WithTimeout(r.Context(), 50*time.Millisecond)
                  defer cancel()
                  d, err := l.Take(ctx, auth.Key(r)+":"+rt.Name, 1)
                  if err != nil {
                      next.ServeHTTP(w, r) // Redis is slow or down
                      return
                  }
                  // lines 30-37: the limited branch and the headers (task 5)
      1. 50 ms budget. The Redis call never adds more than 50 ms to a request.
      2. Fail open. During an outage a key can go over budget. Decision D4 can change this.
    4. 4

      Allowed and limited counters

      Count every decision per route, so a dashboard can show who hits the limit.

      Tier
      1
      Files
      • gateway/metrics/ratelimit.go
      Test first
      TestDecisionsAreCountedPerRoute: 3 allowed and 1 limited give counters of 3 and 1.
      Verify
      go test ./gateway/metrics/
      Budget
      30 min
      Key change

      Sketch · gateway/metrics/ratelimit.go

      One counter, two labels

      var decisions = promauto.NewCounterVec(prometheus.CounterOpts{
          Name: "gateway_ratelimit_decisions_total",
          Help: "Rate-limit decisions, by route and outcome.",
      }, []string{"route", "outcome"})
      
      func Observe(route string, d ratelimit.Decision) {
          outcome := "allowed"
          if !d.Allowed {
              outcome = "limited"
          }
          decisions.WithLabelValues(route, outcome).Inc()
      }
      1. No key label. A label per API key makes one series per customer.
    5. 5

      429 response and headers

      Send Retry-After on 429 and RateLimit-Remaining on every response.

      Tier
      1
      Files
      • gateway/middleware/ratelimit.go
      Test first
      TestRetryAfterRoundsUp: a refill in 1.2 s gives Retry-After: 2.
      Verify
      go test ./gateway/middleware/ -run Retry
      Budget
      30 min
      Key change
    6. 6

      Remove the IP blocklist

      Delete the old middleware after per-key limits run in production for a week.

      Tier
      2
      Files
      • gateway/middleware/ipblock.go
      • gateway/router.go
      Test first
      TestRouterHasNoIPBlock: the middleware chain no longer lists ipblock.
      Verify
      go test ./gateway/... && go vet ./gateway/...
      Budget
      30 min
      Key change

      Diff · gateway/router.go

      The blocklist leaves the chain

      @@ -8,4 +8,3 @@ import (
           "example.com/gateway/auth"
      -    "example.com/gateway/middleware/ipblock"
           "example.com/gateway/middleware"
           "example.com/gateway/proxy"
      @@ -27,6 +26,5 @@
       func routes(r *Router, l ratelimit.Limiter, rt RouteTable) {
           r.Use(auth.Middleware)
      -    r.Use(ipblock.Middleware)
           r.Use(middleware.RateLimit(l, rt))
           r.Handle("/", proxy)
       }
      1. Last import. Nothing else imports ipblock, so the task deletes the package too.
      2. After a week. Remove it only when per-key limits ran in production for a week.
    Build

    Verify and roll back

    Run the tests, then a load test against staging. A flag turns the limiter off in seconds.

    go test ./... -race
    echo "GET https://staging.api/v1/orders" | vegeta attack -rate=120/s -duration=30s -header "Authorization: Bearer $KEY" | vegeta report
    flagctl set gateway.ratelimit.enabled false   # rollback: requests skip the limiter

    The load test sends 3,600 requests in 30 seconds. Expect 1,600 to pass: the burst of 100, plus 50 a second for 30 seconds. The other 2,000 get 429.

    Scope

    Out of scope

    • Billing tiers per user. Every key on a route gets the same budget.
    • A page where customers see their own limits. The response headers carry the numbers for now.