Course contents

09. Reliability and Resilience Lesson 6 of 10

Rate Limiting

Protect a shared API from noisy clients with token buckets: global versus per-client limits, burst size, 429 responses and why instant retries backfire.

14 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Without limits, the noisiest client decides the experience of every other client.
  • A rate limiter refuses excess requests early and cheaply with 429, before they reach the servers.
  • A single shared limit is not fair; limit per API key, user or IP, and keep a global limit as a backstop.
  • Token bucket: the refill rate sets the sustained average, the bucket size sets the allowed burst.
  • Send Retry-After; clients should wait and back off, because immediate retries only add load.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A rate limiter caps how many requests a client may make in a period of time. Requests within the limit pass; requests above it are refused immediately, usually with HTTP 429 Too Many Requests and a Retry-After header saying when to try again. Limits are typically enforced at the edge (API gateway, reverse proxy) and often again inside services.

Why it exists

Servers have finite capacity and it is shared by every client. Without limits, a single buggy script, a scraper or a retry loop can consume all of it, and the servers' queues fill with that client's requests, so everyone else starts seeing timeouts and errors too. A rate limiter makes overload predictable: it refuses the excess at the door, cheaply, before it reaches the expensive parts. It also enforces fairness and commercial quotas (free tier versus paid).

How it works

Token bucket. The most common algorithm. Each client has a bucket that holds up to burst tokens and refills at rate tokens per second. Every request takes one token; if the bucket is empty the request is refused. A client that has been quiet can send a short burst (up to the bucket size), but over time it cannot exceed the refill rate. It needs only two numbers per client: the token count and the time of the last refill.

Other algorithms.

  • Fixed window: count requests per calendar minute. Simple, but a client can send twice the limit around a window boundary.
  • Sliding window log or counter: smooth out the boundary effect at slightly more cost.
  • Leaky bucket: requests drain at a constant rate, which smooths output but adds queueing delay instead of refusing.

What to key on. Per API key or user is the usual choice for authenticated APIs; per IP for anonymous traffic (careful with NAT and proxies); per endpoint for expensive operations. Combine them: a per-client limit for fairness, plus a global limit sized to what the servers can actually handle, as a last line of defence.

Distributed limits. With several gateway instances, each in-memory bucket only sees its share of traffic, so the effective limit multiplies. Either keep counters in a shared store (Redis with atomic increments or a Lua script), or give each instance a fraction of the limit and accept some imprecision.

Responding. Return 429 (not 500 or 503, which suggest the server is broken), include Retry-After, and ideally headers showing the limit and remaining quota. Document the limits so clients can pace themselves.

When to use it

  • Any public or partner-facing API.
  • Expensive endpoints (search, exports, login attempts, AI calls) even for trusted clients.
  • In front of shared internal services that several teams depend on.
  • To enforce plan quotas and protect against abuse (credential stuffing, scraping).

When not to

  • As a substitute for capacity: if legitimate traffic exceeds what you can serve, a limit just turns customers away.
  • With a single shared limit when fairness matters; it penalises well-behaved clients as much as the noisy one.
  • Where requests cannot be retried or deferred and dropping them is worse than slowing down; consider queueing or prioritised load shedding.

Trade-offs

Choice You gain You pay
Per-client limits Fairness; one client cannot starve others State per client; choosing the right key
Global limit only Simple, protects servers Everyone suffers when one client floods
Large burst Tolerates bursty but legitimate clients Short spikes can still hit the servers
Small burst Smooth, predictable load Refuses normal batches
Shared counters (Redis) Accurate limits across instances A network call per request; a dependency to keep available
Local counters Fast, no dependency Limit scales with the number of instances

Alternatives

  • Load shedding: refuse work based on current server load (queue length, latency) rather than a fixed per-client rate; protects capacity but not fairness.
  • Queueing / leaky bucket: delay rather than refuse excess requests.
  • Concurrency limits: cap requests in flight per client instead of requests per second.
  • Priority classes: keep capacity for critical traffic and shed the rest first.
  • Circuit breakers on the client side: callers stop sending when the server is failing.

Failure modes

  • Retry storms: clients that treat 429 like any error and retry immediately multiply their traffic without getting more through.
  • Limiter as a single point of failure: if the shared counter store is down, decide in advance whether to fail open (allow) or fail closed (refuse).
  • Wrong key: limiting by IP blocks a whole office behind one NAT; limiting by a header clients can change does nothing.
  • Limits above capacity: per-client limits that are each reasonable but sum to more than the servers can handle; the global limit catches this.
  • Silent throttling: refusing without telling clients why or when to retry leads to blind retries.

In production

Enforce limits at the gateway, keyed by API key or user, with a global limit sized from load tests. Use token buckets with explicit rate and burst values per plan. Share counters across instances. Return 429 with Retry-After and quota headers. Ship SDKs that honour Retry-After and back off with jitter. Monitor refusals per client and alert when important clients are throttled. Review limits as capacity changes.

Common misconceptions

  • "Rate limiting is only for abuse." It is also capacity protection and fairness for ordinary clients.
  • "One global limit is enough." It protects the servers but not the well-behaved clients.
  • "Retrying a 429 quickly gets the request through." The bucket refills at its own rate; quick retries only waste requests.
  • "With a rate limit, capacity planning is optional." The limit refuses traffic; it does not serve it.

Interview angle

Rate limiting comes up both as a component ("put a rate limiter in the gateway") and as a full design problem ("design a distributed rate limiter"). Be ready to explain token bucket versus sliding window, what you key on, where the counters live and how they stay consistent across instances, what happens when the counter store fails, and how clients should react to 429. Mentioning per-client plus global limits, and Retry-After with client backoff, covers the usual follow-ups.

Model assumptions

The simulation is a simplified model, not a benchmark. Two API servers each have 6 workers, an 80 ms mean service time (lognormal, cv 0.35) and room for 12 waiting requests, about 150 requests per second together; the gateway balances by least connections. Rate limits are token buckets that refill continuously; a refused request fails at once with 429. The engine keeps one bucket per node, so the scraper's per-key bucket is drawn as its own box in front of the gateway; a real gateway keeps one bucket per key internally. The scraper's retries use 4 attempts with 10–40 ms delays and no jitter. Arrivals are Poisson. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A public API with headroom

    App users send about 60 requests per second through an API gateway to two API servers. Together the servers can handle roughly 150 per second.

    They are well under half busy. Latency is the network plus about 80 ms of work, and nothing fails.

    Scene: App users send 60 requests per second through the API gateway to API 1 and API 2, which are well under half busy. Nothing fails.

    Key idea: Capacity is shared: every client draws from the same pool of workers.

  2. 2. One client floods the API

    A partner’s scraper starts hammering the API with 200 requests per second. Total demand is now 260 against a capacity of about 150.

    The servers do not know who is important. Their queues fill and they reject whatever arrives when they are full, so regular users fail too. One misbehaving client has degraded the service for everyone.

    Scene: The scraper adds 200 requests per second. Both API servers are saturated and reject requests from the scraper and from regular users alike.

    Key idea: Without limits, the noisiest client decides the experience of all the others.

  3. 3. A global rate limit

    The gateway gets a token bucket: it holds up to 30 tokens and refills at 120 tokens per second. Each request takes one token; with no token left the gateway answers 429 Too Many Requests at once, without touching the servers.

    The servers are protected: they stay below capacity and latency for admitted requests is normal again. But the bucket is shared, so regular users lose about half their requests too, just like the scraper.

    Scene: The gateway refuses requests above 120 per second with 429. The API servers are no longer overloaded, but regular users are refused about as often as the scraper.

    Key idea: A rate limit protects capacity by refusing excess work early and cheaply. A single shared limit is not fair.

  4. 4. A bucket per API key

    Real gateways keep one bucket per client (per API key, user or IP). We draw the scraper’s bucket as its own box: 20 requests per second, burst 40. The global limit stays as a safety net.

    The scraper now gets its fair share and a steady stream of 429s for the rest. Regular users are back to zero errors: they never touch the scraper’s bucket.

    Scene: The scraper’s requests pass through its own 20 per second bucket; most are refused with 429. Regular users are no longer refused, and the API servers are lightly loaded.

    Key idea: Limit per client so one consumer cannot spend everyone’s capacity. Keep a global limit as the last line of defence.

  5. 5. What the bucket size is for

    The scraper calms down to 5 requests per second, so its bucket fills up to its 40-token burst. One second in, it sends a batch job at 60 requests per second.

    For about a second everything gets through: the job spends the saved-up tokens. Once the bucket is empty, only the refill rate of 20 per second passes and the rest gets 429. The burst size decides how much short-term spikiness you allow; the rate decides the long-term average.

    Scene: At 5 requests per second the scraper’s bucket is full. When it jumps to 60 per second, about a second of requests passes, then the bucket is empty and most requests are refused.

    Key idea: Token bucket: rate = sustained average, burst = how far a client may briefly exceed it.

  6. 6. Clients that retry 429s at once

    The scraper’s client library treats 429 like any error and retries within milliseconds, up to 4 attempts. It sends far more requests than before, yet still gets only about 20 per second through: retrying does not refill the bucket.

    A good client reads the Retry-After header and waits, with exponential backoff and jitter. A good API sends that header and documents its limits so clients can pace themselves.

    Scene: The scraper retries every 429 almost immediately. The number of requests it sends multiplies, but the number that succeed stays at about 20 per second.

    Key idea: A 429 needs a response strategy: back off and honour Retry-After. Immediate retries only add load.

  7. 7. Designing a rate limit

    Decide what to limit (per API key, user, IP, endpoint), where (gateway, service, both), and how (token bucket, sliding window). With several gateway instances, buckets must be shared, for example counters in Redis, or each instance gets a slice of the limit.

    Respond with 429 plus Retry-After, expose remaining quota in headers, and alert when important clients hit limits. A rate limit protects capacity; it does not replace having enough of it.

    Scene: Regular users and the scraper reach the API through the gateway; the scraper is limited by its own bucket and the gateway keeps a global limit.

    Key idea: Rate limits are a fairness and protection policy, and part of your API contract.