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.

Video lesson · Chapter 1 of 5

A burst outruns the report service

0:00 / 4:14

Six questions before a rate limiter, in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

A rate limiter decides, for each request, whether this caller may go ahead now. Its requirements are the rules people agree on before anybody writes code.

They come in two groups. Functional: who is counted, which limits, what a refusal looks like. Non-functional: how fast, how exact, how available, and how easy to change and to watch.

In one line: control who gets how much, and how often.

Why it exists

Two limiters with the same algorithm can behave very differently. One closes the shop when its counter store fails, the other lets everybody in. One counts people, the other counts addresses and blocks a whole school.

Most of these choices belong to the product and the business as much as to engineers: plans, promises to partners, protection of logins. They are cheap to change on paper and costly later.

A short history

  1. 1997

    HTTP/1.1 (RFC 2068) includes Retry-After, so a server can say when to come back.

  2. 2012

    RFC 6585 adds the status 429 Too Many Requests.

  3. 2023

    The OWASP API Security list names unrestricted resource consumption as one of its ten risks.

Words to know

Subject
Who is counted: user, key, account, address.
Rule
Subject, what is counted, limit and time.
Hard limit
Nothing passes above it.
Soft limit
Warns or slows down first, refuses later.
Throttling
Slowing a caller down instead of refusing.
Fail open
If the limiter breaks, let requests pass.
Fail closed
If the limiter breaks, refuse.
Shadow mode
Count and log who would be refused, and refuse nobody.

How it works

Step through the idea, or press Play.

Step 1 of 3

Goal. Protect, share, earn or save: each needs different rules

Understand it

Start here

Rules for a trampoline park

Agreeing the rules before opening

Every rule was agreed before the first child jumped.

Six questions

Why

Start from the goal

Reasons to limit

  • Protection

    A flood or a broken loop must not take the service down.

  • Security

    Slow down password guessing and scraping.

  • Fairness

    One caller cannot use what belongs to all.

  • Cost

    Paid calls and big reports have a ceiling.

  • Product

    Free and paid plans differ; partners get what they signed for.

  • Planning

    Known maximums make capacity and promises possible.

The goal decides the rule

GoalCountExactnessIf the limiter fails
Survive a floodAll requests, and per addressRoughlyKeep a local limit
Stop password guessingFailures per account and per addressStrictClosed
Fair sharingPer keyA few percent is fineOpen
Sell plansPer account, per monthExact enough to bill, counted in the end from recordsOpen, correct later
Protect a budgetMoney per accountStrictClosed, or a small reserve

With limits

  • Load has a known ceiling
  • Costs have a ceiling
  • One heavy user does not hurt the others
  • Guessing is slow
  • Performance stays even

Without

  • Load is whatever arrives
  • A popular post can bring a large bill
  • One client can use nearly everything
  • An easy target
  • Everyone suffers together

Whom

Dimensions

DimensionExample ruleCareful
User or API key1,000 an hour per keyThe normal choice after login
Account10,000 an hour for all its keysSo that many keys do not multiply the limit
IP address100 a minuteMany people can share one; take it from your own proxy
EndpointLogin 5 a minute, search 100 a minuteIn addition, not instead
RegionStricter where you do not offer the serviceBlocking by country is a legal question first
Everything50,000 a second in totalThe last line of defence
Units other than calls, plan tables and the client's side are in rate limits and quotas in APIs.

How strict

Hard, soft and what to do with the rest

Example: 100 a minute

Call numberHard limitSoft limit
1 to 100PassPass
101 to 150429Pass, with a warning in the answer
151 and more429429
A soft limit is kinder to honest bursts. It must be told to the caller, or nobody learns from it.

Four ways to treat a request over the limit

  1. 1

    Reject

    Answer 429 at once. The default: cheap and clear.

  2. 2

    Delay

    Answer slowly. It holds a connection open, so cap how many.

  3. 3

    Queue

    Work on it later. Only for jobs that nobody waits for.

  4. 4

    Degrade

    Serve something cheaper: cached or shorter. See fallbacks.

Over the limit: what now?

Windows come in three kinds: fixed (resets at each full minute), sliding (the last 60 seconds) and a token bucket (a steady refill that allows bursts). As a requirement, say what the caller may do: "bursts up to 20, 100 a minute on average". Which algorithm does it is the subject of rate limiter algorithms.

Where

Placement

Three checks on one path

A client's request passes a CDN that limits by address, then the API gateway that limits by key with counters in Redis, then the service that limits costly work, and only then reaches PostgreSQL.
Each layer checks what it knows: address, then key, then what the work costs.
PlaceKnowsGood forNot good for
CDN or edgeAddress, pathFloods, far from your serversRules per user
Load balancer or web serverAddress, path, some headersSimple rules without another systemPlans and accounts
API gatewayKey, plan, routeMost rules: the usual first choiceWhat a call costs inside
ApplicationEverythingBusiness rules, calls in flightStopping load early
Sidecar proxyWhich service callsCalls between servicesEnd users
Nginx limits with limit_req, Envoy has local and global filters, Kong has plugins, and AWS offers it in API Gateway and WAF.

On the server

  • Cannot be skipped
  • One place to change
  • The only kind that protects you

Only in the client

  • Anyone can leave it out
  • No help against attackers
  • Still useful: it avoids useless calls and is kind to the user

Answer

What the caller gets

HTTP
HTTP/1.1 200 OKX-RateLimit-Limit: 100X-RateLimit-Remaining: 87X-RateLimit-Reset: 1703836860HTTP/1.1 429 Too Many RequestsX-RateLimit-Limit: 100X-RateLimit-Remaining: 0Retry-After: 45
Allowed and refused. The X-RateLimit names are a convention; Retry-After and 429 are standards.

One request

Targets

Requirements you can test

Functional

RequirementSentence to test
Counting101 calls in one minute with a limit of 100: 100 pass
RulesLimit by key, account, address and route, and combine them
PlansA change of plan counts within one minute
AnswerEvery refusal has 429, the name of the limit and Retry-After
ExceptionsSupport can raise one account's limit, with an end date

Non-functional

RequirementExample target
Extra timeAt most 2 ms at p99, never more than 10 ms
Volume350,000 checks a second at peak
ExactnessAt most 1% over the limit, in normal operation
SharedAll gateways of a region count together
AtomicTwo requests at once can never take the last place twice
MemoryAbout 100 bytes for a caller and rule
AvailabilityIf the store fails, the chosen behaviour starts within 50 ms
ChangeNew rules live in 60 s without a restart
VisibleAllowed, refused, errors and time per rule
The numbers are examples to argue about. Higher exactness costs time or availability: every request must ask a shared place.

How many checks?

10 B requests/day86,400 s≈115,700/s,×3≈350,000/s at peak\frac{10\,\text{B requests/day}}{86{,}400\,\text{s}} \approx 115{,}700/\text{s}, \quad \times 3 \approx 350{,}000/\text{s at peak}
One check for each request. With three rules in one script it is still one call.

How much memory?

10 M active callers×3 rules×100 B=3 GB10\,\text{M active callers} \times 3\ \text{rules} \times 100\,\text{B} = 3\,\text{GB}
A counter or a token bucket is small. A log of every call is not: see the algorithms.

Failure

When the limiter breaks

Open, closed or in between?

There is no answer that is right for all routes. Letting everything through is right for most traffic and wrong for a login.

Start

Bringing a limit to life

  1. 1

    Measure

    Calls per caller for some weeks: median, 99th percentile, largest.

  2. 2

    Choose

    Above the busiest honest caller, below what hurts.

  3. 3

    Shadow

    Count, refuse nobody, look at who would be refused.

  4. 4

    Enforce

    For a few percent first, with a switch to turn it off.

A limiter is not enough against a real distributed attack: traffic from very many addresses fills the network before your gateway can count it. That needs a provider at the edge. Limits in the gateway handle the rest.

Check

Do and do not

Do

  • Write requirements as tests
  • Decide open or closed for each route
  • Tell callers what is left
  • Support several subjects at once
  • Log refusals with the rule's name

Do not

  • Block everything when the store fails
  • Limit only by address
  • Forget honest bursts
  • Write limits into the code
  • Leave out Retry-After

Summary

The whole topic in one minute.

Ask six questions: why, whom, what and how much, where, what happens on refusal, and what happens on failure. Write each answer as a sentence that can be tested.

Then give the limiter its own targets: a millisecond or two of extra time, a stated error, no single point of failure, rules that change without a release, and numbers on a dashboard.

  • Six questions: why, whom, how much, where, what answer, what on failure.
  • The goal decides exactness and the failure rule.
  • Check address at the edge, key at the gateway, cost in the service.
  • Targets: 1 to 2 ms, a stated error, rules that change live, visible numbers.
  • Open for most routes with a local limit, closed for logins and money.

Sources