Where to enforce limits and how clients should react
Place limits at the edge, the gateway, the service and per tenant according to what each layer knows, tell clients about them with 429 and Retry-After, read the draft RateLimit fields correctly, and make clients slow down instead of retrying harder.
Contentsand lesson path
On this page
- Why it matters
- Where limits run, and what each layer knows
- Telling clients: 429, Retry-After and the draft RateLimit fields
- How clients should react
- 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
A limit has two halves. The server half decides where the limit runs, and that decides what the limiter can know: an address, an API key, a tenant's plan, or the real cost of a request. The client half decides what happens next. A client that learns it is over a limit and waits does no harm. A client that sees a vague error and retries at once turns one rejected request into dozens, and a thousand such clients turn a short limit into a retry storm.
This lesson covers both halves: the layers where limits usually run, the HTTP signals that tell clients about them (including one that is still a draft), and the client behaviour that makes limits work.
02. Where limits run, and what each layer knows
client -> edge (CDN, WAF, LB) -> API gateway -> service -> database, paid APIs
knows: IP, path, knows: API key, knows: user, operation,
headers tenant, plan real cost, dependencies
cheap to reject after auth most precise, latestThe edge, meaning a content delivery network (CDN), a web application firewall (WAF) or the first load balancer, sees every request before anything else spends work on it. It is the cheapest place to drop floods and anonymous abuse, usually per IP address and path. It rarely knows who the caller is or what a request will cost. Very large floods that fill your network link cannot be limited by your own servers at all; they have to be absorbed upstream by your provider or a scrubbing service. If you use NGINX here, note that limit_req rejects with 503 by default; set limit_req_status 429 when the reason is the client's rate.
The API gateway runs after authentication, so it knows the API key, the tenant and the plan. This is the natural home for per-key limits and quotas sold with a plan, and the place where a shared store (lesson 04) keeps many gateway nodes consistent.
The service knows things nobody before it knows: which account a password reset is for, how many rows an export will scan, how busy the database pool is. Limits that depend on business rules or real cost belong here, such as five password-reset emails per account per hour, or two exports in progress per tenant. Rejecting this late wastes the work already done upstream, so keep cheap, coarse limits in front and precise ones here.
Per tenant is a key, not a layer, and it can run at the gateway or the service. Shared products often use limits in two levels: a cap for the whole tenant and a smaller cap for each user inside it, so one tenant cannot crowd out others and one user cannot use up the tenant's share. Whatever the layer, count by an identity the layer can trust: behind proxies, use the client address that your own proxy recorded, not any value the client sent.
03. Telling clients: 429, Retry-After and the draft RateLimit fields
429 Too Many Requests is defined in RFC 6585: the user has sent too many requests in a given amount of time. The response should explain the condition and may include Retry-After. Two more lines of that RFC matter in practice. A response with status 429 must not be stored by a cache. And a server under attack is not required to answer every excess request with 429, because writing responses costs resources; dropping connections can be the better choice.
Retry-After is defined in RFC 9110, section 10.2.3. Its value is either a number of seconds (Retry-After: 12) or an HTTP date (Retry-After: Tue, 17 Nov 2026 10:00:30 GMT). Use 503 Service Unavailable, optionally with Retry-After, when the server is overloaded or shedding load; 429 says the client went over its limit. A short body in the Problem Details format of RFC 9457 makes the error readable by both people and programs.
RateLimit-Policy and RateLimit are header fields that let a server announce its quota and how much is left before the client hits it. They are not a standard yet. As of November 2026 they are an Internet-Draft of the IETF HTTPAPI working group, draft-ietf-httpapi-ratelimit-headers-11, dated 23 May 2026 and expiring on 24 November 2026. A draft can still change, and this one already has: version 05 (2022) defined four separate fields, RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset and RateLimit-Policy. Many APIs send their own older fields, such as X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, and the draft's appendix notes that their time values mean different things in different APIs: seconds, milliseconds, a Unix timestamp or a date. Document whatever you send, and read a provider's documentation before trusting its fields. The script below produces the fields as draft 11 defines them, for a fixed window of 100 requests per 60 seconds.
"""What a server can tell a client about a fixed-window limit of 100 per 60 s."""
import math
def limit_headers(policy: str, quota: int, window: int, used: int,
now: float) -> dict[str, str]:
left = window - now % window # seconds until this window ends
remaining = max(0, quota - used)
headers = {
'RateLimit-Policy': f'"{policy}";q={quota};w={window}', # draft field
'RateLimit': f'"{policy}";r={remaining};t={math.ceil(left)}', # draft
}
if remaining == 0:
headers['Retry-After'] = str(math.ceil(left)) # RFC 9110, in seconds
return headers
for used, now in [(40, 1_000_035), (100, 1_000_068)]:
status = 429 if used >= 100 else 200
print(f'HTTP/1.1 {status}')
for name, value in limit_headers('per-key', 100, 60, used, now).items():
print(f'{name}: {value}')
print()HTTP/1.1 200
RateLimit-Policy: "per-key";q=100;w=60
RateLimit: "per-key";r=60;t=45
HTTP/1.1 429
RateLimit-Policy: "per-key";q=100;w=60
RateLimit: "per-key";r=0;t=12
Retry-After: 12In draft 11, q is the quota and w the window in seconds; r is what remains and t the seconds in which that remainder applies. Here both t and Retry-After are relative seconds, so the client needs no agreement between clocks. The draft adds that a client must not treat a positive r as a promise, and that when a response has both fields, Retry-After wins. The API design lesson shows the same fields inside an API contract.
04. How clients should react
A well-behaved client follows a short list:
- Honour
Retry-After. For the date form, compute the delay asRetry-Afterminus the response's ownDateheader. Both come from the server's clock, so a client whose clock is wrong still waits the right amount. - Without a hint, back off with jitter. Wait a random time between 0 and
base × 2^attempt, up to a cap, and stop after a few attempts. The retries lesson explains why the random part matters. Retry a request that changes data only if it is idempotent or carries an idempotency key. - Pace before you are told. If you know the limit, run your own token bucket on the client side. Several processes that share one API key share one quota, so they need one shared pacer, or a queue that a fixed number of workers drain at a controlled rate, as the Azure Rate Limiting pattern describes.
- Fail fast where a person waits. AWS notes that synchronous callers should not sit in long retry loops; show a clear message instead. Background jobs can simply slow down.
Google's SRE book adds adaptive throttling for clients that call a service many times a second. Each client counts its requests and the server's accepts over the last two minutes, and rejects new requests itself, before they reach the network, with probability max(0, (requests − K × accepts) / (requests + 1)). The book prefers K = 2. The function below implements both the retry delay and this formula, with a seeded random generator so that the output repeats.
"""How long should a client wait after a 429 or 503? Seeded, so it repeats."""
import random
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
def retry_delay(headers: dict[str, str], attempt: int, rng: random.Random,
cap: float = 30.0) -> float:
value = headers.get('Retry-After')
if value is not None:
if value.isdigit(): # delay-seconds form: "17"
return float(value)
when = parsedate_to_datetime(value) # HTTP-date form: compare it with the
if 'Date' in headers: # server's own Date header, not with our clock
sent = parsedate_to_datetime(headers['Date'])
else:
sent = datetime.now(timezone.utc)
return max(0.0, (when - sent).total_seconds())
return rng.uniform(0, min(cap, 2 ** attempt)) # no hint: full-jitter backoff
def throttle_probability(requests: int, accepts: int, k: float = 2.0) -> float:
"""Adaptive throttling (Google SRE book): drop locally before sending."""
return max(0.0, (requests - k * accepts) / (requests + 1))
rng = random.Random(42)
print(retry_delay({'Retry-After': '17'}, 0, rng))
print(retry_delay({'Date': 'Tue, 17 Nov 2026 10:00:00 GMT',
'Retry-After': 'Tue, 17 Nov 2026 10:00:30 GMT'}, 0, rng))
print([round(retry_delay({}, attempt, rng), 1) for attempt in range(7)])
for accepts in (100, 60, 40, 20):
p = throttle_probability(100, accepts)
print(f'last 2 min: 100 requests, {accepts:>3} accepted -> drop {p:.0%} locally')17.0
30.0
[0.6, 0.1, 1.1, 1.8, 11.8, 20.3, 26.8]
last 2 min: 100 requests, 100 accepted -> drop 0% locally
last 2 min: 100 requests, 60 accepted -> drop 0% locally
last 2 min: 100 requests, 40 accepted -> drop 20% locally
last 2 min: 100 requests, 20 accepted -> drop 59% locallyThe first two lines are the server's hints: 17 seconds, and a date 30 seconds after the response's Date, so 30 seconds whatever the client's clock says. The list shows full-jitter delays for attempts 0 to 6: random, growing, and capped at 30 seconds. The last four lines show adaptive throttling. While the server accepts at least half of the requests, the client sends everything; when it accepts 40 of 100, the client drops 20% locally, and at 20 of 100 it drops 59%, which leaves the server to spend its capacity on real work instead of on rejections.
05. Check your understanding
06. Apply it
Finish the service from the lesson 04 practice task. Make its 429 responses carry Retry-After, computed from the token bucket as (1 − tokens) / rate rounded up, and a short Problem Details body; decide whether you also send the draft RateLimit fields and document that they follow draft 11. Then write a client that honours Retry-After, backs off with full jitter when no hint is present, and paces itself with a local token bucket.
Run two copies of the client against your two instances and report how many 429s they receive with and without pacing. For the API you described in lesson 01, write down which layer runs each of its limits and why that layer knows enough to apply it.
07. Review prompt
Without looking back: name what the edge, the gateway and the service each know about a request, and give one limit that belongs at each. Explain the difference between 429 and 503, the two forms of Retry-After, and why the date form should be compared with the Date header. Say what the current status of the RateLimit header fields is and why that matters. Then list four things a well-behaved client does when it meets a limit.
References
- RFC 6585: Additional HTTP Status Codes (429 Too Many Requests)
- RFC 9110: HTTP Semantics, section 10.2.3 Retry-After
- IETF Datatracker: draft-ietf-httpapi-ratelimit-headers (Internet-Draft)
- RFC 9457: Problem Details for HTTP APIs
- Google SRE book, chapter 21: Handling Overload (client-side throttling)
- AWS Builder Center: Fairness in multi-tenant systems
- Rate Limiting pattern (Azure Architecture Center)
- NGINX documentation: ngx_http_limit_req_module
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.