Backpressure Is What Keeps Agent Fan-Out From Becoming an Outage
Per-run concurrency limits are not enough when hundreds of agents share the same dependencies. This article builds system-level backpressure with bounded queues, rate limits, admission control, and circuit breakers so overload fails predictably instead of cascading.
On this page
A single agent run can look perfectly reasonable and still participate in an outage.
Imagine a research assistant that is allowed to run four searches concurrently. Four is a sensible per-run limit. Now 500 users start research jobs after a notification campaign.
The application has not created four concurrent searches. It has created the possibility of two thousand.
This is where per-request concurrency control stops being enough. The system needs a way to tell incoming work that capacity is already consumed.
That is backpressure.
I think of it as the difference between limiting how fast one car can drive and controlling how many cars are allowed onto the road in the first place. Semaphores inside an agent run help with the first problem. Bounded queues, rate limits, admission rules, and circuit breakers handle the second.
The example here is an AI document-analysis service. A user can submit a document, extract text, retrieve related records, call a model, and run optional enrichment tools. Several downstream systems have finite capacity: a document parser, an embedding service, a model provider, and a third-party company-data API.
Start with a capacity model
Before adding a resilience library, I want to know which resource I am protecting.
For each expensive dependency I write down something close to:
model calls: max useful in-flight: 80 provider request limit: externally defined expected p95 latency: 2.5scompany-data API: max in-flight: 20 sustained request rate: 8 req/s burst tolerance: 15PDF workers: worker concurrency: 12 queue target: < 200 waiting jobsThese are operational values, not constants from an article. They come from provider limits, load tests, service-level objectives, and what the business is willing to pay for.
Without that model, a concurrency setting such as 20 is just a number with good branding.
A bounded queue is an architectural decision
An unbounded queue does not remove overload. It converts overload into waiting time and memory/storage growth.
If workers can process 20 jobs per second while producers submit 50 per second for ten minutes, the queue grows by 18,000 jobs. The service may remain technically “up” while users wait fifteen minutes for work that is already obsolete.
I prefer a queue with an explicit admission result.
type AdmissionResult = | { accepted: true; jobId: string } | { accepted: false; reason: "queue-full" | "tenant-limit" | "service-degraded"; retryAfterMs?: number; };interface JobQueue { depth(): Promise<number>; enqueue(job: AnalysisJob): Promise<string>;}async function admitAnalysisJob( job: AnalysisJob, queue: JobQueue, maxDepth: number,): Promise<AdmissionResult> { const depth = await queue.depth(); if (depth >= maxDepth) { return { accepted: false, reason: "queue-full", retryAfterMs: 30_000, }; } return { accepted: true, jobId: await queue.enqueue(job), };}A real queue-depth check and enqueue should be atomic enough for the technology being used. Two hundred API instances independently reading depth=199 and then all enqueueing is not a reliable capacity guard.
With RabbitMQ, Redis, SQS, Kafka, or a database-backed queue, I would enforce capacity using primitives appropriate to that system rather than pretending this example's two calls are transactional.
The important behavior is explicit rejection or deferral when the system is already saturated.
Backpressure should reach the caller
A bounded queue is less useful if the API catches queue-full and returns a generic 500.
The caller needs a meaningful response:
accepted = falsereason = queue-fullretry_after = 30 secondsFor interactive traffic that can mean HTTP 429 or 503 with a retry hint, depending on whether the limiting condition is client/tenant quota or temporary service capacity.
For internal event producers it may mean pausing consumption, reducing prefetch, or not acknowledging another batch until downstream workers have room.
Backpressure is a signal that should travel upstream. If every layer absorbs it and keeps accepting more work, there is no pressure—only a growing backlog.
Protect tenants from one another
A global limit prevents the whole service from falling over. It does not guarantee fairness.
One customer can submit 10,000 documents and occupy every worker while another customer waits behind them.
I usually want at least two levels of admission:
type TenantCapacity = { maxQueuedJobs: number; maxActiveJobs: number;};A worker pool can combine global and tenant rules:
global active jobs <= 100tenant A active jobs <= 10tenant B active jobs <= 25 (contracted capacity)This is not only performance isolation. In a metered AI product it also limits how quickly one tenant can accidentally burn through shared model/provider capacity.
The exact numbers can be subscription policy, operational policy, or both. I keep those concerns visible instead of burying them in a queue consumer's concurrency=50 setting.
Rate and concurrency solve different problems
A semaphore limits *simultaneous* work.
A rate limiter controls *how often* work begins.
Suppose an API allows ten requests per second and each request takes only 50 ms. A concurrency limit of ten still permits close to 200 requests per second in ideal conditions. It protects sockets but violates the provider's rate contract.
A token bucket is a useful mental model for bursty traffic.
class TokenBucket { private tokens: number; private lastRefillMs: number; constructor( private readonly capacity: number, private readonly refillPerSecond: number, ) { this.tokens = capacity; this.lastRefillMs = Date.now(); } tryTake(nowMs = Date.now()): boolean { const elapsedSeconds = (nowMs - this.lastRefillMs) / 1_000; this.tokens = Math.min( this.capacity, this.tokens + elapsedSeconds * this.refillPerSecond, ); this.lastRefillMs = nowMs; if (this.tokens < 1) return false; this.tokens -= 1; return true; }}That implementation is process-local. In a horizontally scaled service it does not provide a global rate limit. I would use a shared limiter, gateway, Redis script, or provider-aware scheduling layer when the quota is shared across workers.
The code is useful because it makes the semantics clear: a short burst can use stored capacity, while sustained traffic is governed by refill rate.
Provider 429s should feed the limiter
A provider returning 429 is information about current capacity.
If the response includes a retry-after value or quota headers, the connector should use them. Blind exponential backoff without updating local admission means every waiting run may wake up at roughly the same time and create another burst.
I prefer one dependency-level scheduler to understand that the provider is throttled and slow new work before each individual agent discovers it independently.
That prevents a thundering herd of “helpful” retries.
Jitter still matters, but coordination matters more when many runs share one quota.
Circuit breakers answer a different question
A rate limiter asks:
Are we allowed to send this much traffic?
A circuit breaker asks:
Is there any value in sending traffic to this dependency right now?
If the company-data API is returning 503 for almost every call, continuing to send the full allowed rate only adds latency and pressure.
A small state machine is enough to explain the behavior:
type CircuitState = "closed" | "open" | "half-open";class CircuitBreaker { private state: CircuitState = "closed"; private failures = 0; private openedAt = 0; constructor( private readonly failureThreshold: number, private readonly resetAfterMs: number, ) {} allow(now = Date.now()): boolean { if (this.state === "closed") return true; if ( this.state === "open" && now - this.openedAt >= this.resetAfterMs ) { this.state = "half-open"; return true; } return this.state === "half-open"; } success(): void { this.failures = 0; this.state = "closed"; } failure(now = Date.now()): void { this.failures += 1; if (this.state === "half-open" || this.failures >= this.failureThreshold) { this.state = "open"; this.openedAt = now; } }}This is intentionally smaller than a production breaker. A real implementation needs concurrency safety, a bounded number of half-open probes, error classification, and metrics.
Most importantly, not every failure should trip the circuit. A user supplying an invalid company ID is not evidence that the dependency is unhealthy. Timeouts, connection failures, and appropriate 5xx responses are better signals.
A half-open circuit should not unleash the backlog
The dangerous transition is open → healthy enough to try again.
If 5,000 jobs have been waiting, allowing all of them through because one probe succeeded can immediately reopen the circuit.
Recovery should ramp.
That can mean:
- one or a few probe requests while half-open;
- reduced concurrency after close;
- gradual rate increase;
- queue draining at a bounded pace.
Recovery is part of overload control. Systems often fail a second time because the backlog is released faster than the recovered dependency can absorb it.
Degrade features before rejecting the whole request
Not every dependency is equally important.
Our document-analysis service might have this path:
required: parse PDFrequired: core extraction modeloptional: company enrichmentoptional: web researchIf company enrichment is circuit-open, the job may still be useful without it.
I represent that in the workflow rather than treating every tool failure as fatal:
type CapabilityHealth = { name: string; available: boolean; required: boolean;};The planner can receive a deterministic availability map before it selects optional work. Better still, the host can remove unavailable optional capabilities from the execution plan so the model does not waste a turn choosing a tool that will be rejected immediately.
Graceful degradation is cheaper than turning one third-party outage into a complete product outage.
Backpressure and cancellation should work together
A user cancels a job that has been waiting in a queue for four minutes.
If the queue still delivers it later and the worker starts a model call, the system is spending capacity on work nobody wants.
Queued jobs need a run state or cancellation token that the worker checks before expensive work. For queues that support deletion/revocation, use it, but still make workers cooperative because the message may already be in flight.
Likewise, when a deadline expires while a job is waiting for a dependency permit, release the wait. Do not let timed-out runs remain parked inside semaphores and rate-limit queues.
Capacity control is part of the same lifecycle as deadlines.
Backpressure needs observability of its own
I want metrics that explain whether the service is compute-bound, provider-bound, or simply receiving too much work:
queue depthqueue age / oldest job ageadmission rejection rateactive jobsactive jobs by tenant tierrate-limit wait timeprovider 429 ratecircuit state and open counthalf-open probe success ratecancelled-before-start countQueue age is particularly important. A depth of 100 can be healthy if jobs finish in one second and terrible if jobs take five minutes.
The trace from the previous article should also show how long an individual run spent waiting for a permit versus actually calling the dependency.
Without that distinction, load shedding can look like mysterious application latency.
Do not retry work that backpressure already rejected
There is an easy feedback loop:
- queue is full;
- API rejects a job;
- client retries immediately;
- queue is still full;
- traffic multiplies.
The rejection contract needs retry guidance, and clients need exponential backoff with jitter or a server-provided retry time.
For asynchronous internal workloads, it can be better to leave the message upstream and pause consumption instead of repeatedly moving it between queues.
The goal is to reduce offered load until capacity recovers, not to move the same overload around faster.
When this is overengineering
If an internal assistant has ten users, calls one provider, and never approaches its quota, a circuit-breaker platform and tenant scheduler may be unnecessary.
Start with bounded per-run concurrency and sane timeouts. Add system-level controls when traces show shared-resource contention, queue growth, provider throttling, or noisy-neighbor behavior.
Once those signals appear, though, another semaphore inside the agent loop is not enough.
Agents amplify work. One request can become ten, and one retry policy can multiply those ten again. At production scale, reliability depends on controlling the amount of work the system is willing to accept, not only the amount it can execute at the same instant.
That is what backpressure gives you: a way for capacity limits to become visible before every layer is already overloaded.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article