Concurrent Requests and Streaming
Thirty-two streams on one batched engine over real sockets: what overlap buys, why a stream's first token waits for its neighbours, what one slow reader does under four policies, and how long the engine goes on working for a client that has gone.
Thirty-two clients each requested 64 tokens from GPT-2 small. Running the same prompts sequentially took a measured total of 22.05 seconds; streaming them concurrently through this chapter’s batched engine took 1.49–1.55 seconds across three repetitions, a 14.2–14.8× makespan improvement for this workload. Aggregate output rose to 1,320–1,376 generated tokens/s, compared with 90–94 tokens/s for a single stream. All 189 concurrent outputs across the tested batch sizes matched their respective solo greedy token sequences. The gain came from sharing decode iterations on one GPU, not from running thirty-two independent model instances.
The same service exposed two costs hidden by a throughput figure. With deliberately inflated events, one slow reader among eight delayed seven healthy streams from roughly one second to roughly 28 seconds under a blocking fan-out policy. Separately, when a client disconnected, the installed Starlette response normally triggered resource release in roughly 9–19 milliseconds at the measured checkpoints, whereas a deliberately write-only response kept generating to the 200-token cap for about two additional seconds. These are controlled observations of one local software stack, not universal network-buffer or cancellation guarantees.
The question
From Inference Loop to API made the inference loop callable through HTTP and measured the request boundary. Request Scheduling and Admission Control placed an admission gate in front of a single-request-at-a-time engine. This chapter changes the execution model: several requests may be active during the same decode step, while each client receives a sequence of output events. The service must coordinate four distinct lifetimes: the HTTP response, a stream’s application queue, the running sequence in the engine, and its reserved KV-cache blocks. Correctness means not only delivering the right tokens but also making a slow or vanished client incapable of indefinitely consuming everybody else’s progress or retaining memory.
The experiments ask four questions. How much aggregate goodput and individual latency change when requests share decode iterations? Which guarantees belong to server-sent events (SSE), and which require an application-level event protocol? At what point does an unread socket cause backpressure on the engine, rather than merely accumulate buffered bytes? And, for normal completion, cancellation, timeout and disconnect, which component owns cleanup and what evidence shows that resources were released exactly once? The measurements also expose what remains untested: sampled-output isolation, atomic HTTP admission, pause/resume synchronisation, bounded memory under slow readers, and live cancellation at full capacity.
Where this sits
PagedAttention built the paged cache and a decode step for sequences of different lengths. Continuous Batching put them in a continuous-batching scheduler and replayed traces against it with a virtual clock, which is a good way to measure a scheduler and not a service. This chapter takes the same pieces and runs a related paged-cache decode live: HTTP requests enter while prior requests remain active, and output events leave before generation has completed. Prefill and Decode defined time to first token and said it must include what happens before the engine; From Inference Loop to API measured that for a one-token request; here it is measured for a stream as a client sees it. The implementation is not a deployment of a complete vLLM-like serving runtime: its prefill is sequential within a step, and PagedAttention’s paged decode still gathers KV data into a dense working representation. The experiment therefore qualifies this particular step-driven architecture.
The deadline-aware gate from Request Scheduling and Admission Control is not integrated here. The new service has a count-based check on pending requests and a batch-slot limit, neither of which guarantees a latency deadline or a memory budget across clients. Its input check observes queue lengths rather than acquiring an atomic capacity reservation, so it is not yet a concurrency-safe admission primitive under simultaneous arrivals. Reliability, Cancellation and Recovery will revisit cancellation requested by a service or caller, timeouts and retries; this chapter concentrates on cancellation induced by the HTTP stream’s lifetime and on validating resource release. The separation is useful: scheduling, flow control and disconnect detection are different contracts even when they share the same sequence object.
A step-driven engine
A request-at-a-time engine holds a lock until a generation is finished. A step-driven engine instead advances the work in bounded increments, letting an execution controller admit and remove requests between model operations. In this lab, one engine owns the paged KV cache, while an asyncio hub collects HTTP sessions and dispatches events. An iteration can prefill newly admitted sequences and decode one token for each eligible existing sequence. This is the mechanism behind the batch throughput measurements, and a practical instance of the iteration-level scheduling idea described by Orca (OSDI 2022); it is not a reproduction of Orca’s distributed design or results.
- Drain the thread-safe submission and cancellation inbox at the start of a step. Newly submitted requests join FIFO waiting state; accepted cancellations terminate the corresponding sequence.
- Admit waiting requests in FIFO order while batch slots and the reserved-block budget allow. Reserve enough blocks for their prompt and declared maximum generation length, then prefill each prompt sequentially and produce its first token.
- Decode one token for each eligible previously active sequence using the PagedAttention paged-cache batch path. A sequence freshly prefilled during this step is not decoded a second time in the same step.
- Emit token and finish events. Completion and cancellation remove the sequence and release any held cache blocks at an engine-controlled point.
All allocation and free operations on the paged cache occur in BatchEngine.step(), which first drains a lock-protected inbox for submit and cancel. A finish routine checks state and releases owned blocks once; the block table itself raises on a double free. The code does not yet provide the same synchronisation guarantee for pause and resume: these directly set a sequence’s paused flag from the hub thread, rather than queuing a command under the inbox lock. The lab’s pause tests show intended behaviour, but they do not establish race-free state transitions under adversarial interleaving. A publication-quality implementation should route pause/resume through the same inbox and assert that all active-state mutations occur on the engine’s owner thread.
Batched decoding amortises model work: a step containing thirty-two sequences is more expensive than one containing a single sequence, but not thirty-two times as expensive. For steps with no prefill, the recorded GPU-synchronised medians on GPT-2 small are:
| Sequences in the step | 1 | 2 | 4 | 8 | 16 | 32 |
|---|---|---|---|---|---|---|
| Median step time | 9.8 ms | 10.8 | 11.6 | 12.1 | 11.8 | 15.1 ms |
At the endpoints, 32 sequences cost about 15.1 / 9.8 = 1.55 times a single sequence. A straight line through those two points gives an illustrative incremental slope of about 0.17 ms per added sequence, not a fitted performance model. (Memory Bandwidth and Compute Bottlenecks found 7 to 20 per cent more per step for up to 32 sequences with a static cache. This step is the paged one of PagedAttention, which gathers each sequence’s blocks into a padded tensor, and I did not separate the two causes of the larger figure. The small relative growth is consistent with substantial fixed per-step overhead on this small model; the experiment did not profile kernels or independently separate launch overhead, KV gathering, model computation and host work.) The first-order model of a request in a full batch follows from it: its tokens come about one step apart. Note also that these are medians conditional on observed batch size; they are not the latency of an individual request, and they do not include the sequential prefills or network delivery.
The time at which a token is computed is not necessarily the time a client receives it. A newly admitted sequence generates its first token during prefill, but the hub receives and distributes the step’s event list only after that step has finished. In a simultaneous burst, an early prompt can therefore wait for every later prompt’s prefill before its first token becomes visible. The lab records wall-clock TTFT at the client, capturing this batching barrier along with local HTTP and event handling, but does not instrument a per-prefill event-delivery path. This distinction matters for production systems where first-token latency has its own service-level objective.
Isolation
Isolation must be demonstrated at the output boundary. Each sequence has separate position history and KV-cache ownership, but its logits are computed in shared batched operations, which may change floating-point ordering or backend selection. Model Architecture Versus Runtime Architecture found three tie-related token changes in twelve half-precision padded-batch comparisons. Here, for greedy GPT-2 small in float32, all 189 concurrent streams (three repetitions each at 1, 2, 4, 8, 16 and 32 streams) returned the same token IDs as the corresponding solo runs. That validates the tested execution path, not a mathematical promise that all models, samplers or precisions produce invariant output. Sampled isolation should be tested with matched per-request seeds and identical sampler counters.
The wire
SSE is a framing protocol for a finite or long-lived HTTP response; it does not prescribe that generation run forever. The WHATWG HTML Living Standard specifies the text/event-stream media type, UTF-8 decoding, fields named event, data, id and retry, and blank-line event dispatch. LF, CR and CRLF are valid line endings; a leading UTF-8 BOM is ignored, comment lines start with :, and an unterminated final event is discarded. Event IDs support reconnection through Last-Event-ID, but do not themselves provide durable replay or exactly-once delivery. The lab emits monotonically numbered event IDs, yet keeps no replay log and does not implement resumption, so clients must not interpret those IDs as a recovery guarantee. The specification also discusses periodic comment keep-alives for intermediaries; none are sent by this lab.
The application protocol sits above SSE. This service emits start (request identity and prompt-token count), token (index, model token ID and incremental text), done (finish reason and usage), and error (the From Inference Loop to API error envelope). Anthropic’s documented streaming Messages API uses more elaborate event names, including content-block deltas, ping and possible mid-stream errors; those are provider interface documentation, not evidence about its internal scheduler, buffering or cancellation. The lab’s four event names are local conventions, not a claim of compatibility with that API. A resilient consumer must explicitly handle unknown event names and distinguish successful done from a transport ending unexpectedly.
An HTTP status and headers are committed when the server starts its response, not after generation succeeds. The service tries to reject malformed requests, invalid token budgets and an overfull waiting list before constructing and returning a streaming response, using ordinary JSON errors such as 422 or 503. Once the SSE response has begun, a late engine or policy failure must appear as an error event—or the connection may break without a final event. This distinction is important: HTTP 200 alone does not mean the model completed successfully. A client should regard the stream as complete only after a valid terminal done, handle error explicitly, and treat EOF before a terminal event as incomplete. The code has no replay protocol to resolve the outcome of an interrupted stream.
Each model token has an ID; its visible text is produced by the Autoregressive Generation incremental decoder, which may defer bytes until a character can be rendered. Therefore a valid token event may carry an empty text delta even though one model token was generated, and a final flush can emit additional text without adding a new model token. The stop-string matcher operates on the decoded stream, including matches crossing token boundaries; if it matches, the hub records a stop and requests termination of the engine sequence. Clients should count generated tokens from token IDs and usage, not from the number of non-empty text fragments, and should preserve stop-safe text semantics across event boundaries.
I wrote a streaming SSE parser from the WHATWG rules, then fed it the service output to check framing and event semantics. It has unit tests for each rule (a leading byte order mark, all three line endings including a CR at the end of a chunk, comments, an event with no data, an id containing NUL, retry with digits only, an unfinished event at the end, and the same result for one chunk and for one byte at a time). This is a single-author round trip, not independent protocol interoperability: the writer and parser could share an error. A useful next check is a browser EventSource for GET-based streaming or an independently maintained SSE parser for this POST endpoint, with deliberate fragmentation and EOF faults.
Across 40 prompts of 32 tokens, streaming responses were compared with non-streaming responses from the same server. All 40 were HTTP 200 with text/event-stream; request IDs in headers and start events matched; event ordering was start, token events, then done; token IDs, reconstructed text, usage and finish reason matched the non-streaming path. The local parser saw a complete terminal event and a final ID consistent with the number of emitted events in all cases. Median encoded stream size was about 2,392 bytes (approximately 75 bytes per generated token when start/end overhead is included). All 1,280 observed token events had non-empty text deltas on this English-prose sample; that is a property of this sample, not a constraint of the event protocol. No independent browser, proxy or client implementation was used for this check.
Overlapping streams
Question. Under a fixed model, prompt set and HTTP stack, how do aggregate generated tokens per second, median inter-token gap, client-observed time to first token, and end-to-end makespan change as 1, 2, 4, 8, 16 and 32 requests overlap? A second question is whether batching changes greedy token identity relative to running each prompt alone.
Predeclared hypotheses. H1: shared decode steps increase aggregate output rate by much more than they increase each stream’s inter-token gap, while individual streams lose some per-stream throughput. H2: simultaneous first-token latency rises with batch size because the lab performs prefills sequentially and only delivers their events at the end of the step. H3: a request arriving mid-generation pays the current step boundary plus its own prefill, rather than waiting for the long requests to finish. These hypotheses describe the specific lab scheduler; other runtimes may chunk or interleave prefill differently.
Method. The model is GPT-2 small in float32, using the PagedAttention paged cache, with 1,800 blocks of 16 token positions and a 32-sequence batch limit. Each request asks for up to 64 greedy tokens. For concurrency level N, the first N book-derived prompts (about 200 characters) are submitted over separate local HTTP connections, with three repetitions per level. Makespan runs from the first send to the last completion, and a serial reference sums the same prompts run alone. The source records GPU-synchronised, prefill-free step medians separately from client-observed first-token and inter-token times. No concurrent-memory saturation or cross-machine traffic was introduced.
Falsification criteria. H1 would fail on this workload if 32 streams produced less than twice the one-stream throughput or if their median token gap increased approximately thirty-twofold. H2 would fail if the delivered first token did not become progressively later as more prefills entered the same step. H3 would fail if the late joiners waited for existing streams to finish, rather than mainly for the current step and prefill. These are deliberately coarse checks; the three repeats are insufficient to bound tail latency reliably or attribute individual outliers to kernels versus operating-system scheduling.
| Streams | Aggregate tokens/s | Median gap between tokens | Median time to first token | Makespan against back-to-back |
|---|---|---|---|---|
| 1 | 90 to 94 | 9.8 to 10.6 ms | 15 to 27 ms | 0.9 to 1.0 times |
| 2 | 162 to 171 | 10.8 to 11.3 | 27 to 32 | 1.8 to 1.9 |
| 4 | 301 to 308 | 12.0 to 12.1 | 66 to 77 | 3.2 to 3.3 |
| 8 | 499 to 555 | 12.4 to 13.8 | 119 to 124 | 5.5 to 6.1 |
| 16 | 900 to 1,000 | 12.4 to 13.9 | 178 to 223 | 9.8 to 10.8 |
| 32 | 1,320 to 1,376 | 16.2 to 16.8 | 441 to 482 | 14.2 to 14.8 |
(Ranges span three runs per concurrency level. The speed-up denominator is the sum of the N matching solo-request durations; for 32 requests this was 22.05 s, compared with concurrent makespans of 1.49–1.55 s. The solo medians were approximately 16 ms TTFT, 0.68 s total stream duration and 10.1 ms between tokens. All rates count model token IDs emitted, not SSE bytes. Makespan and inter-token gap are different measurements: higher aggregate throughput does not imply lower latency for each individual reader.)
H1 is supported for the measured configuration. At 32 streams, aggregate rate reached 1,320–1,376 token IDs/s—roughly fourteen to fifteen times the single-stream rate—while median inter-token gap grew from roughly 10 ms to 16–17 ms. Per-stream throughput nonetheless fell from roughly 90–94 to 41–43 token IDs/s, a relevant trade-off for interactive readers. As a rough accounting check, 63 decode rounds at the measured 32-way 15.1 ms median take about 0.95 s, and sequential prefills account for roughly another 0.45 s; observed group makespan was 1.49–1.55 s. This is explanatory arithmetic, not a decomposition measured with independently timed kernels. At 16 streams two runs showed roughly 56 ms p99 gaps; the source does not establish their cause, so a tail-SLO claim would require more repetitions and hardware profiling.
H2 is supported and exposes a scheduling choice. In one 32-stream repetition, the median client TTFT was 441 ms and the p99 about 442 ms; across repetitions the median ranged from 441 to 482 ms. The first-token generation of each newly admitted request happens in a sequential prefill loop, but all first-token events are dispatched after the step completes. That barrier compresses the spread of observed TTFT while delaying early arrivals: approximately 32 sequential prefills at around 14 ms each account for much of the common wait. The result does not mean simultaneous arrivals must have equal TTFT in a better designed engine. Chunked/interleaved prefill and early first-token dispatch are concrete alternatives, and Sarathi-Serve (OSDI 2024) studies this throughput/latency interaction in a different system.
H3 is supported in a separate late-joiner probe. Twelve eight-token requests arrived at randomly selected times while eight or twenty-four longer streams were already decoding. Client-observed median TTFT was about 41 ms (p99 62 ms) with eight active streams, 47 ms (p99 77 ms) with twenty-four, versus 16 ms for an idle engine. The joiner did not wait for the other streams’ entire generations. The recorded data are consistent with an in-progress step, a sequential prefill and event delivery, but do not time those pieces independently. None of these probes establishes the same behaviour if all batch slots are occupied, KV blocks are exhausted, or admission itself is contended.
The overlap experiment did not approach the configured 1,800 KV blocks. With a 16-position block and short prompts, each of the thirty-two streams reserved only a small number of blocks (approximately seven per request), so neither reservation pressure nor its FIFO waiting behaviour dominated the measurements. The source has unit tests for block-limited admission and for a sequence waiting for a slot, but not a live overload trial with a full batch or a shared memory budget across many clients. Request Scheduling and Admission Control’s deadline control and PagedAttention’s block ownership remain separate; combining them would require an atomic admission decision over both remaining slots and memory.
Where backpressure begins
A stream producer and its reader may proceed at different speeds. The lab’s path contains at least four relevant buffering stages: engine events, the hub’s per-session asyncio queue, Starlette/uvicorn output handling, and operating-system socket buffers. An application queue being unbounded does not imply that bytes can be written to a stalled network without limit; conversely, TCP eventually applying backpressure does not automatically stop the model if token events have already been accepted into a large application queue. Therefore flow control must specify which boundary is bounded, where it pauses generation, and what resource stays held while paused. The experiment first measures the socket boundary separately from the application’s four slow-reader policies.
For the socket-buffer probe, a test client established a real local connection and then stopped reading. The server repeatedly attempted writes of fixed-size SSE-like chunks until progress ceased for the probe interval. With 133-byte chunks it accepted 252,434 bytes before blocking; with approximately 1 KiB, 262,395; with approximately 16 KiB, 278,613; and with approximately 64 KiB, 262,164–327,705 bytes across the runs. These are bytes counted as accepted by the test writer, not a direct measurement of kernel send-buffer capacity or bytes received by the client. They depend on chunk size and this Windows/uvicorn/loopback configuration; the experiment cannot identify the distribution among application, transport and OS buffers or predict another network path.
The ordinary 32-token SSE probes used about 73–76 bytes per generated token including per-stream framing. Extrapolating roughly 75 bytes/token makes a 256-token completion about 19 KiB, much smaller than the 252–328 KiB stall thresholds measured above. Thus ordinary short completions did not create observable socket backpressure in this test; it would be too strong to say that a 256-token client never could. Buffer sizing, HTTP/2 flow control, proxies, TLS, parallel connections and event payloads could change the threshold. To make the slow-reader effect observable here, every emitted model-token event was padded with a roughly 64 KiB SSE comment, creating about 4 MiB for a 64-token completion. This is intentional stress amplification, not representative output volume or a claim about typical SDK streaming.
A client that cannot keep up
The application-level experiment compares four explicit policies for transferring a model step’s events to each HTTP stream. A useful distinction is whether the policy blocks the shared step loop, accumulates per-session events, reduces the slow request’s decode progress, or cancels that request. The buffer and slot implications differ even when the healthy readers see similar times.
- Naive: the hub awaits a bounded per-session queue write. A stalled stream can block delivery of later events for every other stream, making one reader a global head-of-line dependency.
- Unbounded: the hub appends events without a per-session queue cap and continues advancing the engine; model KV blocks may be released while its HTTP writer still drains queued events, but queued event memory can grow.
- Pause: on reaching eight queued events, the hub directly marks that sequence paused, withholding future decode steps until its queue falls to four or fewer. Its batch slot and reserved KV blocks remain occupied. As implemented, the flag mutation is not marshalled through the engine’s locked inbox.
- Drop: the hub keeps queuing but requests engine cancellation after the eight-event condition persists beyond a 0.25-second stall timeout in the reported run. Its reader later receives an
errorevent of typeslow_clientif still connected; the event can be delayed behind its buffered predecessors.
Eight streams each requested 64 tokens. The client-side harness designated k = 0, 1, 2 or 4 streams as slow; each slow reader consumed one chunk and slept for 0.25 seconds before continuing. Every token event carried an added ~64 KiB comment, so a stream’s output could exceed the previously measured socket-buffer threshold. The benchmark records the healthy streams’ completion times and token gaps separately from slow sessions’ engine-resource release times. Results are single runs per policy and k, with no controlled variance estimate, and the slow client’s HTTP completion can occur long after its engine sequence is freed.
| Policy | Healthy streams’ median completion, k = 0 / 1 / 2 / 4 | Their p99 gap, k = 4 | When a slow stream left the engine |
|---|---|---|---|
| naive | 1.02 s / 28.3 / 28.2 / 28.7 | 1,043 ms | 27 to 29 s |
| unbounded | 1.05 s / 1.04 / 1.10 / 1.13 | 24 ms | 1.0 to 1.1 s |
| pause | 0.94 s / 0.91 / 1.25 / 1.18 | 37 ms | 21.4 to 25.1 s |
| drop | 1.07 s / 0.96 / 1.05 / 1.19 | 17 ms | 0.6 to 0.8 s (cancelled) |
The naive policy fails isolation from slow readers in this stress test. With one deliberately slow reader out of eight, healthy streams’ median completion grew from about 1.02 s to 28.3 s, and their p99 inter-token gap climbed to approximately one second. The source shows that the hub awaits queue.put for the naive policy; the shared event loop cannot route later model events until that await clears. The unbounded, pause and drop policies completed healthy streams in roughly 0.9–1.25 s across the tested k values. These observations show that the other three avoided this head-of-line blockage with a batch of eight; they are not evidence that the policies remain fair or memory-safe at saturation.
The three non-blocking policies transfer cost elsewhere. Unbounded let the engine finish a slow request and release its KV blocks in about 1.0–1.1 s, while the HTTP reader took much longer to consume queued events. In this implementation the queue stores small, unformatted events; the 64 KiB padding is generated as the HTTP writer emits them. The thought experiment of eagerly storing 64 padded token events would be approximately 4 MiB per stalled stream, not an observed memory peak, and the nominal 256-token cap bounds this one request rather than aggregate memory across clients. Pause held the slow request’s batch slot and blocks for 21.4–25.1 s; the healthy streams remained quick because the batch was not filled, but a full batch could exclude new arrivals, which was not measured. Drop freed the slow sequence after roughly 0.6–0.8 s, yet the client-side slow_client error was only received around 18.7–19.7 s once preceding buffered events had drained. Neither cancellation nor server-side resource release guarantees prompt delivery of the reason to a stalled peer.
There is no free universal policy. Naive makes everyone wait for one reader; unbounded pays in queued memory; pause pays in occupied KV and batch capacity; drop sacrifices the stalled request and may deliver its error very late. A production policy could combine a small bounded output queue, a short pause grace period, cancellation after a bounded stall, and separate resource quotas for connections and queued event bytes. That combination was not implemented or benchmarked here. Its contract would need to say whether users can resume, whether unread token events are discarded, and which counter distinguishes an intentional slow-reader drop from an engine error.
When the client goes away
A streaming response can end because generation completes, a stop string matches, the client disconnects, or a server error occurs. In this implementation the response generator owns the HTTP session and calls hub.close(session) in a finally. The hub close is idempotent and, if generation has not already finished, enqueues a cancellation request. The engine applies that request at the next step boundary and its _finish routine frees the sequence’s KV blocks once. The distinction is important: hub.close does not itself synchronously free GPU memory, and a cancelled streaming task cannot safely await arbitrarily long cleanup. The tests check eventual release through engine logs and the block allocator, not merely that the Python generator returned.
The experiment began with an incorrect assumption: that Starlette would only notice client disconnects through failed writes. Reading the installed Starlette 1.7.0 and uvicorn 0.54.0 source showed a version-dependent path. Uvicorn advertised ASGI 2.3, under which the installed Starlette StreamingResponse listened for http.disconnect and cancelled its streaming body; the lab’s uvicorn send returned after disconnection rather than raising. For a controlled counterexample, the lab implemented WriteOnlyStreamingResponse, which deliberately never listens and receives no failing write on this stack. This is a comparison of two response behaviours under the measured installation, not a universal statement that ASGI 2.4 stacks always leak work: an ASGI 2.4-compliant server may raise OSError on a disconnected send, enabling cleanup by that path.
The disconnect probe deliberately closed a raw-socket client by FIN or RST at five stages: before its first received byte, while waiting for a batch slot, after one token, after twenty tokens, and after the terminal done. Six trials were recorded for each closure type and checkpoint, with a four-slot batch. Its primary measurement was the elapsed time from client close until the engine’s release log recorded a finished sequence. An after-done observation is not a cancellation latency: the block was already freed shortly before the connection was closed. The comparison reports engine resource release, not when an external client would learn that cancellation had completed.
| The client leaves | Starlette’s response: median release | Tokens generated / read | Write-only response |
|---|---|---|---|
| before any byte arrives | 17 ms (FIN), 19 ms (RST) | 1 / 0 | runs to 200 tokens; released 2.0 to 2.2 s later |
| while the stream waits for a slot | 12 ms, 9 ms | 0 / 0, never admitted | runs to 200 tokens; released 2.7 to 2.8 s later |
| after the first token | 12 ms, 11 ms | 2 / 1 | runs to 200 tokens; released 2.2 s later |
| after 20 tokens | 10 ms, 13 ms | 21 / 20 | runs to 200 tokens; released 2.0 to 2.1 s later |
after the done event |
nothing to release (the blocks had been freed 0.5 ms earlier) | 12 / 12 | the same |
With the installed Starlette response, median engine release followed client close in approximately 9–19 ms at the measured abandonment checkpoints, with a worst observed 34.5 ms. Waiting streams were never admitted after disconnection; running streams produced at most one more token than the client had read in these trials. The write-only class did not notice the disconnect and generated all 200 configured tokens before releasing the sequence, generally about 2.0–2.9 s later depending on whether it had waited for a slot. FIN and RST did not show a stable ordering in this sample. These figures are single-machine, small-batch observations: cancellation latency can grow with step duration, saturated prefills, delayed disconnect notification or executor failures, none of which this probe bounded.
The second trial stressed aggregate cleanup rather than just one connection. It opened 300 streams, with up to 48 concurrent clients and a batch limit of eight. About 35% read the complete answer; 165 clients left early, including slower readers disconnected after only a few tokens. The measured outcomes were allocator state, release counts, active and waiting sequences, hub sessions, model tokens generated, client tokens read and total wall time. This tests a finite set of intentional disconnect paths; it is not a proof that every future exception or process crash can never leak resources.
| Starlette’s response | Write-only response | |
|---|---|---|
| Streams released, each exactly once | 300 of 300 | 300 of 300 |
Released as disconnected / length |
161 / 139 | 0 / 300 |
| Disconnected before being admitted | 28 | 0 |
| Tokens generated / read, all streams | 5,321 / 4,798 | 10,032 / 4,822 |
| For the 165 who left early | 1,753 / 1,230 | 6,464 / 1,254 |
| Time to run all 300 | 17.6 s | 25.9 s |
| Blocks free afterwards | 1,800 of 1,800 | 1,800 of 1,800 |
In both variants, the block allocator recovered 1,800 of 1,800 blocks, every one of the 300 sequences had one recorded release, and the hub and engine finished without active, waiting or registered sessions. That is strong evidence of no residual in-process KV allocation in these runs. But there is a large work difference: for the 165 early-departing clients, Starlette’s response generated 1,753 tokens while clients read 1,230 (about 1.43 generated/read); the write-only response generated 6,464 while clients read 1,254 (about 5.15 generated/read). Total wall time grew from 17.6 to 25.9 s, roughly 47% longer. A maximum token budget capped zombie work; only disconnect-aware cancellation avoided most of it. The absence of allocator leaks does not make computation for abandoned clients harmless.
The cleanup design has four distinct requirements. First, every response exit path must reach one idempotent session close. Second, close must be non-blocking in the cancelled HTTP task and enqueue work that the engine owner can safely process. Third, only the engine may free KV blocks, and a double free must fail rather than corrupt the allocator. Fourth, tests must inspect more than an HTTP status: release count per sequence, allocator totals, pending inbox and waiting lists, active sequences, hub sessions, and wasted tokens. In the installed Starlette stress run the hub counted 294 events delivered for already-closed session IDs; discarding these events was part of keeping a late engine event from re-opening a dead stream. Remaining gaps include crash recovery, concurrent pause/resume mutation, bounded app queues and atomic admission under simultaneous connections.
What the numbers do not show
- Scope of the model evidence. GPT-2 small, float32, one shared RTX 2060 12 GB, Windows 11, loopback HTTP and an observed faster GPU state. Numerical and network timing results are specific to that setup.
- Correctness only for greedy decoding. The 189-way equality check uses greedy tokens. Sampling with independently seeded request streams, half precision, mixed-length completions and different attention backends were not compared.
- Saturation absent from the throughput trial. The 1,800-block cache did not constrain the 32-way overlap run; pause-held slots were not tested under a full batch. The leak trial used an eight-sequence limit but targeted cleanup, not admission fairness.
- Backpressure was amplified. A 64 KiB SSE comment padded each token event. Socket-buffer thresholds and slow-reader times should not be carried over to normal token-sized messages, browsers, proxies or HTTP/2 without measurement. Each slow-reader configuration was run once.
- No browser interoperability or stream resumption. The parser and writer share authorship;
Last-Event-ID, durable replay, keep-alives, authentication, TLS and proxies are outside the experiment. - Concurrency contracts not fully qualified.
pauseandresumedirectly mutate sequence flags across threads, and the HTTP waiting count is checked without an atomic reservation; the tests do not prove race freedom. - Disconnect detection is version-specific. Installed Starlette/uvicorn behavior was inspected and measured. Another ASGI server or version may follow a different path. A full lifecycle design also needs error recovery after a GPU worker crashes.
Inference Lab increment
The increment is runnable code in examples/ch27/stream_lab.py backed by local unit and HTTP experiments. The components below describe implemented features, while the integration and synchronisation gaps are listed explicitly so they cannot be mistaken for production qualifications:
sse_event,sse_comment,SSEParser: event serialization, comment framing and incremental parser tests against the WHATWG SSE rules; not independent browser compatibility.BatchEngine: sequential prefill plus batched decode on the PagedAttention paged cache, with block reservations, a batch-slot limit and finish records.submit/cancel: lock-protected engine inbox commands applied instep().pause/resume: currently direct flag mutations, requiring an inbox refactor before a race-free claim.Hub: asyncio event fan-out and four slow-reader policies, with idempotent session close and recorded late events.build_stream_app: POST/v1/streamand POST/v1/generatesharing the same engine, plus pre-stream input/budget checks, a non-atomic waiting-count limit and test-only diagnostics.WriteOnlyStreamingResponse: a deliberately non-listening response for the disconnect counterexample, not the recommended serving response.- Commands
sse,buffers,overlap,slowclient,disconnectandserve. Results are archived inresearch/ch27/results.json; the image references and chapter cross-links remain unchanged.
The service example uses a local GPT-2 checkpoint and the pause slow-reader policy. These commands are intended for the lab machine, not for exposure on an untrusted network; authentication, TLS, proxy buffering and production request quotas are not part of the example. Run the server, then issue a POST and inspect start, token and terminal done events:
python examples/ch27/stream_lab.py serve --policy pause --device cuda --port 8000
curl -N http://127.0.0.1:8000/v1/stream -H "content-type: application/json" -d '{"prompt": "The capital of France is", "max_new_tokens": 8}'
The principle established here is narrower and more useful than “streams are fast”: batching can greatly improve aggregate output rate while delaying each stream’s first token, and a streaming service must explicitly assign ownership of output buffering and KV resources. A slow reader must never become an accidental global scheduler, and a disconnected reader should not retain work solely because HTTP writes continue to return. The lab demonstrates a safe eventual release path in measured disconnect cases, with exact release accounting, but still needs an atomic waiting-capacity contract and owner-thread pause/resume commands before being called concurrency-safe. Distributed Inference adds multiple devices; Reliability, Cancellation and Recovery will need to integrate cancellations, deadlines and retries into this lifecycle.
What you should now be able to do
- Explain how a step-driven engine combines serial prefills and a batched decode, and distinguish the time a token is computed from client-observed time to first token.
- Compare concurrent versus solo execution by makespan, aggregate generated token IDs/s, per-stream inter-token gap and identical greedy token sequences.
- Parse an SSE stream according to its framing rules, while distinguishing event IDs from actual durable resumption and a terminal
donefrom an incomplete EOF. - Identify every place a slow client can accumulate buffered output and evaluate naive, unbounded, pause and drop policies by whose time, memory or cache capacity they consume.
- Verify stream abandonment by checking engine release logs, allocator totals and generated-but-unread tokens, not merely client status codes.
- Recognise the present synchronisation and admission limitations, and specify the tests and refactors required to close them.
Key terms
- Step-driven engine: advances multiple requests by one iteration at a time, admitting or removing work at defined boundaries.
- Prefill delivery barrier: waiting to publish all newly produced first-token events until the full step ends.
- Server-sent events (SSE): UTF-8 HTTP event-stream framing with blank-line dispatch; application token events are an additional protocol, not part of SSE itself.
- Time to first token (TTFT): elapsed time from the client’s request until its first model-output event, including server/network stages.
- Backpressure: a slower consumer constraining a faster producer through a bounded queue, write or flow-control window; the engine is backpressured only if that pressure reaches its scheduler.
- Head-of-line blocking: progress for unrelated sessions waits on a stalled reader or operation.
- Session close: idempotent HTTP/hub cleanup that may request, but does not immediately perform, GPU resource release.
- Exactly-once resource release: each held block allocation is returned once, established for tested executions by logs and allocator checks rather than asserted as a universal guarantee.
- Zombie generation: engine work spent generating model tokens for a client that has disconnected.
- Event replay: durable retention of event IDs and payloads sufficient to honour a reconnect; the lab does not implement it.
Reader exercises
- Dispatch each newly prefilled sequence’s first token as soon as that prefill completes. Re-run the 32-way comparison, preserving sequence identity, and report TTFT p50/p99 separately from makespan.
- Route
pauseandresumethrough the locked inbox, just likesubmitandcancel. Stress races between pause, cancel, finish and resume, with one engine owner thread and allocator invariants. - Replace the HTTP
len(waiting) + len(inbox)check with an atomic admission reservation for pending requests, active slots and KV blocks; prove the maximum cannot be exceeded by simultaneous POSTs. - Implement bounded queued bytes, not only queued event counts. Combine a pause grace period with drop, then test a fully occupied batch and quantify the impact on healthy admission.
- Add heartbeats and a replay log keyed by request and event ID; reconnect using
Last-Event-ID, specifying retention, duplicate-handling and how sampling state is preserved. - Run the stream through a proxy, TLS and an HTTP/2 client, repeating socket-buffer and slow-reader measurements without synthetic comment padding.
- Repeat solo/concurrent equivalence under sampled decoding and fp16, using per-request seeds and Model Architecture Versus Runtime Architecture’s divergence-margin diagnosis.
- Replace PagedAttention’s gathered paged decode with a block-table-aware kernel, and profile model execution, KV gather and GPU launch overhead separately.
- Integrate Request Scheduling and Admission Control’s deadline-aware gate: distinguish rejected-before-stream, abandoned-while-waiting, cancelled-while-running and completed-after-deadline outcomes.
- Inject engine errors and process termination during prefill and decode; verify response
error/EOF semantics, bounded zombie work and resource reclamation after restart.
References
- WHATWG HTML Living Standard: Server-sent events — primary protocol specification for UTF-8 framing, fields, blank-line dispatch and reconnect semantics. These rules do not themselves supply durable replay.
- Orca: A Distributed Serving System for Transformer-Based Generative Models — Yu et al., OSDI 2022. Introduces iteration-level scheduling and selective batching; foundational context for step-driven serving, not a reproduced benchmark.
- Efficient Memory Management for Large Language Model Serving with PagedAttention — Kwon et al., SOSP 2023. Primary research on KV-cache paging and memory management; the chapter tests its own PagedAttention cache, not vLLM.
- Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve — Agrawal et al., OSDI 2024. Research on chunked prefill and stall-free scheduling; relevant to the measured first-token prefill barrier, but not reproduced here.
- Anthropic: Streaming messages and Claude API errors — provider documentation of application event types, mid-stream errors and extensibility, not evidence of its internal scheduling.
- Installed Starlette 1.7.0 and uvicorn 0.54.0 sources (
StreamingResponse.__call__, HTTP protocolsendand ASGIspec_version) — source inspection recorded inresearch/ch27/sources.md; applicable only to the inspected installed versions.
Evidence in this chapter
| Claim | Category |
|---|---|
| 32 concurrent streams ran at 1,320 to 1,376 tokens/s against 90 to 94 for one, 14.2 to 14.8 times faster than back to back | Book result (GPT-2, RTX 2060, loopback; 3 repetitions) |
| A step with 32 sequences costs 15.1 ms against 9.8 ms for one | Book result |
| All 189 measured concurrent streams had token IDs identical to their solo greedy runs | Book result (greedy, float32) |
| Time to first token for 32 simultaneous requests was 441 to 482 ms, with p50 equal to p99 | Book result |
| A request joining a busy engine waited a median 41 to 47 ms for its first token | Book result |
| 40 of 40 streams parsed under the SSE rules and equalled the non-streaming answer | Book result; the parser is the author’s |
| In this socket-buffer probe, writes advanced by approximately 252–328 KB of payload before blocking; typical-sized 256-token SSE output is approximately 19 KiB | Book result (this machine) |
| With the naive policy one slow reader raised the others’ completion from 1 s to 28 s; unbounded, pause and drop did not | Book result (single runs, padded events) |
| Pause held a slow stream’s cache for 21 to 25 s; drop released it after 0.6 to 0.8 s | Book result |
| Starlette’s response released a disconnected stream’s blocks in a median 9 to 19 ms; a write-only response ran the sequence to its limit, 2.0 to 2.9 s later | Book result |
| 300 streams with 165 early disconnects: each released once and all blocks free at end; 5.15 versus 1.43 generated/read for abandoned streams | Book result |
| Inspected uvicorn 0.54 code advertised ASGI 2.3 and returned after disconnect; inspected Starlette 1.7 listened for disconnects on this path | Read in the installed source; consistent with the measurements |
| The SSE framing and reconnection rules (not replay guarantees) | Established background (WHATWG specification) |
| Anthropic’s event types and mid-stream errors | Reported by the provider’s documentation; an interface, not an implementation |
| Proxies, TLS, HTTP/2, browsers, resumption, keep-alives, saturation, sampled streams, other models | Not measured |
pause and resume use the same locked step-boundary inbox as submit and cancel |
Not established: the current code mutates pause flags directly; concurrency stress is pending |
| The HTTP waiting-count check is an atomic bound under simultaneous requests | Not established: no atomic slot reservation; this is a required follow-up |
Implementation status
- Manuscript:
content/books/inference/27-chapter.md - Runnable examples:
examples/ch27/streaming.py(original toy stream manager, unchanged),examples/ch27/stream_lab.py(SSE, engine, hub, service, experiments) - Tests:
tests/test_ch27_streaming.py(toy),tests/test_ch27_stream_lab.py(50 tests: SSE formatting and every parser rule, with chunking and round trips; the engine against solo runs and the library, late joiners, single-token requests, eos, cancelling a waiting and a running request, double and late cancels, pausing, block-limited admission in order, the batch limit, locked submission/cancellation, direct pause/resume behaviour, double free as an error, and the step summary; the hub’s four policies including the stall of the naive one, an idempotent close, stop strings; the two response classes on a disconnect (on the installed Starlette/uvicorn versions); the service’s events, refusals before the first byte, waiting limit, stop strings, cleanliness afterwards and concurrent streams; a tiny random GPT-2 on the CPU) - Evidence:
research/ch27/sources.md,research/ch27/results.json,research/ch27/raw/,research/evidence-register.md - Verification command:
python -m unittest discover -s tests -v - Outstanding engineering qualifications: owner-thread pause/resume commands, atomic waiting/memory admission, bounded output bytes, independent SSE interoperability, full-capacity slow-reader stress and engine-crash cleanup. These are not claimed as completed by the 50 CPU-only tests.
The chapter is published from a manuscript marked draft = false, but its experimental conclusions are bounded: GPT-2 small in float32 on one GPU, real loopback sockets, the listed framework versions, a finite test matrix and some deliberately padded streams. The code demonstrates meaningful throughput improvement and reliable cleanup in those recorded trials, but it is not a production-ready streaming server and has not qualified pause/resume synchronisation or concurrent admission. Distributed Inference moves to multi-device execution; Reliability, Cancellation and Recovery should build on these tests to extend cancellation, deadlines, retries and failure recovery across the serving boundary.