Published on

Backpressure for AI Agent Workloads: Rate Limits, Queues and Budgets

Authors
  • avatar
    Name
    André Mello
    Twitter

Intro

Most of the reliability problems I see in AI-powered features today are not about the model. They are about traffic.

A single user request to an agent can turn into dozens of model calls and tool invocations. Some of those fail and get retried. Some trigger sub-tasks that fan out again. Put a few hundred users on top of that, and you have a workload with a shape traditional backend systems were never designed for: bursty, recursive and hard to predict.

The good news is that we already know how to deal with this. It's called backpressure, and the techniques are the same ones we've used for queues and microservices for years. They just need to be applied deliberately.

Take a typical support platform that adds an agent to triage incoming tickets. In testing, each ticket takes four to six model calls. In production, tickets with long email threads trigger extra tool calls to fetch history, summarize attachments and double-check the classification, and the 95th percentile climbs past 30 calls per ticket. A Monday-morning backlog of a few thousand tickets then sends tens of thousands of requests to the model provider within minutes, hits the account's rate limit, and the SDK's automatic retries keep it there — while interactive features sharing the same quota start failing for every customer.

Why Agent Traffic Is Different

Compared to a typical API client, an agent:

  • Fans out. One task becomes many model calls and tool calls, often in parallel.
  • Loops. It decides at runtime how many steps a task needs. The upper bound is whatever you configure — or nothing.
  • Retries aggressively. SDKs retry on 429 and 5xx, and agents often retry failed tool calls on top of that.
  • Has variable cost per call. A request is not a request: one call may use 500 tokens, another 50,000.

This means that request-per-second limits alone don't describe the load. You have to think in terms of concurrency, tokens and money.

Layer 1: Respect the Provider's Limits

Model providers enforce limits on requests and tokens per minute. When you exceed them, you get 429 Too Many Requests, often with a Retry-After header.

The worst reaction is an immediate retry from every in-flight task — a retry storm that keeps you rate-limited for longer. The right reaction is:

  1. Honor Retry-After when present.
  2. Otherwise, use exponential backoff with jitter.
  3. Cap the total number of retries per call.

And, more importantly, don't rely on 429s as your rate limiter. Track your own usage and slow down before the provider forces you to.

Layer 2: Admission Control

Not every request should be accepted immediately. An admission layer decides whether a new agent task can start now, has to wait, or should be rejected.

A simple and effective version is a concurrency limit per tenant plus a global limit:

public class AgentAdmission {

    private final Semaphore global = new Semaphore(200);
    private final Map<String, Semaphore> perTenant = new ConcurrentHashMap<>();

    public <T> T run(String tenantId, Callable<T> task) throws Exception {
        Semaphore tenant = perTenant.computeIfAbsent(tenantId, id -> new Semaphore(10));

        if (!tenant.tryAcquire(2, TimeUnit.SECONDS)) {
            throw new TooManyConcurrentTasksException(tenantId); // 429 to the caller
        }
        try {
            global.acquire();
            try {
                return task.call();
            } finally {
                global.release();
            }
        } finally {
            tenant.release();
        }
    }
}

The per-tenant limit protects other tenants from a single noisy one. The global limit protects your provider quota and your own infrastructure. In a multi-instance deployment you'd back these limits with a shared store like Redis, but the principle is the same.

Layer 3: Queue the Work That Can Wait

Not every agent task needs to answer in real time. Summarizing a batch of documents, classifying tickets or generating reports can go through a queue.

A queue gives you load leveling: producers can burst, while consumers process at a steady, controlled rate that fits your token budget. It also gives you natural places to add priority (interactive users first, batch jobs later) and dead-letter handling for tasks that keep failing.

A useful rule: interactive requests get admission control, everything else gets a queue.

Layer 4: Budgets per Task

Concurrency limits protect the system at a point in time. Budgets protect it over the lifetime of a task. Every agent task should carry explicit limits:

  • Max steps (model calls + tool calls).
  • Max tokens across all calls.
  • Max wall-clock time.
  • Max cost, if you can estimate it.
public record TaskBudget(int maxSteps, long maxTokens, Duration maxDuration) {}

public void checkBudget(TaskContext ctx) {
    if (ctx.steps() >= ctx.budget().maxSteps()
            || ctx.tokensUsed() >= ctx.budget().maxTokens()
            || ctx.elapsed().compareTo(ctx.budget().maxDuration()) > 0) {
        throw new BudgetExceededException(ctx.taskId());
    }
}

When a budget is exhausted, the agent should stop and return what it has — or escalate to a human — instead of looping indefinitely. A task stuck in a loop is the agent equivalent of a runaway query, and it should be killed the same way.

Layer 5: Protect the Tools

Agents don't just call models; they call your APIs and your partners' APIs through tools. Those systems were sized for human-driven traffic.

Treat every tool like any other downstream dependency:

  • A concurrency limit per tool.
  • Timeouts that are shorter than the agent's overall deadline.
  • A circuit breaker, so a failing dependency doesn't absorb every retry.
  • Idempotency keys for any tool that changes state — because the agent will call it twice.

Make It Observable

You can't manage what you don't measure. At a minimum, track per tenant and per feature:

  • Tokens consumed and estimated cost.
  • Steps per task (p50, p95, max).
  • 429s and retries from providers.
  • Rejections from admission control and queue depth.
  • Tasks terminated by budget limits.

The steps-per-task distribution is especially telling. A sudden increase usually means a prompt change, a broken tool or a model behavior change is causing agents to loop.

In a scenario like the one above, steps per task is the metric that tells the story: the median looks healthy, but the tail reveals tasks running ten times longer than designed. An average cost per task hides exactly the outliers that matter.

Common Mistakes

1. Stacking retries at every layer. The HTTP client retries, the SDK retries, the agent framework retries and the agent itself decides to "try again". Three retries at four layers is up to 81 calls for one failure. Fix: pick one layer to own retries (usually the outermost one that knows the task budget) and disable or minimize the rest.

2. One shared API key and quota for everything. A batch job and your interactive chat compete for the same rate limit, and the batch job wins. Fix: separate keys or projects per workload class, or at least separate internal limits with priority for interactive traffic.

3. No timeout on the task, only on each call. Every call finishes in 20 seconds, but the task makes 200 of them. Fix: a wall-clock deadline per task, propagated to every model and tool call it makes.

4. Measuring requests instead of tokens. Request rates look stable while token usage triples because prompts keep growing with conversation history. Fix: track tokens per task and alert on the trend, not only on request counts.

5. Letting the agent call state-changing tools without idempotency keys. Under retries, "send email" and "create refund" will run twice. Fix: generate a key per logical action and enforce it in the tool, exactly like any other API.

A Starting Configuration

If you need defaults to begin with, these are reasonable for an interactive agent feature and easy to tune later:

LimitStarting value
Concurrent tasks per tenant5–10
Max steps per task15–25
Max wall-clock per task60–120 s for interactive, more for batch
Retries per model call2–3, exponential backoff with jitter
Retries per tool call1–2, only for idempotent tools
Alert thresholdp95 steps per task 2x above baseline

Conclusion

AI agents are a new kind of client, but the problem they create is an old one: more demand than the system can safely absorb. The answer is the same toolkit we've always used — admission control, queues, concurrency limits, timeouts and circuit breakers — extended with one new concept: budgets measured in steps, tokens and money.

Design those limits up front. It is much easier than explaining a surprise invoice or a partner outage after the fact.