Building a Request Throttling Service That Scales Across Regions
System DesignModel answerLast updated
Design a service that decides per caller whether each API request is allowed, then scale it to many users and regions and make its limits more accurate, discussing the trade-offs.
Design a throttling service that checks every incoming API request and decides whether the caller who sent it is still within its permitted request quota. Requests over quota are rejected.
Each request carries a caller identifier, such as a user ID or API key. Traffic volume, caller count, quota sizes and latency budget are not specified, so state and justify your own assumptions. You may also ask clarifying questions, for example:
- Is the throttle in a gateway in front of the services, or called by each service?
- Is the quota the same for all callers, or does it vary by caller, plan or endpoint?
- If the throttle's storage is unreachable, should requests be allowed or blocked?
- Is it acceptable for a caller to exceed its quota by a few percent?
Answer in three parts.
Part 1: Basic design. Describe the components of a simple throttling service and trace a single request through them. Cover where the throttle sits, where rules and counters live, how a check reads and updates them, what a rejected client receives, and what operators can observe.
Part 2: Growth. The user base grows a great deal. How do you scale the service, which problems appear, and how do you address them? Consider counters shared across many throttle instances and how they are partitioned, atomic updates under concurrent requests from one caller, very busy callers, the latency added to every request, failure of the counter store, and traffic arriving in several regions.
Part 3: Better accuracy. How would you make the limiting more precise, and what does it cost? Consider the weakness of counting in fixed time buckets, alternative algorithms and their accuracy, memory and per-check cost, and the precision lost through distribution versus the latency and availability price of exact counting.
Hints
Hint 1
A single instance with in-process counters stops working as soon as you have two instances behind a load balancer. Think about where the counter must live and how to update it without a read-then-write race.
Hint 2
Decide the failure policy deliberately: fail open protects availability, fail closed protects the backend. Different endpoints may deserve different answers, and a short local fallback budget is a middle path.
Hint 3
Fixed buckets allow up to twice the limit around a boundary. Compare sliding-window log, sliding-window counter and token bucket on memory per caller, cost per check and accuracy, then ask how much exactness the use case really needs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Assume an API gateway fronting the services, about 100k requests per second at peak, millions of callers, limits that vary by plan and endpoint, and a budget of about 1-2 ms added per request. Assume a few percent of overshoot is tolerable for most traffic.
Part 1: Basic design
Components
- Enforcement point: a middleware in the gateway, so every request is checked before reaching a service and individual services need no throttling logic.
- Rules store: a config database holding limits keyed by caller, plan and endpoint. Instances cache rules in memory and refresh them periodically or via change notifications, so the hot path never queries the database.
- Counter store: a fast in-memory key-value store such as Redis, keyed by
caller:endpoint:window, with a TTL slightly longer than the window so old keys expire themselves. - Metrics and logs: counters for allowed and rejected requests, broken down by caller and rule.
Request path
- The gateway extracts the caller ID, for example from the API key, and the endpoint.
- It looks up the rule from the local cache, falling back to a default.
- It increments the counter and compares the result with the limit.
- If within the limit, the request is forwarded. If not, the gateway returns HTTP 429 with a
Retry-Afterheader and, usefully, headers showing the limit and remaining quota. - The decision is emitted as a metric, and rejections are sampled into logs for debugging and abuse analysis.
Part 2: Scaling up
Shared counters. Counting in each instance's memory fails because a caller's requests are spread over many instances, so the effective limit becomes the limit times the instance count. Counters must be shared. Partition the counter store by hashing the caller key (consistent hashing or Redis Cluster slots), so capacity grows by adding shards and each caller's counter lives on one shard.
Atomic updates. A read, compare, then write sequence races under concurrency and lets extra requests through. Use an atomic increment (INCR with EXPIRE set on first creation), or a Lua script that does the whole check-and-update in one server-side step. This is also needed for token bucket, where refill and decrement must happen together.
Latency. A network hop per request is the main cost. Mitigate with connection pooling, pipelining, and colocating the counter store with the gateway in the same zone. For very high volumes, let each instance take a batch of tokens (say 10% of a caller's quota) from the shared store and spend it locally, trading some accuracy for far fewer remote calls.
Hot callers. One caller can overload its shard. Options: local pre-aggregation with periodic syncs as above, splitting the caller's counter into N sub-counters spread over shards and summing them occasionally, or an in-process coarse check that rejects obviously abusive callers before touching the store. Very large abusers are better blocked at the edge or CDN.
Counter store failure. Choose a policy explicitly. Fail open keeps the API available but removes protection; fail closed protects the backend but turns a throttler outage into a full outage. A common compromise is fail open with a conservative local per-instance limit for a short period, plus alerts. Use replicas with automatic failover, accepting that a failover may lose a few recent increments, which is acceptable here.
Multiple regions. Cross-region synchronous counting adds tens of milliseconds and a new failure mode. Usual choices: give each region a share of the global quota (for example proportional to its traffic) and rebalance periodically, or replicate counts asynchronously and accept brief overshoot. Strict global limits are reserved for cases that really need them, such as billing quotas.
Operations. Monitor the rejection rate per rule, counter store latency and error rate, the fallback activations, and the skew between shards. Version and audit rule changes, since a bad limit can cause a self-inflicted outage.
Part 3: More precise limiting
Fixed-window weakness. A caller can send the full limit at the end of one window and again at the start of the next, reaching up to 2x the limit in a short span.
| Algorithm | Accuracy | Memory per caller | Cost per check |
|---|---|---|---|
| Fixed window counter | Poor at boundaries (up to 2x) | One integer | O(1) |
| Sliding window log | Exact | One timestamp per request | O(log n) or O(n) trimming |
| Sliding window counter | Good approximation, assumes even spread in the previous window | Two integers | O(1) |
| Token bucket | Controls average rate and allowed burst | Tokens plus last refill time | O(1) |
The sliding window counter estimates the count as current + previous * (1 - elapsed_fraction). It is usually accurate within a few percent and is the common default. A sliding log is justified only when limits are small and exactness matters, since memory grows with the limit. Token bucket suits APIs that should permit bursts while capping the sustained rate.
Distribution precision. Local batching, regional quota shares and asynchronous replication all let callers briefly exceed the limit. Exact global counting requires a single authoritative counter per caller and a synchronous call each time, which adds latency and ties availability to that counter. The practical answer is to tier: approximate limits for general traffic, exact limits for the few cases (payments, paid quotas) where overage costs money.
Common mistakes
- Keeping counters in instance memory and ignoring multiple instances.
- Non-atomic read-then-write updates.
- Not deciding what happens when the store is down.
- Querying the rules database on every request.
- Demanding exact global counting without discussing its latency cost.
- Forgetting a
Retry-Afterheader and metrics for operators.