GuideIntermediate2 min read

Distributed API Rate Limiting with Token Buckets

Select the right identity and budget, enforce atomic token accounting, and choose failure behavior by endpoint risk.

Author
Pradeep Gajendra
Published
Updated

Scope of this article

Environment
Pseudocode is intentionally not a working Redis implementation.

Rate limiting protects a finite resource, not just an endpoint. A login attempt, a costly report and a cached article request consume different budgets. A single global '100 requests per minute' rule is both too strict for cheap routes and too generous for expensive ones.

Identify the identity and the scarce resource#

  • Anonymous API: IP limits are coarse and can penalize mobile networks or offices behind NAT.

  • Authenticated API: prefer account, API key and tenant-aware dimensions, with a separate protective IP ceiling.

  • Costly endpoint: weight tokens by estimated CPU, provider calls or rows scanned rather than request count alone.

  • Write-heavy endpoint: pair rate limits with concurrency limits and durable queue bounds.

Token bucket intuition#

A bucket with capacity 20 and refill rate 2 tokens per second permits a small burst while enforcing a long-term mean. Each accepted request spends one token. The model is easy to reason about but depends on accurate coordination between instances.

tokenst+1=min⁡(C,tokenst+rΔt)−cost\text{tokens}_{t+1}=\min(C,\text{tokens}_t+r\Delta t)-\text{cost}

Single-instance code is not distributed enforcement#

limiter-sketch.tstypescript
// Pseudocode: perform atomically in Redis Lua or a transactional store.
async function allow(identity: string, cost: number) {
  const state = await atomicallyLoadAndRefill(identity);
  if (state.tokens < cost) return { allowed: false, retryAfter: state.wait };
  await atomicallyStore(identity, { tokens: state.tokens - cost });
  return { allowed: true };
}

The two operations in this sketch must not be separate non-atomic round trips. Two application instances could otherwise both observe the same remaining tokens and over-admit traffic.

Respond clearly and fail deliberately#

HTTP 429 is the usual response for too many requests; consider Retry-After or standardized RateLimit headers where supported [1]. Decide explicitly what happens when the limiter's backend is unavailable: fail closed for sensitive write operations, or fail open with a local protective limit for public reads.

Observe and test#

  • Measure admitted, rejected and backend-failed requests by policy—not by unbounded user identifiers.

  • Test concurrent bursts across multiple instances for oversubscription.

  • Test an abusive tenant that shares a source IP with ordinary users.

  • Avoid rate limits that turn automated retry loops into a denial-of-service amplifier.

  • Communicate quotas and reset conditions to API consumers.

Sources

  1. [1]
    MDN — HTTP Response Status Codes

    Mozilla · publication date unknown · HTTP · retrieved 2026-11-02

Spotted an error? Use “Suggest a correction” in the discussion, or read our corrections policy.

Discussion

Sign in to join the discussion. Reading is always open.

Loading discussion…

Report comment