AlgoViz

Design an API Rate Limiter

medium 45 min

Decide, in about a millisecond and on every request, whether this caller may go on.

See it run

One request at a time: a bucket check, a sliding window, two gateways that race, and a lease.

Operations

Token bucket check

Every request makes one trip to a script that refills, compares and takes a token.

Step 1 of 11

A request arrives

Our systemClientGatewaywith limiterRedisbucketBackend

caller

user 12345

It carries an API key or a signed token. Why: we need to know whose bucket to use.

Step 1: A request arrives

def handle(request):    key = rate_key(request)                 # user and endpoint    ok, left, retry = redis.evalsha(BUCKET, key, size, rate, 1)    if not ok:        return 429, {"Retry-After": retry}    response = backend.call(request)    response.headers["X-RateLimit-Remaining"] = left    return response
Latency
about 0.5 ms
Store calls
1

Nothing refills in the background. The script works out the refill when a request arrives.

In the real world

The same design an api rate limiter doing real jobs. Pick one and step through it.

The limiter must not become the outage.

Step 1 of 5

No answer

Our systemClientGatewaywith limiterRedisbucketBackend

timeout

2 ms

After 2 ms the gateway stops waiting.

Step 1: No answer

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reading, deciding and writing in three steps

    critical

    Two gateways can decide from the same old value.

    Wrong
    tokens = redis.get(key)if tokens > 0:    redis.set(key, tokens - 1)
    Right
    ok = redis.evalsha(BUCKET, key, size, rate, 1)
  • Deciding from a cached count

    critical

    Every gateway spends the same remaining tokens.

    Wrong
    left = local_cache.get(key)return left > 0
    Right
    # lease: tokens are taken before useok = redis.evalsha(BUCKET, key, size, rate, 10)
  • Using each gateway's clock

    major

    Gateways disagree, so refill jumps back and forth.

    Wrong
    now = time.time()      # in the gateway
    Right
    local t = redis.call('TIME')   -- in the script
  • A long timeout to the store

    critical

    Waiting requests fill the gateway and stop unrelated callers.

    Wrong
    redis.timeout = 5.0
    Right
    redis.timeout = 0.002# then the local bucket
  • Forgetting the burst in the promise

    minor

    100 a minute with a burst of 20 admits 120 in the best minute.

    Wrong
    size = 20; rate = 100 / 60
    Right
    size = 20; rate = 80 / 60    # 100 in any minute

Interview tips

  • Lead with numbers

    • 10M checks a second, 30M at peak.
    • 100 primaries a region, from operations.
    • State is only 15 GB.
  • Show the trade-off

    • Token bucket for bursts, sliding window for per-minute promises.
    • Leases save calls and strand tokens.
    • Shares respect the total and may refuse early.
  • Plan the failure

    • 2 ms, circuit, local 2%.
    • Login refuses.
    • Watch refusal rate and p99 of the check.
  • Think of the client

    • Headers on every response.
    • Retry-After on 429.
    • An endpoint that explains a refusal.