Design Rate Limiting
How to design rate limiting for an AI API: where the checks sit, what to count, how servers share one count, and what happens on failure, explained simply for your AI interview.
In short
Rate limiting caps how much one caller can use in a set time window. Check cheap things at the gateway, count requests and tokens in one shared store so every server agrees, and reply with HTTP 429 and a wait time when someone goes over.
12 min readIntermediateCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
Rate limiting caps how much one caller can use in a set time, so one busy customer can't starve everyone else or run up the bill. I check cheap things at the gateway, count requests and tokens in one shared store so every server agrees, and send a 429 with a wait time when someone goes over. Batch work gets its own lane, so daytime users stay fast.
Start with the goal. The API must stay fast for everyone, and the bill must stay in budget. A rate limit caps how much one caller can use in a time window. I'd limit by user, API key and customer, because one customer's bad job shouldn't slow the rest.
Next, where the checks run. The gateway at the front rejects floods per IP address and per key, cheaply. The service then checks the caller's quota in requests and in tokens, because one request can be a short question or a 50,000-token document. Output tokens are only known when the model finishes, so I estimate them up front and correct the count at the end.
Then the shared count. Ten servers each allowing 100 a minute let through 1,000, so every server must read and update one shared store, with each check done as a single step. I'd use a token bucket: it refills steadily, allows short bursts, and never resets all at once. When someone goes over, the reply is HTTP 429 with a Retry-After time, and clients add jitter, a small random delay, so they don't all retry together.
Last, failure. If the counter goes down, I'd fail open for general traffic so users aren't locked out, and fail closed for spend caps. I'd accept a few extra requests, because an exact count is expensive. And I'd give batch jobs their own lane, so an overnight load can't slow daytime users.
What is rate limiting, in plain words?
A rate limit is a cap on how much one caller can use in a set time. The caller might be a person, an app, a customer or a batch job. The cap stops one caller from starving everyone else, and from running up a bill nobody agreed to.
Think of a turnstile at a stadium gate. It lets people through at a set pace, so one crowd can't block everyone behind it. An AI API needs the same guard, with one twist: a single request can cost a little or a lot, depending on how much text the model reads and writes.
Picture a contract-review app with 800 law-firm seats. One overnight job sends 40,000 requests. By nine in the morning the lawyers are still waiting for replies. A rate limit keeps that job in its own lane.
Key words
- Rate limit
- A cap on use within a time window, such as 60 requests a minute.
- Window
- The span of time a cap counts over, such as one minute or one day.
- Shared counter
- One place where all your servers record usage, so they agree.
- Token
- A small chunk of text, often a word or part of one, that the model reads and writes. Cost and speed grow with the number of tokens.
- HTTP 429
- The reply code for too many requests. It tells the caller to slow down and try again.
Where do the checks go, and what do you count?
Put cheap checks first and precise checks near the model. The gateway, the front door of the API, rejects floods per IP address and per API key (the secret code an app sends to identify itself) before they cost anything. The service then checks the caller's own quota, in tokens as well as requests, before it calls the model.
How one request passes the checks
Lawyer's app
one seat, daytime use
Overnight batch
40,000 requests in one go
Gateway check
per key and per IP, cheap
Shared counter
one count for every server
Model call
output tokens counted after reply
429 reply
with a Retry-After time
Reply
inside the limits
- 1The request reaches the gateway, which rejects floods cheaply.
- 2The overnight job arrives at the same gateway, and is counted like any caller.
- 3The gateway asks the shared counter whether this caller has room left.
- 4Under the limit, the request goes on to the model.
- 5Over the limit, the caller gets a 429 reply with a wait time.
- 6The model's answer goes back to the caller.
- Who
Key the count
Per user, per API key and per customer, with a per-IP limit for people who aren't signed in. One customer's jobs must not use up anyone else's count.
- What
Count two things
Requests catch floods. Tokens track cost, because one long document costs far more than one short question.
- Where
Check at the front door
Reject cheap bad traffic at the gateway. Keep the exact token check beside the model, where the request is read.
“Rate limits are defined at the organization level and at the project level, not user level.”
OpenAI
So the per-user layer is yours to design. OpenAI sets its own limits per organisation and per project, and an API you build sits on top of that with its own keys and lanes. Anthropic sets separate per-minute limits for input tokens and output tokens, so you may need both counts too.
Tip
Asked what to count? Say both: requests to stop floods, tokens to control cost. Then name the key, the window and the reply.
What happens when a caller goes over, or the store fails?
The reply should be clear. Return HTTP 429 with a Retry-After header, and the client waits that many seconds. Anthropic's docs describe the same rule for their API, and say a 429 names which limit was hit.
Clients also need jitter, which is a little random delay. Without it, every client that failed in the same second retries in the same second, and the retries hit the service together. AWS's engineers found that retries can make load worse, so they limit retries with a token bucket too.
“Retries can amplify the load on a dependent system.”
AWS
“Rate limiting rules are not designed to allow a precise number of requests to reach your origin server.”
Cloudflare
The origin server in that quote is your own server, behind Cloudflare's network. An exact count is expensive, so accept a small overshoot. Cloudflare says its counters may lag by up to a few seconds, so a burst can slip past the line briefly. Plan for that.
- Fail open
Let traffic through
Users keep working if the counter is down. The risk: a spike gets through, so each server keeps a simple local backup limit.
- Fail closed
Block the calls
Protects the bill and the model. The risk: one dead store becomes an outage for every customer.
Tip
Asked what if the counter is down? Say you choose per limit: open for general traffic, closed for spend caps. Then say you alert on it.
How would you stop a nightly batch job from hurting daytime users?
Give each lane its own share. Interactive users keep 300 of the tenant's 400 requests a minute, and the batch lane may use at most 100. The batch job runs slower, but daytime users keep their 300 slots even while it pushes. At 100 a minute, 40,000 requests take 400 minutes, about 6 hours 40 minutes, which fits an overnight window.
Here it is in plain Python. The batch job asks first, and the interactive lane still gets its share.
# One tenant: 400 requests a minute, of which the batch lane may use at most 100.
# Interactive users always keep the other 300, however hard the batch job pushes.
TENANT_LIMIT = 400
BATCH_CAP = 100
used = {"interactive": 0, "batch": 0}
def admit(lane):
total = used["interactive"] + used["batch"]
if total >= TENANT_LIMIT:
return False
if lane == "batch" and used["batch"] >= BATCH_CAP:
return False
used[lane] += 1
return True
results = {"interactive": [0, 0], "batch": [0, 0]} # admitted, rejected
# The batch job asks first: 150 requests in the same minute. Then 320 interactive ones.
for lane in ["batch"] * 150 + ["interactive"] * 320:
results[lane][0 if admit(lane) else 1] += 1
for lane in ["batch", "interactive"]:
ok, no = results[lane]
print(f"{lane:12} admitted {ok:3} rejected {no:3}")
print(f"tenant total {used['batch'] + used['interactive']} of {TENANT_LIMIT}")Output
batch admitted 100 rejected 50 interactive admitted 300 rejected 20 tenant total 400 of 400
What does the interviewer want to hear?
A strong answer covers
- Clear limits: who is counted, per what window, in requests and in tokens.
- One shared count with a check-and-add in one step, so every server agrees.
- Fair sharing: reserved shares per customer and a lane for batch work.
- A 429 reply with Retry-After, and clients that back off with jitter.
- A stated choice on failure: fail open or closed, per limit, with alerts.
- Honest limits: the count is approximate, and output tokens are known late.
Common traps
Trap"Each server can keep its own count."
BetterTen servers multiply the limit by ten. Put one shared count where every server reads and updates it.
Trap"Counting requests is enough."
BetterA short question and a 50,000-token document count the same. Count tokens too, because they drive cost.
Trap"Just return an error."
BetterSend 429 with a Retry-After time, so clients wait instead of hammering the API again.
Can you spot the problem?
Spot the problem
Your API runs on 20 servers. Which setting breaks the limit of 100 requests a minute per customer?
Quick check
A customer's nightly batch job sends 40,000 requests, and daytime users get slow replies. What is the best first fix?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 27 November 2026
Running an AI API that many customers share?
Venkat designs and builds AI products and agents, the UI and the system behind it. Book a short call and say what you need.