Notas / 11
How to prove a gateway actually streams
A response can be labelled text/event-stream, be chunked on the wire, and still arrive as one lump because something in the path is holding bytes until the body is complete. The only reliable test is timing: measure when each event actually reaches you and look at the distribution. This article builds a probe on http.client that reads event lines directly, records arrival times, and prints time-to-first-token, event count and gap percentiles next to a non-streaming control. It covers the three settings that produce fake streaming, how to read the headers that betray a buffering proxy, and what a healthy distribution looks like.
Measure arrivals, not sizes
requests with stream=True is convenient but puts a library between you and the socket, and resp.text or a single read() collapses everything you were trying to observe. http.client is in the standard library, reads line by line, and reports per-header values you would otherwise lose.
#!/usr/bin/env python3
"""stream_audit.py — prove token-by-token delivery, with a control."""
import http.client, json, os, ssl, statistics, sys, time
HOST = os.environ.get("HOST", "api.tokenaimodels.com")
PATH = "/v1/chat/completions"
KEY = os.environ["MODELRY_API_KEY"]
MODEL = os.environ.get("MODEL", "deepseek-chat")
PAYLOAD = {
"model": MODEL,
"messages": [{"role": "user",
"content": "Write 40 short numbered lines about HTTP chunking."}],
"max_tokens": 700,
"stream": True,
}
def audit(stream: bool) -> dict:
body = dict(PAYLOAD, stream=stream)
raw = json.dumps(body).encode()
ctx = ssl.create_default_context()
conn = http.client.HTTPSConnection(HOST, timeout=180, context=ctx)
started = time.monotonic()
conn.request("POST", PATH, body=raw, headers={
"Authorization": "Bearer " + KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream" if stream else "application/json",
})
resp = conn.getresponse()
headers = {
"status": resp.status,
"transfer-encoding": resp.getheader("Transfer-Encoding"),
"content-encoding": resp.getheader("Content-Encoding"),
"content-type": resp.getheader("Content-Type"),
"x-request-id": resp.getheader("x-request-id"),
}
if resp.status != 200:
raise SystemExit(f"HTTP {resp.status}: {resp.read()[:300]!r}")
if not stream:
resp.read()
return {"headers": headers, "total": time.monotonic() - started, "events": 1}
arrivals: list[float] = []
while True:
line = resp.readline()
if not line:
break
if line.startswith(b"data:"):
arrivals.append(time.monotonic() - started)
if line.strip() == b"data: [DONE]":
break
conn.close()
gaps = [b - a for a, b in zip(arrivals, arrivals[1:])] or [0.0]
p95 = statistics.quantiles(gaps, n=20)[-1] if len(gaps) >= 20 else max(gaps)
return {
"headers": headers,
"events": len(arrivals),
"ttft": arrivals[0] if arrivals else None,
"total": arrivals[-1] if arrivals else None,
"span": (arrivals[-1] - arrivals[0]) if len(arrivals) > 1 else 0.0,
"median_gap": statistics.median(gaps),
"p95_gap": p95,
"max_gap": max(gaps),
}
if __name__ == "__main__":
control = audit(stream=False)
print("control (non-streaming): total=%.2fs" % control["total"])
s = audit(stream=True)
print("headers:", json.dumps(s["headers"]))
print("events=%d ttft=%.2fs span=%.2fs" % (s["events"], s["ttft"] or 0, s["span"]))
print("gaps: median=%.3fs p95=%.3fs max=%.3fs"
% (s["median_gap"], s["p95_gap"], s["max_gap"]))
buffered = s["events"] < 5 or s["span"] < 0.05
print("VERDICT:", "BUFFERED" if buffered else "STREAMING")
sys.exit(1 if buffered else 0)
Reading the verdict
A real stream produces dozens to hundreds of events whose arrival times are spread across the generation: span of a second or more on a 700-token answer, a median gap in the tens of milliseconds, and a ttft well below total. A buffered path produces one or two events with span ≈ 0 — everything arrived in the same read, microseconds apart. The max_gap is diagnostic too: a single multi-second gap in the middle of a fast stream is normal (a provider-side hiccup), while max_gap close to total means the first event carried everything.
The control run matters. If the non-streaming call and the streaming call finish at about the same time, you are not comparing a fast path with a slow one; you are watching one buffered path twice.
Failure 1: the client buffered, not the server
resp.read(), resp.text, json.load(resp), or a shell pipeline through tee into a formatter — all of them read to completion before doing anything visible, and all of them will make a perfectly good stream look buffered. The same is true of curl without -N when the output is a pipe. Before you file a ticket, confirm the *reader* is line-oriented: readline(), iter_lines(), or a for await over a byte stream with an explicit line buffer.
Failure 2: the hostname is the proxy
An apex domain fronted by a CDN built for HTML is the single most common cause of "streaming does not work". CDNs buffer to compute compression, to measure length, or to fill a fixed-size buffer; a document endpoint can wait for kilobytes while an SSE response has nothing to fill them with. The fixed hostname usually differs from the marketing one — on this platform the API lives on the api. subdomain, and the documentation states that the apex may buffer while the API host guarantees token-by-token delivery. Test the host you will actually ship against, and check Transfer-Encoding: chunked with no Content-Encoding in the response.
Failure 3: a three-token answer that cannot prove anything
max_tokens: 5 produces one or two events even on a perfect stream, and span < 0.05 then flags a false positive. Ask for several hundred tokens of output, run the audit two or three times, and compare the distributions rather than trusting a single sample. Variance matters too: a test from a laptop on hotel wifi will occasionally show a large gap that has nothing to do with the gateway, so run the audit from the network your production traffic will use.
What to watch when you speak to a gateway instead of OpenAI
Streaming through a gateway adds a hop that can behave differently from the origin. No keep-alive comments: some gateways emit SSE comment lines during slow generations and some do not; if yours does not, "silence" is normal and a 30-second idle timeout that works elsewhere will cut a healthy reasoning request. Failover before first byte only: where a second channel is configured, a request that fails before any output may be retried on another channel, which can add a visible delay before the first event without any error surfacing — a slow ttft on a request that eventually succeeds is not necessarily your network. x-request-id on every response: when a stream truncates, that header is the only way to have the request traced through the gateway to the provider, so capture it in the audit and in production logs alike.
Running the audit on a schedule
Run it from the network your production traffic uses, twice a day, and keep the last thirty results. Buffering is usually introduced by a configuration change rather than by the origin: a CDN rule, a new proxy in front of the API host, a WAF in blocking mode. Detecting it from a scheduled audit takes one cycle; detecting it from a customer complaint takes a week and a postmortem. Store events, ttft, span and max_gap as numbers, alert when events drops below a floor or span collapses toward zero, and treat the alert as a transport incident rather than a model incident — the model did not change, the path did.
If your organisation terminates TLS at an inspection appliance, run the audit from inside that path deliberately: it is the most common place a stream becomes a lump in a corporate network, and it is invisible from a laptop on a home connection. Compare the two runs; a difference in events between them is the appliance, not the endpoint.
Point the audit at https://tokenaimodels.com's API host before you trust any benchmark: run it once against https://api.tokenaimodels.com/v1 with your own key, and keep the verdict line in your deployment notes.
A Modelry opera uma plataforma que serve modelos DeepSeek atrás de um único endpoint HTTP, com créditos pré-pagos e impostos tratados pelo merchant of record no checkout, além de uma política de retenção de dados documentada. Comece com $0.50 de crédito de teste: criar uma chave.