Why limit: abuse, fairness, cost and overload
See the four reasons services limit their callers, and how each reason decides what you count, whose requests you count together, and what happens to the excess.
Contentsand lesson path
On this page
- Why it matters
- Four reasons to limit
- What a limit changes for everyone else
- Choose the key, the unit and the response
- Check your understanding
- Apply it
- Review prompt
Lessons of Rate Limiting
- Why limit: abuse, fairness, cost and overload Concept · 15 min
- Token bucket, leaky bucket, fixed and sliding windows Concept · 20 min
- Implementing token-bucket and sliding-window limiters Lab · 30 min
- Going distributed: atomic counters, races and store outages Worked example · 25 min
- Where to enforce limits and how clients should react Concept · 15 min
- Rate limiter check Knowledge check · 6 questions
What you will learn
- Choose where to enforce limits (edge, gateway, service, per tenant) and how clients learn about them (429, Retry-After, rate-limit headers).
01. Why it matters
Picture a public API that has run quietly for months. On a Friday evening one customer deploys a script with a bug: when a call fails, it calls again at once, in a tight loop. Within minutes that one script sends more traffic than all other customers together. Pages slow down for everyone, the database team gets paged, and a paid service that the API calls on every request starts to send a large bill.
A rate limit is a rule that caps how much work one caller may ask for in a period of time, for example 100 requests per minute for each API key. Requests over the cap are rejected or delayed. The thing you count against, here the API key, is called the key of the limit. A rate limiter is usually the cheapest protection between a shared service and a single caller that misbehaves, by accident or on purpose.
Teams add limits for four different reasons: abuse, fairness, cost and overload. The reason is not a detail. It decides what you count, which requests you count together, and what should happen to the excess. A limit designed for one reason often does little for another, and this lesson shows why. Lesson 02 then explains the algorithms, and lesson 05 covers where limits run and how clients learn about them.
02. Four reasons to limit
Abuse. Some callers want something you do not want to give away at speed. Credential stuffing tries leaked username and password pairs against your login form. Scraping copies your catalogue page by page. Enumeration guesses identifiers such as order numbers, coupon codes or one-time passwords. A limit on these operations does not make the attack impossible, because attackers spread their requests over many IP addresses and accounts. It makes the attack slower and more expensive, and it makes it visible in your metrics. The OWASP API Security Top 10 (2023) lists missing limits as risk API4, Unrestricted Resource Consumption, and asks for stricter limits on sensitive operations such as validating a one-time password.
Fairness. A shared service has a fixed amount of capacity at any moment: worker threads, database connections, CPU. Without limits, whoever sends the most requests gets the most capacity, and a polite client gets whatever is left. In a multi-tenant product, where many customers (tenants) share one deployment, fairness usually means a limit per tenant, often sized by the tenant's plan.
Cost. Many requests cost money beyond your own servers: a call to a paid model API, a text message, a map lookup, outbound data. A client stuck in a loop turns that price into a bill. The script below makes the arithmetic visible. The price and the rate are assumptions for the example, not a real price list.
"""What does a runaway client cost before someone notices? Assumptions below."""
PRICE = 0.002 # assumed USD per downstream call (a paid API); not a real price list
RATE = 50 # calls per second from one client stuck in a retry loop
QUOTA = 10_000 # a daily quota per API key, if you have one
for label, hours in [('noticed after 1 h', 1), ('noticed next morning, 12 h', 12),
('noticed after a weekend, 60 h', 60)]:
calls = RATE * 3600 * hours
capped = min(calls, QUOTA * -(-hours // 24)) # quota resets every 24 h
print(f'{label:<30} {calls:>11,} calls ${calls * PRICE:>8,.0f}'
f' with quota ${capped * PRICE:>4,.0f}')noticed after 1 h 180,000 calls $ 360 with quota $ 20
noticed next morning, 12 h 2,160,000 calls $ 4,320 with quota $ 20
noticed after a weekend, 60 h 10,800,000 calls $ 21,600 with quota $ 60The bill grows with the time until someone notices; the quota caps it at $20 a day whatever the delay. Change PRICE and RATE to your own numbers: a range from "noticed in an hour" to "noticed after a weekend" is the honest way to present such an estimate. The OWASP list also asks for spending limits at every paid provider, because a limit inside your code only works if every path to the provider goes through it.
Overload. Here a limit protects the service itself. It helps, but it has a blind spot. A per-key rate limiter compares each caller with that caller's own limit. It does not look at how busy the servers are. If 50,000 well-behaved users arrive at once, each under its limit, the limiter admits all of them. Stripe's engineering blog draws this line clearly: a rate limiter decides from the caller's own usage, while a load shedder decides from the state of the whole system and drops lower-priority work when servers are in trouble. Stripe also runs a concurrent requests limiter, which caps how many requests a caller has in progress at once, for its most expensive endpoints. You need limits, shedding and enough capacity together; the overload guards lesson shows a concurrency cap and load shedding in code.
04. Choose the key, the unit and the response
Every limit answers three questions. Write the answers down before you choose an algorithm.
- Key: whose requests are counted together? An IP address is known before any login, which makes it useful against floods and anonymous abuse. But many people can share one address (offices, mobile carriers that use carrier-grade NAT, as in the model above), and an attacker can rent thousands of addresses. An API key, a user or a tenant identifies the caller much better, but you only know it after authentication. Many systems combine keys: per user and per tenant, or per account and per operation, with a much stricter limit on login or password reset than on search. Against guessing, count by the thing being guessed, such as an account or a one-time code: an attacker can rent more addresses, but cannot multiply its target. Also cap how many new codes one account can request per hour, or each new code brings fresh guesses.
- Unit: what is counted? Counting requests is simple and works when requests cost about the same. When cost varies a lot, count something closer to the cost: the number of requests in progress at once, bytes, rows scanned, model tokens, or CPU time. The Google SRE book describes per-customer limits expressed in CPU seconds per second for exactly this reason. Long-window caps, such as 10,000 calls per day or a monthly allowance tied to a billing plan, are usually called quotas.
- Response: what happens to the excess? You can reject it at once (HTTP 429, lesson 05), delay it in a queue so that it runs later at a steady pace, or serve a cheaper answer, such as a cached result. Rejecting is honest and cheap for the server; delaying is friendlier for batch work but holds memory and connections while requests wait.
Limits also have a cost of their own: a limit set too low blocks paying customers, and nobody notices until they complain. Both the Stripe and the AWS write-ups recommend a careful rollout: run a new limit first in an evaluation mode, where it only logs the requests it would reject, check that it hits the traffic you meant, and keep a switch that turns the limit off quickly.
05. Check your understanding
06. Apply it
Choose an API you use or build, or the public API of a product you know. For three of its operations, write one line each: the main reason to limit it (abuse, fairness, cost or overload), the key, the unit, the limit, and what happens to the excess. Include at least one operation where counting requests is the wrong unit.
Keep the notes. The practice task of this skill asks you to build a token-bucket limiter in Redis that two application instances share, and the key and limit you write down here are the ones you will implement in lesson 04.
07. Review prompt
Without looking back: name the four reasons to limit and give one example of each. Explain why a per-IP limit can treat honest users worse than an attacker, why counting requests fails when request costs vary, and why a per-key rate limiter does not protect a service whose capacity has just dropped. Then say how you would roll out a new limit without hurting real customers.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.