SysDesignAtlas

Rate Limiting

The five algorithms with their exact tradeoffs, where to enforce limits, and how to make counters correct across a distributed fleet.

HLDMedium11 min readrate-limitthrottlingprotection
Confidence

#Why it exists

Rate limiting is capping how many requests one caller may make in a given period — 100 a minute per user, say — and rejecting the rest. It protects a system from being asked for more than it has. Four distinct motivations, and naming which one applies changes the design:

  1. Abuse prevention — automated password guessing, scraping, spam.
  2. Fairness — one customer can't starve the others. (The noisy neighbour problem: shared capacity, one tenant taking it all.)
  3. Cost control — every request to an expensive downstream (an LLM, a payment provider, an SMS gateway) costs money.
  4. Stability — shedding excess load is what keeps you from cascading failure.

The response is normally 429 Too Many Requests — the HTTP status that means "not now" rather than "never" — with a Retry-After header saying when to come back, plus headers telling the caller their limit, how much they have left, and when the count resets, so a well-written client can slow itself down before being blocked.

#The five algorithms

#1. Fixed window counter

Count requests per fixed interval; reset at the boundary.

   key = user:123:minute:1042      counter++, TTL 60s
   allow if counter <= limit

Pro: trivially simple, one counter per key, minimal memory. Con: the boundary burst. With a limit of 100/min, a client can send 100 at 10:00:59 and 100 more at 10:01:00 — 200 requests in one second, twice the intended rate.

Fine for coarse quotas ("10,000 API calls per day"); poor for protecting against bursts.

#2. Sliding window log

Store a timestamp per request; count those inside the trailing window.

   ZADD  user:123  now  request_id          (sorted set)
   ZREMRANGEBYSCORE user:123 -inf (now-60s)  drop expired
   ZCARD user:123 → count, allow if < limit

Pro: exactly correct. No boundary artifacts, no approximation. Con: memory is O(requests) per key. A limit of 10,000/hour means storing 10,000 timestamps per user. At a million users that's untenable.

Use when limits are small and precision matters (e.g. 5 login attempts per 15 min).

#3. Sliding window counter

The practical compromise. Keep counters for the current and previous fixed windows, and interpolate:

   estimate = current_count
            + previous_count × (overlap fraction of previous window)

   At 10:01:15 with 1-min windows:
   75% of the window still overlaps the 10:00 window
   → estimate = count(10:01) + count(10:00) × 0.75

Pro: O(1) memory (two counters), smooths the boundary burst, accurate in practice — measured error is typically well under 1%. Con: an approximation; assumes requests were spread evenly within the previous window.

This is the default answer for API rate limiting and what most production limiters use.

#4. Token bucket

Picture a bucket that holds up to B tokens and is topped up at R tokens per second. Every request takes one token; if the bucket is empty, the request is rejected. Because tokens accumulate while you're idle, a caller who has been quiet can spend a burst all at once — which is usually the behaviour you want.

   ┌─────────────┐  refill R tokens/sec, cap B
   │  ● ● ● ● ●  │
   │  ● ● ●      │  request → take 1 token
   └─────────────┘  no token → 429

Pro: allows bursts up to B while enforcing an average rate of R. This matches real traffic, which is bursty by nature — a user opening a page fires 12 requests at once and that's legitimate. Only two values need storing (token count, last refill time), and nothing has to run in the background to refill buckets. Instead the refill is computed lazily, when a request arrives: if the bucket had 3 tokens 2 seconds ago and R = 5/s, it now has min(B, 3 + 2 × 5) = 13 tokens (assuming B ≥ 13).

Con: two parameters to tune, and a burst can briefly overload a downstream that can't absorb it.

Best general-purpose choice when you want to be permissive to real users and strict on sustained abuse. Cost-control limits (API quotas) usually want this.

#5. Leaky bucket

Requests enter a queue that drains at a fixed rate. Overflow is rejected.

Pro: perfectly smooth output — the downstream sees a constant rate regardless of input shape. Ideal when the thing you're protecting genuinely cannot handle bursts (a legacy system, a third-party API with a hard per-second cap).

Con: no burst tolerance at all, and queuing adds latency. Requests wait rather than failing fast, which is sometimes worse.

#Choosing

NeedAlgorithm
Simple daily/monthly quotaFixed window
Exact small limits (login attempts)Sliding window log
General API limitingSliding window counter
Allow natural bursts, cap the averageToken bucket
Protect a burst-intolerant downstreamLeaky bucket

#What to limit on

The key determines who gets throttled, and getting it wrong is its own failure:

  • API key / user ID — the right choice for authenticated traffic. Precise and fair.
  • IP address — the only option before the user has logged in, but blunt. With NAT (network address translation), many devices behind one router appear to the internet as a single IP — an entire office, or thousands of phones on the same mobile carrier. Limit that IP and you punish all of them together. Use generous limits and combine with other signals.
  • Endpoint — expensive endpoints deserve tighter limits (/search at 10/min, /profile at 1000/min).
  • Tenant / organization — for B2B, the account is the unit of fairness.
  • Global — a system-wide ceiling as a last line of defense.

In practice you apply several tiers simultaneously and the most restrictive wins.

#Distributed rate limiting

Here's the real problem. With 50 application servers, per-server counters mean the effective limit is 50× your intended one.

#Centralized store (the standard answer)

All servers read/write counters in a shared Redis:

   -- atomic, single round trip via Lua
   local n = redis.call('INCR', KEYS[1])
   if n == 1 then redis.call('EXPIRE', KEYS[1], window) end
   return n

Correct and simple. It has to happen as one indivisible step — reading the count and then writing it back as two separate commands lets two servers both read "99" and both allow the request. Redis runs one command at a time per shard, so a single increment is safe on its own; anything involving more than one command goes into a small script (Lua) that Redis runs start to finish without interruption.

Costs: ~0.5 ms added to every request, and Redis becomes something every single request depends on — if it's slow, every request is slow. Decide the failure mode explicitly: if Redis is down, do you fail open (allow everything — availability over protection) or fail closed (reject — protection over availability)? For abuse prevention, fail open is usually right; for cost control against an expensive downstream, fail closed. Being asked "what if Redis is down?" and having a considered answer is a real differentiator.

#Local counters with async sync

Each server keeps a local counter and periodically reconciles with a central store, adjusting its local allowance. For example, every second each of 10 servers reports its counts. If the central total shows a user has used 900 of their 1,000 for this minute, each server lets that user through roughly 10 more times until the next sync.

Fast (no synchronous network call) and resilient, at the cost of accuracy — brief overshoot is possible between syncs. Right when your limits are approximate ("about 1000/min") and latency is precious.

#Token allocation

A central coordinator hands out batches of tokens to each server (e.g. "you may serve 200 requests"). Servers spend locally and request more when low. Dramatically fewer central round trips; slightly lossy when a server dies holding unspent tokens. This is how very high-throughput limiters work.

#Where to enforce

   Client ──► CDN/Edge ──► API Gateway ──► Service ──► DB
              ▲             ▲                ▲
         volumetric    per-user quotas   business rules
         DDoS, bots    the main tier     (e.g. 3 transfers/day)

Enforce as early as possible. A request rejected at the edge costs you nothing; one rejected at the service has already consumed a connection, a thread, and possibly a database round trip. But business-logic limits ("max 5 password resets per day") need application context and must live deeper.

Client-side self-limiting is a courtesy, never a control — it helps well-behaved clients avoid tripping limits and does nothing against attackers.

#Details that show experience

  • Return the right headers. Retry-After lets clients back off intelligently instead of hammering.
  • Add jitter to Retry-After, or every throttled client retries in the same instant — the thundering herd again.
  • Don't count rejected requests toward the limit. Otherwise a client that trips the limit and keeps retrying adds to its own count with every rejected attempt, so it stays over the limit and can never recover within the window.
  • Separate read and write limits. Writes are usually more expensive and more abusable.
  • Warn before enforcing. Log-only mode first, so you discover that your "obviously safe" limit would have broken a major customer.
  • Allow-list internal traffic — health checks and internal service calls shouldn't consume user quota.
  • Make limits configurable at runtime. During an incident you want to tighten limits without a deploy.

For a full end-to-end design of a rate limiting service — including capacity math, storage, and failure handling — see the Rate Limiter case study.

#Check yourself

What's wrong with a fixed-window counter?Show answer
The boundary burst: with 100 per minute, a client can send 100 at 10:00:59 and 100 more at 10:01:00 — 200 in one second, twice the intended rate.
Why is the sliding-window counter the usual default for API limits?Show answer
It keeps only two counters per key and estimates the trailing window as the current count plus the previous window weighted by its overlap — smooth at boundaries, with error typically well under 1%.
What does a token bucket allow that a leaky bucket doesn't?Show answer
Bursts: tokens build up to a cap B while idle and refill at rate R, so a page load of a dozen requests passes while the average stays at R. A leaky bucket drains at a fixed rate and allows no burst.
When is a leaky bucket the right choice?Show answer
When the thing you're protecting can't absorb bursts — a legacy system or a third-party API with a hard per-second cap — because it releases requests at a perfectly smooth rate.
Why is limiting by IP address blunt?Show answer
Whole offices and mobile carriers share one IP behind NAT, so one heavy user can throttle thousands. Prefer API key or user ID once authenticated, and keep IP limits generous.
Why must a distributed limiter's check-and-increment be atomic?Show answer
Read-then-write as two commands lets two servers both read 99 and both allow the request. Use a single INCR, or a Lua script Redis runs without interruption.
If the shared Redis is down, fail open or fail closed?Show answer
Decide per purpose: for abuse prevention, usually fail open (availability over protection); for cost control on an expensive downstream, fail closed.
Name three details that show you've run a rate limiter in production.Show answer
Return Retry-After with jitter; don't count rejected requests toward the limit; run in log-only mode before enforcing; allow-list health checks and internal calls; make limits changeable at runtime.

#What to carry forward

  • Know why you're limiting — abuse, fairness, cost or stability — because it changes the design.
  • Sliding-window counter is the default; token bucket when bursts are legitimate; leaky bucket to protect burst-intolerant downstreams.
  • Limit by the caller identity that matters, in tiers, and enforce as early as possible.
  • Distributed limits need a shared, atomic counter — or local counters and token batches when approximate is fine.
  • Choose fail-open or fail-closed deliberately, and send Retry-After with jitter.
00:00
/ 11m