AlgoViz

Rate limits and quotas in APIs

easy 22 min

A limit is part of an API's contract.

Video lesson · Chapter 1 of 6

Spend a bucket of tokens

0:00 / 4:01

429: what it says and what to do, in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A rate limit says how many calls one caller may make in a period, for example 100 a minute. A quota is the same idea over a long time, such as 10,000 a month. A budget counts money instead of calls.

This topic is about using limits well: what to promise, how to say no, and how a client should react. How a limiter counts, and how many servers share one count, is in rate limiter.

Why it exists

Every API has a capacity, and many share it. One broken loop in one customer's script can use all of it. A limit keeps service fair, protects what is behind it, and keeps the bill predictable.

Refusing is not enough. A client that is refused without explanation tries again at once, which makes things worse. Clear limits and headers turn angry retries into calm waiting.

A short history

  1. January 1997

    HTTP/1.1 (RFC 2068) includes the Retry-After header.

  2. April 2012

    RFC 6585 adds status 429 Too Many Requests, which may carry Retry-After.

  3. March 2015

    Amazon's Marc Brooker publishes measurements of exponential backoff with jitter: random waiting keeps clients from returning together.

  4. November 2026

    Standard RateLimit headers are still being written: the IETF draft reaches version 12 after several changes of format.

Words to know

RPM
Requests per minute.
TPM
Tokens per minute: units of text, used by language model APIs, where one request can be small or huge.
Burst
How many calls may come at once before the steady rate applies.
Quota
An allowance over a long period, such as a month.
Tier
A level of service with its own limits, such as free or pro.
429
Status code: too many requests from this caller.
Retry-After
Header: wait this many seconds, or until this date.
Pacing
A client spreading its calls so that it never hits the limit.
Jitter
A random part in a waiting time, so clients do not all return together.

How it works

Step through the idea, or press Play.

Step 1 of 3

Publish. Limits per tier, in the docs and in response headers

Understand it

Start here

The water fountain story

Think of the water fountain at school. The water pressure is limited, and everyone is thirsty.

Fair turns at the fountain

The important part is the sign: it says how long, so nobody has to push.

Four reasons to limit

  • Fairness

    One caller cannot use what belongs to all.

  • Protection

    A broken loop or a guessing attack is stopped early.

  • Cost

    Expensive calls cannot run without end.

  • Product

    Plans differ in what they allow.

Choose

What to count, and for whom

What to count

UnitGood forWeakness
RequestsCalls that cost about the sameA heavy report counts like a tiny read
Points or tokensCalls of very different sizeCost must be estimated before the call
Calls in flightSlow calls, uploads, exportsNeeds a release when the call ends, or a timeout
BytesFiles and streamingKnown only at the end
MoneyPaid services behind your APIPrices change
Most APIs combine two or three: calls a minute, units a minute, money a month.

For whom

KeyUseWatch out
API key or userNormal choice after authenticationOne person may hold several keys: add a limit for the account
Account or organisationBusiness plansOne member can use up everyone's share
IP addressBefore loginA whole school can share one address; use your proxy's trusted address, not a header the client sends
Account name at loginGuessing passwordsDo not lock out the owner for ever
EndpointCostly or risky routesAdd to the others, not instead of them

Which limits does this endpoint need?

Tiers

Different limits for different plans

An example plan table

PlanRequests a minuteTokens a minuteBudget a day
Free310,0001 USD
Pro60100,00050 USD
Enterprise5001,000,000500 USD
Invented numbers. A request must pass all three columns.

Can we keep the promise?

2,000×6060=2,000;req/s promised10% used=200,×3=600;at peak\frac{2{,}000 \times 60}{60} = 2{,}000 ;\text{req/s promised} \qquad 10\% \text{ used} = 200, \quad \times 3 = 600 ;\text{at peak}
Assumed: 2,000 pro customers who use 10% of their limit on average. Promising more than you can serve at once is normal. Know the ratio, and keep a limit for the whole system too.

One request against three limits

Check all, then take from all. Otherwise a refused request still uses part of the allowance.

Architecture

Limits in layers

Each layer stops what it understands

A client's requests pass a CDN with limits per address, then the API gateway with limits per key that are counted in Redis, then a service that caps calls in flight, and finally a paid provider outside our system. The service records cost in a usage database.
The edge knows addresses, the gateway knows keys, the service knows the work and what it costs.
LayerLimitStops
CDN or edgePer addressFloods and simple bots
API gatewayPer key, per planBroken scripts, unfair use
ServiceCalls in flight, pointsSlow and heavy work
BudgetMoney a day or monthSurprise bills

The counters themselves must be shared and atomic, and somebody must decide what happens when the store fails. Both are in rate limiter.

Contract

How to say no

HTTP
HTTP/1.1 429 Too Many RequestsContent-Type: application/problem+jsonRetry-After: 20X-RateLimit-Limit: 60X-RateLimit-Remaining: 0X-RateLimit-Reset: 1735689620{"type": "https://api.example.com/problems/rate-limit", "title": "Too many requests", "status": 429, "detail": "60 requests a minute on the pro plan. Try again in 20 seconds.", "limit": "requests"}
A refusal that helps. The X-RateLimit names are a common convention; the reset here is a time in seconds since 1970.

The headers

HeaderMeansStatus
Retry-AfterWait this many seconds, or until a dateStandard (RFC 9110)
X-RateLimit-Limit, -Remaining, -ResetAllowance, what is left, when it renewsConvention. Reset is a timestamp in some APIs and seconds in others
RateLimit-Policy: "basic";q=100;w=60The rule: quota 100 per 60 secondsIETF draft 12
RateLimit: "basic";a=60;w=58Now: 60 left, for the next 58 secondsIETF draft 12
Earlier drafts used other field names and letters. Send the headers on successful answers too, so that clients can slow down before they are refused.

Which status?

CaseStatus
This caller sent too many429
The whole service is overloaded503, also with Retry-After
Quota for the month is used up429 with a clear reason; some APIs use 403
The request itself is too large413, or 400 for too many items
Never 500: it looks like a bug and invites retries. Never drop silently: the client waits and tries again.

Softer

Serve less before refusing

A phone plan slows down when the data is used up instead of cutting you off. APIs can do the same: a cheaper model, an older cached answer, fewer results.

Example levels by use of the allowance

LevelFree fromPro fromEnterprise fromWhat is served
Full0%0%0%Best quality
Reduced70%85%95%Smaller model, cached answers allowed
Minimal90%95%99%Cached answers only
Blocked100%100%100%429
Always tell the caller which level they got, for example in a header. Some callers prefer an error to a worse answer, so let them choose. See fallbacks.

What happens to a call

Money

Budgets and alerts

Cost of one call

c=nin1000pin+nout1000pout=20001000×0.01+5001000×0.03=0.035c = \frac{n_{in}}{1000} p_{in} + \frac{n_{out}}{1000} p_{out} = \frac{2000}{1000} \times 0.01 + \frac{500}{1000} \times 0.03 = 0.035
With invented prices per 1,000 tokens. A request limit alone cannot protect a budget: one call may cost a hundred times another.
  1. 1

    Record

    Per account: input, output, cost, time. Use decimal numbers, not floating point, for money.

  2. 2

    Warn

    Tell the owner at 50%, 75%, 90% and 100% of the budget.

  3. 3

    Stop

    A hard limit refuses new calls. Reserve the cost before the call, so that parallel calls cannot all pass the check.

  4. 4

    Review

    Look at who is near the limit, who never is, and what the next month will cost.

Client

How a good client behaves

Pace yourself

gap=time until resetremaining=20 s40=0.5 s\text{gap} = \frac{\text{time until reset}}{\text{remaining}} = \frac{20\,\text{s}}{40} = 0.5\,\text{s}
With 40 calls left and 20 seconds to go, one call every half second never hits the limit.

A refusal, handled well

One 429 pauses all workers that share the key, not only the one that received it.

Do

  • Read the headers and slow down early
  • Wait at least Retry-After, plus jitter
  • Share one limiter between all your workers
  • Give up after a few tries and report it
  • Batch, cache and use webhooks instead of polling
  • Ask for a higher limit before a launch

Do not

  • Retry at once in a loop
  • Start more workers when it gets slow
  • Spread calls over many keys to get around a limit
  • Ignore 429 because most calls work
  • Retry a payment without an idempotency key

Waiting times without a header, backoff and retry budgets belong to retries.

Feel

A bucket, seen from outside

Many APIs use a token bucket: it holds up to a burst of tokens and refills at a steady rate. From the outside you notice two numbers: how much at once, and how much per second.

How long to wait

t=needed−haverefill=15−1010=0.5 st = \frac{\text{needed} - \text{have}}{\text{refill}} = \frac{15 - 10}{10} = 0.5\,\text{s}
Capacity 100, refill 10 a second, 15 tokens per request. Five quick requests leave 25; a sixth leaves 10; the seventh must wait half a second.

What each style feels like

StyleClient seesGood when
Token bucketShort bursts pass, then a steady rateInteractive apps
Sliding windowSmooth, no jump at the minuteStrict fairness
Fixed windowEverything renews at once, up to double across the edgeSimple quotas by day or month
The algorithms, their memory and their shared counters: rate limiter.

Operations

Choosing and changing limits

  1. 1

    Measure first

    Look at calls per caller for some weeks. A limit a little above the busiest honest caller hurts nobody.

  2. 2

    Run in shadow

    Count and log who would be refused, without refusing.

  3. 3

    Announce

    Tell the callers near the limit, and give a date.

  4. 4

    Enforce slowly

    Start high, lower in steps, and keep a switch to raise a limit for one account.

  5. 5

    Watch

    Share of 429 answers, callers above 80%, waiting time, and whether the limiter itself is healthy.

Summary

The whole topic in one minute.

Choose the unit that reflects cost, count it per caller, and publish the numbers. Combine a short limit against bursts, a long quota, and a budget in money where calls differ in price.

When a caller goes over, answer 429 with a waiting time, or give a smaller service. A good client reads the headers, spreads its calls, waits with jitter and gives up after a few tries.

  • Count what costs you: calls, tokens, calls in flight, money. Use more than one.
  • Key by account after login and by address before it. Check all limits, then take from all.
  • Say no with 429, a reason and Retry-After. Show what is left on every answer.
  • Serve less before serving nothing, and say so.
  • A good client paces, waits with jitter, shares one limiter, and stops after a few tries.

Sources