Skip to main content
Distributed Systems & Caching

Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe)

Staff / Principal

Architect an ultra-low latency distributed rate limiter deployed across global edge points of presence (PoPs) to throttle abusive traffic.

Production Scale: 500 Billion Requests/Day • 1,000,000 Peak QPS • Sub-2ms Evaluation

Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe): Request Topology

4 Stages · 4 Sizing Benchmarks

Request traversal order for Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe) (Distributed Systems & Caching) under target workload 500 Billion Requests/Day • 1,000,000 Peak QPS • Sub-2ms Evaluation:

Stage 1

Local In-Memory L1 Cache (Go / Envoy Filter)

Stage 2

Distributed Redis Cluster L2 (Lua Scripts)

Stage 3

Asynchronous Rule Synchronizer (gRPC / Kafka)

Stage 4

Telemetry & Anomaly Detection Pipeline (ClickHouse)

Functional Requirements

  • •Enforce rate limits based on Client IP, API Key, User ID, and HTTP endpoint
  • •Support configurable algorithm strategies: Token Bucket, Leaky Bucket, and Sliding Window Counter
  • •Return standard HTTP 429 (Too Many Requests) headers: X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After

Non-Functional Requirements

  • •Ultra-low latency overhead (<2ms p99 latency per request)
  • •High fault tolerance (Fail-Open policy: if rate limiter fails, allow user traffic through)
  • •Global consistency across multi-region edge clusters

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Peak Throughput1,000,000 QPS globally
Active Clients Tracked500 Million unique keys / day
Memory Footprint~32GB RAM in Redis Cluster (64 bytes per counter)
Evaluation Latency Target<1.5ms via local memory L1 + Redis L2

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

+---------------------------------------------------------------------------------------------------+
| [CLIENT REQUEST] API Request with API Key / IP Address Ingress Headers                             |
+-------------------------------------------------+-------------------------------------------------+
                                                  |
                                                  v
+-------------------------------------------------+-------------------------------------------------+
| [LOCAL EDGE RATE LIMITER] In-Memory Token Bucket in Envoy / Cloudflare Worker (< 1ms Decision)    |
+-------------------------------------------------+-------------------------------------------------+
                                                  | (Synchronize Token Batches)
                                                  v
+-------------------------------------------------+-------------------------------------------------+
| [GLOBAL SLIDING WINDOW REDIS CLUSTER] Atomic Sorted Set (ZSET) or Sliding Window Counter           |
+-------------------------------------------------+-------------------------------------------------+
                                                  |
                        +-------------------------+-------------------------+
                        |                                                   |
                        v (Allowed: Rate <= Limit)                          v (Rejected: Rate > Limit)
+-----------------------+-----------------------+   +-----------------------+-----------------------+
| [FORWARD TO UPSTREAM APPLICATION SERVICE]     |   | [RETURN HTTP 429 TOO MANY REQUESTS]           |
| - Append RateLimit-Remaining Headers          |   | - Include Retry-After: <Seconds> Header       |
+-----------------------------------------------+   +-----------------------------------------------+

1Local In-Memory L1 Cache (Go / Envoy Filter)

Evaluates 90% of non-violating traffic locally using in-memory sliding windows to avoid remote network calls.

2Distributed Redis Cluster L2 (Lua Scripts)

Atomic Redis Lua scripts executing Token Bucket increment and TTL expiration without race conditions across nodes.

3Asynchronous Rule Synchronizer (gRPC / Kafka)

Broadcasts dynamic quota updates and blacklisted IP ranges from management dashboards to all edge nodes in <500ms.

4Telemetry & Anomaly Detection Pipeline (ClickHouse)

Ingests rate limiting events asynchronously to identify coordinated botnet attacks and adjust thresholds dynamically.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe) at a scale of 500 Billion Requests/Day • 1,000,000 Peak QPS • Sub-2ms Evaluation requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureAP (High Availability & Sub-Millisecond Latch Evaluation)CP (Strict Global Consensus per Ingress Token Request)Rate limiting must evaluate requests in sub-millisecond time at the edge. A network partition must fail open rather than dropping legitimate API traffic due to consensus timeout.
Rate Limiting AlgorithmSliding Window Log via Redis Sorted Sets (ZSET)Fixed Window CounterEliminates boundary burst vulnerabilities where callers consume 2x limit at window edges (e.g. at 00:59 and 01:00).
Synchronization ArchitectureHybrid Local Token Batching + Central SyncPure Synchronous Global Redis CallEdge workers acquire batches of 100 tokens locally, reducing network latency on 99% of requests to zero.
Storage Precision vs. MemorySliding Window Counter (Approximation)Exact Microsecond Timestamp LogsConsumes only 20 bytes of RAM per key compared to megabytes for high-throughput raw timestamp arrays.
Failure Behavior PostureFail-Open with Alerting NotificationFail-Closed (Block all traffic on Redis down)Preserves core business availability during transient infrastructure failures rather than causing a complete outage.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 500 Billion Requests/Day • 1,000,000 Peak QPS • Sub-2ms Evaluation demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe):

1. Redis Cluster Master Node Network Failure

Blast Radius: Rate limiter cannot update central token counts.

Remediation Protocol: Gateway immediately fails open, falling back to local thread-level rate limits while emitting critical alerts.

2. Clock Skew Across Distributed Edge Workers

Blast Radius: Sliding window evaluations drift between global datacenters.

Remediation Protocol: Use relative Unix timestamps from central NTP-synchronized Redis nodes rather than worker local clocks.

3. High Memory Usage from Millions of Dormant IPs

Blast Radius: Expired rate limit keys consume Redis memory.

Remediation Protocol: Explicit EXPIRE commands set 2x window TTL on all keys, ensuring automatic memory reclamation.

4. Distributed Botnet IP Rotation

Blast Radius: Attackers distribute requests across 100,000 distinct residential proxy IPs.

Remediation Protocol: Layer account-level, API-key, and behavioral fingerprint limits alongside basic IP rate limiting.

Production Algorithm Implementation: Atomic Sliding Window Rate Limiter in Redis Lua

Lua

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe):

-- Sliding Window Counter Rate Limiter
-- KEYS[1]: rate_limit:{identifier}
-- ARGV[1]: window_size_in_sec
-- ARGV[2]: max_allowed_requests
-- ARGV[3]: current_timestamp

local key = KEYS[1]
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local clear_before = now - window

-- Evict timestamps outside current sliding window
redis.call('ZREMRANGEBYSCORE', key, 0, clear_before)
local current_requests = redis.call('ZCARD', key)

if current_requests < limit then
  redis.call('ZADD', key, now, now)
  redis.call('EXPIRE', key, window)
  return {1, limit - current_requests - 1} -- Allowed
else
  return {0, 0} -- Rejected (429)
end

Design Distributed Rate Limiter & Abuse Prevention Gateway (Cloudflare / Stripe): Design Scope & Constraints Summary

This staff / principal blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 500 Billion Requests/Day • 1,000,000 Peak QPS • Sub-2ms Evaluation. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Distributed Systems & Caching.

Architectural FAQs & Interview Deep Dives

1Why pair an in-process L1 sliding window with L2 Redis Lua counters instead of querying Redis on every request?

Executing a remote Redis round-trip for every incoming HTTP call at 1,000,000 QPS saturates network interfaces and blows the <1.5 ms p99 evaluation budget. Serving 90% of non-violating traffic out of an in-memory Go/Envoy L1 cache—and syncing batch deltas asynchronously to L2 Redis—cuts remote cache traffic by an order of magnitude while reserving synchronous L2 checks for keys approaching their quota.

2How do Redis Lua scripts eliminate race conditions in Token Bucket and Sliding Window Counter enforcement?

A naive `GET` followed by `SET` in application code allows concurrent workers to read the same remaining token balance and double-spend the last unit. Packaging the timestamp delta calculation, token refill, decrement, and `EXPIRE` update into a single Lua script executes atomically on Redis's single-threaded event loop with zero interleaving.

3What happens to API availability if a regional L2 Redis shard stalls or becomes unreachable?

The rate-limiting middleware enforces a strict fail-open policy with a 1-2 ms socket timeout and circuit breaker: if L2 Redis fails, legitimate traffic continues flowing rather than causing a global outage, while edge proxies fall back to conservative local per-PoP L1 caps until Redis health probes recover.

4How does the Asynchronous Rule Synchronizer propagate emergency IP bans across global edge PoPs under 500 ms?

Policy changes committed in the control plane emit compact versioned Protobuf diffs over Kafka and gRPC streaming channels to every edge PoP. Local Envoy/Go filters swap updated CIDR trie and API-key quota maps lock-free in memory while streaming violation events into ClickHouse to auto-detect coordinated botnet bursts.