Rate Limiting Algorithms Explained: Token Bucket, Leaky Bucket and Sliding Window

Compare rate limiting algorithms — fixed window, sliding log, sliding window counter, token bucket, leaky bucket — with Redis implementations.

Published December 6, 2026

Rate limiting protects APIs from abuse, brute-force attacks, runaway clients and accidental traffic spikes, and it enforces fair use between customers. The algorithm you choose determines how bursts are treated, how accurate the limit is and how much state you store. Here are the main options and when each fits.

The concept

Fixed window counts requests per calendar window (for example per minute) and resets at the boundary; it is simple but allows double bursts around the boundary. Sliding window log stores a timestamp per request and counts those within the last window; it is exact but memory-heavy. Sliding window counter approximates the log by weighting the previous window's count, offering good accuracy with tiny state.

Token bucket gives each client a bucket that refills at a steady rate up to a capacity; each request spends a token. It allows controlled bursts and is the most common choice for APIs. Leaky bucket processes requests at a constant output rate, smoothing traffic, often used for queues and outbound throttling. In distributed systems, counters live in a shared store like Redis, updated atomically with Lua scripts or built-in commands.

Comparison

AlgorithmBurstsAccuracyState per client
Fixed windowUp to 2x at boundariesLow1 counter
Sliding logNone beyond limitExactOne entry per request
Sliding window counterSmoothedGood approximation2 counters
Token bucketAllowed up to capacityGoodTokens + timestamp
Leaky bucketQueued, released at fixed rateGoodQueue level + timestamp

How bursts differ

Fixed window (boundary burst)up to 200 in 2 sSliding window counter≈100-110Token bucket (cap 20, 100/min)100 + burst 20
Illustrative maximum requests in a short span for a 100/minute limit.

In practice

ClientAPIRedisrequestEVAL token_bucket(key)allowed, 7 tokens left200 + RateLimit headersrequest (burst)429 + Retry-After: 3
A distributed limiter with Redis.

Practical examples

Sliding window counter in Redis (Python)

Weighted previous window + current window.

import time
def allow(r, key, limit=100, window=60):
    now = time.time()
    cur = int(now // window)
    prev_count = int(r.get(f"{key}:{cur-1}") or 0)
    cur_count = r.incr(f"{key}:{cur}")
    r.expire(f"{key}:{cur}", window * 2)
    weight = 1 - (now % window) / window
    return prev_count * weight + cur_count <= limit

Standard response headers

Tell clients their limits and when to retry.

HTTP/1.1 429 Too Many Requests
Retry-After: 3
RateLimit-Policy: 100;w=60
RateLimit: limit=100, remaining=0, reset=3

NGINX request limiting

Leaky-bucket style limiting with burst allowance at the edge.

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        proxy_pass http://app;
    }
}

Common mistakes

  • Rate limiting only by IP, punishing users behind shared NAT and missing distributed attackers.
  • Non-atomic read-then-write counters that undercount under concurrency.
  • No Retry-After header, causing aggressive client retries.
  • One global limit instead of separate limits for expensive endpoints like login or search.

Key takeaways

  • Choose by burst behaviour and accuracy needs; token bucket is a solid default.
  • Use atomic operations in a shared store for distributed limits.
  • Return 429 with Retry-After and rate limit headers.
  • Apply stricter limits to sensitive endpoints.

FAQ

Where should rate limiting happen?

At multiple layers: edge/CDN or gateway for coarse protection, application for per-user and per-endpoint business limits.

What key should I limit on?

API key or user ID for authenticated traffic; IP plus other signals for anonymous traffic.

How do I limit login attempts?

Combine per-account and per-IP limits with progressive delays, and consider breached-password checks and CAPTCHA after repeated failures.

More Security articles