AlgoViz

Requirements of a rate limiter

easy 24 min

Before choosing an algorithm, agree on the rules: who is counted, what counts, how strict the limit is, where it is checked, what a refused caller gets, how fast the check must be, and what happens when the limiter itself fails.

See it run

Each question in a picture: why, whom, where, how strict, and what if the limiter breaks.

Operations

Why: a spike

The same traffic with and without a limit of 100 a second.

Step 1 of 6

Normal

Our systemClients10 a secondAPI gatewaylimit 100 a secondService10 a second
Passed
10
Refused
0

10 requests a second. All pass.

Step 1: Normal

rule = Rule(name="api", subject="account",            limit=100, window="1 s")if count(rule, caller) >= rule.limit:    return 429, retry_after(rule)return next(request)
Question
Why?
Decide by
Goal

Name the goal before the number.

In the real world

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

Who would be refused, before anybody is.

Step 1 of 3

Plan

Accounts
Under 609,940
60 to 20055
Over 2005

Example numbers

Limit 60 a minute. Count for a week, refuse nobody.

Step 1: Plan

Common mistakes

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

  • Open for everything

    critical

    With the store down, password guessing has no limit.

    Wrong
    except Timeout: return allow
    Right
    except Timeout:    return local_limit(rule) if rule.fail_open else refuse
  • Trusting a forwarded header

    critical

    A client can write a new address into it for each call.

    Wrong
    ip = headers["X-Forwarded-For"].split(",")[0]
    Right
    ip = last_entry_added_by_our_proxy(request)
  • No waiting time

    major

    Clients guess, and try again at once.

    Wrong
    return 429
    Right
    return 429, {"Retry-After": seconds}
  • Limits in the code

    major

    Raising one customer's limit needs a release.

    Wrong
    LIMIT = 100
    Right
    limit = rules.for_request(route, plan).limit

Interview tips

  • Explain it in one line

    • Why, whom, how much, where, what answer, what on failure.
  • LIMIT

    • Low time, Identify, Multiple rules.
    • Inform, Track.
  • Good targets

    • 2 ms extra, 5 ms timeout.
    • 1% error.
    • Rules live in 60 s.
  • Expect these questions

    • Open or closed?
    • By address or by user?
    • How exact must it be?