Rate limiting and load shedding¶
What you'll be able to do¶
- Choose a rate limiter whose burst behavior matches an API's capacity and fairness rules.
- Explain where a limit belongs, how to share its state, and what to return when a request is rejected.
- Protect an overloaded service by bounding work and shedding lower-priority requests early.
Why turn work away?¶
An API worker finishes 100 requests per second while callers send 150. The extra 50 each second queue up. After ten seconds, roughly 500 wait, so the last one starts about five seconds later. A bigger queue hides overload, then worsens latency. See latency and queueing.
Four related controls solve different problems:
| Control | Decision | Example |
|---|---|---|
| Rate limit | Is this client allowed to spend capacity now? | 10 requests per second per API key |
| Quota | Has this client spent its allowance for a period? | 1 million tokens this month |
| Backpressure | Can the producer slow down? | Pause a queue consumer while workers catch up |
| Load shedding | Is the service too busy to accept more work? | Reject batch jobs while interactive requests still fit |
Limits contain abuse and accidental loops, protect other tenants, enforce quotas, and cap costs. Yet 1,000 clients each allowed ten requests per second can together send 10,000 per second. Load shedding provides a separate defense.
Count requests in a window¶
A fixed window keeps one counter per key for each interval. With a limit of five per ten seconds, floor(now / 10) identifies the window. Reset when that number changes. It is simple and uses constant memory per key, but it can admit up to twice the window allowance across a boundary, with the requests arbitrarily close together:
A sliding window log stores each accepted timestamp and cost. Discard expired entries and sum the rest. At 10.0, the five requests from 9.9 remain, so another is refused. It is precise, but memory grows with accepted requests per key.
A sliding window counter saves current and previous counts. Estimate usage as current + previous × fraction_still_covered. At second 12 of a ten-second window, five previous requests contribute 5 × 0.8 = 4. Memory stays constant per key, but the estimate cannot tell whether those requests arrived at second 0 or 9.
now, previous, current, limit, request_cost = 12, 5, 0, 5, 1
window = int(now // 10)
estimated = current + previous * (1 - (now % 10) / 10)
allowed = estimated + request_cost <= limit
print(allowed) # True: 4 estimated + 1 new = 5
If those five arrived at second 9.9, all of them are still inside the true trailing ten seconds at second 12. The counter estimates four and admits one more, so six requests now sit in a sliding window whose limit is five. The approximation does not enforce an exact sliding limit.
request_cost lets an expensive operation count as more than one request. Use a log when exact sliding accounting matters.
Budget bursts with buckets¶
A token bucket starts with capacity tokens and refills at rate tokens per second, capped at capacity. A request spends its cost if enough remain. Capacity five and rate one admit a burst of five, then one more after a second. It stores balance and update time per key, precisely enforcing refill while permitting bursts. This is a useful default for interactive APIs.
capacity, rate, tokens, now, last_time, cost = 5, 1, 2, 3, 2, 3
tokens = min(capacity, tokens + rate * (now - last_time))
if tokens >= cost:
tokens -= cost
allowed = True
else:
retry_after = (cost - tokens) / rate
allowed = False
print(allowed) # True
A leaky bucket drains admitted work at a steady rate. At one unit per second, an empty capacity-three bucket can admit three one-unit requests immediately, but schedules them to start one second apart. Store backlog and update time per key: constant memory for the schedule. It smooths output; admission does not mean immediate execution, so bound the wait or worker queue.
| Algorithm | Memory per key | Window accuracy | Burst behavior |
|---|---|---|---|
| Fixed window | One counter | Exact per fixed interval | Up to 2× at boundary |
| Sliding log | One entry per accepted request | Exact sliding interval | No boundary double burst |
| Sliding counter | Two counters | Approximate | Can exceed the exact sliding limit |
| Token bucket | Balance and time | Exact refill rule | Up to capacity |
| Leaky bucket | Backlog and time | Exact drain schedule | Input buffered; output smoothed |
Put limits where the work happens¶
A client-side limiter smooths your calls. An edge, CDN, or gateway rejects before application workers. Services and scarce resources such as GPUs may need separate limits. Load balancing distributes traffic but does not create capacity.
Choose a key matching the fairness policy: IP, user, API key, tenant, or endpoint. IP is a rough abuse signal because NAT and proxies combine users. Charge expensive endpoints more: if search costs roughly five status reads, charge five units. Identify the caller before spending its budget; see API design.
With three application instances, three independent local limits of 100 requests per second can admit about 300 in total. A shared store can keep counters per key, but check then update must be atomic: two workers that both read 99 can each decide to admit request 100. For a calendar fixed window, atomically read the key's count, reject without incrementing if the new cost exceeds the limit, and otherwise increment and expire the key at the next calendar boundary. A server-side script or equivalent atomic transaction can make that one decision, for fixed windows and for more complex buckets. Redis documentation covers the shared-store primitives.
Shared state adds a network hop and can fail. Local approximate limiters with periodic synchronization reduce that dependency but allow overshoot. Choose fail open for availability, with a local backstop, or fail closed for strict spending control. Clock skew can split requests across windows: use monotonic elapsed time for local refill and a common time source for shared windows.
Reject usefully; shed before queues grow¶
Return HTTP 429 Too Many Requests when the caller exceeds its rate limit. For service-wide overload, where a caller within its limit is turned away, return 503 Service Unavailable. With either status, include Retry-After when the server can give a useful wait. Other rate-limit headers can expose remaining budget and reset time, but conventions vary; document yours. Clients should honor Retry-After, use exponential backoff with jitter for other retryable failures, and stop at a deadline. See timeouts and retries.
When overloaded, bound queue length and wait, reserving capacity for interactive traffic. Reject expired work before it consumes compute. An adaptive concurrency limit lowers in-flight jobs as latency rises and raises them cautiously after recovery. This protects total capacity even when each client stays within its own limit.
For AI engineers¶
For AI engineers
Your training or evaluation script is often an API client. A provider may separately limit requests and input/output tokens per minute. Before a batch call, estimate token spend, reserve it in a client-side budget, and refund unused tokens after the response. Credit the refund to the window that was charged: if that minute has ended, it must not enlarge the new minute's allowance. Use bounded concurrency so many tasks do not all hit a limit together. On 429, honor Retry-After; otherwise retry with jitter and a deadline. A monthly cost quota is a different counter from a per-minute rate limit.
If you serve a GPU-backed endpoint, charge tenants by estimated token or compute cost, not just request count. Keep interactive inference ahead of batch work with explicit queue priorities. If predicted queue wait exceeds the response deadline, shed that work early rather than letting a GPU finish an answer after the caller has left. A per-tenant bucket protects fairness, while the global queue and concurrency limits protect the GPU fleet.
Common mistakes¶
- Limiting only by IP: NAT and shared proxies make unrelated users share a budget. Prefer authenticated identity or tenant keys when available.
- Assuming fixed windows prevent bursts: five requests just before and after a boundary become ten in a fraction of a second.
- Using only per-instance counters: total allowance grows with instance count unless requests are pinned or state is shared.
- Returning a bare 429 or retrying immediately: give a useful retry time, and make clients back off with jitter.
- Failing open without a backstop: a limiter outage can flood an already weak service. Keep a local safety bound or shed at the resource.
- Charging every request equally: one long generation can consume far more capacity than a short lookup; define cost units that reflect work.
Check yourself¶
Five requests arrive at 9.9 seconds and five at 10.0 seconds under a fixed limit of five per ten seconds. What happens, and would a sliding log agree?
The fixed-window limiter accepts all ten because they fall in different windows. A sliding log still sees the first five at 10.0 and rejects the second group until old entries expire.
A token bucket has capacity five, rate one token per second, and is empty at time 4. When can a request costing three pass?
At time 7: three seconds refill three tokens. The request can then spend all three. No more than five can accumulate even after a long idle period.
Three service instances each allow 100 requests per second for one tenant. Why might the tenant reach 300, and what changes that?
Each instance counts independently. Shared atomic state gives the tenant one global budget; a local approximate design needs an explicit error allowance and synchronization.
Every tenant is under its individual rate limit, but a GPU queue's wait rises past the response deadline. What should the service do?
Bound the queue and shed work that cannot finish usefully, usually starting with lower-priority batch jobs, and answer with 503 rather than 429 because no caller exceeded its limit. Per-tenant policy does not guarantee total capacity.
Lab¶
Build small limiters and overload controls in code/rate-limiting/ using an injected clock. Compare fixed windows, a sliding log, and an approximate sliding counter at a boundary. Implement token and leaky buckets with per-key state, weighted costs, and retry times. Then shed expired low-priority queue items and reserve/refund a minute's token budget. Read the README for the exact APIs and boundary rules. Run: cd code/rate-limiting && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Interactive: Designed to Scale – rate limiting
- Your handbook: Software Engineering Handbook, ch. 12 "Bảo mật API"
- Reference: Redis documentation
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.
