Phase 05/Operating a distributed serving fleet/Serving agents and RL rollouts
PHASE 05 · Operating a distributed serving fleet

Serving agents and RL rollouts

0%
9 h6 subtopics3 lessons · 2 required
In plain English

Chatbots used to answer one question at a time. Now most traffic comes from agents, programs that ask the model what to do, run a tool such as a web search or a code test, feed the result back, and repeat for dozens of rounds. Each round re-sends the whole growing conversation, so the same long prefix hits the servers again and again. Research teams also run reinforcement learning, where the model generates thousands of short attempts, gets graded, has its weights updated, and generates again. Both workloads look nothing like a chat transcript. Think of a restaurant that used to serve walk-in diners and now mostly serves a catering client who phones in the same large order every ten minutes with one dish changed. You would stop cooking from scratch and keep the common dishes warm. This topic is about recognising these shapes and tuning the serving system for them: remembering shared prefixes, budgeting the time between tool calls, and swapping model weights while the kitchen stays open.

Why it matters

Agent sessions and RL rollouts are the fastest-growing inference workloads at the labs hiring for these roles. They stress prefix caching, routing and scheduling in ways chat does not, and RL adds a new requirement, weight hot-swap between generation rounds. Engineers who understand these shapes design the caches, routers and APIs the next generation of serving needs.

Hiring signal

xAI's training and inference role asks engineers to accelerate research on scaling test-time compute and RL rollout, Cursor notes that every agent session and tab completion flows through its routing and inference stack, and poolside wants inference throughput and latency improvements for evals and reinforcement learning.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Cursor, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Poolside, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Characterise agent traffic (turn count, context growth, tool-call gaps, prefix sharing) from a trace and contrast it with chat traffic.
  • Measure prefix-cache hit rate under different routing and cache-size choices using synthetic agent traces.
  • Build a latency budget for a multi-step agent loop and show where prefix caching and tool latency dominate.
  • Explain how RL frameworks (TRL, verl) use vLLM for rollouts and what weight synchronisation requires from the engine.
  • Demonstrate a weight hot-swap in a running model server with bounded pause and verified outputs.

Key concepts

Agent loop
Model turn, tool call, tool result appended, repeat; context grows every turn and most of it is identical to the previous turn.
Prefix cache hit rate
Fraction of prompt tokens whose KV was already resident; the dominant lever on agent TTFT and prefill cost.
Session affinity
Routing all turns of one agent session to the same replica so its KV blocks stay hot; trades balance for hit rate.
Cache-aware routing
Routing by predicted cache locality (prefix hash or KV index) rather than by session id alone, as in vLLM production-stack and SGLang router.
Tool-call latency budget
The breakdown of one agent step into TTFT, decode, tool-call parsing and tool execution, and the SLO for the whole step.
Test-time compute
Spending more generation per task (many samples, long reasoning, verifiers); multiplies decode load per user request.
Rollout
Generating many completions from the current policy for RL training; short outputs, huge batch, throughput-bound.
Weight hot-swap
Loading new weights into a running engine between rollout rounds without reloading the process, usually via NCCL broadcast from the trainer or a shared store.
Sleep mode and KV reset
Releasing or offloading engine memory while the trainer runs so GPUs can be shared between training and generation.

Subtopics

  1. 1. Shape of agent traffic

    Turn counts of 10 to 100, context growth per turn, high prefix overlap, bursty tool gaps, long tails; how it differs from chat in a trace.

  2. 2. Prefix caching at scale

    Block-hash caching in vLLM, radix trees in SGLang, eviction policy, hit rate versus cache size and replica count, cache-aware routing.

  3. 3. Tool calls and structured output in the loop

    Tool-call parsing, constrained decoding cost, streaming partial tool calls, parallel tool calls, keeping the engine busy during tool execution.

  4. 4. Latency budgets for multi-step loops

    Decomposing per-step latency, where TTFT versus decode versus tool time dominate, and the SLO for a 20-step task.

  5. 5. RL rollout serving

    Throughput-bound generation of short completions, synchronous versus asynchronous rollouts, colocated versus separate generation GPUs, vLLM in TRL and verl.

  6. 6. Weight synchronisation and hot-swap

    NCCL broadcast from trainer to engine, load_weights without restart, KV cache invalidation, sleep and wake-up modes, versioned weights for in-flight requests.

Resources

documentation
paper
repo

Hands-on lessons

L1

Prefix-cache hit rate on synthetic agent traces

CPU · your Macnotebook120 minrequired

Goal · A simulator of block-level prefix caching across N replicas fed by synthetic agent sessions, reporting token-level hit rate for random, session-affinity and prefix-hash routing across cache sizes.

  1. 1Generate 500 agent sessions, each with a 1200-token shared system prompt, a session-specific 400-token task, and 8 to 40 turns where each turn appends 300 to 900 new tokens and reuses the entire previous context.
  2. 2Interleave sessions in time so that at any moment about 50 sessions are active, and emit one request per turn with its full token sequence.
  3. 3Implement a per-replica block cache with 16-token blocks, chained block hashing and LRU eviction, parameterised by capacity in blocks.
  4. 4Implement three routers (random, session-affinity by session id, prefix-hash of the first 1600 tokens with least-loaded fallback) over 4 replicas.
  5. 5For capacities of 50k, 200k and 1M tokens per replica, run all three routers and record token-level hit rate, requests per replica (balance) and total uncached prefill tokens.
  6. 6Plot hit rate versus capacity per router and a bar chart of per-replica load variance.
  7. 7Repeat with 1 replica to get the upper bound and report how far each router sits from it.
Deliverable
prefix_cache_sim.ipynb with the two plots and a summary table.
Check
With 4 replicas and 200k-token caches, session-affinity hit rate is at least 2x the random-routing hit rate; hit rate is monotonically non-decreasing with capacity for every router; the single-replica hit rate is the highest value in the table.
L2

Latency budget for a 10-step agent loop

CPU · your Macscript90 minrequired

Goal · A model of one agent task that breaks each step into TTFT, decode and tool time, shows the effect of prefix caching, and produces a per-step budget table.

  1. 1Parameterise TTFT as 50 ms plus 0.1 ms per uncached prompt token, ITL as 20 ms, 60 output tokens per step, tool latency log-normal with median 300 ms, context starting at 2000 tokens and growing 800 tokens per step.
  2. 2Simulate 10 steps with no prefix cache (every token uncached) and with a perfect cache (only the 800 new tokens uncached per step); sum TTFT, decode and tool time per step and in total over 1000 Monte Carlo runs.
  3. 3Compute the share of total latency from TTFT, decode and tools in both cases and print p50 and p99 total task latency.
  4. 4Add a cache-miss probability of 20 percent per step (for example after a replica change) and recompute.
  5. 5Write a budget table that allocates a 25 s p99 target across the three components and states which component is over budget in each scenario.
  6. 6Add a parallel-tool-call variant where two tools run concurrently per step and report the change.
Deliverable
agent_budget.py and the printed budget tables for the three scenarios.
Check
Without caching total TTFT over 10 steps is about 6.1 s and roughly 29 percent of a roughly 21 s task; with a perfect cache total TTFT is about 1.3 s and under 10 percent, and total task latency drops by at least 20 percent.
L3

Weight hot-swap in a running model server

CPU · your Macscript120 minoptional

Goal · A FastAPI server around GPT-2 small that keeps serving generations while swapping to a second set of weights, with the pause measured and the post-swap outputs verified against an offline model.

  1. 1Create weights v2 by loading gpt2, adding a fixed-seed small perturbation to the LM head, and saving a state_dict; keep the original as v1.
  2. 2Write server.py exposing /generate (greedy, 16 tokens, batched across concurrent requests every 50 ms) and /swap which loads a state_dict into the live model under a lock using load_state_dict and tags responses with a weights version.
  3. 3Run a client sending 20 concurrent requests in a loop for 60 s; at 30 s call /swap to v2; record per-request latency and version.
  4. 4Measure the pause as the maximum gap in completions around the swap and the number of requests that observed each version.
  5. 5Verify that every response tagged v2 for a fixed prompt equals the output of an offline model loaded with v2 weights, and the same for v1.
  6. 6Read the TRL vLLM integration page and list which vLLM API the trainer uses to push weights and how KV cache is handled after a swap; add a short comparison to your approach.
Deliverable
server.py, the client log and a note comparing your swap with the TRL and verl mechanisms.
Check
No request fails during the swap; the maximum completion gap around the swap is under 3 s on the Mac; all v2-tagged outputs for the fixed prompt match the offline v2 model exactly and differ from v1.

Build your own

Build your own agent-trace replayer

PythonCPU · your Mac~6 h

A load generator that replays multi-turn agent sessions with dependent turns and tool latencies against an OpenAI-compatible endpoint, reports prefix-cache hit rate per routing policy and produces a per-step latency budget.

The real thing: github.com/vllm-project/vllm/tree/main/benchmarks/multi_turn ↗

How you know a stage passes

Write tests/test_replayer.py first. Traces are JSONL validated against a schema; the replayer runs against your Phase 3 GPT-2 server with block-level prefix caching (which reports cached_tokens in usage) or against the stub fleet behind your router. Hit rates on synthetic traces are compared with closed forms, and timestamps in the output CSV are checked for dependency ordering. Run `pytest -q`.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01trace format and generator
    A session is a list of turns; each turn has the full prompt (system, history, tool results), an output length and a tool latency; a generator produces sessions from a parameter file and an importer converts your own ReAct loop logs.
    test · The schema validates generated and imported traces; a 100-session trace has mean turns per session and mean prompt growth per turn within 5 percent of the parameters.
  2. 02dependent-turn replay
    Sessions run concurrently but turns within a session are sequential, the next turn starting only after the previous output completes plus the tool latency; per-turn TTFT, ITL and status go to a CSV.
    test · No turn's start timestamp precedes the previous turn's end plus tool time (asserted for every session); at concurrency 1 the wall time is within 10 percent of the critical-path lower bound.
  3. 03prefix-cache hit accounting
    Cached versus computed prompt tokens per turn are taken from the server's cached_tokens field (or from your own block hashes) and aggregated per session and per replica.
    test · Against one replica with 16-token blocks the hit rate at turn k equals the closed form from the shared prefix length; against 4 replicas with random routing it is about one quarter of the single-replica value.
  4. 04routing policies in the loop
    The replayer can route itself (random, session affinity, prefix hash) across N endpoints, or send everything through your router, and prints hit rate against p50 and p99 TTFT per policy.
    test · At N=4 session affinity gives at least 3x the hit rate of random and lower p50 TTFT; the comparison table is written to results/ and the README.
  5. 05the per-step latency budget
    For a 10-step task the report breaks each step into TTFT, decode and tool time, shows the share of each over the whole task, and supports what-if flags such as prefix cache off or 2x faster tools.
    test · The budget table sums to the measured session latency within 5 percent; the what-if prediction for prefix cache off matches a real re-run with caching disabled within 10 percent.
  6. 06RL rollout mode with weight hot-swap
    Many short sessions sample from a prompt pool while the replayer calls the hot-swap endpoint from lesson l3 between batches and records the pause and throughput before and after.
    test · No request fails during the swap, the swap pause is under 5 s for GPT-2 small, and generated-token throughput before and after the swap agree within 10 percent.

Knowledge check

QWhy does agent traffic get a much higher prefix-cache hit rate than chat traffic?

Every turn re-sends the whole previous context plus a small addition, so most prompt tokens were already prefilled by the previous turn on the same replica.

QWhat does session-affinity routing cost you, and when is prefix-hash routing better?

It can unbalance replicas because sessions differ in length and rate; prefix-hash routing with a least-loaded fallback keeps locality for shared prefixes while spreading load.

QWhy are RL rollouts throughput-bound rather than latency-bound?

Thousands of short completions are generated per step and nobody is waiting on an individual one; the goal is tokens per second per GPU, so very large batches are used.

QWhat must a serving engine do when new weights arrive between rollout rounds?

Load the weights into the existing process (ideally via NCCL from the trainer), invalidate or drain the KV cache so stale activations are not reused, and version responses so in-flight requests are not mixed.

QIn a 10-step agent loop with a perfect prefix cache, which component dominates latency?

Decode time; TTFT falls to a small share once only the new tokens are prefilled, and tool time is workload dependent.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • Lesson l1 simulator shows the expected hit-rate ordering and monotonicity.
  • Lesson l2 budget tables reproduce the stated shares and the caching gain.
  • Can describe how TRL or verl use vLLM for rollouts and name the weight-sync mechanism.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →