A rate limiter decides whether a request may proceed. It protects services from accidental overload, abusive clients, expensive operations, and unfair resource usage.
The decision is simple in a single process: increment a counter and compare it with a limit. It becomes interesting when thousands of application instances must enforce the same policy at the same time.
Let’s define the requirements, compare the main algorithms, build a working design, and then solve the problems introduced by distribution.
Functional Requirements: What Should the System Do?
For the initial version, we’ll support four features:
- Limit requests by a configurable key. A policy may apply to a user, API key, IP address, tenant, or endpoint.
- Allow a burst and control the sustained rate. For our running example, a full bucket holds 60 tokens and refills at 1 token per second. The client can spend its saved tokens together, then must wait for capacity to refill.
- Return a decision and useful metadata. The caller receives whether the request is allowed, the remaining capacity, and when it should retry.
- Update policies without redeploying applications. Operators can change limits centrally.
The limiter is not an authentication system. It must derive trustworthy identities from authenticated context or a trusted proxy, not blindly accept a client-supplied user ID or forwarded IP header.
Outside the initial scope: billing-grade quotas, bot detection, global traffic shaping, and permanently banning abusive users. Multi-region deployment is a later extension, not part of the first regional implementation. Those systems can consume rate-limit signals, but they have different correctness and operational requirements.
Non-Functional Requirements: How Well Should It Perform?
These are design goals for our hypothetical system:
| Requirement | Design goal |
|---|---|
| Low latency | Add less than 5 ms at p95 on the healthy regional decision path; measure outage and cross-region paths separately. |
| High availability | If the limiter is temporarily unavailable, each protected API follows a configured fallback. For example, product reads may continue with a small local limit, while login attempts may be rejected for safety. |
| Correctness | One Redis primary atomically checks and consumes each bucket. State the possible over-admission from failover or fallback explicitly. |
| Scalability | Target 1 million decisions/s across many keys; protect the system from hot keys without assuming one bucket can use several shards. |
| Configurability | Target policy propagation within one minute while the policy-distribution path is healthy. |
| Observability | Keep simple counters for allowed, rejected, and failed checks so operators can spot problems without storing a log for every request. |
Capacity Estimation
Assume the protected platform receives:
- 500,000 requests per second on average
- 1 million requests per second at peak
- 10 million active rate-limit keys during a busy window (a sizing assumption explained below)
- 100 bytes of logical state per active key
Every request needs one rate-limit decision, so the limiter must sustain 1 million decisions per second at peak.
Work through key counts and Redis memory
Why 10 million keys? A key is one bucket being tracked, such as user:8472, tenant:42, or login:203.0.113.10. One user can also create multiple keys when different endpoints have different policies. We assume that, during the busiest bucket-expiration window, about 10 million distinct user, tenant, IP, and endpoint combinations are active at least once. This number is not calculated from 1 million RPS; it is a separate workload assumption that should come from product traffic data. We use it to estimate memory.
Using the powers-of-ten method from System Design Interview Math: Round Faster, Estimate Better:
10 million keys = 10^7 keys
100 bytes/key = 10^2 bytes/key
10^7 keys × 10^2 bytes/key
= 10^9 bytes
= 1 GB of logical state
The key units cancel, leaving bytes. Since 10^9 bytes is 1 GB, the raw bucket data is about 1 GB. This is only the logical state. Real memory usage will be higher because Redis also stores the key text, value structure, expiration metadata, allocator overhead, and replication buffers. If a complete in-memory entry averages 250 bytes, then 10 million × 250 bytes = 2.5 GB for the working set, before replicas and safety headroom.
The total rate does not reveal the hardest load pattern. One popular tenant or one shared IP behind a carrier-grade NAT could create a hot key receiving hundreds of thousands of decisions per second.
API Design
The rate limiter usually sits behind a local client library or a gateway filter, but its logical interface can be represented as an API.
Check and Consume Capacity
Endpoint: POST /v1/limits/check
{
"policy_id": "write-comments",
"key": "user:8472",
"cost": 1
}
The gateway is the trusted caller of this internal interface. Here, key identifies user 8472 and policy_id selects the server-managed rule. The response limit means bucket capacity, which is 60 in our example.
The service performs one atomic operation: check the available capacity and consume cost only if the request is allowed. A separate check followed by decrement would be unsafe because concurrent callers could all observe the same capacity.
Allowed response:
{
"allowed": true,
"limit": 60,
"remaining": 42,
"retry_after_ms": 0
}
Rejected response:
{
"allowed": false,
"limit": 60,
"remaining": 0,
"retry_after_ms": 380
}
The gateway translates a rejection into an HTTP response such as:
HTTP/1.1 429 Too Many Requests
Retry-After: 1
RateLimit-Limit: 60
RateLimit-Remaining: 0
Retry-After tells the client how long to wait before trying again. In this example, the limiter calculates a wait of 380 milliseconds, but this HTTP header uses whole seconds. The gateway therefore rounds the value up to 1, meaning “try again after one second.” Rounding up prevents the client from retrying too early.
The RateLimit-Limit and RateLimit-Remaining names are illustrative API headers, not a promise that every service uses the same convention. Rate-limit header specifications continue to evolve, so the public API must document the exact field names, units, and meaning of “remaining” for its chosen algorithm.
| Status | Meaning |
|---|---|
200 OK |
The decision completed; inspect allowed. |
400 Bad Request |
Unknown policy or a request cost greater than the bucket capacity. |
422 Unprocessable Content |
Invalid request fields in the FastAPI example below. |
503 Service Unavailable |
The limiter could not make a decision and the caller must apply its configured failure policy. |
Choosing a Rate-Limiting Algorithm
Choose an approach below to expand its explanation, worked example, and tradeoffs. You can keep several approaches open to compare them.
The easiest way to understand the algorithms is to watch the same client send requests over time. In the illustrations below, A means allowed and R means rejected.
1. Fixed Window CounterSimple counters; bursts near window boundaries
Split time into fixed windows and keep one counter for each window. Suppose the limit is three requests every 10 seconds:
First window Next window
0s ----------------------------- 10s ----------------------------- 20s
7s 8s 9s | 11s 12s 13s 14s
Request A A A | A A A R
Window counter 1 2 3 | 1 2 3 4
↑ resets to 0 at 10s
The first three requests use the first window’s allowance. At exactly 10 seconds, the counter resets to zero, so the requests at 11, 12, and 13 seconds are also allowed. The request at 14 seconds is the fourth request in the new window, so it is rejected. This method is simple and uses little memory.
Challenge: The client sent six requests between 7 and 13 seconds, a period of only six seconds, even though the limit sounds like “three requests per 10 seconds.” Requests near the boundary can use the end of one window and the start of the next window to create a larger burst.
2. Sliding LogPrecise tracking; stores a timestamp per allowed request
Store the time of every allowed request. For each new request, remove timestamps older than 10 seconds and count what remains:
Limit: 3 requests in the previous 10 seconds
12s request arrives
look back 10 seconds
2s ---------------------------------------------- 12s
4s(A) 8s(A) 11s(A) 12s(R)
└──────── three requests ───────┘
At 12 seconds, the requests at 4, 8, and 11 seconds are still inside the previous 10 seconds. The new request is rejected. This method matches the rule very accurately.
Challenge: A busy client needs many timestamps. A limit of one million requests per hour could require storing up to one million timestamps for just one key, plus continuously deleting old entries.
3. Sliding Window CounterCompact state; estimates the rolling request count
Keep only the current and previous fixed-window counters. Estimate how much of the previous window still overlaps the last 10 seconds:
Previous window: 6 requests Current window: 2 requests
0s ------------------------- 10s ------------------------- 20s
now = 12s
Assumption: requests were spread evenly across the previous window
80% of the previous window still overlaps the last 10 seconds
estimated count = (6 × 80%) + 2 = 6.8 requests
At 12 seconds, the rolling 10-second range starts at 2 seconds. Eight seconds of the previous 0s to 10s window still overlap that range, so the algorithm uses 80% of the previous counter. It does not know when those six requests actually arrived. It assumes they were spread evenly and estimates that 6 × 80% = 4.8 of them belong in the rolling window. It then adds the two requests from the current window.
This uses much less memory than a sliding log because it stores two counters instead of every timestamp.
Challenge: It is an estimate. The calculation assumes requests were spread evenly through the previous window. If all six actually arrived near its beginning or end, the estimated count can be different from the real count.
4. Leaky BucketSmooth traffic; queued requests must wait
Put requests into a queue and release them at a steady rate, like water leaving a bucket through a small hole:
Five requests arrive together
time 0s 1s 2s 3s 4s
queue [1 2 3 4 5] → [2 3 4 5] → [3 4 5] → [4 5] → [5] → empty
sent 1 2 3 4 5
The downstream service receives smooth traffic instead of a sudden burst.
Challenge: Requests wait in the queue, which increases latency. If the queue becomes full, new requests must be rejected. This is useful when work can wait, but less natural when an API needs an immediate allow-or-reject answer.
5. Token BucketAllows short bursts while controlling the sustained rate
A token is permission to send one request. The bucket has two settings: capacity 60 and refill rate 1 token/s. It starts full and never stores more than 60 tokens.
For every request:
- Refill. Add the tokens earned since the previous update.
- Cap the balance. Keep at most 60 tokens.
- Decide and save. If enough tokens remain, spend the request’s cost and allow it. Otherwise reject it and calculate the wait until enough tokens refill.
balance = min(capacity, old_balance + elapsed_seconds × refill_rate)
| Time | Request | Balance before spending | Result |
|---|---|---|---|
| 0s | First request | Full bucket: 60 | Allow; save 59 |
| 3s | Next request | min(60, 59 + 3) = 60 | Allow; save 59 |
| 3s | Another request | No time passed: 59 | Allow; save 58 |
| 10s | Next request | min(60, 58 + 7) = 60 | Allow; save 59 |
| Same instant, after the remaining tokens are spent | One more request | 0 | Reject; retry after 1 second |
Store tokens and last_refill together. No background timer needs to add tokens every second; the next request calculates the refill from elapsed time.
This is not a strict rolling limit of 60 requests in every minute. A full bucket can allow a burst and then admit refilled tokens during that same minute. The sustained refill rate is 60 tokens/minute. Use a sliding-log policy if the requirement instead demands an exact count over every rolling window.
The refill, decision, and deduction must be atomic. Otherwise, two callers could both spend the last token. Problem 1 explains how Redis handles that race.
Recommended algorithm
We’ll choose the token bucket because it directly matches our requirement: allow short bursts while enforcing a long-term rate.
High-Level Design: Follow One Request
The gateway asks the limiter for an allow-or-reject decision. It forwards the original request to the protected service only after an allowed result. The limiter does not relay the business request itself.
1. Identify the Caller and Policy
Client → API Gateway → Rate-limiter service
- The gateway authenticates the caller or obtains an IP from a trusted proxy.
- It chooses the policy, such as
write-comments, from the endpoint configuration. - It passes the verified identity and request cost to the limiter. Client-provided user IDs must not select someone else’s bucket.
The resulting bucket key is rate_limit:write-comments:user:8472. The same user and policy must reach the same shared state even when requests hit different gateway instances.
2. Support Bursts and a Steady Rate
Limiter → Local policy cache → Redis bucket
- Read the rule locally. The cached
policiesrecord suppliescapacity,refill_rate, andfailure_mode. - Read and update one bucket. A Redis hash stores
tokensandlast_refill. Run refill, cap, check, deduction, and save in one atomic script. - Expire idle state. A missing bucket starts full. Choose its idle expiry no shorter than the time an empty bucket takes to refill completely; deleting it sooner would grant tokens early.
The bucket is request state; the policy is configuration. The policy database is not queried for each decision, and we do not need a multi-table database transaction to update this one Redis key.
3. Return the Decision and Metadata
Redis → Limiter → Gateway → Protected service or 429
If allowed, return the remaining whole-token count and let the gateway forward the request. If rejected, return the refill wait and let the gateway answer 429 Too Many Requests with a rounded-up Retry-After value. If the limiter cannot decide, use the policy’s failure behavior from Problem 4.
4. Update Policies Without Redeploying
Policy store → Background loader → Each limiter’s local cache
Keep durable policies records keyed by policy_id, with capacity, refill rate, failure mode, version, and update time. A database such as DynamoDB can hold them; a versioned configuration file also works.
Validate and publish a new version, then refresh local caches within the one-minute target while distribution is healthy. Keep the bucket identity stable when a version changes. Clamp a saved balance to a reduced capacity rather than deleting the bucket and granting a fresh burst. Document how a changed refill rate applies at the next update.
During a configuration outage, ordinary policies can use their last valid rules; sensitive policies need a configured expiry and conservative fallback. This is a separate decision from what to do when Redis itself fails.
Problem 1: Concurrent Requests Spend the Same Token
A naive implementation reads the bucket, calculates the new balance in the application, and writes it back. Two instances can read 1 token at the same time, both allow their request, and both write 0. We have admitted two requests using one token.
Redis must perform the refill, check, token deduction, and state update as one atomic operation. A Lua script or Redis Function can do this so no other request can modify the same bucket halfway through the calculation. Inactive bucket keys receive an expiration time so Redis can remove them automatically.
Practical Redis Example
The Python API receives a rate-limit request and calls one Lua script in Redis. The example uses the same capacity of 60 tokens and refill rate of 1 token per second.
This is a local demonstration for one cached policy. Authentication and the background policy loader are omitted; production calls must come through a trusted gateway.
Save this as app.py:
from pathlib import Path
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from redis.asyncio import Redis
from redis.exceptions import RedisError
app = FastAPI()
redis = Redis.from_url("redis://localhost:6379", decode_responses=True)
token_bucket_script = Path(__file__).with_name("token-bucket.lua").read_text()
POLICIES = {"write-comments": {"capacity": 60, "refill_rate": 1}}
class LimitRequest(BaseModel):
policy_id: str
key: str = Field(min_length=1, max_length=200)
cost: int = Field(default=1, ge=1)
@app.post("/v1/limits/check")
async def check_limit(request: LimitRequest):
policy = POLICIES.get(request.policy_id)
if policy is None:
raise HTTPException(400, "Unknown policy")
if request.cost > policy["capacity"]:
raise HTTPException(400, "Request cost exceeds bucket capacity")
redis_key = f"rate_limit:{request.policy_id}:{request.key}"
try:
allowed, remaining, retry_after_ms = await redis.eval(
token_bucket_script,
1,
redis_key,
policy["capacity"],
policy["refill_rate"],
request.cost,
)
except RedisError as error:
raise HTTPException(503, "Rate-limit decision unavailable") from error
return {
"allowed": bool(allowed),
"limit": policy["capacity"],
"remaining": remaining,
"retry_after_ms": retry_after_ms,
}
The API passes one Redis key followed by the capacity, refill rate, and request cost. Redis then executes the following script as one atomic operation.
Save this as token-bucket.lua:
-- KEYS[1] = rate-limit key
-- ARGV[1] = capacity, for example 60
-- ARGV[2] = refill rate per second, for example 1
-- ARGV[3] = tokens spent by this request
local SCALE = 1000000
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local capacity_units = math.floor(capacity * SCALE)
local refill_units_per_second = math.floor(refill_rate * SCALE)
local cost_units = math.floor(cost * SCALE)
if capacity_units <= 0 or refill_units_per_second <= 0 or cost_units <= 0
or cost_units > capacity_units then
return redis.error_reply('invalid capacity, refill rate, or cost')
end
local time = redis.call('TIME')
local now_ms = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local bucket = redis.call('HMGET', KEYS[1], 'tokens', 'last_refill')
local tokens = tonumber(bucket[1]) or capacity_units
local last_refill_ms = tonumber(bucket[2]) or now_ms
now_ms = math.max(now_ms, last_refill_ms)
local elapsed_ms = now_ms - last_refill_ms
local earned = math.floor(elapsed_ms * refill_units_per_second / 1000)
tokens = math.min(capacity_units, tokens + earned)
local allowed = 0
if tokens >= cost_units then
tokens = tokens - cost_units
allowed = 1
end
local retry_after_ms = 0
if allowed == 0 then
local missing = cost_units - tokens
retry_after_ms = math.ceil(missing * 1000 / refill_units_per_second)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_refill', now_ms)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / refill_rate) * 2)
local remaining = math.floor(tokens / SCALE)
return {allowed, remaining, retry_after_ms}
Start a local Redis server on port 6379, then install the dependencies and start the API:
pip install fastapi uvicorn redis
uvicorn app:app --reload
The Lua script returns 1 when the request is allowed and 0 when it is rejected. It also returns the whole-token balance and the retry delay promised by the API. Internally, time is measured in milliseconds and each token is stored as one million integer units. This fixed-point representation supports gradual refills. Policy validation must keep values within the script’s supported numeric range. Clamping time to the previous update avoids granting the same elapsed time twice after a backward clock adjustment.
Every Python API instance calls the same script, and Redis completes the entire script before processing another command. Two instances therefore cannot spend the same token.
If a request times out after Redis has already deducted a token, retrying may spend another token. Simple APIs often accept this rare extra count. Expensive operations can attach a unique request ID so the same request is not charged twice. The underlying race-condition and atomicity concepts are covered in Understanding Concurrency, Part 1: Counters, Locks, Redis, and Databases.
Problem 2: A Single Redis Node Is a Single Point of Failure
A single Redis node can fail or become overloaded. These are different problems with different solutions:
| Problem | Solution | What it does |
|---|---|---|
| The Redis primary fails | Replicas and automatic failover | A replica copies the data and becomes the new primary after a failure. |
| One primary cannot handle the traffic or memory | Sharding | Keys are divided across multiple Redis primaries so they share the load. |
For our estimated load, sharding is required because of traffic. The roughly 2.5 GB working set can fit in one Redis node’s memory, but the peak is 1 million atomic rate-limit decisions per second. We should not send all of that traffic to one primary.
The exact shard count must come from a load test of our Lua script and hardware. For example, if one primary can safely handle 100,000 decisions per second under the target latency, the basic calculation is:
1,000,000 peak decisions/s ÷ 100,000 decisions/s per shard
= 10 primary shards
The 100,000 figure is a planning assumption, not a universal Redis limit. Add extra shards for traffic growth and capacity headroom.
How Keys Reach a Shard
Redis Cluster hashes each key into a slot, and each slot belongs to one shard. Text inside {} is called a hash tag. When braces are present, Redis hashes only the text inside them:
rate_limit:{user:8472}:comments → hash user:8472 → shard A
rate_limit:{user:8472}:uploads → hash user:8472 → shard A
rate_limit:{user:9321}:comments → hash user:9321 → shard B
The first two keys use the same hash tag, so they reach the same shard. This is useful when one Lua script or transaction must work with related keys. Different hash tags usually spread users across different shards. If each rate-limit decision touches only one key, hash tags are optional.
Can We Use Consistent Hashing?
Yes. A custom client can use consistent hashing to map each key to a Redis node. When a node is added or removed, only part of the keys move. However, Redis Cluster already provides key placement, node discovery, and hash-slot movement. Use Redis Cluster unless the system has a specific reason to manage sharding itself.
Why Replicas Are Still Required
Sharding spreads load, but it does not create a backup. If shard A fails, every key stored on shard A becomes unavailable.
Give each primary shard at least one replica:
Primary shard A → Replica A
Primary shard B → Replica B
The primary processes token updates, and its replica copies the data. If the primary fails, Redis promotes the replica and the shard becomes available again. Replicas provide availability; they do not normally increase write capacity because rate-limit decisions must update the primary.
Redis Cluster normally replicates writes asynchronously. A primary can acknowledge a token deduction and fail before its replica receives that update. If the replica is promoted, its older balance may temporarily restore already-spent tokens and allow extra requests. This is usually an acceptable availability tradeoff for ordinary API limits, but it must be stated explicitly. Security-sensitive policies can use a more conservative fallback or stronger coordination at the cost of latency and availability.
Problem 3: One Hot Key Can Overload a Shard
A hot key is one rate-limit key that receives far more requests than other keys. For example, a large customer may send 300,000 requests per second through one shared API key.
Redis Cluster sends every request for that API key to the same shard because all requests must update the same token balance atomically. The result can look like this:
Shard A: 300,000 decisions/s from one hot key
Shard B: 70,000 decisions/s from many normal keys
Shard C: 65,000 decisions/s from many normal keys
Adding more normal shards does not split the hot key. Adding a random suffix to the key would spread its requests, but it would also create separate token balances and could allow the customer to exceed the intended limit.
Choose a solution based on the traffic pattern and how strict the limit must be.
Option 1: Route a Known Customer to a Dedicated Shard
Keep a small routing configuration that maps unusually busy tenants to dedicated Redis connections. Everyone else continues using the shared cluster:
def redis_for(tenant_id: str):
if tenant_id in dedicated_redis:
return dedicated_redis[tenant_id]
return shared_redis_cluster
redis = redis_for(tenant_id)
redis.evalsha(token_bucket_sha, 1, rate_limit_key, 60, 1, 1)
Store this routing map in configuration so it can be changed without redeploying the application. The dedicated shard should have its own replica. This isolates the tenant from other customers, but it does not make one bucket use several CPUs or shards. Its legitimate decision rate must still fit that primary. A dedicated shard cannot by itself solve a 300,000-decisions/s hot key if that primary is safe only up to 100,000 decisions/s.
Option 2: Add a Local Protection Limit Before Redis
Run a small in-memory limiter inside each gateway before calling the shared Redis limiter:
Request
→ local gateway limit
→ obvious flood: reject immediately
→ accepted locally: check the exact shared limit in Redis
For example, if one gateway receives 100,000 requests per second from one key, its local limit might allow only 5,000 of them to reach Redis. Redis still makes the final decision using the shared token balance.
The local limit is protection for Redis, not a replacement for the global limit. Different gateways have separate local counters, so the local result alone cannot enforce an exact system-wide allowance.
In practice, these options can be combined. Use a local protection limit for sudden floods and dedicated shards for a small number of permanently large customers.
Problem 4: The Limiter Fails
If Redis or the network is unavailable, the gateway must choose between two imperfect outcomes:
- Fail open: allow the request. Availability remains high, but the protected service may be overloaded or abused.
- Fail closed: reject the request. Protection remains strict, but a limiter outage becomes an application outage.
Choose a fallback for each policy
Configure this per policy:
| Endpoint type | Suggested failure behavior | Reason |
|---|---|---|
| Product reads | Fail open with a small local emergency limit | Preserve availability while bounding one instance’s traffic |
| Login attempts | Fail closed or use a conservative local limit | Brute-force protection matters more than availability |
| Expensive writes | Fail closed | Unbounded admission could create high cost or duplicate work |
| Internal health checks | Bypass the remote limiter | Avoid circular failure during recovery |
A local emergency bucket should have a deliberately small allowance. It is not synchronized across instances, so total admission can be roughly the local allowance multiplied by the number of instances.
Do not make every request wait a long time when Redis is unavailable. Set a short timeout, such as 50 milliseconds. If several checks fail in a row, a circuit breaker stops calling Redis for a short period and immediately uses the configured fallback, such as a small local limit or rejecting the request. It occasionally tries Redis again. When Redis responds successfully, normal rate-limit checks resume.
Problem 5: Multiple Regions Need One Limit
A synchronous global bucket requires a cross-region round trip or a globally consistent datastore on every request. That increases latency and makes a regional network partition part of the request path.
Option 1: Divide the Budget Between Regions
For high-volume policies, split both the refill rate and burst capacity. For example, a global refill rate of 1,000 tokens/s and capacity of 1,000 can be divided as follows:
| Region | Refill rate | Capacity |
|---|---|---|
| US | 600 tokens/s | 600 tokens |
| India | 400 tokens/s | 400 tokens |
| Total | 1,000 tokens/s | 1,000 tokens |
Each request checks its region’s Redis bucket without a cross-region call. Unused US capacity cannot automatically be spent in India.
Changing the allocation needs coordination. Reduce the old region’s budget before increasing another region’s budget, and version allocations with an expiry. A disconnected region must not keep spending an expired allocation while another region uses its replacement. If a safe handoff cannot finish, keep the smaller budget rather than granting both old and new allowances.
Do not give every region the full global refill rate or full burst capacity. A regional configuration change must not reset its bucket to a new full balance.
Option 2: Route Each User to a Home Region
Use this approach when one exact token balance matters, such as login protection. Assign each user a home region with consistent hashing and send all rate-limit checks for that user there:
home_region = consistent_hash(user_id)
user:8472 → India
user:9321 → US
If user:8472 sends a login request to the US region, the US gateway asks the India rate limiter for the decision. Every login attempt for that user reaches the same Redis bucket, so the regions do not keep independent allowances. The asynchronous-replica failover tradeoff from Problem 2 still applies; a home region alone does not guarantee lossless counting.
This provides stricter counting, but a request may need a cross-region call. If the home region is unavailable, the login policy can reject the request or apply a very small local emergency limit.
Use regional allocation for high-volume APIs where low latency matters. Use a home region for security-sensitive limits where exact counting matters more than cross-region latency.
Where We Have Arrived
We started with one regional allow-or-reject decision. The final design adds more limiter instances and Redis shards while keeping one primary responsible for each bucket.
- Identify the key. The gateway derives a trustworthy caller identity and policy, then applies a small local flood-protection limit.
- Apply the rule. A stateless limiter reads its local policy cache and atomically refills and spends tokens on the Redis primary owning that key.
- Allow or reject. The gateway forwards allowed requests; rejected requests receive
429and retry information. A limiter outage follows the configured policy fallback. - Update and scale. Refresh versioned rules without redeploying, add primary shards for many keys, and give each primary a replica. A hot key still needs protection or explicit isolation.
- Extend across regions when needed. Split rate and burst budgets for local decisions, or route a key to a home region when one shared bucket matters more than cross-region latency.
How We Address the Non-Functional Requirements
| Requirement | How the final design addresses it |
|---|---|
| Low latency | Keep policies in local memory, run one short Redis script, and keep normal checks regional. The p95 target below 5 ms needs load testing. |
| High availability | Give primary shards replicas and use short timeouts with a policy-specific fallback. Fallback trades exact enforcement against service availability. |
| Correctness | Atomic scripts prevent concurrent requests from spending the same token on one primary. Asynchronous failover and local fallback can still permit extra requests; this is not a billing-grade guarantee. |
| Scalability | Scale stateless limiters and shard many bucket keys. Test the exact script, network, and hot-key distribution before selecting shard counts. |
| Configurability | Validate versioned policy updates and distribute them to local caches, targeting one minute while the control path is healthy. Keep bucket identity stable across updates. |
| Observability | Record allowed, rejected, failed, and fallback counters plus latency histograms; use sampled logs rather than a durable write for every decision. |
These are design targets, not benchmark results. Test contention, Redis failover, policy changes, and the configured outage behavior before claiming the system meets them.
The gateway identifies and forwards requests. The limiter applies the policy. Redis owns the shared token balance for each key.
Interview tip: Explain one token bucket and one request first. Then show why the update must be atomic, how many keys use shards, and what happens when Redis cannot answer.
Join the discussion
Spot a mistake or have another perspective? Share your feedback, insights, or suggestions.