Sub topic 1
Why services need rate limiters
A rate limiter decides, for each incoming request, whether the service should handle it now or turn it away. This chapter covers the goals a limiter serves, the failure it prevents, and the vocabulary the rest of the tutorial uses. It writes no limiter code yet. Later chapters build the algorithms.
Prerequisites
This chapter assumes you know:
- Basic HTTP request and response concepts: methods, status codes, and headers.
- A general-purpose programming language such as Python. Examples read like pseudocode, but you should be comfortable with loops and dictionaries.
- The basic idea of a key-value store such as Redis: you store a value under a key and read it back.
- How web services are deployed behind a load balancer, which spreads requests across several identical servers.
What a rate limiter does
A rate limiter caps how much work a caller can ask of a service in a period of time. A caller might be a user, an API key, an IP address, or another service. The cap might be "100 requests per minute" or "5 login attempts per 15 minutes."
The limiter sits in the request path. Each request is checked against a rule. If the caller is within its allowance, the request goes on. If not, the service rejects it quickly, usually with HTTP status 429 (Too Many Requests), and spends almost no resources doing so.
Why services need one
Every service has finite capacity: CPU, memory, database connections, thread pools, and money spent on downstream APIs. Without a limit, any single caller can consume as much of that capacity as it can generate load. A limiter turns an open-ended demand into a bounded one. Several distinct goals follow from that.
Protecting availability
Overload is rarely graceful. As a server nears saturation, queues grow, latency rises, and requests start timing out. Clients then retry, which adds load and pushes the server further past its limit. This feedback loop can keep a service down even after the original spike ends.
A limiter breaks the loop by refusing excess work early. Rejecting a request costs far less than starting it and abandoning it halfway through. The service stays responsive for the traffic it can serve.
Fairness between callers
Capacity is shared. If one customer runs a runaway script that sends 10,000 requests per second, other customers see slow responses or errors through no fault of their own. This is the "noisy neighbor" problem, and it matters most in multi-tenant systems, where many customers share the same infrastructure.
Per-caller limits keep one caller's behavior from taking away what the others depend on. The service stays fair even when its total load is high.
Defending against abuse
Some traffic is hostile or abusive:
- Credential stuffing and password guessing, where an attacker tries many logins.
- Scraping of data you would prefer to serve at a human pace.
- Denial-of-service floods, in which many requests aim to exhaust resources.
- Enumeration, such as probing for valid user IDs or coupon codes.
A rate limiter does not stop a determined attacker. A distributed attack comes from thousands of addresses, each below any sensible per-address limit. It does raise the cost of simple attacks, and it is the first line of defense for sensitive endpoints like login and password reset. Treat it as one layer next to authentication, monitoring, and dedicated DDoS protection.
Controlling cost
Many requests cost money. They may call a paid third-party API, run an expensive query, or trigger a machine learning inference on a GPU. A limit puts an upper bound on spending per caller and per period. This is why API providers tie limits to pricing plans: a free tier gets a small allowance, and a paid tier gets more.
Smoothing traffic and enforcing contracts
Limiters also shape load. A batch job that sends a million requests in one burst can be slowed to a rate the backend handles comfortably. And a limit is a clear, enforceable statement of what a plan includes, so both sides know what "100 requests per minute" means.
Summary of goals
The goals differ, and they push the design in different directions.
| Goal | Typical key | Typical limit shape | What matters most |
|---|---|---|---|
| Availability | Whole service or endpoint | Global cap | Speed of the check, protecting the backend |
| Fairness | User or API key | Per-caller rate | Accuracy per caller |
| Abuse defense | IP address, account, endpoint | Tight limit on sensitive routes | Low limits, hard to evade |
| Cost control | API key or plan | Quota per day or month | Durable counts, billing accuracy |
| Traffic shaping | Client or job | Steady rate | Smooth output |
A real system usually combines several of these. Later chapters show how to layer them.
Limiting is not the only tool
Rate limiting is related to, but different from, other overload controls:
- Load shedding drops requests based on the server's current health, such as CPU or queue depth, not on who sent them. A rate limiter reacts to caller behavior. Load shedding reacts to server state.
- Backpressure slows producers by signaling that a consumer is full, often by blocking or by using bounded queues.
- Quotas are long-horizon allowances, such as 1 million calls per month. They are rate limits with a long window, though they are often stored and billed differently.
- Concurrency limits cap how many requests are in flight at once, not how many arrive per second. They suit slow or variable-cost requests better than rate limits do.
A well-protected service often uses a rate limiter for fairness and abuse, plus load shedding as a last resort for overload. Knowing which problem you have tells you which tool to reach for.
The costs of a limiter
A limiter is not free, and a poor one causes problems of its own.
- Added latency. Every request pays for a check. If the check needs a network call to a shared store, that adds a round trip to the hot path.
- False rejections. A limit set too low, or counted inaccurately, rejects legitimate users. Users behind a shared corporate or mobile network address can be blocked as one caller if you key limits on IP.
- Another failure point. If the limiter depends on a store such as Redis and the store goes down, you must decide whether requests are allowed or blocked. Later chapters cover this decision.
- Client friction. Clients need to learn their limits and back off. If the limiter gives no useful signal, well-behaved clients cannot adapt.
These costs shape the design questions in the next chapters: how accurate the count must be, where to enforce it, and what to do when parts of the system fail.
A first look at the decision
Before choosing an algorithm, answer a few questions. This tutorial returns to each one.
- What are you protecting: a backend, a budget, a login endpoint, or fairness between customers?
- Who is the caller, and how do you identify it reliably?
- Is a short burst acceptable, or must the rate stay steady?
- How exact must the count be? Is a 5% error fine, or does it affect billing?
- Does the limit apply on one server or across a fleet?
- What happens to the caller when it is limited, and what happens to the service if the limiter fails?
Exercises
Exercise
A public API has one customer whose script sends far more requests than anyone else, and other customers report slow responses. Which goal of rate limiting does this describe, and what is a sensible key for the limit?
Show answer
This is fairness (the noisy neighbor problem). Key the limit on the customer's identity, such as the API key or account, so one customer's load cannot consume capacity that others depend on. Keying on IP address could block many customers behind a shared address, or miss one customer that uses many addresses.
Exercise
Your service is overloaded because its database is slow, and all callers are well-behaved and within their limits. Will a per-caller rate limiter fix this? Which related technique fits better?
Show answer
No. Every caller is within its allowance, so a per-caller limiter rejects nothing. The problem is the server's health, not caller behavior. Load shedding, which drops requests based on server state such as queue depth or latency, fits better. A global cap or a concurrency limit can also help.
Exercise
Name two costs a rate limiter adds to a service, and say how each can hurt legitimate users.
Show answer
Added latency, because every request waits for the limit check, which is slower if it needs a network call to a shared store. False rejections, because a limit that is too low or keyed on a shared IP address blocks legitimate users. Another valid answer is a new failure point: if the limiter's store is down, the service must either block everyone or let everyone through.