Mhonn YbañezSRE, DevOps, AI Engineer
 Today I Learned
Read the full page

How does an API gateway throttle and rate limit traffic?

Posted
Tags
system-design, reliability, api-design

An API gateway is the front door to a set of services, and one of its jobs is to say slow down before a client or a spike overwhelms what is behind it. The methods differ in how they treat bursts, memory and fairness, and the hard part is doing it across many gateway instances.

I keep getting rate limited when I use AI models, mostly Gemini and Claude. A message comes back saying I sent too much, wait a bit, and it works again. I got curious about how a service decides that. How does it count my requests, and why does it let me burst sometimes but not others?

The question I had

How does an API gateway decide to slow a client down, and is that what happens when an AI model tells me I am sending too much?

What I found

What an API gateway is

An API gateway is the single front door to a set of services. Every request goes through it first. It handles the jobs that every service would otherwise repeat: routing to the right service, checking who is calling, terminating TLS, logging, and limiting how much any one caller can send. The services behind it can then focus on their own logic.

Limiting at the front door is the point. A request that is turned away there never uses a thread, a database connection or a model on the other side.

Rate limiting and throttling

The two words get used for the same thing in some products and for different things in others. The split I found most common:

TermWhat it meansWhat the caller feels
Rate limitingA cap per caller over a period of time ("100 requests per minute")Extra requests are rejected
ThrottlingShaping or capping the flow to protect the backend, sometimes for everyone togetherRequests may be delayed, queued or rejected

I will say "rate limiting" for the cap per caller and use "throttling" loosely, because the methods below serve both.

What a limit is counted against

A limit needs a key: who or what is being counted.

  • An API key or user, so each person gets a fair share.
  • A plan or tenant, so a free tier gets less than a paid one.
  • A route, so an expensive endpoint is capped lower than a cheap one.
  • An IP address, which is easy but unfair when many people share one (an office, a mobile network, a proxy).
  • Everyone together, as a global cap that protects the backend.

Real gateways often stack several of these. A caller can be inside their own limit and still be turned away by the global one.

The common methods

MethodHow it countsHow it treats burstsThe catch
Fixed windowA counter per clock window ("this minute"), reset at the boundaryLets the whole limit through at onceAround a boundary a caller can send the limit at the end of one window and again at the start of the next, nearly double in a short time
Sliding window logKeeps the time of every request and counts those in the last N secondsExact, no boundary spikeMemory grows with the limit, for every caller
Sliding window counterBlends the current window's count with a share of the previous oneSmooth, close to exactAn approximation, not an exact count
Token bucketA bucket refills at a steady rate, and each request takes a tokenAllows a burst up to the bucket size, then holds a steady rateTwo numbers to tune: refill rate and bucket size
Leaky bucketRequests join a queue that drains at a fixed rate, and a full queue drops new onesSmooths the output to a constant rateRequests wait in the queue, so it adds delay

The two buckets sound alike, so it helps to keep them apart. A token bucket spends saved-up capacity, so a quiet caller can burst. A leaky bucket empties at one fixed pace no matter how the requests arrive.

A token bucket in a few lines

This is small enough to read in one go. The clock is passed in so it can be tested without waiting.

class TokenBucket:
    def __init__(self, rate, capacity, now):
        self.rate = rate          # tokens added per second
        self.capacity = capacity  # the most it can hold: the burst size
        self.tokens = capacity
        self.now = now
        self.last = now()

    def allow(self, cost=1):
        t = self.now()
        self.tokens = min(self.capacity, self.tokens + (t - self.last) * self.rate)
        self.last = t
        if self.tokens >= cost:
            self.tokens -= cost
            return True
        return False

With a refill of 1 per second and room for 3, five quick requests give True, True, True, False, False. Two seconds later, three more give True, True, False, because only two tokens came back.

Why AI services count tokens, not just requests

The cost argument is the part I did not expect to matter. A request to a normal API costs about the same as the next one. A request to a language model does not: one is a single short question and the next is a huge document.

So an AI API usually limits more than one thing at once: requests per minute, and also the amount of text per minute (measured in model tokens), and sometimes a daily total too. In bucket terms, a request spends tokens in proportion to how big it is, so a few huge requests can empty the bucket as fast as many tiny ones. That could explain being limited without having sent many requests: one very large request can use up the allowance on its own.

Many gateways, one limit

A busy gateway is not one machine. Requests spread across several copies, and each copy sees only part of a caller's traffic. If each copy counted for itself, the caller could send the limit to every copy.

  • A shared counter. The copies keep the count in one fast store. The count must be increased and given its expiry in one atomic step, or two requests can both read the old value and slip past the limit. It costs an extra network trip per request.
  • A local share. Each copy enforces its slice of the limit on its own. It is cheap and has no extra hop, but the total is approximate.

Then there is the question of what to do when the shared store is down. Failing open lets everyone through and risks overload. Failing closed turns everyone away and risks an outage. It is a product decision, not a rule.

What the client sees

The standard answer to a rate limit is status 429, Too Many Requests. A Retry-After header says how long to wait. Many APIs also send headers showing how much of the limit is left; the names X-RateLimit-... are a common convention, and a draft standard exists for unprefixed RateLimit headers, but I would not treat it as finished.

A good client does not retry at once. It waits at least as long as Retry-After says, then backs off a little longer each time and adds a random bit of jitter, so many clients do not all come back at the same moment. That is the retry storm from my earlier post.

A different status, such as 503, usually means the service itself is overloaded, not that I used too much.

Rate limiting is not load shedding

They are easy to blur:

Rate limitingLoad shedding
QuestionIs this caller using more than their share?Is the whole system too busy right now?
Who gets turned awayThe caller over their limitWhoever is cheapest to drop, often low priority work
Works whenTraffic is uneven between callersEveryone is within their limit and it is still too much

A system needs both. Fair shares do not help if every caller is fair and there are simply too many of them.

The gateway is not the only guard

A gateway can let through a modest number of requests per second that are each very slow. The services behind it still need their own limits, such as a cap on how many requests they work on at once, or they can run out of threads (that is the story in my thread pool exhaustion post). The gateway keeps the load fair at the door. The service protects itself inside.

Takeaway

A rate limit is a promise about fairness and a safety valve for the backend. I pick the method by how I want to treat bursts: fixed window for simple and cheap, a sliding window when the boundary spike matters, a token bucket when short bursts are fine, a leaky bucket when I want a steady flow. When requests differ a lot in cost, as with AI models, the limit should count cost and not just requests. And the limit has to hold across every copy of the gateway, not just one.