AlgoViz

Rate limits and quotas in APIs

easy 22 min

A limit is part of an API's contract.

See it run

See a limit from both sides: what the server counts and answers, and what a good client does next.

Operations

A bucket, seen from outside

Capacity 100, refill 10 a second, 15 tokens for each request.

Step 1 of 7

Full bucket

Our systemClientAPI gatewayrefill 10 a secondService
Tokens of 100
100

requests

The client starts with a burst of 100 tokens.

Step 1: Full bucket

def take(bucket, n, now):    bucket.tokens = min(100, bucket.tokens + (now - bucket.last) * 10)    bucket.last = now    if bucket.tokens >= n:        bucket.tokens -= n        return 200    wait = (n - bucket.tokens) / 10    return 429, {"Retry-After": ceil(wait)}
Refused with
429 + Retry-After
Client does
Waits
How it is built and shared
see the rate limiter topic

Two numbers: burst size and refill rate.

In the real world

The same rate limits and quotas in apis doing real jobs. Pick one and step through it.

600 calls with a limit of 60 a minute.

Step 1 of 3

As fast as possible

PassedRefused
At once60540
Paced--

The script sends 600 at once. 60 pass and 540 are refused.

Step 1: As fast as possible

Common mistakes

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

  • Retrying at once

    critical

    The retries are extra load on a service that has none to spare.

    Wrong
    while send().status == 429:    pass
    Right
    r = send()if r.status == 429:    sleep(r.retry_after * (1 + random() * 0.1))
  • Taking before all limits are checked

    major

    A refused request still uses a call, and the caller cannot understand the numbers.

    Wrong
    calls += 1if tokens_used + n > tpm: return 429
    Right
    if calls + 1 > rpm or tokens_used + n > tpm:    return 429take_from_all()
  • Check, then spend

    critical

    Ten parallel calls all see room and all pass.

    Wrong
    if spent(account) < budget:    call_provider()
    Right
    if reserve(account, estimate):   # atomic    call_provider()    settle(account, real)
  • Trusting a caller's own header

    critical

    A client can send a new user ID with every call and never be limited.

    Wrong
    who = request.headers["X-User-ID"]
    Right
    who = verify(request.token).account

Interview tips

  • Explain it in one line

    • A limit is a promise to all callers and a rule for each.
    • Say no with a reason and a waiting time.
  • BUCKET

    • Burst, Usage, Cost.
    • Quota, Enforce, Track.
  • Good numbers

    • Gap = time to reset / remaining.
    • Wait = (needed - have) / refill.
    • Warn at 50, 75, 90 and 100%.
  • Expect these questions

    • Which key do you count by?
    • What does the client do on 429?
    • How do you add limits to a live API?