# 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.

AI and LLM interview question Q356, LLM system design. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/design-rate-limiting

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, How one request passes the checks: A request passes the gateway, then the shared counter. Under the limit, the model answers. Over it, the caller gets a 429 reply with a wait time. Output tokens are added when the reply ends.*
1. The request reaches the gateway, which rejects floods cheaply.
2. The overnight job arrives at the same gateway, and is counted like any caller.
3. The gateway asks the shared counter whether this caller has room left.
4. Under the limit, the request goes on to the model.
5. Over the limit, the caller gets a 429 reply with a wait time.
6. The 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.

## How do many servers share one count?

A count kept in one server's memory is not enough. Ten servers, each allowing 100 requests a minute, let through 1,000. Every server has to read and update one shared count, kept in a fast store that all of them reach.

*Diagram, Ten servers, one limit of 100: Top: each server counts alone, so the limit is multiplied tenfold. Bottom: one shared count holds the line at 100. Same traffic, different answer.*
1. Each server lets through its own 100, so the total is multiplied.
2. One shared count stops the 101st request, wherever it lands.

The update must be atomic, meaning the check and the add happen as one step, so two servers can't both take the last free slot. Many designs use a token bucket: a bucket refills at a steady rate up to a set size, and each request takes one token. Anthropic's docs say their API works this way, with capacity refilled continuously rather than reset at fixed times.

API Gateway, the AWS service, uses the same idea. You set a rate in requests a second, and a burst size, which is the most the bucket holds at once.

1. **Key each caller:** Pick the key: user, API key or customer. Count each key on its own, so one busy customer can't hide in another's total.
2. **Check and add in one step:** The store does both at once, so two servers can't both take the last slot.
3. **Let old counts expire:** Drop each count once it no longer matters, so the store never fills with old data.
4. **Reserve shares:** Give each customer a reserved share, and let it borrow shared capacity only when it needs more. Azure's Rate Limiting pattern uses this reserve-then-borrow idea, though for processes rather than customers.

## 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.

```python
# 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:

```text
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." Better: Ten servers multiply the limit by ten. Put one shared count where every server reads and updates it.
- Trap: "Counting requests is enough." Better: A short question and a 50,000-token document count the same. Count tokens too, because they drive cost.
- Trap: "Just return an error." Better: Send 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?

A. 100 requests a minute per customer, counted in one shared store
B. 100 requests a minute per customer, counted in each server's own memory
C. A 429 reply with a Retry-After header when the limit is hit
D. A cap of 300,000 input tokens per minute per customer

**Answer:** B. Each server counts alone, so 20 servers let through up to 2,000 a minute. One shared count keeps the limit true. The other three settings are sound.

**Quick check:** A customer's nightly batch job sends 40,000 requests, and daytime users get slow replies. What is the best first fix?

A. Give the model a shorter system prompt
B. Reserve capacity for interactive traffic and cap the batch lane
C. Switch off rate limits for that customer
D. Move the batch job to a bigger model

**Answer:** B. A reserved share protects daytime users, and the batch job still finishes, just more slowly. A prompt or a bigger model doesn't change who gets the shared capacity, and switching off limits removes the protection altogether.

## Can you answer these from memory?

**Flash cards**

- **What does a rate limit do?** Caps how much one caller can use in a time window, so one caller can't starve the rest.
- **Why count tokens, not only requests?** Tokens drive model cost and time. One request can be a short question or a 50,000-token document.
- **Why one shared counter?** Ten servers each allowing 100 let through 1,000. One shared count keeps the limit true.
- **Which reply means too many requests?** HTTP 429, sent with a Retry-After time so the client knows how long to wait.
- **Fail open or fail closed?** Open keeps users working if the counter is down. Closed protects spend. Choose per limit.
- **Why add jitter to retries?** A random delay spreads the retries over time, so clients don't all hit the service in one second.

## Likely follow-up questions

- Q330 How do you handle rate limits and 429 errors? https://designervenkat.online/interview/ai/how-do-you-handle-rate-limits-and-429-errors
- Q337 Timeouts, retries and backoff? https://designervenkat.online/interview/ai/timeouts-retries-and-backoff
- Q353 Design an LLM gateway. https://designervenkat.online/interview/ai/design-an-llm-gateway
- Q357 Scale to millions of users. https://designervenkat.online/interview/ai/scale-to-millions-of-users
- Q187 How do you control agent cost? https://designervenkat.online/interview/ai/how-do-you-control-agent-cost
- Q471 Implement a rate limiter (per-user and global). https://designervenkat.online/interview/ai/implement-a-rate-limiter
