AI

Serving LLM Features: Backpressure, Deadlines and Streaming

A semaphore caps concurrency yet still queues without limit, so we bound admission, split deadlines, resume SSE streams and stop retries from feeding outages.

Weaveward ai editorial illustration

Most advice on serving language model features stops at three moves: make the endpoints async, stream the answer, put an asyncio.Semaphore in front of the provider. They are the right first moves, and they are not enough. A semaphore limits how many calls run at once; it does nothing about how many requests wait for it. Under a spike or a slow provider, that line grows until clients time out, while the server keeps paying for answers nobody will read.

Our view is that an LLM API is a queueing system with an expensive, rate-limited, sometimes slow server behind it, and should be designed as one: a bounded line with an honest "come back in N seconds", one time budget that every stage respects, streams that survive proxies and reconnects, and retries that cannot multiply load during an outage.

Below are the pieces we use, with Python 3.12 and FastAPI code we ran against a local Uvicorn server: an admission controller with per-tenant caps, a deadline helper, and a resumable Server-Sent Events endpoint.

A semaphore caps concurrency, not waiting

Little's law says the average number of items in a stable system equals the arrival rate times the average time each item spends inside: L = λW. Apply it to the semaphore. Suppose, as an illustrative example, each model call holds a slot for 8 seconds on average and the semaphore allows 40. The most you can serve is 40 / 8 = 5 requests per second, whatever you do in Python.

Now let 6 requests per second arrive. Each second the line grows by one. After five minutes 300 requests are waiting, and the newest will wait 300 / 5 = 60 seconds before its model call starts. A client with a 30 second timeout has long gone, but its coroutine is still parked on semaphore.acquire(), and when its turn comes the server spends a slot, and real money, on a closed socket. Utilisation reads 100% while goodput collapses.

The fix is not a bigger semaphore; the slot count should match what the provider can sustain. The fix is to bound the waiting and refuse quickly once the line is long enough. Little's law sizes that line too: accepting at most 2 seconds of queueing at 5 requests per second means room for about 10 waiting requests. Request number 11 is better served by an immediate refusal than by a timeout half a minute later.

Bounded admission: refuse early and say when to retry

The controller below bounds requests in flight, requests waiting, and how much of both one tenant may hold. Slots pass directly to the next waiter in FIFO order, so newcomers cannot jump the line, and a waiter cancelled at the moment it is granted a slot passes the slot on instead of leaking it.

import asyncio
import math
import time
from collections import Counter, deque
from contextlib import asynccontextmanager, suppress

from fastapi import HTTPException


class Shed(HTTPException):
    def __init__(self, status: int, retry_after_s: int, reason: str) -> None:
        super().__init__(status, reason, headers={"Retry-After": str(retry_after_s)})


class Admission:
    def __init__(self, max_inflight: int, max_queue: int, per_tenant: int, max_wait_s: float):
        self.max_inflight, self.max_queue, self.per_tenant = max_inflight, max_queue, per_tenant
        self.max_wait_s, self.inflight, self.service_s = max_wait_s, 0, 5.0
        self.queue: deque[asyncio.Future[None]] = deque()
        self.tenants: Counter[str] = Counter()  # queued + running, per tenant

    def retry_after(self) -> int:
        waves = (self.inflight + len(self.queue)) / self.max_inflight
        return max(1, math.ceil(waves * self.service_s))

    def _release(self) -> None:
        while self.queue:
            waiter = self.queue.popleft()
            if not waiter.done():
                waiter.set_result(None)  # hand the slot over; inflight is unchanged
                return
        self.inflight -= 1

    async def _acquire(self) -> None:
        if self.inflight < self.max_inflight:
            self.inflight += 1
            return
        if len(self.queue) >= self.max_queue:
            raise Shed(503, self.retry_after(), "queue_full")
        waiter = asyncio.get_running_loop().create_future()
        self.queue.append(waiter)
        try:
            async with asyncio.timeout(self.max_wait_s):
                await waiter
        except BaseException as exc:  # timed out, or cancelled while queued
            if waiter.done() and not waiter.cancelled():
                self._release()  # a slot arrived as we gave up: pass it on
            with suppress(ValueError):
                self.queue.remove(waiter)
            if isinstance(exc, TimeoutError):
                raise Shed(503, self.retry_after(), "queue_timeout") from None
            raise

    @asynccontextmanager
    async def slot(self, tenant: str):
        if self.tenants[tenant] >= self.per_tenant:
            raise Shed(429, self.retry_after(), "tenant_cap")
        self.tenants[tenant] += 1
        try:
            await self._acquire()
            started = time.monotonic()
            try:
                yield
            finally:
                self.service_s += 0.1 * (time.monotonic() - started - self.service_s)
                self._release()
        finally:
            self.tenants[tenant] -= 1
            if not self.tenants[tenant]:
                del self.tenants[tenant]

Our asyncio tests covered FIFO order, 503 for a full queue and for a waiter exceeding max_wait_s, 429 for a tenant at its cap while other tenants got through, cancellation while queued, and the grant-then-cancel race. A burst of 300 requests never exceeded the concurrency limit, and every request was either served or shed with a Retry-After of at least one second.

The status code tells the client whose problem it is:

Situation Response Why
Tenant already holds its share of slots and queue 429 with Retry-After This caller is over its share; others are fine
Queue is full 503 with Retry-After The service is saturated for everyone
Waited longer than max_wait_s 503 with Retry-After Admitting now would blow the caller's deadline
Instance is draining for a deploy 503 with Retry-After Another replica should take it

RFC 9110 defines Retry-After as an HTTP date or a whole number of seconds; on a 503 it says how long the service expects to be unavailable. Our estimate is deliberately crude, the "waves" of work ahead times a moving average of slot hold time, but any hint that spreads retries out beats none.

The per-tenant cap counts queued and running requests together, so one noisy tenant cannot fill the queue. This is the per-customer limit from the Google SRE book's overload chapter: under overload, errors should go to the customers exceeding their share. Two caveats. The counters live in one process, so with N replicas a tenant gets N times its cap; global limits belong in Redis or a gateway. And a queued request does not notice its client leaving, so keep max_wait_s short and cap it at the remaining deadline.

Hold the slot for the whole stream

A classic bug: acquire the semaphore inside the endpoint, return a streaming response, and the slot is released before a single token is sent. In current FastAPI the fix is a dependency with yield, declared as Depends(admitted, scope="request"), wrapping admission.slot(tenant). A Shed raised before the yield becomes a normal 429 or 503 with headers, and the code after the yield runs only once the response has finished. Against Uvicorn, two streams held both slots, a third request from the same tenant got 429, another tenant got 503, and both slots returned when the clients disconnected.

Provider limits are a token budget, not a request count

Providers limit requests per minute and tokens per minute, and the token limit bites first because one request can cost 200 tokens or 20,000. A request counter alone admits ten huge prompts that together exceed the provider's limit, and the resulting 429s get multiplied by your retries.

Our Model Gateway & Evals prototype, a TypeScript service on Hono, keeps two token buckets per API key, one for requests and one for tokens, both refilling per minute. Before a call it charges an estimate: the prompt at roughly three UTF-8 bytes per token plus a small per-message overhead, plus the maximum output tokens, since real output length is unknown. Afterwards it adjusts the bucket by actual usage minus the reservation. A request larger than the bucket's whole capacity is refused as too large rather than told to retry, and rate-limit refusals carry a Retry-After from the refill time, rounded up to whole seconds.

Reserving max_tokens up front means a generous default quietly wastes capacity, so set realistic output limits per feature. And give interactive traffic a reserved share of the provider limit, leaving batch work what remains.

Deadlines: one budget, spent in stages

A user-facing request has one budget. Every stage should know how much remains, and none should start work it cannot finish. The helper turns the budget into per-stage asyncio.timeout scopes: each stage gets at most its cap, never eats the time reserved for later stages, and refuses to start below its useful minimum.

import asyncio
import math


class BudgetExhausted(Exception):
    """Too little time left to start a stage: fail now instead of starting doomed work."""


class Deadline:
    def __init__(self, budget_s: float) -> None:
        self._loop = asyncio.get_running_loop()
        self.expires_at = self._loop.time() + budget_s

    @classmethod
    def from_header(cls, value: str | None, default_s: float = 30.0, max_s: float = 120.0) -> "Deadline":
        try:
            ms = float(value) if value is not None else math.nan
        except ValueError:
            ms = math.nan
        ok = math.isfinite(ms) and ms > 0
        return cls(min(ms / 1000, max_s) if ok else default_s)

    def remaining(self) -> float:
        return max(0.0, self.expires_at - self._loop.time())

    def stage(self, cap_s: float, reserve_s: float = 0.0, min_s: float = 0.05) -> asyncio.Timeout:
        """At most cap_s for this stage, never eating the time later stages need."""
        allowed = min(cap_s, self.remaining() - reserve_s)
        if allowed < min_s:
            raise BudgetExhausted(f"{allowed:.3f}s left for a stage that needs {min_s}s")
        return asyncio.timeout(allowed)

# Usage inside a handler:
#   async with deadline.stage(cap_s=1.5, reserve_s=8.0):    retrieval
#   async with deadline.stage(cap_s=25.0, reserve_s=0.5, min_s=3.0):  model call
#   async with deadline.stage(cap_s=0.5):                   post-processing

The header parsing mirrors the gateway's per-request timeout header: a positive, finite value is clamped to a configured maximum (120 seconds in its shipped config), anything else falls back to a default (30 seconds). Our tests covered a slow retrieval capped at its share while the model stage still ran, a model stage timing out inside the total budget, a request refused before any work because the reserve could not be met, and a 0.5 second budget that ended after 0.506 seconds.

Three habits make deadlines real. Pass remaining() downstream as a timeout, so the next service stops when your caller does. Decide per stage whether a timeout degrades or fails: a slow reranker can be skipped, a slow model call cannot. And map BudgetExhausted to a fast 504, so the client learns in milliseconds what it would otherwise learn in thirty seconds.

Streaming that survives proxies, reconnects and walk-aways

Since version 0.135, FastAPI streams Server-Sent Events natively through EventSourceResponse. It sends a : ping comment after 15 seconds without an event, following the HTML specification's advice for keeping proxies from dropping idle connections, and sets Cache-Control: no-cache and X-Accel-Buffering: no so Nginx does not buffer. We confirmed all three on the wire. What it cannot decide for you is what an event id means, how a reconnect resumes, and what a disconnect cancels.

For anything beyond a quick answer, we run the model call as a job that appends events to a per-job log, and the HTTP stream only reads that log. Event ids are the log's sequence numbers, so a browser's Last-Event-ID header on reconnect is a resume point.

from collections.abc import AsyncIterable
from typing import Annotated

from fastapi import FastAPI, Header
from fastapi.sse import EventSourceResponse, ServerSentEvent

app = FastAPI()
TERMINAL = {"done", "failed", "cancelled"}
# log: append-only events per job (Redis Streams in production).
# jobs: counts readers and cancels a job left without readers after a grace period.


@app.get("/jobs/{job_id}/events", response_class=EventSourceResponse)
async def job_events(
    job_id: str,
    last_event_id: Annotated[int, Header(ge=0)] = 0,
) -> AsyncIterable[ServerSentEvent]:
    cursor = last_event_id  # 0 on first connect, the last seen id on reconnect
    jobs.attach(job_id)  # a reader is back: cancel any pending orphan timer
    try:
        yield ServerSentEvent(comment="connected", retry=2000)
        while True:
            for seq, kind, data in await log.read_after(job_id, cursor, wait_s=10.0):
                yield ServerSentEvent(id=str(seq), event=kind, data=data)
                cursor = seq
                if kind in TERMINAL:
                    return
    finally:
        # Runs on a terminal event and when the client disconnects (FastAPI
        # cancels this generator). The job keeps running for grace_s so a
        # reconnect with Last-Event-ID can resume; after that it is cancelled.
        jobs.detach(job_id, grace_s=30.0)

Against Uvicorn with an in-memory log, a client that dropped after three events resumed at event 4 by sending Last-Event-ID: 3 and received everything through done. With a short grace period, a job whose only reader vanished was cancelled; a reader returning inside the window kept it alive.

That grace window reconciles two goals that pull against each other. For a short answer streamed straight from the provider, a disconnect should cancel upstream at once: the generator's cancellation closes the provider request. For a longer job, an instant cancel would throw away work a mobile client needs after a brief network change. The gateway takes the first approach: its deadline aborts the upstream call when the client leaves, an aborted attempt is never retried, an idle timeout between chunks ends a stalled stream, and failover happens only before the first token. After that, a failure ends the stream with an in-band stream_interrupted event rather than switching models mid-answer.

Jobs, lanes and draining a deploy

Long submissions need an Idempotency-Key. Store it per tenant with a hash of the request body and the job id in one atomic insert. A replay with the same key and body returns the existing job; the same key with a different body is rejected. Without this, a client retrying after a network timeout pays for a second generation of the same document.

Interactive and batch work should not share a line:

Interactive lane Batch lane
Transport SSE straight from the request Job queue (Arq, Celery), results via the event log
Deadline Seconds, set by the client Minutes to hours, set by the job
When saturated Shed fast with 429 or 503 Wait in the durable queue
Provider tokens Reserved share Whatever interactive leaves
On disconnect Cancel upstream Keep running

The SRE book calls this criticality: batch traffic tolerates partial unavailability, so it is the first to be slowed.

Deploys are planned overload, so drain in a fixed order. Mark the instance not ready so the load balancer stops routing to it, then flip admission to draining so stragglers get 503 with Retry-After. Give interactive streams a bounded window; Uvicorn's --timeout-graceful-shutdown caps the wait for open connections. Job streams can simply close, since the client reconnects elsewhere with Last-Event-ID, which works only because the log lives outside the process. Batch workers stop taking jobs and finish or requeue the current one.

Retries that cannot amplify an outage

Retries are the fastest way to turn a provider brownout into your own outage. The AWS Builders' Library gives the arithmetic: in a five-layer stack where every layer retries three times, load on the bottom layer can grow 243 times. Three rules prevent it:

  • Retry at one layer only. If a gateway retries provider calls, the application behind it should not retry the same failures again
  • Cap retries per request and per client. The SRE book describes up to three attempts per request plus a per-client budget that allows retries only while they stay under 10% of requests, limiting growth to about 1.1 times in the general case
  • Use exponential backoff with full jitter and honour Retry-After, so clients that failed together do not return together

Deadlines add a fourth: never start a retry the deadline cannot cover. The gateway retries the same provider only for transient outcomes such as timeouts, 5xx responses, rate limits and overload, only within its configured retry count, only while the provider's circuit breaker is closed, and only when the backoff delay is shorter than the remaining deadline. Backoff uses full jitter under a ceiling that starts at 250 ms and is capped at 2 seconds, raised to the provider's Retry-After when one is sent. Our article on gateway failover, budgets and PII covers the rest.

The metrics that tell you it is working

Averages hide everything in this article. These are the signals we chart, split by lane and, where cardinality allows, by tenant:

  • Queue wait: arrival to admission; a rising p95 means limits are too tight or the provider slowed
  • Time to first token: what users feel as speed. The gateway stores it on every request row
  • Tokens per second after the first token: separates a slow provider from a slow queue
  • Shed rate by reason: tenant cap, queue full, queue timeout and draining need different fixes
  • Cancel rate: streams abandoned before the terminal event, often the first sign latency crossed users' patience
  • Retry ratio: must stay under the retry budget
# p95 queue wait per lane
histogram_quantile(0.95, sum by (le, lane) (rate(llm_queue_wait_seconds_bucket[5m])))

# share of requests shed, by reason
sum by (reason) (rate(llm_shed_total[5m]))
  / ignoring(reason) group_left sum(rate(llm_requests_total[5m]))

# p95 time to first token
histogram_quantile(0.95, sum by (le) (rate(llm_ttft_seconds_bucket[5m])))

# streams abandoned by the client before the final event
sum(rate(llm_streams_total{outcome="client_cancelled"}[5m])) / sum(rate(llm_streams_total[5m]))

# retry ratio, compared against the 10% retry budget
sum(rate(llm_upstream_attempts_total{retry="true"}[5m])) / sum(rate(llm_upstream_attempts_total[5m]))

The metric names are our convention. Alert on time to first token and shed rate against an error budget, as our burn-rate alerting article shows.

Checklist

  • Bound the queue with Little's law: queue length is throughput times acceptable wait
  • Shed with 429 for a tenant over its share and 503 for global saturation, always with Retry-After
  • Charge token buckets with prompt estimate plus max_tokens, then settle to actual usage
  • Hold admission slots for the life of a stream with a request-scoped dependency
  • Split one deadline across stages, pass the remainder downstream, and refuse work that cannot finish
  • Give SSE events ids from a durable log, resume from Last-Event-ID, and decide per lane what a disconnect cancels
  • Require idempotency keys on job submission and keep batch work in its own lane
  • Retry at one layer, within a budget, with full jitter and only inside the deadline

Primary references

The gateway behaviour described here comes from our Model Gateway & Evals prototype, and our AI solutions team builds serving layers like these for production features.

Let’s connect the dots

What would this look like for your business?

Let's turn the right ideas into a clear next step.

Discuss your project