Distributed Rate Limiting Architecture: Token Buckets, Leaky Buckets, and Failure Modes

API traffic dashboard showing rate limited requests
Infrastructure · API Design

Distributed Rate Limiting Architecture: Token Buckets, Leaky Buckets, and Failure Modes

A naive rate limiter implemented as requests_this_minute > 100 ? reject : allow, resetting on a fixed clock boundary, contains a structural edge exploit. An automated client can dispatch 100 requests at 00:59 and another 100 requests at 01:00, delivering 200 requests inside two seconds while remaining within the nominal quota of every discrete window. Under high concurrency or adversarial traffic, that boundary surge can saturate downstream database connection pools and thread executors.

Rate limiting is a core reliability control plane mechanism rather than a trivial counter check. Its accuracy, memory footprint, concurrency safety, and fallback behavior under infrastructure faults determine whether your API absorbs load spikes gracefully or collapses under self inflicted retry storms.

The Fixed Window Boundary Exploit

Fixed window counters partition wall clock time into discrete buckets and increment a key per interval. The implementation is simple and fast in a single process, yet its boundary behavior distorts real request rates:

def is_allowed(key, limit=100, window=60):
    current_window = int(time.time() // window)
    count = redis.incr(f"{key}:{current_window}")
    if count == 1:
        redis.expire(f"{key}:{current_window}", window)
    return count <= limit

In the worst case, a client straddling a window boundary can push up to 2x the configured quota across a narrow slice of time. If a downstream microservice has a hard concurrency ceiling of 120 requests per minute and a public endpoint allows 100 per minute with a fixed window, a burst of 200 requests near a minute rollover can trigger queue buildup, tail latency spikes, and cascading timeouts.

2x
Peak Burst, Fixed Window
O(1)
Atomic Bucket Evaluation
429
Standard Throttle Status
A rate limiter that permits double the nominal throughput across a window edge measures coarse interval totals while leaving short term burst capacity unguarded.
Network traffic shaping and request queue visualization
Choosing between burst tolerance and strict traffic smoothing depends on downstream capacity and latency budgets.

Core Rate Limiting Algorithms and Tradeoffs

  1. Sliding Window Log

    Records an individual timestamp per accepted request and prunes timestamps older than now - window before counting active entries. It eliminates boundary spikes completely, but storing unbounded timestamps per active key consumes significant memory under high request rates and requires sorted set trimming on every evaluation.

  2. Sliding Window Counter

    Approximates a true rolling window in constant memory by weighting the previous interval count by its remaining overlap fraction and adding the current interval count. If 60 seconds is the window and 15 seconds have elapsed in the current window, the previous window contributes 45 / 60 of its count. This removes sharp cliff edges while keeping state compact.

  3. Token Bucket

    Models a bucket with maximum burst capacity C that refills continuously at rate R tokens per second. Each request consumes one token; if fewer than one token is available, the request is throttled. It allows legitimate bursts after idle periods while bounding long term average throughput, aligning well with interactive web and mobile clients.

  4. Leaky Bucket and GCRA

    Enforces a steady egress rate by draining requests from a bounded queue at a constant cadence or spacing arrivals using a theoretical arrival time schedule (the Generic Cell Rate Algorithm). This protects fragile downstream workers from sudden concurrency shocks at the expense of queuing delay during traffic surges.

Atomic Token Bucket Execution via Redis Lua Scripting

In production systems, reading bucket state in application memory, computing new token balances in Python or Go, and writing back in separate calls creates race conditions when multiple workers handle requests for the same key simultaneously. Executing the read, refill calculation, and state update inside a single atomic Redis Lua script serializes mutations on the Redis single threaded command loop:

-- KEYS[1]: rate limit key
-- ARGV[1]: capacity (max burst tokens)
-- ARGV[2]: refill_rate (tokens per second)
-- ARGV[3]: now (unix timestamp as float/string)
-- ARGV[4]: ttl (key expiration in seconds)

local data = redis.call("HMGET", KEYS[1], "tokens", "last_refill")
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local ttl = tonumber(ARGV[4])

local tokens = tonumber(data[1])
local last_refill = tonumber(data[2])

if tokens == nil then
  tokens = capacity
  last_refill = now
else
  local elapsed = math.max(0, now - last_refill)
  tokens = math.min(capacity, tokens + (elapsed * refill_rate))
  last_refill = now
end

local allowed = 0
if tokens >= 1.0 then
  tokens = tokens - 1.0
  allowed = 1
end

redis.call("HMSET", KEYS[1], "tokens", tokens, "last_refill", last_refill)
redis.call("EXPIRE", KEYS[1], ttl)
return {allowed, math.floor(tokens)}

With capacity = 50 and refill_rate = 10, an idle client can execute up to 50 requests immediately during an initial burst and then sustain up to 10 requests per second thereafter. Notice that setting a sensible ttl keeps idle keys from lingering forever in memory, preventing gradual keyspace bloat across millions of ephemeral clients or IP addresses.

Anti Pattern

Applying a single global quota across all callers or keying solely by mutable client headers such as X-Forwarded-For without trusted proxy normalization, allowing spoofing or punishing legitimate enterprise tenants behind shared NAT gateways.

Engineering Pattern

Partitioning limiters by verified identity (authenticated user ID, API key, or tenant tier) with endpoint specific costs for heavy operations, paired with edge IP limits enforced only after normalizing trusted proxy headers.

HTTP Semantics, Backpressure, and Retry Storms

When a request exceeds quota, returning 429 Too Many Requests signals explicit backpressure rather than an ambiguous client error or gateway fault. Including clear retry guidance helps well behaved SDKs and clients pace retries instead of hammering the API in tight loops:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 4
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 4

{"error": "rate_limit_exceeded", "retry_after_seconds": 4}

Without Retry-After and jittered backoff on the client side, thousands of throttled clients can synchronize their retries at the exact same millisecond, creating a self inflicted retry storm that keeps CPU and connection pools saturated even after the initial traffic spike subsides.

Distributed State, Fail Open vs Fail Closed, and Key Cardinality

Running multiple stateless API pods behind a load balancer requires centralized state so each pod does not grant its own independent quota. However, introducing a centralized Redis dependency adds a network hop and a potential fault point on the hot request path.

  • Fail open vs fail closed: If the rate limit store times out or becomes unreachable, failing open (allowing traffic through with a short circuit breaker timeout, typically 5 to 15 milliseconds) preserves availability for core reads and writes during a cache outage. Failing closed (rejecting requests when the limiter errors) makes sense for high risk abuse surfaces such as login endpoints, password resets, or payment authorization where unthrottled traffic is dangerous.
  • High cardinality key explosion: Generating keys from unbounded values such as raw query strings, user agents, or unauthenticated random tokens can flood memory and degrade eviction performance. Always normalize keys around bounded identifiers and enforce explicit TTLs.
  • Weighted costs for asymmetric endpoints: A lightweight health check or profile read should not consume the same budget as a heavy search query, report export, or batch write. Deducting a weighted token cost per request aligns rate limits with actual compute and database load.

Key Takeaways

  • Fixed windows can allow up to 2x the nominal rate across window boundaries, whereas sliding window counters and token buckets smooth burst behavior more predictably.
  • Token buckets allow controlled bursts up to bucket capacity while enforcing a steady average refill rate, and leaky buckets or GCRA enforce strict output pacing.
  • Atomic operations such as Redis Lua scripts prevent read modify write race conditions across concurrent distributed workers.
  • Returning HTTP 429 with Retry-After and client side jittered backoff helps prevent synchronized retry storms.
  • Choose fail open or fail closed per endpoint risk profile, bound key cardinality with TTLs, and weight token costs for expensive operations.

Post a Comment

Previous Post Next Post