Sub topic 2
Clarifying requirements: what to limit, how strictly, and for whom
A rate limiter is easy to build and hard to build correctly for the wrong problem. Before you choose an algorithm or a place to run it, you need written answers to a few questions. This chapter covers those questions and shows how to record the answers as a limit policy.
This chapter assumes you know basic HTTP request and response concepts, can read Python, and have a rough idea of what a key-value store such as Redis does. Later chapters build the algorithms. Here we only decide what they must satisfy.
Why requirements come first
The same phrase, "limit each user to 100 requests per minute," can describe very different systems. It could mean a hard billing quota, a soft guard against runaway scripts, or a way to keep a database from falling over. Each reading leads to a different algorithm, a different storage design, and a different behavior when something fails.
Skipping this step usually produces one of two outcomes. The limiter is stricter and more expensive than needed. Or it is too loose to protect the thing it was meant to protect.
Question 1: What are you protecting?
Start with the goal. Common goals are:
- Availability: keep one noisy client from starving others, or keep total load below what a backend can handle.
- Cost control: cap calls to a paid downstream service, or cap compute-heavy endpoints.
- Fairness: give each tenant a predictable share.
- Abuse prevention: slow credential stuffing, scraping, or enumeration.
- Business rules: enforce plan quotas such as 10,000 calls per month.
The goal sets the unit of measure. Protecting a database means counting queries or concurrent requests. Protecting a payment provider means counting calls to that provider. Counting raw HTTP requests is often only a proxy for the real constraint.
Question 2: What exactly do you count?
Decide the unit and its weight.
- Requests per time period is the usual choice.
- Weighted cost charges expensive operations more. A search might cost 5 tokens and a health check 0. The token bucket in a later chapter supports this through its
costargument. - Concurrency limits requests in flight at one time, rather than requests per time. It suits slow endpoints.
- Bandwidth or payload size applies to uploads and exports.
Also decide which requests count. Do rejected requests count against the limit? Do requests that fail validation count? Do internal health checks count? If rejected requests count, a client that keeps retrying stays locked out. If they do not count, retries cost you only the check itself. Pick one on purpose.
Question 3: For whom? Who gets which limit?
A limit applies to some identity, called the key. Candidates are a user, an API key, a tenant, an IP address, or an endpoint. The next chapters cover how to choose and extract the key. For requirements, you only need to answer these questions:
- Are all clients treated alike, or are there tiers (free, paid, internal)?
- Is there one limit per key, or several limits that stack?
- Do some callers get exemptions, such as health checks or trusted partners?
- Is there a global cap in addition to per-key limits?
Write these as a table of policies. If the table has many rows, you already know you need multiple tiers and a way to look up limits by key.
Question 4: How strict must it be?
Strictness is the requirement that most affects cost. Ask how bad it is if the limiter lets a few extra requests through, or rejects a few that should have passed.
| Level | Meaning | Example | Implication |
|---|---|---|---|
| Approximate | Small errors are fine | Protecting a web API from scripts | Cheap counters, cached or local state |
| Accurate | Errors are rare and small | Public API with documented limits | Sliding window or token bucket, shared store |
| Exact | No request over the limit, ever | Paid quota, legal or contractual cap | Atomic shared state, often a log or ledger |
Exactness costs more in memory, latency, and coordination. A limiter that is exact across ten servers needs every check to reach shared state, and that adds a network hop to every request. Many teams find "within a few percent" is enough for protection, and reserve exactness for billing quotas.
Strictness also has a time dimension. Decide whether short bursts are acceptable. A limit of 600 per minute can mean "10 per second, smoothed" or "600 at any pace within the minute." Clients usually want bursts, and backends usually want smoothness. This choice leads directly to the fixed window and token bucket discussions later.
Question 5: What happens when a request is rejected, and when the limiter fails?
Two behaviors need decisions now, because they change the design.
- Rejection behavior. Do you return an error immediately, queue the request and delay it, or degrade the response? Immediate rejection is simplest. Delay smooths traffic but holds connections open. Later chapters cover the HTTP 429 response and retry hints.
- Failure behavior. If the store holding counters is down, do you allow traffic (fail open) or block it (fail closed)? A limiter that protects a fragile backend may need to fail closed. A limiter in front of a login page that must stay reachable probably fails open. Decide per policy, not once for the whole system.
Question 6: Scale and latency budget
Estimate the numbers that constrain the design:
- Requests per second at peak, and the number of distinct keys.
- Number of application servers that must share state.
- The latency the limiter may add. A common target is a few milliseconds at most.
- Memory per key multiplied by the number of active keys.
If you have a million active keys and store a timestamp log of 1,000 entries per key, the memory cost is obvious. Doing this arithmetic early rules algorithms out before you write code.
How the questions fit together
The diagram shows how the answers narrow the design.
Recording the answers as a policy
Write the answers in a form that code can read. A small, explicit policy object keeps the requirements visible and testable. The example below does not enforce anything. It records requirements and rejects inconsistent ones.
from dataclasses import dataclass
from enum import Enum
class OnStoreFailure(Enum):
FAIL_OPEN = "fail_open"
FAIL_CLOSED = "fail_closed"
class Strictness(Enum):
APPROXIMATE = "approximate"
ACCURATE = "accurate"
EXACT = "exact"
@dataclass(frozen=True)
class LimitPolicy:
name: str
key_by: str # "user", "api_key", "ip", "endpoint"
limit: int # requests allowed per window
window_seconds: int
burst: int # largest short burst allowed
strictness: Strictness
on_store_failure: OnStoreFailure
def validate(self):
if self.limit <= 0 or self.window_seconds <= 0:
raise ValueError(f"{self.name}: limit and window must be positive")
if self.burst < 1:
raise ValueError(f"{self.name}: burst must be at least 1")
if self.burst > self.limit:
raise ValueError(f"{self.name}: burst cannot exceed limit")
if (self.strictness is Strictness.EXACT
and self.on_store_failure is OnStoreFailure.FAIL_OPEN):
raise ValueError(
f"{self.name}: an exact limit cannot fail open"
)
@property
def average_rate(self):
return self.limit / self.window_seconds
POLICIES = [
LimitPolicy("public-api", "api_key", 600, 60, 20,
Strictness.ACCURATE, OnStoreFailure.FAIL_OPEN),
LimitPolicy("login", "ip", 10, 60, 3,
Strictness.APPROXIMATE, OnStoreFailure.FAIL_OPEN),
LimitPolicy("monthly-quota", "api_key", 100000, 30 * 24 * 3600, 1000,
Strictness.EXACT, OnStoreFailure.FAIL_CLOSED),
]
for policy in POLICIES:
policy.validate()
print(f"{policy.name}: {policy.average_rate:.4f} req/s average, "
f"burst {policy.burst}, {policy.strictness.value}")The validate method catches a contradiction before it ships: an exact quota that fails open can overspend whenever the store is down.
Common mistakes
- Choosing the algorithm first. Teams pick token bucket because it is popular, then discover they needed an exact monthly quota.
- One global rule. A single limit for all endpoints lets a cheap endpoint use up the budget of an expensive one, or does the reverse.
- Ignoring rejected requests. If clients retry in a tight loop and each retry is counted and processed, the limiter itself becomes load.
- Vague strictness. "Accurate" means different things to different people. Put a number on it, such as "no more than 5 percent over the limit."
- No decision on failure. The default behavior in an untested code path is usually the wrong one.
Summary of what to bring forward
Leave this chapter with a short list: the goal, the unit and its weight, the keys and tiers, the strictness level, the rejection and failure behavior, and the scale numbers. The following chapters use that list to choose where to enforce limits, how to identify the client, and which algorithm fits.
Exercise
A team wants to limit a report-generation endpoint. Each report takes about 20 times the server time of a normal request, and customers pay for a monthly allowance of 500 reports. Name the unit you would count, the strictness level for the monthly allowance, and its failure behavior if the counter store is down. Give a reason for each.
Show answer
Count weighted cost or, more simply, reports generated, not raw HTTP requests, because a report costs far more than a normal request and the allowance is stated in reports. The monthly allowance is a paid quota, so it should be exact. If the store is down, it should fail closed so customers cannot exceed the allowance. If that is unacceptable for availability, a fallback is to accept requests and reconcile afterward, but that must be a deliberate decision. A separate short-term limit on concurrency or per-minute rate would also protect the servers, and that one could be approximate and fail open.
Exercise
A policy says limit=100, window_seconds=10, burst=150. Why does the validate method reject it, and what does the limit of 100 per 10 seconds mean as an average rate?
Show answer
The burst of 150 exceeds the limit of 100, so the policy is inconsistent: a burst cannot be larger than the total allowed in the window. The average rate is 100 / 10 = 10 requests per second.