4/10
Technical Architecture & AI Engineering · 7 min read

System Design: Distributed Rate Limiter Across Regions (Sliding Window and Token Bucket)

Architect a 50,000-QPS multi-region rate limiter with sub-2ms overhead using regional Redis Lua token buckets, local L1 batching, and safe fail-open degradation.

Why This Matters at Engineering Leadership Scale

A rate limiter sits directly in front of every API request your company serves. Done right, it stops buggy retry loops, mitigates credential-stuffing bots, and enforces paid API tiers cleanly. Done poorly, it adds 150ms of cross-region latency to every call or takes down 100% of paying customers during a Redis failover.

At Staff Engineer and EM scale, distributed rate limiting is an explicit trade-off across global accuracy, <2ms tail latency, and graceful availability under partial failure.

Core Mental Model & Architecture

Anchor the design in concrete QPS, memory, and RPC math first:

  • Traffic & SLO: 50,000 QPS globally across 3 regions (US, EU, AU -> ~17k QPS/region, ~4.3B reqs/day), <2ms added latency, tiered limits (100 req/min Free, 10,000 req/min Enterprise).
  • Memory & RPC Math: 1M active tenant/IP keys * ~128 bytes/key = ~128 MB RAM per regional Redis cluster (tiny memory footprint; pure CPU/RTT bound). Adding a 500ms local L1 in-memory counter sync inside gateway pods slashes Redis RPCs by 80% (from 50k/sec down to ~10k/sec globally).
AlgorithmBurst SupportMemory/KeyBoundary SpikeBest Fit
Fixed WindowPoor (2x edge burst)1 intHigh (:59+:01)Coarse internal limits
Sliding LogExactVery HighNoneLow-QPS security rules
Sliding CounterSmooth approx2 intsMinimal (<0.5%)Strict smooth rates
Token Bucket (Chosen)Controlled burst + sustained cap2 floatsNonePublic SaaS APIs

Select atomic Redis Lua Token Buckets regionally, paired with 500ms L1 local batching and async cross-region sync.

Step-by-Step Implementation Tutorial

1. Design the Regional L1/L2 Gateway Topology

Keep enforcement strictly regional (0.5ms Redis RTT) and sync global consumption asynchronously every 1 second.

text
CLIENT (US/EU/AU) -> Regional LB -> API Gateway (Envoy/Go):
  1. Tenant tier rule from local RAM (updated via Pub/Sub)
  2. Local L1 Counter Batcher (<0.05ms RAM; flushes deltas every 500ms)
  3. Regional Redis Cluster (Same-AZ) executes Atomic Token Bucket Lua
  4. Return `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `Retry-After` (HTTP 429)
  5. Async Cross-Region Sync (1s cadence via Kafka / Active-Active Redis CRDTs)

2. Implement Atomic Token Bucket Lua With Fail-Open Timeout Guard

Enforce a strict 5ms Redis timeout and fall back to a local per-pod cap on cache degradation rather than returning 500 to customers.

typescript
const TOKEN_BUCKET_LUA = `
  local key, cap, rate, now, cost = KEYS[1], tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
  local s = redis.call("HMGET", key, "tokens", "ts")
  local tokens = math.min(cap, (tonumber(s[1]) or cap) + math.max(0, now - (tonumber(s[2]) or now)) * rate)
  if tokens < cost then
    return {0, math.floor(tokens), math.ceil((cost - tokens) / rate)}
  end
  redis.call("HMSET", key, "tokens", tokens - cost, "ts", now)
  redis.call("PEXPIRE", key, math.ceil((cap / rate) * 2))
  return {1, math.floor(tokens - cost), 0}
`;

export async function checkLimit(
  evalRedis: (lua: string, k: string[], a: string[], timeoutMs: number) => Promise<number[]>,
  localFallback: (k: string, podCap: number) => boolean,
  key: string,
  capacity: number,
  refillPerSec: number
) {
  try {
    const [ok, remaining, waitMs] = await evalRedis(
      TOKEN_BUCKET_LUA, [`rl:${key}`],
      [String(capacity), String(refillPerSec / 1000), String(Date.now()), "1"], 5
    );
    return { allowed: ok === 1, remaining, retryAfterSec: Math.ceil(waitMs / 1000), mode: "redis" };
  } catch {
    // Cache degraded: fail open into local per-node safety cap + fire SEV2 alert
    const ok = localFallback(key, Math.max(10, Math.ceil(capacity / 4)));
    return { allowed: ok, remaining: ok ? 1 : 0, retryAfterSec: 1, mode: "fail_open_local" };
  }
}

3. Handle the Minute-25 Curveball: Cross-Region Split Attack & Regional Redis Partition

"What if an attacker splits traffic across US, EU, and AU to triple their quota, AND what happens if US-East Redis partitions completely?"

  1. Cross-Region Split Bypass: Async 1-second delta sync (Kafka or Active-Active Redis CRDTs) converges global token buckets across regions within 1 to 2 seconds without adding 150ms locks. For ultra-sensitive endpoints (POST /login, OTP), pin verification to a single home region or tighten regional quotas to limit / 3.
  2. Regional Redis Partition: When evalRedis exceeds 5ms or errors, the gateway trips a circuit breaker, pages SEV2 on-call, and fails open into local per-pod memory limits so legitimate customer traffic keeps flowing cleanly.

4. Split Multi-Squad Ownership

  • Edge & API Gateway Squad (5 engineers): Owns Envoy filter runtime, L1 local batching, regional Redis Clusters, fail-open circuit breakers, and 429 telemetry.
  • Identity & Monetization Squad (5 engineers): Owns dynamic tier policies (Free, Enterprise), temporary sales overrides, and customer usage dashboards.

Worked Production Scenario: Before vs. After

A global API SaaS previously enforced quotas in a central US-East Postgres table. AU and EU users paid a 210ms rate-limit tax on every request, and one Enterprise retry storm saturated Postgres CPU, triggering a 22-minute global fail-closed outage. Moving to regional Redis Lua token buckets, 500ms L1 batching, and fail-open local caps eliminated both problems.

MetricBefore (Central Postgres)After (Regional Redis + L1 Sync)Net Impact
Added p99 Latency (AU/EU)210ms1.3ms160x faster edge
Redis RPCs at 50,000 QPSN/A (Postgres died at 8k QPS)~9,800 RPCs/sec (-80% via L1)5x regional headroom
Cache Failure Blast RadiusFull API outage (fail-closed)Zero downtime (local fail-open)Preserved 99.99% SLO
Throttle Support Tickets40+/month<5/month (Retry-After headers)Clean client backoff

Common Failure Modes & Anti-Patterns

1. Failing Closed on Cache Blips for Standard API Traffic

The trap: Returning 500 or 429 to every customer during a Redis failover, turning a minor cache blip into a SEV1 outage. The structural fix: Default to fail-open with local per-pod safety caps + SEV2 alert, reserving fail-closed strictly for high-risk fraud or credential endpoints.

2. Returning Bare 429 Without Retry-After

The trap: Clients immediately retry in tight loops, doubling ingress traffic during load spikes. The structural fix: Always return X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After, and ship official SDKs with jittered exponential backoff.

3. Hot-Key Redis Shard Saturation

The trap: One 15,000-QPS enterprise tenant pins to one Redis Cluster slot, maxing a single CPU core. The structural fix: Flush batched L1 deltas every 500ms instead of per request, and shard extreme hot keys across rl:{tenant}:{0..3}.

How to Handle Pushback in the Room

Security Engineer: "Doesn't 1 to 2 seconds of cross-region eventual sync let an attacker briefly exceed their quota by 25%?"

Calm Executive Response: "Synchronous cross-region locks add 150ms to every customer call and couple regional availability. For standard SaaS APIs, 1-second eventual drift has zero commercial impact; for auth, OTP, and billing endpoints where strict global caps matter, we pin those specific routes or cap each region at limit / 3."

Enterprise Account Manager: "Our biggest client is running a weekend migration and hitting 10,000 req/min. Do we need a code deploy to bump them?"

Calm Executive Response: "No deploy required. Tier rules live in our dynamic policy control plane and sync to gateway RAM via Pub/Sub within 5 seconds. We can set a time-boxed 48-hour override for their tenant_id that auto-expires Monday morning."

Key Takeaways & This Week's Action Rep

  • Enforce rate limits regionally: Accept 1 to 2s async global convergence instead of paying a 150ms cross-region RTT tax.
  • Pair Redis Lua Token Buckets with 500ms L1 batching: Prevent race conditions while cutting Redis RPCs by 80% and neutralizing hot-key shards.
  • Fail open safely on cache degradation: Protect global availability with local per-pod caps and immediate SEV2 alerting.
  • Always emit standard Retry-After headers: Help client SDKs back off instead of amplifying bursts.
  • This Week's Action Rep: Verify whether your production gateway fails open or closed during a simulated cache timeout, measure its p99 overhead, and confirm Retry-After headers appear on every 429.