vishal patel
UnderstoodIntermediateUpdated 2026-09-23

Design: Distributed Rate Limiter

Protect APIs and tenants — algorithms (token bucket, sliding window), distributed counters in Redis, and where to enforce limits.

redisapi-gatewaymulti-tenantalgorithms

Requirements

  • Limit requests per key (API key, tenant, user, IP) per time window. Return 429 with a Retry-After header.
  • Low overhead (under 1 ms), accurate across many gateway instances, and tolerant of Redis blips.

Algorithms

AlgorithmHowPros / cons
Fixed windowCounter per minuteSimple; allows a 2× burst at window edges
Sliding window logStore timestampsExact; memory-heavy
Sliding window counterWeighted current + previous windowGood accuracy, cheap. Common choice
Token bucketTokens refill at rate r, bucket size bAllows controlled bursts. Very common for APIs
Leaky bucketQueue drained at a constant rateSmooths output; adds latency

Architecture

diagram
  • Run the check in a Lua script so read-modify-write is atomic in Redis.
  • Key design: rl:{tenantId}:{route} keeps tenant keys on the same Redis slot.
  • Fail open or fail closed? Usually fail open for availability, with an alert. Fail closed for expensive or abusable endpoints.
  • Layers: edge/CDN for IP floods, gateway for API-key quotas, and in-service limits for expensive operations like bulk jobs.
Architect's tip

In multi-tenant SaaS, rate limits are also a fairness tool. Combine per-tenant request limits with per-tenant concurrency limits on background jobs so one big tenant can't monopolise workers.

Cheatsheet

The whole topic on one page. Click to open full screen.

Sources & further learning

Videos, courses, docs and books I recommend for this topic.

Related topics