Skip to main content

One Tenant's Burst, Everyone's 429: Fair LLM Rate Limits in Django (Part 11)

Reserve requests and tokens from the provider pool and the tenant's share in one atomic Redis script, settle with real usage, pause the pool on a provider 429 instead of opening the breaker, and tell the client whose limit it hit.

Updated 18 min readMarkdown
One Tenant's Burst, Everyone's 429: Fair LLM Rate Limits in Django (Part 11)

On November 23, Baseten announced that from December 3 its Model APIs will return 529 Overloaded when serving capacity runs out. Some of those responses are 429s today. A 429, the changelog says, "will continue to mean that a request exceeded your requests-per-minute or tokens-per-minute rate limit."

Small change, useful distinction. A 529 is about the provider. A 429 is about your account. In a multi-tenant app, your account is shared by every customer you have.

So when one customer's batch import drains your tokens-per-minute, everyone gets the 429. If your error handling treats a 429 as "provider unhealthy", one customer has just pushed every other customer onto the fallback.

This is Part 11 of Shipping AI Agents in Django. Part 10 built the fallback chain: error classes, one deadline, a circuit breaker, and fallbacks that have to pass evals before they're enabled. This part puts a fair-share layer in front of that chain, so one tenant can't drain the shared provider quota, and so a quota problem doesn't get treated as an outage.

Short version

  • A provider rate limit is one pool shared by all your tenants. Give each tenant its own token buckets on that pool, sized as a share of it, for requests and tokens.
  • Admit a call only if the pool and the tenant can both pay for it. Do the check and the debit in one Redis Lua script, so concurrent workers can't oversubscribe.
  • Reserve an input-token estimate plus max_tokens before the call. Afterwards, settle against the usage the provider reports: refund what wasn't used, charge any overage as debt.
  • Size the pool from the provider's rate-limit headers, and lower your local count when the provider says it has less left than you think.
  • A provider 429 with retry-after pauses that pool for every tenant. It doesn't count toward the circuit breaker. A spend-cap 429 still opens it.
  • A tenant over its share gets a 429 with Retry-After, a short wait inside the deadline, or a degraded answer. It never gets failed over. A drained pool fails over and tells the client 503.
  • Money budgets (Part 5) and throughput limits are different. You need both.

The demo is Part 10's Django 5.2 app plus a quota module. It has 93 passing pytest tests: 59 carried over from Part 10 (one row deliberately changed) and 34 new ones. The Lua scripts really execute in the tests (fakeredis runs them through an embedded Lua), and the same suite passes against a real Redis 8.0.2 server.

How one tenant puts everyone on the fallback

Part 10's classifier treated a 429 with retry-after as rate_limited: retry if the wait fits the deadline, and count it as a breaker failure. Five failures in 30 seconds opened the breaker for every request.

Now add tenants. One customer kicks off a bulk re-moderation. The shared requests-per-minute drains, the provider returns 429s to everyone, the breaker counts five, and every tenant moves to the secondary provider. Nothing was down, and the noisy tenant now drains the secondary too.

Providers make bursts riskier than the per-minute numbers suggest. Anthropic's rate limits page says "a rate of 60 requests per minute (RPM) might be enforced as 1 request per second," and that ramp limits can return a 429 "even while you're under your ITPM and OTPM rate limits. A burst of requests within a few seconds can also count as a sharp increase." OpenAI's rate limits guide has its own version: "rapid traffic increases now return 429 with slow_down." It also notes that "unsuccessful requests contribute to your per-minute limit, so continuously resending a request won't work." A tenant hammering retries makes things worse for everyone else.

Money and throughput are different limits

Part 5 built a budget guard: before each call, check spent + worst_case against the workflow's dollar budget, under a row lock, and fail closed. That limits how much a workflow can spend. It doesn't limit how fast. A tenant well inside its monthly budget can still take a minute's worth of shared tokens in ten seconds.

A dollar budget resets when the period ends. A rate limit refills constantly, so its refusal is "not yet", not "no". Check the budget first (final), then throughput (retry later).

Step 1: model the pool you actually share

The two big providers count throughput differently, and your buckets should count the same way.

Anthropic measures RPM, input tokens per minute (ITPM) and output tokens per minute (OTPM) per model class. Its docs say the API "uses the token bucket algorithm," so "your capacity is continuously replenished up to your maximum limit, rather than being reset at fixed intervals." Only uncached input counts: "only input_tokens + cache_creation_input_tokens count toward your ITPM limit." Output is counted as it's produced: "The max_tokens parameter does not factor into OTPM rate limit calculations."

OpenAI uses RPM and TPM, among others, at "the organization level and at the project level, not user level," and its guide says "Your rate limit is calculated as the maximum of max_tokens and the estimated number of tokens based on the character count of your request."

So the demo describes a pool with whichever dimensions the provider uses:

@dataclass(frozen=True)
class Pool:
    """One provider account's limits, per minute. Anthropic-style: rpm/itpm/otpm.
    OpenAI-style: rpm/tpm (tpm is charged input estimate + max_tokens)."""
    name: str
    per_minute: dict                  # {"rpm": 4000, "itpm": 2_000_000, "otpm": 400_000}
    burst_s: float = 10.0             # bucket holds this many seconds of refill, not a minute
    safety: float = 0.8               # leave headroom for traffic we don't see

    def capacity(self, dim, share=1.0):
        rate_s = self.per_minute[dim] * self.safety * share / 60
        return max(1.0, rate_s * self.burst_s), rate_s / 1000     # (capacity, refill per ms)

burst_s is 10 seconds, not 60: a bucket holding a whole minute lets a tenant send it all at once, the spike that ramp limits punish. safety keeps 20% back because your app is rarely the only user of the org's limit. Both numbers are illustrative.

Step 2: give each tenant a share, and keep headroom for interactive traffic

Each tenant gets the same set of buckets on each pool, scaled by a tier share:

LLM_QUOTA = {
    "pools": {
        "primary": {"per_minute": {"rpm": 4000, "itpm": 2_000_000, "otpm": 400_000},
                    "burst_s": 10, "safety": 0.8},
        "secondary": {"per_minute": {"rpm": 500, "tpm": 200_000}, "burst_s": 10, "safety": 0.8},
    },
    "tiers": {"standard": 0.25, "pro": 0.5, "internal": 1.0},   # max share of each pool
    "tenants": {"acme": "pro", "ops": "internal"},              # everyone else: standard
    "batch_headroom": 0.2,   # batch traffic can't take the pool below 20% of its burst
}

A share is a ceiling, not a reservation, so shares add up to well over 100% on purpose: most tenants are idle most of the time. The pool bucket is the hard limit; tenant buckets stop anyone taking more than their slice.

Within the pool, whoever sends fastest still wins. So one more rule: requests marked priority="batch" must leave 20% of the pool's burst untouched. A nightly re-moderation job can use the pool while it's quiet, but it can't take the last fifth that a user waiting on a page needs.

Step 3: one Lua script, so admission is atomic

Check-then-debit in Python is a race: two workers read "3 left", both debit. Part 10's breaker could afford a lost increment; a quota can't. Redis documents the property we need: "Redis guarantees the script's atomic execution. While executing the script, all server activities are blocked during its entire runtime."

The script gets a pause key plus every bucket the call touches: the pool's and the tenant's for each dimension. It refills them all lazily from elapsed time and checks them all. Only if every bucket can pay does it debit every one:

local now = tonumber(ARGV[1])
if not now then local t = redis.call('TIME'); now = t[1] * 1000 + math.floor(t[2] / 1000) end
local paused = tonumber(redis.call('GET', KEYS[1]))
if paused and paused > now then return {0, 1, paused - now} end
local level, wait, blocked = {}, 0, 0
for i = 2, #KEYS do
  local a = 2 + (i - 2) * 4
  local cap, rate = tonumber(ARGV[a]), tonumber(ARGV[a + 1])
  local cost, floor = tonumber(ARGV[a + 2]), tonumber(ARGV[a + 3])
  if cost + floor > cap then return {-1, i, 0} end           -- can never fit
  local h = redis.call('HMGET', KEYS[i], 't', 'ts')
  local t, ts = tonumber(h[1]), tonumber(h[2])
  if not t then t, ts = cap, now end
  t = math.min(cap, t + math.max(0, now - ts) * rate)
  level[i] = t
  local short = cost + floor - t
  if short > 0 then
    local w = math.ceil(short / rate)
    if w > wait then wait, blocked = w, i end
  end
end
if blocked > 0 then return {0, blocked, wait} end
-- every bucket can pay: debit them all (HSET t, ts and a PEXPIRE per bucket)

A denial returns which bucket blocked and the milliseconds until it could pay, which becomes Retry-After. It writes nothing, so a refused tenant uses no pool capacity.

Three Redis details matter in production:

  • Keys in, not built inside. Redis says "all names of keys that a script accesses must be explicitly provided as input key arguments." The demo's keys look like llmq:{primary}:t:acme:itpm. On Redis Cluster, only the part inside {...} is hashed, so all of one pool's keys land in one slot and one script can touch them. A test checks the slots match.
  • The script cache is volatile. Redis: "The Redis script cache is always volatile," so it can be emptied by a restart or a failover. redis-py's register_script sends EVALSHA and falls back to EVAL on NOSCRIPT. A test flushes the cache mid-run.
  • One clock. In production, now comes from Redis TIME, so workers with drifting clocks agree. Tests pass a fake clock instead.

Step 4: estimate, reserve, then settle with real usage

You don't know the token count until the response comes back, so reserve a pessimistic guess:

def estimate_input_tokens(messages) -> int:
    """Deliberately pessimistic: ~3 chars per token plus overhead. Reconciled after the call."""
    return sum(math.ceil(len(m["content"]) / 3) + 8 for m in messages)

Three characters per token is my conservative heuristic, not a provider figure. For a better number, Anthropic's token counting endpoint "is free to use but subject to requests per minute rate limits," with limits "separate and independent" from message creation. The docs still call its result "an estimate". The output reservation is max_tokens from the prompt version. For OpenAI that matches how the provider counts. For Anthropic it's local caution, since OTPM counts real output.

After the call, settle against the provider's usage:

def settle(ticket: Ticket, usage: dict | None):
    if not ticket.admitted or not usage:
        return              # timeout or error: keep the reservation, the provider may have counted it
    pool = pool_for(ticket.pool)
    actual = actual_costs(pool, usage)
    delta = {d: ticket.reserved[d] - actual[d] for d in ticket.reserved if d != "rpm"}
    _adjust(pool, ticket.tenant, ticket.share, "add", delta)   # can go negative: debt

actual_costs maps usage onto the pool's dimensions: for Anthropic ITPM that's input_tokens + cache_creation_input_tokens, so cache reads cost nothing. A second Lua script applies the delta to the pool and tenant buckets. Unused output goes back right away. If the estimate was low, the bucket goes negative and the tenant's next request waits until it refills past zero.

Step 5: learn the real limits from response headers

Your config is a guess. The provider's headers aren't. Anthropic returns anthropic-ratelimit-requests-limit, -input-tokens-limit, -output-tokens-limit and matching -remaining and -reset headers. OpenAI returns x-ratelimit-limit-requests, x-ratelimit-limit-tokens and their remaining and reset counterparts. After every response, success or 429:

def observe_headers(pool_name, headers: dict):
    """Learn the real limits, and if the provider has less left than we think (other services
    share the org limit), pull our pool down to match. Never raise it from headers."""
    h = {k.lower(): v for k, v in headers.items()}
    pool = pool_for(pool_name)
    learned = {dim: int(h[k]) for k, dim in LIMIT_HEADERS.items()
               if k in h and dim in pool.per_minute}
    if learned:
        cache.set(f"llmq:limits:{pool_name}", learned, timeout=None)
        pool = pool_for(pool_name)
    remaining = {dim: int(h[k]) * pool.safety for k, dim in REMAINING_HEADERS.items()
                 if k in h and dim in pool.per_minute}
    if remaining:
        _adjust(pool, "", 1.0, "clamp", remaining, who=("pool",))

"Lower only" is deliberate. If the provider says 3 requests are left and you think 400, someone else shares the org's limit, so believe it. If it says more, keep your count, which includes calls still in flight. Details: Anthropic rounds token remaining "to the nearest thousand." Its combined anthropic-ratelimit-tokens-* headers show "the most restrictive limit currently in effect." Its resets are RFC 3339 timestamps, while OpenAI's look like 6m0s, so parse_reset() handles both.

For a few big tenants, Anthropic also lets you set rate limits per workspace, though "Organization-wide limits always apply, even if workspace limits add up to more."

Step 6: a provider 429 pauses the pool, not the breaker

The classifier now reads the error code as well as the status:

if s == 429 and (exc.code == "enforced_spend_limit_reached" or exc.retry_after is None):
    return Failure("quota", Next.FAILOVER)          # spend cap: breaker opens for 10 minutes
if s == 429:
    kind = "ramp_limited" if exc.code == "ramp_limit_exceeded" else "rate_limited"
    return Failure(kind, Next.RETRY, trips_breaker=False, retry_after=exc.retry_after)

Part 10 inferred a spend cap from a missing retry-after. Anthropic's docs give a better signal: on the Messages API, the spend-cap 429 carries error.details.error_code enforced_spend_limit_reached, and a ramp limit carries ramp_limit_exceeded. The errors page adds that "the set of codes can grow" and that unknown codes should be handled by type or status, which is why the missing-header rule stays as the fallback.

A rate-limit 429 now does something more useful than counting toward the breaker. It pauses the pool for everyone:

if failure.kind in ("rate_limited", "ramp_limited"):
    quota.pause(pv.provider, failure.retry_after)   # every worker, every tenant

pause is a short Lua script that stores a pause-until time and never shortens one. Part 10's loop is unchanged: sleep and retry if retry-after fits the deadline, otherwise move on. The difference is that the next request, from any tenant, sees the pause at admission and skips that pool without spending an attempt on a known 429.

Step 7: when a tenant is out, say whose limit it was

Admission happens inside Part 10's retry loop, before every attempt:

ticket = _admit(pv, tenant, text, policy, deadline, sleep)
if not ticket.admitted:
    scope = ticket.blocked_by.split(":")[0]
    if scope == "tenant":
        # This customer's share is used up. Failing over would just let them
        # drain the next provider too, so stop here.
        return None, None, "tenant_limited", attempts, ticket.retry_after
    if scope == "too_large":
        return None, None, "too_large", attempts, 0
    pool_waits.append(ticket.retry_after)   # "pool" or "paused": capacity, not health
    break                                   # try the next provider's pool

That asymmetry is the core of this post. A drained pool is a capacity problem, which is what a fallback is for. A drained tenant is a fairness problem; failing over just hands them a second pool.

What the caller sees depends on the feature's on_limit policy:

  • "wait": sleep once if a full attempt still fits in the deadline afterwards, otherwise reject.
  • "reject": raise Limited("tenant", retry_after).
  • "degrade": no model call; use the safe action (hold) with reason tenant_limited.

The view maps the scope onto HTTP:

except Limited as e:
    # 429: you are over your share. 503: we're out of provider capacity for everyone.
    resp = JsonResponse({"error": f"{e.scope}_limited"}, status=429 if e.scope == "tenant" else 503)
    resp["Retry-After"] = str(max(1, math.ceil(e.retry_after)))   # whole seconds
    return resp

RFC 6585 defines 429 as "the user has sent too many requests in a given amount of time" and allows a Retry-After. RFC 9110 defines 503 as "a temporary overload" and says Retry-After there indicates "how long the service is expected to be unavailable." The tenant who caused the problem gets told so. Everyone else learns it isn't their fault.

Easy to miss: a limited request writes no Decision row. decide() is idempotent on its key (Part 10), so a stored rejection would be replayed on every retry. A test checks the retry runs.

Trade-offs I'd flag in review

Burst size limits the largest prompt. A bucket can't admit a request bigger than its capacity, so a standard tenant's 10-second ITPM burst is also the largest prompt it can ever send. The demo refuses those outright with too_large instead of making them wait forever. If you need big prompts, raise burst_s for ITPM only, or cap prompt size upstream.

Pessimistic estimates under-use the pool. Reserving max_tokens holds capacity until settle refunds it. With long calls and generous max_tokens, a lot of capacity sits reserved for nothing. Tighter max_tokens per prompt version helps more than a cleverer estimator.

Failed calls keep their reservation. After a timeout you don't know what the provider counted, so the demo assumes the worst. A flaky provider will throttle you below its real limit until the buckets refill.

Shares are static. A share-of-pool ceiling is simple to reason about. It isn't max-min fair: two busy tenants on the same tier don't split the capacity an idle third one leaves unused. Weighted fair queuing does that, but it needs a queue rather than an admit-or-refuse check.

Redis or Postgres. At modest traffic, bucket rows refilled and debited under select_for_update() give the same all-or-nothing behaviour as Part 5's budget guard, but every LLM call then queues on one hot pool row. Redis keeps that out of your database.

Redis is now on the serving path. If Redis is down, do you fail open (call the provider unthrottled) or closed (refuse)? The demo fails closed because the exception propagates. For a moderation feature with hold as the safe action, that's acceptable. For a chat product, maybe not.

What the tests prove

pytest -q: 93 passed (Python 3.13.5, Django 5.2.19, pydantic 2.14.3, pytest 9.2.0, pytest-django 4.14.0, redis-py 8.2.0, fakeredis 2.41.0 with lupa 2.8). With QUOTA_REDIS_URL set, the same 93 pass against Redis server 8.0.2. One Part 10 test row changed on purpose: a 429 with retry-after no longer trips the breaker.

The 34 new tests cover: buckets that admit their burst, return a wait, refill continuously and deny all-or-nothing; refunds, debt, cache reads and failed calls in settle; 80 reservations from 8 threads against a 10-request bucket admitting exactly 10; the TIME path, a flushed script cache and one cluster slot per pool; a noisy tenant stopping at its share while others continue; batch headroom; both providers' headers and reset formats; rate, ramp and spend-cap 429s. The headline case: six requests hitting provider 429s leave the breaker closed, and another tenant is served by the primary once the pause ends. Others check that a limited tenant never reaches the secondary, that a limited request stores nothing so its retry runs, wait and degrade, a drained pool failing over with the breaker closed, and the 429/503 responses.

These prove plumbing: who's admitted, what's debited, what's paused, what the client hears. They can't tell you your real limits or whether 25% is the right share. Your headers and traffic decide those.

The series so far

  1. Human-in-the-loop AI agents in Django: approval gates
  2. Least-privilege agent identity in Django
  3. Your MCP server is a second API
  4. Permission-aware RAG without post-filters
  5. Cost per successful workflow
  6. Tracing agent runs with OpenTelemetry
  7. Structured outputs that don't break
  8. AI moderation helpers with appeals
  9. Shipping prompt and model changes safely
  10. Provider fallbacks without surprises
  11. Per-tenant rate limits and token budgets (this post)

Next, Part 12: moving agent runs off the request. wait and reject both assume a person is waiting for an answer. For bulk work, the better answer is a queue: background workers that pull per tenant in fair order, steps that resume after a crash, and a status endpoint for the client to poll.

The demo is the Part 10 app plus quota.py (three Lua scripts), edits to errors.py, serve.py, chain.py and views.py, a migration and tests/test_quota.py.

Open question for readers

The trade-off I can't settle: when a tenant hits its limit, should the request wait or fail? Waiting inside the deadline hides the limit from users and keeps the product smooth, but it holds a worker and a connection open, and under heavy load those waits pile up into a backlog. Failing fast with a 429 is honest and cheap, but it pushes retry logic onto every client, and some clients will retry immediately and make the burst worse.

The demo waits once, and only when a full attempt still fits in the deadline. Where do you draw the line? Do you size tenant shares by plan, by observed usage, or not at all, and just let the pool sort it out? I'd like to hear what's worked for you.

About the author

  • Custom software & AI development company. We build production-ready AI integrations, mobile apps, and web platforms for businesses that want real results. lycore.com

No comments yet. Be the first to comment.

More from this blog