Nguyen Le Phong

Rate Limiting and Throttling Without Punishing Real Users

What to count, which algorithm to pick, how to word a 429, and why client retries matter as much as server limits, with real numbers from Stripe, GitHub and Cloudflare.

Your marketing team launches a campaign at noon. By half past, the login API is slow for everyone. Nothing is down, exactly. A new mobile build retries every failed login right away, a few thousand phones are doing that at once, and the database connection pool is full of requests from the same handful of clients. The people who just want to log in once wait behind them.

Rate limiting and throttling are how a system shares limited capacity fairly when demand spikes. CPU, database connections, queue depth, vendor quotas and your support team's attention are all finite. Without limits, the most aggressive traffic tends to win and everyone else gets timeouts. This post covers how to pick what you count, which algorithm to use, what to tell the caller, and the client-side habits that keep a busy minute from turning into an outage.

Engineers look at an overload dashboard and request-flow sketches while talking through how to share capacity during a traffic spike.
Good limits start with seeing where the capacity goes before a spike decides for you.

Rate limiting and throttling are two different jobs

A rate limit answers "how much may this caller do in a given window?" A hundred requests per minute per API key, ten login attempts per account per hour, one heavy export at a time. Go over and you get turned away, usually with a 429, even if the servers are idle.

Throttling and load shedding answer a different question: "the system is under pressure right now, what do we drop or slow down so the rest survives?" That's about protecting the server, whoever is calling. You delay, queue, reject or do less work on purpose, so the whole thing stays up.

Stripe's write-up of its own setup shows both side by side. It runs four limiters: a request rate limiter per user, a concurrent request limiter, a fleet-wide load shedder that keeps part of the infrastructure for critical requests, and a last-resort shedder that drops low-priority traffic when workers are overloaded. Stripe calls the per-user request rate limiter "by far the most important one" and suggests starting there (Tarjan, Scaling your API with rate limiters).

Decide what you're counting

The 429 status code in RFC 6585 leaves this part to you on purpose: the spec "does not define how the origin server identifies the user, nor how it counts requests." That choice shapes the experience more than the algorithm does.

  • Per IP is easy and often wrong. A whole office or campus can share one NAT address, and mobile carriers put many users behind few IPs. Keep it for anonymous traffic.
  • Per user, account or API key is fairer for authenticated traffic. GitHub's REST API allows 60 requests an hour per IP without a token and 5,000 an hour for an authenticated user (GitHub Docs).
  • Per endpoint or by cost, because requests aren't equal. GitHub's secondary limits charge most GET requests 1 point and most POST, PATCH, PUT and DELETE requests 5, and cap concurrent requests at 100.
  • Per sensitive action. OWASP's API Security Top 10 lists "unrestricted resource consumption" as API4:2023 and describes an attacker hammering "forgot password" so every request sends a paid SMS. It also warns that batching many operations into one request can slip past a per-request limit (OWASP API4:2023).

One global number rarely fits every path. A public search endpoint, an admin export, a webhook receiver that gets traffic in waves and a password reset form each need their own policy.

Pick an algorithm by what you want to allow

The algorithm decides whether a real customer can finish a normal task during a busy minute. Here's how the common ones behave:

AlgorithmHow it countsGood atWatch out for
Fixed window A counter per caller that resets every minute (or hour). Dead simple, one number per key. A caller can spend the full limit at the end of one window and again at the start of the next.
Sliding window log Stores a timestamp per request and counts the last N seconds. Exact. Memory grows with traffic.
Sliding window counter Current window count plus the previous window's count, weighted by how much of it still overlaps. Smooth and cheap: two counters per key. An approximation, though a close one in practice.
Token bucket Tokens refill at a steady rate up to a cap. Each request takes one. Allows short bursts while holding a long-run average. Two knobs (rate and burst) to tune per endpoint.
Leaky bucket Requests join a queue that drains at a fixed rate. Smooths output into a steady flow for a fragile backend. Queued requests add latency, so set a queue limit.

Cloudflare uses the sliding window counter. On 400 million requests from 270,000 sources, it found that only 0.003% of requests were wrongly allowed or rate limited (Cloudflare, Counting things, a lot of different things). Stripe uses a token bucket per user, kept in Redis, and AWS API Gateway throttles with a token bucket too, where you set a rate and a burst (AWS docs). The token bucket fits in a few lines:

// token-bucket.ts: one bucket per caller, kept in memory
class TokenBucket {
  private tokens: number
  private lastRefill = Date.now()

  constructor(
    private readonly capacity: number, // biggest burst allowed
    private readonly refillPerSecond: number, // long-run average rate
  ) {
    this.tokens = capacity
  }

  tryTake(): boolean {
    const now = Date.now()
    const elapsedSeconds = (now - this.lastRefill) / 1000
    this.tokens = Math.min(this.capacity, this.tokens + elapsedSeconds * this.refillPerSecond)
    this.lastRefill = now
    if (this.tokens < 1) return false
    this.tokens -= 1
    return true
  }
}

// 10 requests at once are fine, then 1 per second on average
const loginBucket = new TokenBucket(10, 1)

This version lives in one process's memory. Run ten instances behind a load balancer and each caller effectively gets ten buckets, so a real deployment keeps the counters in a shared store like Redis and updates them atomically.

A small team compares request-flow diagrams and bucket models, working out how bursts and averages should behave.
Rate and burst are two separate promises. Decide both on purpose.

Tell the caller what happened and when to come back

A generic 500 leaves the caller guessing, and guessing clients usually retry harder. RFC 6585 defines 429 Too Many Requests and says the response may include a Retry-After header saying how long to wait. A useful response looks something like this:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30

{"error": "rate_limited", "message": "Too many login attempts. Try again in 30 seconds."}

Many APIs also send the remaining budget on every response, so clients can slow down before they hit the wall. GitHub sends x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-used and x-ratelimit-reset. There's an IETF effort to standardize this as RateLimit and RateLimit-Policy headers, but as of draft 11 (May 2026) it's still an Internet-Draft, not an RFC (IETF datatracker). If you adopt it now, document which version you follow.

When there's a UI in front, the message should sound like a person: we're busy, your action is safe, try again in a moment. Clear wording cuts support tickets and panicked double-clicks.

Two teammates review API response states and support notes while designing what a throttled user should see.
A good limit says what happened, what's still safe, and when to try again.

Clients can make overload better or much worse

The scene at the top of this post was a retry problem as much as a capacity problem. Marc Brooker's AWS Builders' Library article shows how fast retries stack up: in a call chain five services deep, where each layer retries three times, the database at the bottom can see 243 times the load (Brooker, Timeouts, retries and backoff with jitter). His fixes: retry at one layer, back off exponentially, and add jitter so clients don't all retry in the same second.

Google's SRE book adds two budgets. A single request stops retrying after three failed attempts, and a client keeps retrying only while retries stay under 10% of its requests. It also describes adaptive throttling, where each client tracks how many of its requests the backend accepted and starts rejecting some locally once attempts reach about twice the accepted count (Google SRE book, Handling Overload). The client sheds load before it ever reaches the network. For the full set of retry, timeout and circuit-breaker patterns, see the resilience post.

Roll limits out carefully and decide who goes first

A new limit that blocks a big customer's nightly batch is an incident you caused yourself. Stripe's advice: dark launch each limiter and watch what it would have blocked, tune it so normal traffic passes, fail open if the limiter or Redis breaks, and keep a kill switch and metrics on every trigger.

Limits also drag product decisions into the open. Who gets priority when capacity runs short? Checkout probably matters more than a background export, and paid plans may come with stronger guarantees than free ones. The SRE book's answer is criticality levels on every request, from CRITICAL_PLUS down to SHEDDABLE, so the system knows what to drop first. Architecture can't make those calls for the team. It can make them visible early enough that the team decides before an incident does.

Healthy systems say no sometimes, on purpose and in a way callers can act on, so they can keep saying yes to everyone else. A good first step this week: find the one endpoint that costs real money per call (SMS, email, an AI model, a payment check), confirm it has a per-account limit, and read what your 429 actually tells the caller.

What did you think?

Frequently asked questions

What is the difference between rate limiting and throttling?
Rate limiting caps how much one caller may do in a time window, such as 100 requests per minute per API key, and rejects the excess with a 429 even when servers are idle. Throttling and load shedding protect the system as a whole when it is under pressure, by delaying, queueing or dropping lower-priority work regardless of who sent it.
Which rate limiting algorithm should I use?
A token bucket is a good default when you want to allow short bursts while holding an average rate. Stripe and AWS API Gateway both use it. A sliding window counter is cheap and smooth, and Cloudflare measured only 0.003% of requests wrongly allowed or limited with it. A fixed window is simplest but lets a caller spend double the limit across a window boundary.
What should an API return when a client is rate limited?
Return 429 Too Many Requests, which RFC 6585 defines, with a Retry-After header saying how long to wait and a message a person can act on. Many APIs also send remaining quota on every response, like GitHub's x-ratelimit headers. The IETF RateLimit header fields are still an Internet-Draft as of draft 11 in May 2026.
Should I rate limit by IP address or by user?
Use the user, account or API key for authenticated traffic. IP-based limits are easy to set up but can block a whole office or mobile network sharing one address, so keep them for anonymous traffic. Add separate limits for costly or sensitive actions such as password reset or SMS, which OWASP lists under API4:2023 Unrestricted Resource Consumption.
How should clients retry after a 429 or an overload error?
Wait for Retry-After when it is present, back off exponentially with jitter, and retry at one layer of the stack only. AWS shows that five layers each retrying three times can multiply load on the bottom service by 243. Google's SRE book also caps retries at three per request and under 10% of a client's traffic.