Building a High-Throughput Request Throttling System
System DesignModel answerLast updated
Design a service that enforces per-client request limits across a distributed application, handling 100k+ QPS with single-digit millisecond latency.
You're building a request throttling system for a platform with many backend services. Each client (identified by API key or user ID) has a request quota that must be enforced consistently, even when traffic is distributed across multiple application servers.
What You Need to Support
Your system should provide a check operation that services call before processing requests:
- Input: an identifier (client key), a quota limit, and a time window duration
- Output: whether the request is permitted, plus metadata like remaining quota
The system must work correctly when the same client sends requests through different application instances simultaneously.
Performance and Reliability Goals
- Response time: Each throttling check should complete in under 10 milliseconds
- Throughput: The system must support at least 100,000 checks per second
- Reliability: Throttling failures should not bring down the entire platform
- Consistency: All application instances must see the same quota state to prevent clients from exceeding limits
What to Address
- Overall system structure: how components fit together and where checks happen
- Storage backend selection: justify your choice based on the performance requirements
- Concurrent access: how you prevent race conditions when multiple servers check the same quota simultaneously
- Hot spot handling: strategies for clients that generate disproportionately high traffic
Consider which throttling algorithm to use (fixed windows, sliding windows, token buckets, etc.) and explain your reasoning. Discuss where the solution might struggle and how you'd address those limitations.
Hints
Hint 1
Think about where atomic operations can replace distributed locks
Hint 2
Consider what happens when one storage node fails
Hint 3
Memory usage differs significantly between algorithms that store every timestamp versus those that maintain counters
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Request Throttling System Design
A strong response demonstrates progression from basic design to handling real-world challenges. Start with core requirements, build a working architecture, then address the failure modes and bottlenecks that emerge at scale.
Understanding Requirements and Scale
Begin by clarifying ambiguities:
- Key composition: Are limits per API key, per user, per endpoint combination? Assume composite keys like
tenant:key:resource. - Precision needs: Can we tolerate 2-3% over-admission during traffic bursts? Typically yes for abuse prevention, but billing systems need stricter accuracy.
- Geographic scope: Single datacenter or multi-region? Start with regional enforcement to avoid cross-region latency.
Capacity planning:
- Request volume: 100k checks/second baseline, planning for 3× surge means 300k/sec capacity.
- Storage throughput: A single in-memory data store instance handles roughly 100k simple operations/second. Complex atomic operations reduce this. Plan for 8-12 sharded nodes with replication.
- Latency budget: Sub-millisecond operations within a datacenter leave comfortable room under the 10ms limit, assuming single-hop checks.
- Memory footprint: With 10 million active keys and counter-based tracking at ~100 bytes per key, expect about 1GB. Timestamp-based approaches storing individual request times would consume 10-100× more memory.
Interface Design
checkQuota(identifier, limit, windowSeconds) -> {
permitted: boolean,
remaining: integer,
resetTimeMs: integer
}
Gateways translate denials into HTTP 429 responses with X-RateLimit-Remaining and Retry-After headers. Quota definitions typically come from a configuration service with local caching, not from each caller, enabling operators to adjust limits without code deployment.
Architecture Overview
Client Request
↓
API Gateway / Service Mesh Proxy
↓
Throttle Check (local library or RPC call)
├── Local Cache: rules, temporary blocks, batched tokens
└── Shared State Store (hash-sharded, replicated)
Configuration Service → broadcasts rule updates
Enforcement point: Run checks at the network edge—in API gateways or service mesh sidecars like Envoy. This prevents abusive traffic from reaching business logic.
Stateless checkers: All shared state lives in the backing store. Checker instances are fungible and horizontally scalable. Any instance can validate any key, satisfying the consistency requirement.
Storage Backend Decision
In-memory data grid (Redis Cluster or similar) is the optimal choice:
- Sub-millisecond read/write operations
- Atomic primitives: increment operations, compare-and-set, Lua scripting for multi-step atomicity
- Horizontal sharding by key hash
- Built-in TTL expiration for automatic cleanup
Alternative approaches fall short:
- Strongly consistent databases (PostgreSQL, etcd): Too slow for per-request writes. Synchronous replication and disk I/O push latency into double-digit milliseconds.
- Local memory only: Fastest possible, but breaks consistency. With N instances, total admitted traffic could reach N× the intended limit.
- Eventually consistent wide-column stores: Higher latency than pure in-memory; better suited for analytics than real-time decisions.
Redis replication is asynchronous, so primary failures may lose recent increments. Explicitly acknowledge this tradeoff: brief over-admission during failover is acceptable for this use case.
Algorithm Selection
| Approach | Memory per Key | Precision | Characteristics |
|---|---|---|---|
| Fixed window | One counter | 2× burst at boundaries | Simplest to implement |
| Sliding log | O(limit) timestamps | Exact | High memory cost at scale |
| Sliding window hybrid | Two counters | ~5% variance | Good balance |
| Token bucket | Token count + timestamp | Exact, configurable burst | Best for bursty workloads |
Sliding window counter provides a good default. It maintains current and previous window counters, estimating the current window as:
effectiveCount = currentCount + previousCount × (1 - elapsedFraction)
Token bucket works well when you want to permit short bursts while enforcing a steady rate. Tokens refill at a constant rate; requests consume tokens.
Both approaches use constant memory per key and require one storage round-trip per check. Avoid the sliding log approach at high scale due to memory overhead.
Handling Concurrent Updates
The problem: Two servers simultaneously read count=99 against limit=100. Both see quota available and both admit requests, exceeding the limit.
Avoid distributed locks. They require multiple round-trips, serialize access to popular keys creating a bottleneck, and risk deadlock or timeout issues if a lock holder crashes.
Use atomic operations within the storage layer:
-
Fixed window: The increment operation returns the new value atomically. Reject if the returned value exceeds the limit. Set expiration only when creating the key (value=1) to avoid race conditions.
-
Token bucket or sliding window: Implement as a Lua script. The storage engine executes scripts atomically without interleaving, making the entire read-check-update sequence one atomic operation.
Example token bucket script structure:
-- Retrieve current tokens and timestamp
-- Calculate refill based on elapsed time
-- Cap at maximum capacity
-- Check if sufficient tokens exist for this request
-- If yes: deduct tokens; if no: leave unchanged
-- Update stored state
-- Set expiration for cleanup
-- Return decision
Clock drift consideration: Different servers may report slightly different timestamps. Either use the storage engine's internal clock command (ensures monotonicity), or implement safeguards to never let timestamps move backward.
Addressing Hot Keys
When a single identifier generates millions of requests, all operations hit one storage shard. This creates two problems: that shard becomes a bottleneck, and other keys sharing the shard experience degraded performance.
Mitigation strategies, ordered by implementation complexity:
1. Local rejection caching: Once a key exhausts its quota, cache that state in each instance's memory with an expiration. Subsequent requests are rejected locally without storage calls. This alone handles most abuse scenarios with zero additional complexity.
2. Token batching: Instead of checking storage for every request, each instance atomically claims a chunk of quota (e.g., 1% of the limit) and tracks it locally. Requests consume from the local batch. When exhausted, claim another batch. This reduces storage calls by ~100× for hot keys, at the cost of bounded over-admission (roughly one batch size per active instance).
3. Key fragmentation: Split a hot key into N sub-keys (identifier#0 through identifier#N-1), each with quota limit/N. Route requests to sub-keys via hash or random selection. This distributes load across storage shards. The downside is quota imbalance—if traffic isn't uniformly distributed across sub-keys, some may exhaust while others have quota remaining.
4. Tiered detection: Monitor per-key request rates. When a key exceeds thresholds (say, 10% of total traffic), automatically promote it to a specialized handling path with batching or fragmentation. Demote when traffic normalizes. This keeps the common case simple while handling outliers.
High Availability Strategies
Storage layer: Deploy with replication. Each shard has a primary and at least one replica. On primary failure, promote a replica. Accept brief inconsistency during failover.
Checker layer: Run multiple instances behind load balancing. They're stateless except for local caches, so any instance failure is transparent.
Failure modes:
- Storage unreachable: Choose either fail-open (allow all requests, risking abuse) or fail-closed (reject all, ensuring protection). Most systems fail-open with circuit breaker logic—after consecutive failures, temporarily stop calling storage and admit traffic, avoiding cascading failures.
- Configuration service down: Continue using cached rules. They're read-heavy and change infrequently, so local caches remain valid for minutes or hours.
Monitoring: Track check latency percentiles (p50, p99, p999), rejection rates per key, storage node health, and cache hit rates. Alert on latency spikes or storage failures.
Common Mistakes to Avoid
- Using distributed locks for coordination—adds latency and becomes a bottleneck
- Storing every request timestamp—memory cost becomes prohibitive at high limits
- Ignoring clock drift between servers—can cause incorrect calculations
- Not planning for hot keys—one abusive client can degrade service for everyone
- Forgetting to set TTLs—stale keys accumulate and waste memory
- Synchronous cross-region checks—adds unacceptable latency
Extensions and Follow-ups
Multi-region: Enforce per-region limits to keep latency low, then aggregate metrics asynchronously for global visibility.
Dynamic limits: Store per-key overrides in the configuration service. Check key-specific rules first, falling back to defaults.
Quota borrowing: Allow brief overdrafts with exponential backoff penalties, smoothing out spiky traffic while still protecting the system.
Cost-based throttling: Different operations consume different quota amounts. Heavy operations (database writes) cost more tokens than lightweight ones (cache reads).