Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·179

AI Serving and Infrastructure

Putting models behind reliable, efficient interfaces: API styles (REST, gRPC, SSE, WebSockets, WebRTC) and when each fits, streaming tokens end to end through proxies and gateways, dynamic micro-batching implemented with asyncio, concurrency limits, queueing and backpressure with admission control and load shedding, timeouts, retries and fallbacks across providers, autoscaling on the right signals with scale-to-zero and cold starts, GPU scheduling on Kubernetes (device plugins, MIG and time-slicing, node pools, bin-packing, priorities), model caching at every layer (weights, KV/prefix, response and semantic caches), asynchronous jobs for long work, model gateways, multi-region and cost controls, with a runnable FastAPI service and patterns in Java, Go, TypeScript and Rust.

24 topics · ~19 min read · 29-question quiz
Updated Suggest a correction

Start here: putting a model behind an API

Serving means making a model available to applications: an HTTP endpoint that accepts a prompt and returns text, fast enough, for many users at once, without falling over. Three ideas carry most of the weight.

Stream the answer

A model produces tokens one at a time, so send them as they're made. With streaming (usually Server-Sent Events, SSE), the user sees the first words in milliseconds instead of waiting for the whole answer. In the lab, a 48-token answer took 184 ms in full, but its first token arrived after 9 ms. On a large model the difference is seconds, and it changes how fast the product feels.

Share the model between requests

The naive server runs each request's generation separately; requests then queue for the processor. A batching server combines requests so each pass through the model serves several users (chapter 166). The lab's two servers, same model, same machine, 16 users at once:

Tokens per second Time to first token (median) Full answer (median)
one generation per request 261 1,266 ms 2,320 ms
simple batching 1,287 251 ms 592 ms

Batching gave nearly 5× the throughput and made every user's experience better, not worse.

Protect the service

Production endpoints add authentication, per-user rate limits and token budgets, timeouts, request size limits, queue limits with clear "busy" responses, health checks, and autoscaling. Under overload, a fast "try again shortly" beats a two-minute hang.

How deep to go in AI serving

Volume 17 defines six mastery levels; for serving they look like this:

Level You can…
L1 explain streaming, batching, rate limits and why they matter
L2 serve a model behind a streaming API with an inference engine or provider
L3 explain scheduling, queueing, autoscaling signals and gateway features
L4 debug latency spikes, overload, stuck streams and cost blow-ups
L5 design serving architecture: gateways, routing, fallbacks, multi-region, capacity
L6 run AI serving fleets with SLOs, cost governance and incident response

The serving stack

clients API gatewayauthn · limits app / orchestratorRAG · tools AI gatewayroute · fallback REST · gRPC · SSE external model provider APIs self-hosted inference servers GPU pod GPU pod GPU pod async jobsqueue → workers→ object storage→ webhook autoscale onqueue depth
Layers of an AI serving stack. Clients call an API over REST or gRPC, often streaming responses with server-sent events. An API gateway handles authentication and rate limits; an AI or model gateway routes requests to providers or self-hosted models with fallbacks, caching and cost tracking. Self-hosted inference servers run on GPU node pools managed by Kubernetes, scaled on queue depth, with model weights cached locally.

API styles

Style Strengths Use for
REST + JSON Universal, cacheable, easy to debug; OpenAI-compatible APIs are a de facto standard for LLM endpoints Public APIs, most application calls
gRPC (HTTP/2 + Protobuf) Typed contracts, compact binary payloads, bidirectional streaming, deadlines and cancellation built in Service-to-service inference (Triton, internal embedding/ranking services), high-throughput low-latency calls
Server-sent events (SSE) Simple one-way streaming over HTTP (text/event-stream), works through most proxies, auto-reconnect in browsers Token streaming to browsers and clients
WebSockets Full-duplex, low-latency messaging Interactive sessions, collaborative UIs, realtime voice over a server
WebRTC Low-latency audio/video with jitter buffers and NAT traversal Realtime voice and video agents in browsers/apps (chapter 173)
Async job APIs Submit → job id → poll or webhook Long tasks: batch embeddings, video generation, large document processing

Batch APIs offered by providers (submit many requests, results within hours, at a discount) suit offline workloads like evaluation runs and backfills.

Streaming end to end

Streaming tokens (chapter 156) is the single biggest perceived-latency win. Making it work across a real stack:

  • Every hop must stream: application → gateway → load balancer → CDN/proxy → client. Disable response buffering on proxies (e.g. NGINX proxy_buffering off or X-Accel-Buffering: no), avoid middleware that reads whole bodies (compression on SSE, some WAFs), and set idle timeouts longer than the longest generation.
  • SSE format: data: {...}\n\n events; send periodic comments (: keep-alive) for long silent phases (tool calls, reasoning); end with a terminal event.
  • Cancellation: when the client disconnects, cancel the upstream generation (saves tokens and GPU time).
  • Partial failures: a stream can fail midway; send an error event the client can render, and make retries idempotent.
  • Structured streaming: stream text deltas, tool-call events and final metadata (usage, finish reason) as typed events.

A runnable service: streaming, batching, limits, caching

Python
import asyncio, hashlib, json, time
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

app = FastAPI()

# --- Dynamic micro-batching for an embedding model ---------------------------------------------
class MicroBatcher:
    """Collect requests for up to max_wait_ms or max_batch items, run one batched model call."""
    def __init__(self, model_fn, max_batch=32, max_wait_ms=5):
        self.model_fn, self.max_batch, self.max_wait = model_fn, max_batch, max_wait_ms / 1000
        self.queue: asyncio.Queue = asyncio.Queue(maxsize=1024)     # bounded → backpressure
        self.batches = []                                             # batch sizes, for the demo
        self._task = None

    async def submit(self, text):
        if self._task is None: self._task = asyncio.create_task(self._loop())
        fut = asyncio.get_running_loop().create_future()
        try:
            self.queue.put_nowait((text, fut))
        except asyncio.QueueFull:
            raise HTTPException(503, "overloaded, retry later", headers={"Retry-After": "1"})
        return await fut

    async def _loop(self):
        while True:
            items = [await self.queue.get()]
            deadline = time.monotonic() + self.max_wait
            while len(items) < self.max_batch and (left := deadline - time.monotonic()) > 0:
                try: items.append(await asyncio.wait_for(self.queue.get(), left))
                except asyncio.TimeoutError: break
            self.batches.append(len(items))
            vectors = await asyncio.to_thread(self.model_fn, [t for t, _ in items])   # one GPU call
            for (_, fut), v in zip(items, vectors): fut.set_result(v)

def fake_embed_batch(texts):                       # stand-in: batched calls cost little more than single ones
    time.sleep(0.01)
    return [[len(t), sum(map(ord, t)) % 97] for t in texts]

batcher = MicroBatcher(fake_embed_batch)

class EmbedIn(BaseModel):
    text: str

@app.post("/v1/embed")
async def embed(body: EmbedIn):
    return {"embedding": await batcher.submit(body.text)}

# --- Concurrency limit + exact-match response cache + SSE streaming -----------------------------
GEN_SLOTS = asyncio.Semaphore(8)                    # max concurrent generations per replica
CACHE: dict[str, list[str]] = {}

class ChatIn(BaseModel):
    prompt: str
    tenant: str

async def fake_generate(prompt):                    # stand-in for an inference server or provider stream
    for word in f"Answer to: {prompt}".split():
        await asyncio.sleep(0.005); yield word + " "

@app.post("/v1/chat/stream")
async def chat_stream(body: ChatIn, request: Request):
    key = hashlib.sha256(f"{body.tenant}|{body.prompt}".encode()).hexdigest()   # tenant-scoped cache key
    if GEN_SLOTS.locked():
        raise HTTPException(429, "too many concurrent requests", headers={"Retry-After": "2"})  # shed load early

    async def events():
        if key in CACHE:
            for tok in CACHE[key]: yield f"data: {json.dumps({'delta': tok, 'cached': True})}\n\n"
        else:
            async with GEN_SLOTS:
                toks = []
                async for tok in fake_generate(body.prompt):
                    if await request.is_disconnected(): return              # client left → stop generating
                    toks.append(tok); yield f"data: {json.dumps({'delta': tok})}\n\n"
                CACHE[key] = toks
        yield f"data: {json.dumps({'done': True})}\n\n"

    return StreamingResponse(events(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})

Exercising it in-process:

Python
import httpx

async def demo():
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://svc") as client:
        rs = await asyncio.gather(*[client.post("/v1/embed", json={"text": f"doc {i}"}) for i in range(50)])
        print(len(rs), rs[0].json(), batcher.batches)          # 50 requests → batches [32, 18]: two model calls
        async with client.stream("POST", "/v1/chat/stream", json={"prompt": "hi", "tenant": "acme"}) as r:
            print([line async for line in r.aiter_lines() if line.startswith("data:")][:2])

asyncio.run(demo())

Batching

Batching is how GPU serving becomes economical (chapter 166):

  • LLM generation: inference engines do continuous batching internally; your service should send requests concurrently and let the engine batch.
  • Encoders, rerankers, classifiers, embeddings: dynamic micro-batching (as above, or built into Triton, TorchServe, Ray Serve, BentoML, TEI) trades a few milliseconds of waiting for much higher throughput.
  • Offline batch: large jobs (embedding a corpus, scoring a dataset) go through batch pipelines or provider batch APIs, not the online path.

Tune max batch size and max wait against latency SLOs; measure throughput vs p95 latency curves.

Concurrency, queueing and backpressure

When demand exceeds capacity, something must give. Decide what, deliberately:

  • Concurrency limits per replica (in-flight generations), per tenant and per user; protect shared GPUs from noisy neighbours.
  • Bounded queues: an unbounded queue turns overload into unbounded latency and memory growth. Bound the queue, and when full, reject fast (HTTP 429/503 with Retry-After) rather than time out slowly.
  • Admission control and priorities: interactive traffic before batch; paid tiers before free; short requests may get separate lanes so long prompts don't block them.
  • Load shedding at the edge when queues grow beyond SLO-compatible depths (Little's law: queue length = arrival rate × wait time).
  • Client behaviour: exponential backoff with jitter, respect Retry-After, idempotency keys (chapter 168).
  • Deadlines propagated across hops (gRPC deadlines, timeouts in HTTP clients) so abandoned work stops.

Timeouts, retries and fallbacks

  • Timeouts sized to the operation: first-token timeout (detect stalls quickly) and total timeout (long generations).
  • Retries only for retryable errors (429, 5xx, network), with backoff and limited attempts; never retry non-idempotent tool calls blindly.
  • Fallbacks: provider A → provider B, large model → smaller model, live answer → cached or degraded answer ("we're busy; here's the help-centre article"). Gateways (LiteLLM, cloud AI gateways, Spring AI/LangChain4j abstractions) implement routing and fallback chains; evaluate each fallback model on your suite (chapter 175) so degraded mode is still acceptable.
  • Circuit breakers (chapter 67) stop hammering a failing provider.

Autoscaling

Signal Why
Queue depth / waiting requests Directly predicts latency for GPU-bound servers
In-flight requests / concurrency per replica Saturation of batching capacity
KV-cache utilisation LLM memory headroom (chapter 166)
Tokens per second vs capacity Throughput saturation
GPU utilisation Useful but lagging; high utilisation can be healthy
CPU Usually the wrong signal for GPU inference

Tools: Kubernetes HPA with custom/external metrics, KEDA (event-driven scaling, including from queue lengths and Prometheus queries), Knative/KServe (scale-to-zero for infrequently used models), Ray Serve autoscaling, cloud managed endpoints.

Cold starts are the hard part: pulling a 20 GB container, downloading 40 GB of weights and loading them into GPU memory can take minutes. Mitigations: keep minimum replicas warm for interactive models, cache weights on node-local NVMe or a shared high-throughput filesystem, use pre-pulled images, load weights with memory mapping / streaming loaders, scale ahead of predictable peaks, and reserve scale-to-zero for batch or rarely used models.

GPU scheduling

On Kubernetes:

  • Device plugins (NVIDIA GPU Operator) expose nvidia.com/gpu as a schedulable resource; pods request whole GPUs.
  • Sharing: MIG (Multi-Instance GPU) partitions A100/H100-class GPUs into isolated slices with dedicated memory; time-slicing and MPS share a GPU without memory isolation; Dynamic Resource Allocation (DRA) gives richer device requests in newer Kubernetes versions. Small models (embeddings, rerankers) often fit MIG slices.
  • Node pools per GPU type (inference-optimised vs training GPUs), with taints/tolerations and node affinity so only GPU workloads land there.
  • Topology: tensor-parallel replicas need GPUs connected by NVLink on the same node; use topology-aware scheduling.
  • Bin-packing and priorities: pack inference pods efficiently, preempt batch jobs for interactive load (PriorityClasses), use gang scheduling (Kueue, Volcano) for multi-GPU training jobs.
  • Spot/preemptible GPUs for batch and fault-tolerant workloads; on-demand or reserved capacity for latency-critical serving.
YAML
# A vLLM deployment requesting two GPUs on an H100 node pool, scaled by KEDA on waiting requests
apiVersion: apps/v1
kind: Deployment
metadata: { name: llm-qwen32b }
spec:
  replicas: 2
  selector: { matchLabels: { app: llm-qwen32b } }
  template:
    metadata: { labels: { app: llm-qwen32b } }
    spec:
      nodeSelector: { gpu.type: h100 }
      tolerations: [{ key: nvidia.com/gpu, operator: Exists, effect: NoSchedule }]
      containers:
        - name: vllm
          image: vllm/vllm-openai:stable                # pin an exact version in production
          args: ["--model", "/models/qwen3-32b", "--tensor-parallel-size", "2", "--enable-prefix-caching"]
          resources: { limits: { nvidia.com/gpu: 2 } }
          readinessProbe: { httpGet: { path: /health, port: 8000 }, periodSeconds: 5 }
          volumeMounts: [{ name: models, mountPath: /models, readOnly: true }]
      volumes: [{ name: models, persistentVolumeClaim: { claimName: model-cache } }]
---
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: llm-qwen32b }
spec:
  scaleTargetRef: { name: llm-qwen32b }
  minReplicaCount: 2
  maxReplicaCount: 8
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus.monitoring:9090
        query: sum(vllm:num_requests_waiting{app="llm-qwen32b"})
        threshold: "10"

Model caching

Caching appears at several layers:

Layer What's cached Notes
Weights Model files on local NVMe / shared filesystem / in a warm pool Cuts cold starts
KV / prefix cache Attention state for shared prompt prefixes (engine-level), provider prompt caching Lower TTFT and cost; design prompts stable-prefix-first (chapter 166)
Exact response cache Responses for identical (normalised) requests, keyed by model, prompt version, parameters and tenant Only for deterministic-enough requests (temperature 0, no personal context); invalidate on prompt/model version changes
Semantic cache Responses for requests whose embeddings are very close to a cached one Risky: near-identical wording can need different answers; use high thresholds, scope by tenant, restrict to FAQ-like traffic, evaluate false-hit rates
Embedding cache Embeddings of documents/queries keyed by text hash and model version Saves recomputation in RAG pipelines
Tool-result cache Results of idempotent, slow tools TTLs matching data freshness

Asynchronous work

Long or heavy tasks (document batches, video, multi-agent research, fine-tuning jobs) should not hold HTTP connections open:

  1. POST /jobs validates and enqueues (Kafka, SQS, Pub/Sub, Redis streams, a workflow engine), returns 202 Accepted with a job id.
  2. Workers (GPU or CPU pools) process with retries, checkpoints (chapter 171) and idempotency.
  3. Results go to object storage; status in a database.
  4. Clients poll GET /jobs/{id}, subscribe via SSE/WebSocket, or receive a signed webhook.

Multi-region, cost and capacity

  • Region selection: data residency requirements, latency to users, provider model availability per region, GPU capacity.
  • Failover across regions/providers via the gateway; regular failover tests.
  • Capacity planning from measured goodput per replica (chapter 166) and growth forecasts; reserve capacity for baseline, burst with on-demand or providers.
  • Cost controls: per-tenant quotas, model routing (small models for easy work, chapter 158), caching, batch APIs for offline work, right-sized GPUs, utilisation reviews, turning off idle endpoints.

Across stacks

// Java: Spring WebFlux SSE endpoint streaming tokens from Spring AI
@RestController
class ChatController {
    private final ChatClient chat;
    ChatController(ChatClient.Builder b) { this.chat = b.build(); }

    @PostMapping(path = "/v1/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<ServerSentEvent<String>> stream(@RequestBody Ask ask) {
        return chat.prompt().user(ask.prompt()).stream().content()
                   .map(t -> ServerSentEvent.builder(t).build())
                   .timeout(Duration.ofSeconds(90));     // cancellation propagates when the client disconnects
    }
}

Lab: a streaming model server, naive and batched

Setup. FastAPI 0.162 with sse-starlette under uvicorn 0.54 (one process), chapter 156's tiny GPT with a KV cache, PyTorch on 2 CPU threads, on the lab machine. POST /generate takes a prompt and streams 48 tokens as SSE events (data: {"token": "…"}, then data: [DONE]). Prompts are cut or padded to 32 tokens. A load generator (httpx async client) runs 8 requests at concurrency 1, and 32 requests at concurrency 4 and 16, measuring time to first token (TTFT), time to the full response, and total tokens per second. Scope: CPU and a 2 M-parameter model; with GPUs and real engines the absolute numbers change by orders of magnitude, and the shape of the results doesn't.

Two serving modes:

  • per-request: each request runs its own prefill and decode loop in a worker thread; a lock lets one forward pass run at a time, so requests take turns step by step.
  • batched: a scheduler thread collects requests arriving within 5 ms, runs them as one batch (one prefill, then one decode step per token for all of them together) and routes each token to its stream. New requests wait for the current batch to finish (static batching).

Results

Mode Concurrency TTFT p50 TTFT p95 Full response p50 Tokens/s
per-request 1 9 ms 11 ms 184 ms 261
per-request 4 26 ms 30 ms 726 ms 261
per-request 16 1,266 ms 2,344 ms 2,320 ms 261
batched 1 13 ms 14 ms 155 ms 304
batched 4 18 ms 25 ms 236 ms 748
batched 16 251 ms 255 ms 592 ms 1,287

What the numbers say

  • Streaming: at one user, the first token arrived in 9–13 ms out of a 155–184 ms response. A non-streaming endpoint would show the user nothing until the end.
  • Per-request serving hit a ceiling: throughput stayed at 261 tokens/s whatever the load, because each forward pass computed one token for one user. Extra users only lengthened the queue: at 16, the median user waited 1.3 s for the first token. (Part of that wait was also uvicorn's default thread pool, which runs only a handful of generations at once; the rest queued before starting.)
  • Batching multiplied throughput by 4.9× at 16 users and cut the median full response from 2.3 s to 0.6 s: the same CPU did more useful work per pass.
  • Static batching's flaw is visible in TTFT: at 16 users, a request arriving mid-batch waited for that batch to finish (≈ 250 ms). Continuous batching (chapter 166) admits it at the next decode step; that's what vLLM, SGLang, TGI and TensorRT-LLM do, with paged KV-cache memory so batches can grow and shrink freely. In production you put a gateway (authentication, rate limits, budgets, routing, retries, fallbacks) in front of such an engine rather than writing the batcher yourself.

Try it yourself

  1. Add an asyncio.Semaphore admission limit with a 429 response when the queue is full, and measure p95 TTFT at concurrency 32 with and without it.
  2. Make the batcher admit new requests between decode steps (continuous batching) by keeping per-request KV caches and positions; measure TTFT at 16.
  3. Detect client disconnects and cancel their generation; measure the wasted tokens it saves.
  4. Put two server replicas behind nginx with least_conn and measure throughput at concurrency 32.

Revision sheet: AI serving

Key ideas

  • Serving options: hosted APIs, managed endpoints, self-hosted engines (vLLM, SGLang, TGI, TensorRT-LLM, llama.cpp/Ollama).
  • Streaming (SSE or WebSockets) for perceived latency; handle disconnects and cancel work.
  • Batching: continuous batching in the engine; the web tier shouldn't block on generation.
  • Gateways: authentication, rate limits and token budgets per user/tenant, routing across models/providers, retries and fallbacks, caching, logging, cost attribution.
  • Capacity: concurrency × (prompt + output tokens) vs engine throughput; queue limits and load shedding (429 with Retry-After).
  • Autoscaling on queue depth, KV-cache utilisation or tokens/s, not CPU; cold starts dominated by weight loading.
  • Reliability: health and readiness checks, timeouts at every hop, idempotent retries, multi-region and multi-provider fallbacks.
  • Cost: right-size models, route simple requests to small models, cache, quantise, use batch APIs for offline work.

Numbers to remember

  • Lab: TTFT 9 ms vs full answer 184 ms at one user (streaming).
  • Lab: 16 users: per-request 261 tok/s, TTFT p50 1,266 ms; batched 1,287 tok/s, TTFT 251 ms.

Pitfalls

  • Running generation inside the async event loop or an unbounded thread pool.
  • No admission control: overload becomes multi-minute latency.
  • Autoscaling on CPU for GPU-bound work.
  • Retrying non-idempotent operations across providers.
  • Not cancelling generation when clients disconnect.

Glossary

  • SSE: Server-Sent Events, one-way HTTP streaming.
  • Gateway: a proxy enforcing policy and routing for model calls.
  • Load shedding: rejecting excess work quickly to protect latency.
  • Fallback: an alternative model or provider used on failure.
  • Cold start: delay to start a replica, mainly loading weights.