5 Rate Limiting Algorithms Explained: From Fixed Window to Sliding Window Counter

Rate limiting is one of those backend building blocks that looks trivial on a whiteboard—until traffic spikes, clients retry in lockstep, or a distributed cluster starts double-counting. Every algorithm trades off accuracy, memory, burst handling, and implementation complexity.

In this guide, we will walk through the 5 core rate limiting algorithms, how they work under the hood, where each one breaks, and which one production systems actually choose.


1. Fixed Window

How it works: Time is divided into discrete, equal-sized intervals (e.g. 1s, 1m, 1h). Each client (user, IP, or API key) gets a single integer counter per window. Once the counter hits the limit, further requests are rejected (typically with HTTP 429) until the next window begins and the counter resets.

Window 1 [00:00 - 01:00]   Window 2 [01:00 - 02:00]
|              N requests| |N requests              |
+------------------------+-+------------------------+
                     ^         ^
                     | 2N burst in ~1s!
  • Memory & CPU: O(1) per client per window—just one integer counter and a TTL.
  • Distributed behavior: Naturally atomic. A single Redis INCR + EXPIRE cannot double-allow a request under concurrency the way a naive read-then-write token bucket can.
  • The defining flaw — boundary burst: A client can send N requests at the very end of Window 1 and N more at the very start of Window 2, pushing 2N requests through in less than a single window’s duration.

Real-world notes: Reddit’s 60 req/min OAuth limit is famously gameable at window boundaries. Amazon API Gateway deliberately avoids pure fixed windows in favor of token buckets, and Figma’s engineering team rejected naive fixed windows for the same 2× burst reason before building a sliding-window-counter hybrid.

Best for: Simple per-IP throttling, login brute-force protection, hard billing/quota resets, or embedded/IoT environments where O(1) simplicity beats strict smoothness.


2. Sliding Window Log

How it works: Instead of a single counter, the limiter stores the timestamp of every accepted request per client. On each incoming request, it drops timestamps older than now - window_size, counts the remaining entries, and accepts the request only if the count is below the limit.

In Redis, this is the canonical Sorted Set (ZSET) + Lua pattern:

  1. ZADD <key> <now> <request_id>
  2. ZREMRANGEBYSCORE <key> -inf <window_start>
  3. ZCARD <key>
  4. Conditionally accept + EXPIRE <key> <window>
  • Accuracy: The only classic counting algorithm with zero boundary-burst error. If the limit is 100 req/min, a client can never exceed 100 requests in any 60-second span.
  • The killer weakness — memory: Memory scales as O(limit) per active key. A 100 req/min tier stores up to 100 entries per user; a 10,000 req/min tier stores 10,000 timestamps per user. At 10M active keys × 100 entries × ~50–100 bytes/entry, you are looking at 50–100 GB of RAM.

Best for: Exactness-critical workloads—billing enforcement, strict per-customer SLAs, abuse investigations, or low-volume endpoints where approximate counters could over- or under-charge.


3. Token Bucket

How it works: A bucket holds up to b tokens (capacity / max burst) and refills at a steady rate r (sustained rate). Each conforming request removes a token; if the bucket is empty, the request is rejected and the bucket’s state is left unchanged.

Refill rate: r tokens/sec
+-----------------------+
|  [t] [t] [t] [t] [t]  |  capacity = b (max burst)
+-----------------------+
            |
            v  1 token per request
  • Memory & CPU: O(1) per key—only the current token count and last_refill timestamp are stored.
  • Lazy refill: No background timer is needed. On each request, elapsed time is used to compute new tokens: tokens = min(b, tokens + (now - last_refill) * r)
  • Burst-friendly: An idle client accumulates tokens up to b and can fire a burst of b requests immediately, while long-run throughput stays bounded by r.
  • Distributed caveat: Because updating tokens requires reading tokens and last_refill, computing the refill, and writing both back, distributed stores like Redis need an atomic Lua script to avoid race conditions.

Real-world notes: Token-bucket-family algorithms power AWS API Gateway, Stripe’s rate limiting, Go’s golang.org/x/time/rate, and Linux’s HTB traffic control.

Best for: Public APIs where legitimate clients occasionally send short bursts (e.g. page loads firing parallel requests) but average traffic must stay bounded.


4. Leaky Bucket

How it works: Water enters a bucket intermittently and leaks out at a constant rate. If water arrives faster than it leaks—or in a burst larger than the bucket’s capacity—the bucket overflows and requests are dropped.

A persistent source of confusion is that “leaky bucket” refers to two distinct algorithms in the literature:

  1. Leaky bucket as a meter: A counter that checks conformance—mathematically a mirror image of the token bucket.
  2. Leaky bucket as a queue: A FIFO buffer of capacity n drained at a fixed rate r (this is what most system-design interviews mean).
  • Memory & CPU: O(1) accounting state per client (water level + timestamp, dripped lazily). The queue variant buffers up to n items.
  • Traffic shaping vs. burst absorption: Unlike the token bucket, which allows bursts up to capacity, the leaky bucket smooths bursts into a perfectly steady output stream.
  • GCRA (Generic Cell Rate Algorithm): Standardized by ITU-T (I.371) and the ATM Forum, GCRA is the drip-free, meter-based formulation used in modern libraries like Go’s throttled (used in production at Stripe and Heroku).

Real-world notes: Nginx’s ngx_http_limit_req_module, router QoS/traffic shaping, and ATM network policing all rely on leaky-bucket-style smoothing.

Best for: Protecting fragile downstream services (databases, legacy APIs, payment processors) that need a smooth, predictable request rate rather than bursty traffic.


5. Sliding Window Counter

How it works: Approximates a true sliding window by blending the request counts of the current fixed window and the previous fixed window, weighted by how much of the current window has elapsed:

estimated = prev_count * (1 - progress) + current_count
where progress = (now - current_window_start) / window_size

For example, if the limit is 100 req/min, the previous minute had 80 requests, the current minute has 30 requests, and we are 25% into the current minute (progress = 0.25):

estimated = 80 * 0.75 + 30 = 90 (allowed).

  • Memory & CPU: O(1) per key—exactly two integer counters (prev and current), matching Fixed Window’s tiny footprint.
  • Near-exact accuracy: Cloudflare analyzed 400 million requests from 270,000 distinct sources and found only 0.003% of requests were wrongly allowed or rate limited, with an average 6% difference between the real and approximate rate.
  • Approximation source: It assumes requests in the previous window were uniformly distributed. A burst at the start of the previous window gets slightly over-weighted later; a burst at the end gets slightly under-weighted.
  • Distributed-friendly: Two keys per client + a short Redis Lua script give an atomic read-decide-increment with no TOCTOU race.

Real-world notes: Cloudflare chose Sliding Window Counter for its edge rate limiting after rejecting Fixed Window, Sliding Window Log, and Leaky Bucket. Redis’s official rate-limiting guide also calls it the best fit for most APIs.

Best for: The de-facto default for general-purpose API rate limiting—combining O(1) memory, high accuracy, and smooth boundary behavior.


Quick Comparison

Algorithm Memory / Key Boundary Burst Allows Bursts? Distributed Atomicity
Fixed Window O(1) (1 counter) Yes (2× limit) At boundaries Native (INCR)
Sliding Window Log O(limit) None (exact) Up to limit Lua script (ZSET)
Token Bucket O(1) (2 numbers) None Yes (up to b) Lua script
Leaky Bucket O(1) (or O(n) queue) None No (smooths output) Lua script / Queue
Sliding Window Counter O(1) (2 counters) Minimal (~0.003% error) Gradually Lua script

Which One Should You Pick?

  • Default choice for most APIs: Sliding Window Counter — O(1) memory with near-exact accuracy.
  • Need to allow short client bursts: Token Bucket — clean two-parameter model (capacity, refill rate).
  • Need to protect a fragile downstream service: Leaky Bucket — smooths spikes into a constant drain rate.
  • Need 100% exactness (billing, strict SLAs): Sliding Window Log — worth the O(limit) RAM only when exactness is non-negotiable.
  • Need the simplest possible counter: Fixed Window — just accept the 2× boundary burst.