AlgoViz

Design a rate limiter

medium 45 min

Protect services against overload, abuse and surprise bills.

See it run

Many gateways, one count: follow a request, a race, a failure, a hot caller and a second region.

Operations

One request

From the client to the answer.

Step 1 of 7

A request arrives

Our systemClientLoad balancerAPI gatewayrules in memoryRedis42 tokensService

The client sends a request with its key.

Step 1: A request arrives

def handle(request):    caller = verify(request.token)    rule = rules.find(request.path, request.method, caller.plan)    ok, left, wait = redis.script(key(caller, rule), rule)    if not ok:        return 429, {"Retry-After": wait}    return forward(request, remaining=left)
Extra time
about 1 ms
Error
None

Rules in memory, counts in Redis.

In the real world

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

A ticket sale begins and scripts try to buy everything.

Step 1 of 3

Before

TriesPassed
People--
Scripts--

5 booking tries a minute per account, 300 a minute per address.

Step 1: Before

Common mistakes

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

  • GET, then SET

    critical

    Parallel requests read the same number and all pass.

    Wrong
    n = redis.get(key)if n < limit: redis.set(key, n + 1)
    Right
    ok = redis.script(BUCKET, key, limit)
  • Expiry in a second call

    major

    If the process stops in between, the key stays and the caller is blocked for ever.

    Wrong
    n = redis.incr(key)if n == 1: redis.expire(key, 60)
    Right
    INCR and EXPIRE in one script
  • Waiting for Redis

    critical

    A slow helper makes every request slow.

    Wrong
    redis = Redis()   # default timeout
    Right
    redis = Redis(timeout="5 ms")fallback = local_limit
  • A missing plan matches

    major

    Callers without a plan slip under a rule made for others.

    Wrong
    if rule.tiers and tier and tier not in rule.tiers:    skip
    Right
    if rule.tiers and tier not in rule.tiers:    skip

Interview tips

  • Explain it in one line

    • Many gateways share one count with one atomic step, and have a plan for its failure.
  • REDIS

    • Redis for a shared count, Expire keys.
    • Distribute, Include headers, Script.
  • Good numbers

    • 350,000 checks a second, 12 shards.
    • 3 GB of buckets.
    • 5 ms timeout.
  • Expect these questions

    • What if Redis is down?
    • What about one huge caller?
    • One limit for two regions?