Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 1

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

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.

Python · runaway_bill.py
"""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}')
Expected output (python3 runaway_bill.py)
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 $  60

The 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.

03. What a limit changes for everyone else

The script below uses a deliberately simple model of an overloaded API. The API can serve 100 requests per second. Three apps send 20 requests per second each, and one runaway script sends 300. When demand is higher than capacity, every request has the same chance of being served, as with a busy queue that drops requests at random. Then it compares no limit, a limit of 25 per client, and a limit of 25 per IP address when the three apps sit in one office behind a single public IP address (a NAT gateway, which lets many machines share one address).

Python · share.py
"""Who gets served when demand exceeds capacity? A deliberately simple model."""

CAPACITY = 100  # requests per second the API can serve
DEMAND = {'app-a': 20, 'app-b': 20, 'app-c': 20, 'runaway': 300}
OFFICE = {'app-a', 'app-b', 'app-c'}  # three apps behind one office IP (NAT)


def serve(demand: dict[str, float]) -> dict[str, float]:
    """Over capacity, every request has the same chance of being served."""
    total = sum(demand.values())
    share = min(1.0, CAPACITY / total)
    return {name: rate * share for name, rate in demand.items()}


def per_key_limit(demand: dict[str, float], limit: float, key_of) -> dict[str, float]:
    """Cap each key at `limit`; clients that share a key share the cap."""
    totals: dict[str, float] = {}
    for name, rate in demand.items():
        totals[key_of(name)] = totals.get(key_of(name), 0) + rate
    return {
        name: rate * min(1.0, limit / totals[key_of(name)])
        for name, rate in demand.items()
    }


no_limit = serve(DEMAND)
per_client = serve(per_key_limit(DEMAND, 25, key_of=lambda name: name))
per_ip = serve(per_key_limit(
    DEMAND, 25, key_of=lambda name: 'office' if name in OFFICE else name))

print(f'capacity {CAPACITY} req/s, demand {sum(DEMAND.values())} req/s')
print(f'{"served req/s":<12}{"no limit":>10}{"25 per client":>15}{"25 per IP":>11}')
for name in DEMAND:
    row = (no_limit[name], per_client[name], per_ip[name])
    print(f'{name:<12}{row[0]:>10.1f}{row[1]:>15.1f}{row[2]:>11.1f}')
Expected output (python3 share.py)
capacity 100 req/s, demand 360 req/s
served req/s  no limit  25 per client  25 per IP
app-a              5.6           20.0        8.3
app-b              5.6           20.0        8.3
app-c              5.6           20.0        8.3
runaway           83.3           25.0       25.0

Without a limit, the runaway script receives 83 of every 100 answers, and each well-behaved app gets fewer than 6 of the 20 requests it needs. Nothing is broken in the servers; the capacity simply goes to whoever asks loudest. With a limit of 25 per client, the script is cut down to 25, total demand falls to 85, and every app gets everything it asked for.

The last column shows the price of choosing the wrong key. Counting per IP address puts the three office apps under one shared cap of 25, so each gets about 8 requests per second while the script, alone on its own address, still gets 25. Each honest app now gets a third of what the script gets, although only the script misbehaved. Real models are messier, but the lesson holds: a limit is only as fair as the key it counts by.

04. Choose the key, the unit and the response

Every limit answers three questions. Write the answers down before you choose an algorithm.

  1. 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.
  2. 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.
  3. 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

Practice check · 3 questions

Reasons, keys and units

Three scenarios about what a limit can and cannot do.

Q1. A free plan allows 50 calls a day per account to an endpoint that costs you about $0.01 per call. Overnight a bot signs up 20,000 free accounts and runs up $10,000 in calls, yet no account goes over its limit. What does this show?
Q2. A password-reset flow emails a 6-digit code that stays valid for 15 minutes. The endpoint that checks codes allows 100 requests a minute per IP address. An attacker spreads guesses for one account's code over 2,000 IP addresses. Which limit stops the guessing?
Q3. Each API key has a fixed limit of 100 requests a minute, checked by a per-key rate limiter. During an incident the database can handle only half its usual load, and every key is still under its limit. What does the rate limiter do about the overload?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check