Skip to content

Design an API Rate Limiter, stage 2 of 10: decide

Choose the algorithm

Good clients are bursty: a dashboard loads and fires 20 requests at once, then nothing for a minute. Bad clients are sustained: a loop that never stops. You want to allow the first and stop the second, with little memory per key across ~50,000 keys.

System so far· 4 parts
123CLIENTAPI clientsEDGELoad balancerSERVICEAPI instancesDATABASEPostgres

Select a component to see what it is responsible for and which state it owns.

  1. 1API clients → Load balancer: Requests with API key
  2. 2Load balancer → API instances: Round-robin across instances
  3. 3API instances → Postgres: Admitted requests; plan lookups (cached)

What you need to know

0 of 3 checks done
  1. There are four common rate-limiting algorithms. They differ in what they remember per key:

    AlgorithmState per keyEnforces
    Fixed windowone counterN per calendar window
    Sliding logevery accepted timestampN in any window-length span
    Sliding window countertwo countersan estimate of N in the last window
    Token buckettokens and a timestampa burst of B, then a steady rate r
  2. Try each pattern below. Watch the most in any 10 s figure for each algorithm: that is how much traffic the limiter really lets through in a short span, whatever the plan says.

    Same requests, four limiters. The limit is 5 requests per 10 seconds. Pick a pattern or click the timeline to add requests.
    Requests (10)
    Fixed window10 through · most in any 10 s: 10
    Sliding log5 through · most in any 10 s: 5
    Sliding window counter6 through · most in any 10 s: 6
    Token bucket6 through · most in any 10 s: 6
    15.0s
    Fixed window:
    Counts per calendar window; the count resets at 10 s.
    Sliding log:
    Keeps every accepted timestamp from the last 10 s.
    Sliding window counter:
    Weights the previous window's count by how much of it still overlaps: an estimate, slightly off either way.
    Token bucket:
    Holds 5 tokens and refills one every 2 s, so a full bucket plus refills can admit a little over 5 in a 10 s span.
  3. Check

    With the burst at the boundary, which algorithm lets through twice the limit in under four seconds?