Why Local LLM Streams Arrive All at Once: Proxy and Client Buffering
Why Local LLM Streams Arrive All at Once: Proxy and Client Buffering
Search
Ask the AI

Why Local LLM Streams Arrive All at Once: Proxy and Client Buffering

The server sends text in stages, yet the client displays the answer only at the end. First-content latency also depends on whether a proxy buffers the response and whether the client parses it as it arrives. We isolate those two stages with the same Chinese text and a fixed schedule, recording HTTP-header arrival, the first content event, and client read-plus-parse completion separately.

In this experiment, a forwarding proxy and streaming reader delivered the first content event after 166.3 ms. Changing only the client to a whole-body reader delayed it to 805.7 ms. The corresponding total client times were 805.2 and 805.7 ms. The text stayed identical; its delivery schedule changed.

First content, read-plus-parse completion and header arrival for four proxy and reader combinations, with five sequential runs each
Five sequential measurements per condition. Bars show medians and circles show individual measurements. Header arrival is plotted separately on the right. Open full-size SVG.

1. HTTP 200, a received event, and visible content mark different times

Response headers can arrive early, before the body is complete. In all four conditions, median header arrival was below 2.4 ms, while the first content event differed by about 640 ms. Timing only the return from getresponse() therefore misses the wait for text.

Here, time to first content means the time when the client parses the first nonempty choices[].delta.content. It is separate from the first network byte, a role declaration, and reasoning output. A client that displays only the answer should not count an earlier role, reasoning_content, or usage event as its first answer text.

For a local chat client, the useful timestamps are when the upstream emits an event, when the proxy forwards it, when the client parses it, and when the interface renders it. llama.cpp exposes streaming chat completions. We replace inference output with fixed events so that delivery and reading can be tested independently.

2. Fix the text and its emission schedule

The experiment ran on a MacBook Air M3 with Python 3.13. A Python upstream and proxy bind to temporary ports on 127.0.0.1. Each of the four conditions runs five times, sequentially, for 20 requests; the condition order rotates between repetitions. This is an application-layer control experiment with no model inference or nginx process. The Python whole-body buffer is a deliberate control mechanism, not a measurement of every response under nginx’s default buffering configuration.

The prompt label is “只输出:你好,本地流式输出。” and the complete answer is “你好,本地流式输出。”. After sending its response headers, the upstream follows this schedule:

Time / ms Event Counts as first content?
0 Role declaration, empty content No
40 reasoning_content No
80 usage, empty choices No
160 / 280 / 400 / 520 “你好,” / “本地” / “流式” / “输出。” The event at 160 ms is first
640 / 720 / 800 finish_reason / [DONE] / HTTP body end Recorded separately

Both proxy modes forward HTTP headers immediately. One forwards body bytes as they arrive; the other reads the entire upstream body before sending it. The client either passes available bytes from read1() into the parser or waits for read() to return the whole body. A monotonic client clock records all times. Total elapsed time is recorded after body reading, parser.finish(), and final event processing; it includes the client’s parsing work.

3. Four delivery paths for the same answer

Proxy and reader HTTP headers / ms First content / ms Read + parse completion / ms
Forwarding proxy + streaming reader 1.7 (1.1–5.6) 166.3 (162.2–167.3) 805.2 (802.3–810.8)
Forwarding proxy + whole-body reader 2.2 (0.9–2.4) 805.7 (805.2–808.6) 805.7 (805.2–808.6)
Whole-body buffer + streaming reader 2.4 (1.1–3.5) 807.1 (804.8–813.0) 807.3 (804.9–813.1)
Whole-body buffer + whole-body reader 2.1 (1.5–3.2) 806.3 (802.5–807.7) 806.3 (802.5–807.7)

Values are medians, with the full five-run range in parentheses. All 20 main requests returned identical content hashes, a finish reason, and the terminal marker. The three combinations with buffering delivered their first content at about 805–807 ms. Forwarding plus streaming delivered it at about 166 ms. Total client read-plus-parse time remained close to 0.8 s.

Changing the proxy to a whole-body buffer makes even the streaming client wait. Keeping the forwarding proxy but changing the client to whole-body reading has the same effect. A streaming option in the request, or a proxy that supports forwarding, does not establish that the application processes content incrementally.

The download contains the complete client. The two readers differ at the following step; they use the same event parser:

# Stream: feed each available byte block into the same parser.
while True:
    block = response.read1(65536)
    if not block:
        break
    consume(parser.feed(block))

# Whole body: parsing starts only after read() finishes.
body = response.read()
consume(parser.feed(body))

4. Byte blocks, text lines, and SSE events have separate boundaries

A read may end inside a Chinese UTF-8 character or a JSON line. The WHATWG SSE specification uses UTF-8 and a blank line to delimit an event. Multiple data: lines are joined with a newline. An event that lacks its final blank line is discarded at EOF.

The script decodes UTF-8 incrementally, retains line state between reads, and then assembles events at blank lines. The predefined event sequence survived 600 random byte partitions: 200 fixed seeds for each of LF, CRLF, and CR. One-byte partitions, comments, and multiple data lines also passed. A deliberately naive decoder that decodes each byte block independently failed at a split Chinese character.

For an HTTPX client, the official streaming API provides stream() with iter_bytes(), iter_text(), or iter_lines(). A line iterator supplies lines; the application still assembles SSE events. Our measurements use the standard library. HTTPX illustrates the same distinction at its API boundary.

5. Preserve partial content and completion state when a connection ends

Connection closure and answer completion are separate observations. After the main matrix, we ran four negative controls sequentially. The content, finish reason, and [DONE] marker form this fixture’s completion contract; SSE itself does not define that marker.

Negative control Content retained by the client Detected outcome
Complete content and finish reason, but no [DONE] 你好,本地流式输出。 missing_done
End after the second content event 你好,本地 truncated_content
EOF before the event’s final blank line Empty; the three earlier non-content events arrived incomplete_event
Stall for 1 s after first content; client read timeout 0.12 s 你好, read_timeout, recorded at 289.5 ms

All four anomalies were detected. The timeout row retains its first-content time of 168.4 ms, received text, and error type. The missing-marker row retains the full answer. These records distinguish late delivery, lost content, and a broken completion contract instead of reducing them to one generic failure.

6. What to check in an existing nginx deployment

The nginx proxy documentation describes incremental forwarding when response buffering is disabled. Buffering uses memory and may use temporary files. For an existing nginx deployment whose upstream is actually 127.0.0.1:8000, this is a documentation-based configuration example:

location /v1/chat/completions {
    proxy_pass http://127.0.0.1:8000;
    proxy_buffering off;
    proxy_read_timeout 300s;
}

proxy_read_timeout limits the idle gap between upstream reads; choose 300 s to match the intended maximum silence. An upstream X-Accel-Buffering: no can also control buffering when nginx processes that header. proxy_ignore_headers can disable that control. Whole-body client reading will still delay content delivery.

7. Reproduce the result and locate the wait in your own path

Download the complete experiment, extract it, and run:

cd llm-streaming-lab
python3 streaming_lab.py --out my-run
python3 plot_results.py --results my-run --out my-figures

The first Python command uses only the standard library; plotting additionally needs Matplotlib. metrics.csv retains all 20 main requests and four abnormal requests, events.csv retains per-event times, and parser-tests.json records partition tests. An initial development execution timed out before response headers because a handler name collided with a standard-library attribute. Its records and correction notes remain in the package. The table uses the corrected implementation’s complete 20-request run, with the schedule and conditions unchanged.

For a real endpoint, hold the input, output limit, and network path fixed. Record headers, the first nonempty content event, and read-plus-parse completion separately. If headers arrive early but text arrives late, compare direct and proxied access, then incremental and whole-body reading. If the parser receives text promptly, inspect interface rendering next. The controlled comparisons show how each stage changes delivery timing; measure those stages separately on the actual path.

Related: reverse proxies and external access for a local LLM, and connecting chat clients. The code, raw measurements, and frozen plan are described in the experiment README.

Leave a Reply

Scroll down