Core Concepts
Rate Limiting
Share one allowance across an account's requests, then handle bursts, concurrent checks, and limiter failures.
A rate limit defines how much traffic a caller can send in a given period. Decide who shares that allowance before you choose how to count requests.
Decide what the allowance covers
For the Reports API, account A17 has one key for its daytime dashboard and another for its nightly exporter. The gateway verifies the credential and resolves it to account A17. It looks up one allowance by account ID. Other customers who share A17's office network keep their own allowances. Counting by IP address would group those callers together. Counting by API key would give A17 a new allowance for each key.
On the normal path, the gateway spends one unit before passing a request to the Reports API. The request uses its unit even if the Reports API returns an error. When the limiter determines the account has no allowance left, the request stops at the gateway. With one gateway, an in-memory counter is enough to try this policy, so long as the gateway can tolerate allowance resetting on restart.
A fixed window resets all at once
Start with a rule that allows 10 requests per second. The gateway keeps one counter for account A17 in the second from 0 to 1, then a fresh counter in the second from 1 to 2. These periods are fixed windows.
A17 can use ten permits at 0.990 seconds and ten more at 1.010 seconds. The two bursts are just 20 milliseconds apart, but each has a separate window and both pass. If the actual rule is at most ten requests within any trailing second, keep a sliding-window log of accepted request times. At each arrival, remove entries at or before the one-second cutoff, count the remaining entries, and record the new arrival only if there is room. At 1.010 seconds, the previous ten entries are still present, so the new requests are rejected.
The log enforces the rolling rule at the resolution of its clock and keeps one entry per accepted request. If several requests have the same timestamp, each still needs a separate entry. A fixed window keeps only a counter per account and active window. Use the log if the rolling boundary is part of the promise. Redis rate limiter algorithm comparison
Save up credit for a burst
Now change the policy. A17 can send 10 requests per second over time and may send up to 20 immediately after a quiet period. A token bucket gives the account an available balance. One request costs one token. Elapsed time adds 10 tokens per second, up to a capacity of 20. Amazon API Gateway also uses a token bucket, with best-effort throttling targets. Amazon API Gateway token bucket settings
After a quiet period, A17 sends 20 requests together and empties the bucket. One more at that instant gets 429 Too Many Requests. After 100 milliseconds, one full token has accrued and the next request can spend it. The account can use its stored allowance and any additional refill in the same one-second interval. If the policy promises a hard rolling cap, that extra burst credit would violate it.
The owner stores the balance and the time of the last update. When a request comes in, it computes min(capacity, saved balance + elapsed seconds × refill rate). It spends one token if there is a full token available and saves the updated balance and time. Keep fractional credit across checks so two arrivals 50 milliseconds apart can accumulate one token over 100 milliseconds.
When the balance is below one token, divide the missing credit by the refill rate to estimate when a full token will be available. HTTP lets Retry-After use a date or whole seconds. The Reports API uses whole seconds and rounds the computed 100-millisecond wait up to Retry-After: 1. Other requests on A17 may spend the next token first. HTTP 429 · HTTP Retry-After
Let one owner spend the last token
Add a second gateway. If both keep separate buckets, each can spend up to 20 saved tokens. Instead, both gateways send checks for account A17 to the same bucket owner, the service or shard that holds its allowance state. Routing by account ID lets different accounts use different owners as traffic grows.
A17 has one token left. Gateway A reads one. Gateway B also reads one before A saves the debit. If the read and write happen in separate steps, both requests can pass.
We need one atomic operation per check, so the refill, decision, and saved debit happen together with no competing check in between. A short Redis script can do those steps where the bucket lives. The second check starts with the state the first check left behind. If it runs before another full token refills, it returns 429. Redis atomic script execution
Use the owner's clock for elapsed time so both gateways share the same timing reference. If the clock moves backward, give no refill for that interval and keep the last saved timestamp. With capacity 20 and refill 10 per second, even an empty bucket fills in two seconds. Once that much real time has passed since its last update, a bucket can expire because a new full bucket behaves the same. Redis expiry uses wall-clock time. A forward clock jump or early eviction can make a depleted bucket disappear too soon. Preserve the state or withhold decisions when the owner cannot establish that enough time has elapsed. Redis expiration
A17 can still be busier than its owner can handle. All of its checks, even rejections, arrive at that owner. Measure peak check latency and set a short deadline so a slow shard ties up as few gateway requests as possible.
Decide what to do when the check fails
If the limiter reports a spent allowance, the gateway returns 429. If the gateway cannot get a decision by its deadline, this API returns 503 Service Unavailable and withholds the request. The walkthrough calls this failing closed. Gateways that can still reach a usable owner continue checking and forwarding requests. An API that can absorb extra traffic may choose to fail open, allowing requests when the check is unavailable and accepting that callers can exceed their allowances during the outage. HTTP 503
A deadline can expire after the owner spent the token but before the reply arrived. The gateway holds back that request. Repeating a check blindly can spend another token. Accept the occasional debit for an unforwarded request or make check retries safe with a stable check ID and a saved decision.
Replica promotion has a different failure mode. If the old Redis primary saves a debit but its replica takes over before copying it, the new owner can restore the spent token. Redis Cluster can acknowledge a write before the replica receives it. Redis Cluster write safety
To enforce a strict token-bucket limit during failover, first prevent the old owner from admitting more requests. A replacement that has the latest balance and timestamp can carry on with the same allowance. If the balance is unknown, the replacement can start empty and refill from the handoff using a reliable clock. It may reject requests the old bucket still had credit for, but it stays within the ceiling. Token-bucket conformance
Track allowance rejections and unavailable checks separately. A rise in 429 responses points to customers reaching their policy. A rise in limiter-related 503 responses points to the dependency or its network path. The Reports API also needs a capacity check of its own. Many accounts can stay within their allowances and still send more simultaneous work than the service can handle.
See also
- Redis covers atomic updates and the persistence choices for shared state.
- Idempotency explains how to repeat a check after losing its result.
- Database Sharding covers splitting keys across owners and the effect of a hot key.
- Backpressure and Load Shedding protects shared capacity when requests can still fit their account policies.
Used in
- Rate Limiter applies the refill and debit together across gateways and handles a failed limiter check.
- ChatGPT checks minute and day limits together for an account, then admits work only when concurrent slots are available.
Done reading? Mark it so it sticks in your dashboard.