esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

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.

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

  1. 1The request reaches the gateway, which rejects floods cheaply.
  2. 2The overnight job arrives at the same gateway, and is counted like any caller.
  3. 3The gateway asks the shared counter whether this caller has room left.
  4. 4Under the limit, the request goes on to the model.
  5. 5Over the limit, the caller gets a 429 reply with a wait time.
  6. 6The model's answer goes back to the caller.
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.
  • 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.

Ten servers, one limit of 100

Each server counts alone

10 servers

each one allows 100 a minute

One shared count

One counter

every server reads and updates it

1,000 allowed

ten times the limit

100 allowed

the limit holds

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

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

    Check and add in one step

    The store does both at once, so two servers can't both take the last slot.

  3. 3

    Let old counts expire

    Drop each count once it no longer matters, so the store never fills with old data.

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

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

1 / 6

What will they ask next?

  1. Q330How do you handle rate limits and 429 errors?12 min
  2. Q337Timeouts, retries and backoff?14 min
  3. Q353Design an LLM gateway.12 min
  4. Q357Scale to millions of users.13 min
  5. Q187How do you control agent cost?13 min
  6. Q471Implement a rate limiter (per-user and global).12 min

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.