DS·76
Rate Limiting and Traffic Control
Controlling how much work enters a system: why limit (fairness, protection, cost, abuse), the algorithms (fixed window, sliding log, sliding window counter, token bucket, leaky bucket, GCRA) with their burst behaviour and trade-offs, distributed rate limiting with Redis and atomic Lua scripts, local versus global limits, quotas, concurrency limits and adaptive limits (AIMD, Little's law, Netflix concurrency-limits), load shedding and prioritisation, client-side cooperation (429, Retry-After, RateLimit headers), and where limits live (gateway, mesh, application). Code in Java, Go, Rust, Python and Lua.
Start here: saying "not now" on purpose
Why limit traffic
Every service has a capacity. Without limits, one buggy client in a retry loop, a scraper, or a marketing push can use it all, and then everyone's requests slow down or fail. Rate limiting caps how many requests a client (a user, an API key, an IP, a tenant) may make in a period; load shedding rejects work when the whole service is overloaded. Both are about failing a few requests fast and cleanly (HTTP 429 Too Many Requests or 503) instead of failing everything slowly.
The token bucket
Imagine a bucket that holds up to capacity tokens and is refilled at rate tokens per second. Each request takes one token; with no token, the request is refused. Bursts up to the capacity are allowed, and the long-run rate can't exceed the refill rate:
tokens = math.min(cap, tokens + (now - ts) * rate)
if tokens >= cost then tokens = tokens - cost; ok = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
1) token bucket, capacity 10, refill 5/s; 30 requests at 20/s:
✓✓✓✓✓✓✓✓✓✓✓✓✓✗✗✗✗✓✗✗✓✗✗✗✓✗✗✗✗✓ → 17 allowed
The first 13 passed (the 10 stored tokens plus refills during the burst), then roughly one in four: exactly the 5 per second being refilled. Two numbers per client (tokens and last update) are all the state needed. Stripe, AWS API Gateway and most API platforms use token buckets.
The fixed-window trap
The simplest limiter counts requests per calendar minute. It has a boundary problem:
2) fixed window, 100 requests per minute; 200 requests between 0:59 and 1:01: 200 allowed within 2 seconds
token bucket, capacity 100, refill 100/min, same traffic: 103 allowed
100 requests at the end of one minute and 100 at the start of the next were all allowed: twice the limit in two seconds. Sliding windows and token buckets don't have that edge (the lab compares four algorithms).
| Algorithm | State per key | Bursts | Accuracy |
|---|---|---|---|
| Fixed window counter | 1 counter | Up to 2× at boundaries | Coarse |
| Sliding log | A timestamp per request | None beyond the limit | Exact, memory-hungry |
| Sliding window counter | 2 counters | Small overshoot | Good approximation |
| Token bucket | Tokens + timestamp | Up to capacity, by design | Exact for its model |
| Leaky bucket (queue) | A queue | Smoothed out | Exact; adds delay |
Telling clients what happened
A good limiter answers with 429 plus headers so well-behaved clients slow down instead of hammering: Retry-After: 2, and the IETF's RateLimit-Policy/RateLimit headers (or the common X-RateLimit-Limit, -Remaining, -Reset). Clients should back off with jitter (chapter 74).
How deep to go in rate limiting
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain why limits exist, 429, and the token bucket |
| L2 | Configure limits in a gateway or library (Envoy, Nginx, Bucket4j, Resilience4j) with headers |
| L3 | Compare algorithms; implement distributed limits atomically; concurrency and adaptive limits |
| L4 | Diagnose over-admission, unfair limits, retry storms and queueing collapse |
| L5 | Design tiers, quotas, priority and shedding policies across a platform |
| L6 | Operate global limiting at the edge with fairness, abuse detection and capacity planning |
Why control traffic
A service has finite capacity: CPU, memory, connections, downstream quotas, database throughput. Without limits:
- One client can starve everyone (a buggy script, a noisy tenant, a crawler).
- Overload collapses throughput: past saturation, queues grow, latency grows, timeouts fire, clients retry, and goodput (useful completed work) drops toward zero (congestion collapse, chapter 78).
- Costs explode: per-request spend on LLM APIs, SMS, third-party APIs.
- Abuse succeeds: credential stuffing, scraping, enumeration, denial of service.
Traffic control has several distinct tools that are often conflated:
| Tool | Limits | Example |
|---|---|---|
| Rate limit | Requests per unit time | 100 requests/minute per API key |
| Quota | Total usage over a long period | 1 M API calls per month; 10 GB storage |
| Concurrency limit | Requests in flight at once | At most 50 concurrent DB queries; 5 concurrent uploads per user |
| Load shedding | Reject work when the server is overloaded, regardless of client | Drop low-priority requests when CPU > 90% or queue latency > 100 ms |
| Backpressure | Slow producers down by not accepting more | Bounded queues, TCP flow control, reactive streams demand |
Rate-limiting algorithms
Fixed window counter
Count requests in fixed windows (e.g. per calendar minute); reject once the count exceeds the limit; reset at the window boundary.
- Simple and cheap: one counter per key per window (
INCR+EXPIREin Redis). - Boundary burst problem: a client can send the full limit at 12:00:59 and again at 12:01:00, so 2× the limit in two seconds.
Sliding window log
Store a timestamp for every request; count those within the last window (e.g. 60 s); reject if over the limit.
- Exact, no boundary bursts.
- Memory heavy: O(limit) timestamps per key. Fine for small limits (login attempts), expensive for 10,000/minute.
Sliding window counter
Approximate the sliding window from two fixed windows: estimated count = current window count + previous window count × (fraction of the previous window still inside the sliding window).
Example: limit 100/min; previous minute had 80, current minute has 30, and we're 25% into the current minute. Estimate = 30 + 80 × 0.75 = 90, so allow.
- O(1) memory per key, smooths boundary bursts, slightly inaccurate (assumes uniform distribution in the previous window). Cloudflare reported very low error rates in practice with this approach.
Token bucket
A bucket holds up to capacity B tokens and is refilled at rate r tokens per second. Each request takes one token (or more, for weighted costs); if no token is available, reject (or wait).
- Allows bursts up to B, while the long-run average is limited to r.
- O(1) state: (tokens, last refill time); refill is computed lazily on each request:
tokens = min(B, tokens + (now − last) × r). - The most common algorithm for APIs (AWS API Gateway, Stripe, Envoy local rate limit, Guava's RateLimiter variant, Go's
x/time/rate).
Leaky bucket
Two interpretations:
- As a queue (shaper): requests enter a FIFO queue of capacity B and leave at a constant rate r; overflow is rejected. Output is perfectly smooth, so it suits protecting downstreams that need steady flow (NGINX
limit_reqwithoutnodelaybehaves like this: it delays excess requests). - As a meter: equivalent to a token bucket viewed upside down: the "water level" rises with each request and leaks at rate r; reject if it would overflow.
GCRA
The Generic Cell Rate Algorithm (from ATM networks) is a leaky-bucket meter with a single stored value: the theoretical arrival time (TAT) of the next request. Allow if now ≥ TAT − burst tolerance; then set TAT = max(TAT, now) + emission interval. Precise, O(1), and good for Redis (used by the redis-cell module and the Go throttled library).
| Algorithm | Memory per key | Bursts | Accuracy | Typical use |
|---|---|---|---|---|
| Fixed window | 1 counter | Up to 2× at boundaries | Low | Simple quotas, coarse limits |
| Sliding log | O(limit) | None beyond limit | Exact | Low limits: logins, OTP sends |
| Sliding window counter | 2 counters | Smoothed | Approximate | General API limits at scale |
| Token bucket | 2 values | Up to B, configurable | Exact | API rate limits, client throttling |
| Leaky bucket (queue) | Queue | None (smooth output) | Exact | Traffic shaping, protecting steady-rate downstreams |
| GCRA | 1 value | Configurable tolerance | Exact | Redis-based limiters |
Implementing limits
In-process
For one instance, a lock-free or mutex-protected token bucket is enough. Libraries:
- Go:
golang.org/x/time/rate(token bucket) - Java: Resilience4j
RateLimiter, Bucket4j (token bucket; supports distributed backends: Redis, Hazelcast, JDBC), GuavaRateLimiter - Rust:
governor(GCRA);tower::limitfor Tower services - Python:
limits,slowapi(FastAPI/Starlette) - .NET:
System.Threading.RateLimiting(built-in: fixed window, sliding window, token bucket, concurrency) and ASP.NET Core rate-limiting middleware - Node:
rate-limiter-flexible
// Go: per-client token buckets with x/time/rate (10 req/s, burst 20)
type Limiters struct {
mu sync.Mutex
m map[string]*rate.Limiter
}
func (l *Limiters) get(key string) *rate.Limiter {
l.mu.Lock(); defer l.mu.Unlock()
lim, ok := l.m[key]
if !ok { lim = rate.NewLimiter(rate.Limit(10), 20); l.m[key] = lim } // evict idle keys in production
return lim
}
func (l *Limiters) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
res := l.get(apiKey(r)).Reserve()
if !res.OK() || res.Delay() > 0 {
res.Cancel()
w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(res.Delay().Seconds()))))
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
// Rust: governor (GCRA) keyed limiter
use governor::{Quota, RateLimiter};
use std::num::NonZeroU32;
let limiter = RateLimiter::keyed(
Quota::per_second(NonZeroU32::new(10).unwrap()).allow_burst(NonZeroU32::new(20).unwrap()));
match limiter.check_key(&api_key) {
Ok(()) => handle(req).await,
Err(not_until) => {
let wait = not_until.wait_time_from(governor::clock::DefaultClock::default().now());
too_many_requests(wait) // 429 with Retry-After
}
}
// Java: Bucket4j token bucket (local); the same API works with distributed backends
Bucket bucket = Bucket.builder()
.addLimit(limit -> limit.capacity(20).refillGreedy(10, Duration.ofSeconds(1)))
.build();
ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
response.setHeader("X-RateLimit-Remaining", Long.toString(probe.getRemainingTokens()));
chain.doFilter(request, response);
} else {
long waitSec = TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()) + 1;
response.setHeader("Retry-After", Long.toString(waitSec));
response.sendError(429);
}
# Python: a tiny token bucket (single process, thread-safe)
import threading, time
class TokenBucket:
def __init__(self, rate: float, capacity: float):
self.rate, self.capacity = rate, capacity
self.tokens, self.last = capacity, time.monotonic() # monotonic clock!
self.lock = threading.Lock()
def try_acquire(self, cost: float = 1.0) -> bool:
with self.lock:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
Distributed rate limiting
With N instances behind a load balancer, per-instance limits give an effective limit of N × L, which changes as you autoscale. Options:
- Centralised counter store (usually Redis): every instance checks and updates the shared state. Must be atomic: a read-then-write from the app races; use a Lua script (executed atomically in Redis) or atomic commands (
INCR,CL.THROTTLEfrom redis-cell). - Local limits with global coordination: each instance gets L / N (from service discovery), or instances periodically sync counts (gossip, or batch updates to Redis), trading accuracy for latency.
- Dedicated rate-limit service: Envoy's global rate limit service (gRPC
ShouldRateLimit, reference implementation in Go backed by Redis), Kong, and API gateways. - Sticky routing by client key so each client's traffic hits one instance.
-- Redis Lua: atomic token bucket. KEYS[1]=bucket key; ARGV: rate/s, capacity, now (ms), cost
local rate, cap, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (math.max(0, now - ts) / 1000) * rate)
local allowed = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000) * 2)
return {allowed, tostring(tokens)}
-- Pass 'now' from the app or use redis.call('TIME') inside: app clocks across instances may skew (chapter 75)
Distributed concerns:
- Latency: a Redis round trip per request (≈0.2–1 ms in-zone). Mitigate with pipelining, local pre-check caches, or approximate limits.
- Redis failure: decide fail-open (allow traffic, risking overload) or fail-closed (reject, causing an outage). Most user-facing APIs fail open with a local fallback limit; security-critical limits (login attempts) fail closed.
- Hot keys: one huge tenant's counter on one Redis shard; split counters or use local approximations.
- Clock skew: use the Redis server's time (
TIME) or the window keyed by the store's clock, not each app's clock.
Distributed counters in general
Rate limiting is a special case of distributed counting. Approaches beyond a single Redis key:
- Sharded counters: N sub-counters summed on read (Firestore's pattern for high write rates).
- CRDT counters (chapter 71): each node increments locally, merges periodically; eventually accurate, coordination-free, can overshoot the limit by the sync lag × rate.
- Approximate structures: count-min sketch for heavy hitters, HyperLogLog for distinct counts (Redis
PFADD).
Keys, tiers and quotas
What to limit by (the key):
- API key / client ID / OAuth client (most APIs)
- User or tenant ID (fairness in multi-tenant SaaS)
- IP address or prefix (anonymous traffic; beware NAT and IPv6 rotation)
- Endpoint and method (expensive endpoints get lower limits)
- Cost-weighted: a search costs 10 tokens, a GET costs 1; LLM APIs limit tokens per minute as well as requests
Layered limits are normal: per-IP at the edge (DDoS), per-API-key at the gateway, per-tenant concurrency in the service, per-endpoint for expensive operations, and global limits protecting shared dependencies.
Quotas (daily or monthly allowances) are billing and product concepts: stored durably (database), checked with some lag, with notifications at 80%, soft overage policies, and plans (free, pro, enterprise).
Concurrency limits and adaptive limits
Why concurrency is the better signal
Rate limits are in requests/second, but servers are constrained by work in progress. Little's law ties them together:
L = λ × W: average concurrency = arrival rate × average latency.
At 1,000 req/s and 50 ms latency, about 50 requests are in flight. If a downstream slows to 500 ms, the same rate means 500 in flight, exhausting threads, connections and memory. A concurrency limit (bulkhead, Vol. 3 ch. 52) caps in-flight work directly and adapts naturally: slower requests mean fewer get admitted.
Adaptive concurrency
The right limit changes with load, hardware and dependencies, so adaptive limiters discover it, borrowing from TCP congestion control:
- AIMD (additive increase, multiplicative decrease): increase the limit by 1 on success; halve it on timeout, error or latency spike.
- Gradient / Vegas-style: compare current latency with the minimum observed (no-queue) latency; when latency rises, queues are forming, so reduce the limit.
- Libraries: Netflix concurrency-limits (Java: Vegas, Gradient2, AIMD), Envoy adaptive concurrency filter, gRPC-Go and Linkerd-style load-aware balancing, Uber's work on adaptive admission.
// Java: Netflix concurrency-limits, adaptive server-side limiter for a gRPC/servlet entry point
Limiter<Void> limiter = SimpleLimiter.newBuilder()
.limit(Gradient2Limit.newBuilder().initialLimit(50).maxConcurrency(500).build())
.build();
Optional<Limiter.Listener> token = limiter.acquire(null);
if (token.isEmpty()) { reject(503); return; } // over the adaptive limit: shed
try {
handle(request);
token.get().onSuccess(); // latency sample feeds the algorithm
} catch (TimeoutException e) {
token.get().onDropped(); // signals overload: limit shrinks
} catch (Exception e) {
token.get().onIgnore();
}
Load shedding and prioritisation
When the server itself is overloaded, rejecting early and cheaply keeps it healthy:
- Shed before doing work: reject at the edge or first middleware, before parsing large bodies or touching the database. A rejected request should cost microseconds.
- Shed by priority: classify traffic as critical (checkout, health checks from the load balancer), normal and sheddable (prefetch, analytics, batch). Google's SRE book describes criticality propagated through RPCs. Shed sheddable first.
- Shed by queue time: if a request has waited longer than its deadline allows, drop it (its client has probably given up). CoDel-style queue management drops when the minimum queueing delay over an interval exceeds a target.
- Prefer LIFO under overload for some queues (newest requests are most likely still wanted), as done by some RPC frameworks.
- Deadline propagation: pass remaining time budgets downstream (gRPC deadlines,
context.Contextin Go) so servers don't do work for requests that have already timed out.
Client cooperation
Signalling limits
- 429 Too Many Requests for client-specific rate limits; 503 Service Unavailable for server overload (both may include Retry-After: seconds or an HTTP date).
- RateLimit headers (IETF draft
RateLimit-PolicyandRateLimitfields; widespread de factoX-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset) let clients pace themselves. - gRPC:
RESOURCE_EXHAUSTEDstatus; retry pushback via thegrpc-retry-pushback-mstrailer.
Well-behaved clients
- Honour Retry-After; exponential backoff with jitter; retry budgets (e.g. retries ≤ 10% of requests) so retries don't multiply load (chapter 78).
- Client-side throttling: Google's "adaptive throttling" has clients reject locally with probability
max(0, (requests − K × accepts) / (requests + 1))when the backend is rejecting, sparing it the cost of rejections. - Client-side token buckets that match the server's documented limits (SDKs for cloud APIs do this).
Where limits live
| Layer | Examples | Good for |
|---|---|---|
| Edge / CDN / WAF | Cloudflare, AWS WAF rate-based rules, Akamai | DDoS, per-IP abuse, bots |
| API gateway | Kong, Apigee, AWS API Gateway (usage plans), Azure API Management, Envoy Gateway, Spring Cloud Gateway (RequestRateLimiter with Redis) |
Per-key/plan limits, quotas, monetisation |
| Service mesh / proxy | Envoy local and global rate limit, Istio, NGINX limit_req / limit_conn |
Uniform policy across services, concurrency |
| Application | Middleware with Bucket4j, x/time/rate, governor, slowapi | Business-aware limits (per tenant, per operation cost) |
| Dependency client | Client-side buckets for third-party APIs; DB connection pools | Staying within others' limits |
# NGINX (http context): 10 req/s per IP with a burst of 20 served without delay, plus 20 concurrent connections
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conns:10m;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
limit_conn conns 20;
limit_conn_status 429;
}
}
Lab: limiters and overload, measured
Redis 7 on one machine with redis-py; experiments 1, 3 and 5 are simulations on generated traffic so that every limiter sees exactly the same requests.
Experiment 1: four algorithms, one burst
60 seconds of background traffic (600 requests) plus a burst of 300 requests around t = 30 s; limit 100 per 10 seconds:
fixed window : 588 of 900 allowed, worst 10 s span 199 (limit 100), state per key: 1 counter
sliding log : 563 of 900 allowed, worst 10 s span 100 (limit 100), state per key: up to 100 timestamps
sliding window counter : 578 of 900 allowed, worst 10 s span 111 (limit 100), state per key: 2 counters
token bucket (cap 100, 10/s): 678 of 900 allowed, worst 10 s span 196 (limit 100), state per key: 2 numbers
The burst straddled a window boundary, so the fixed window let through almost double the limit in one 10-second span. The sliding log was exact but stores a timestamp per request (at 10,000 requests per minute per key that's real memory). The sliding window counter, which weights the previous window's count by how much of it overlaps, overshot by 11% with only two counters: the usual production compromise (Cloudflare described measuring 0.003% wrong decisions with it at scale). The token bucket allowed 196 in 10 s by design: a full bucket (100) plus 10 seconds of refill (100). If a burst of that size is unacceptable, lower the capacity.
Experiment 2: the limiter must be atomic
Limit 50; 20 threads each make 20 requests at once:
GET then SET from the client: 400 allowed (382–400 across runs)
Lua token bucket (atomic): 50 allowed
Reading the counter and writing it back from the client let concurrent requests see the same value and overwrite each other's increments, so almost every request passed. Doing the read-modify-write inside Redis (a Lua script, or INCR and checking its result) makes each check atomic. The same applies to any shared limiter: use the store's atomic operations.
Experiment 3: local limits versus a shared limit
A customer is allowed 400 requests per second, served by four instances that each enforce a quarter (100/s) locally. A sticky load balancer sends 55%, 25%, 15% and 5% of the customer's traffic to the four:
1,000 requests in a second: per-instance limits of 100 allowed 353, a shared Redis limit allows 400
Splitting a limit across instances works only if traffic splits evenly; here the customer got 12% less than they paid for, while instance 3 sat under-used. A shared store gives the exact limit at the cost of a network call per request (experiment 4). Common hybrids: local token buckets that periodically sync with a central counter, or Envoy's global rate-limit service with local limits as a first line.
Experiment 4: what a shared check costs
one Lua token-bucket check against local Redis: 0.112 ms
About a tenth of a millisecond on the same machine; a few hundred microseconds across a data-centre network. Fine for most APIs, and the reason limiters sit in front of expensive work, not cheap work. Decide what happens if Redis is unreachable: fail open (allow; protects availability) or fail closed (deny; protects the backend). Most public APIs fail open with a local fallback limit.
Experiment 5: shedding load keeps latency bounded
A simulated service with 10 workers at about 100 ms per request (capacity 100 requests per second) is offered 150 requests per second for 20 seconds:
unbounded queue: rejected 0, median latency 5.08 s, p99 9.48 s
queue capped at 20, reject the rest (429/503): rejected 941, median latency 0.25 s, p99 0.63 s
Accepting everything meant the queue grew by about 50 requests every second; by the end, requests waited nearly 10 seconds, long after most clients had timed out and retried (making it worse). Capping the queue rejected a third of the requests immediately, and everyone else got sub-second answers. Overload can't be absorbed, only chosen: either everyone gets a slow failure, or some get a fast refusal. Concurrency limits (cap in-flight work, as Netflix's concurrency-limits and Envoy's adaptive concurrency do, adjusting the cap from measured latency) and priority shedding (drop analytics before checkout) refine this.
Try it yourself
- Implement the sliding window counter in Redis with two keys and rerun experiment 1 against it.
- Add
Retry-AfterandRateLimitheaders to the chapter 74 payments API and make the client honour them. - In experiment 5, add client retries on rejection without backoff. What happens to the offered load?
- Implement an AIMD concurrency limit: raise the limit by 1 when latency is under target, halve it when over.
Revision sheet: rate limiting and traffic control
Key ideas
- Purposes: protect capacity, fairness between clients, cost control, abuse prevention, contractual quotas.
- Algorithms: fixed window, sliding log, sliding window counter, token bucket (burst + rate), leaky bucket (smoothing, GCRA).
- Implementation: atomic operations in a shared store (Lua,
INCR), local buckets, hybrid sync, gateways (Envoy, Nginxlimit_req, Kong), libraries (Bucket4j, Resilience4j, GuavaRateLimiter). - Keys and tiers: per API key, user, IP, tenant, endpoint and cost (weighted requests); quotas per day/month.
- Concurrency and adaptive limits: Little's law, in-flight caps, AIMD/gradient algorithms, bulkheads.
- Load shedding and prioritisation: bounded queues, LIFO under overload, deadline propagation, criticality tiers, brownouts.
- Client cooperation: 429/503,
Retry-After, RateLimit headers, exponential backoff with jitter, retry budgets. - Where limits live: edge/CDN, API gateway, service mesh, in-process, database.
Numbers to remember
- Little's law: concurrency = arrival rate × latency.
- Lab: fixed window allowed 199 per 10 s against a limit of 100; sliding counter 111; client-side GET/SET allowed ~400 against 50; uneven local limits gave 353 of 400; a Redis check cost 0.11 ms; an unbounded queue at 1.5× capacity reached p99 9.5 s, a capped one 0.63 s.
Pitfalls
- Fixed windows for strict limits.
- Non-atomic distributed counters.
- Unbounded queues ("we'll catch up").
- Limits without headers, so clients can't adapt.
- Retrying 429s immediately.
- One global limit with no priorities, so health checks or checkout get shed with everything else.
Glossary
- Token bucket: capacity + refill rate limiter.
- GCRA: generic cell rate algorithm, a leaky bucket with one timestamp.
- Load shedding: rejecting work to stay within capacity.
- Bulkhead: isolated resource pools so one workload can't exhaust all.
- Fail open / fail closed: allow or deny when the limiter itself is unavailable.
- Retry budget: cap on retries as a fraction of requests.