Streaming tokens: SSE, WebSockets and gRPC
Watch one chat answer reach the screen as a stream of small messages.
Explain it simply
The top line is your app, the client, and the bottom line is the server. The teal arrow is your question going down. The model writes 218 tokens on the server line, and one blue arrow brings the whole answer back. Until then your screen stays empty.
One request goes from the client to the server. The server makes 218 tokens. One reply returns at 6.07 s.
The reply waits for setup, the trip there and back, prefill and decode.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import re
PROTO, PER, RTT = "sse", 1, 80 # protocol, tokens per message, round trip (ms)
PROMPT, TPS, DECODE = 608, 1500, 25 # R25's prompt tokens, prefill tokens/s, ms per token
ANSWER = "A chat model writes its answer one token at a time. Each token takes the GPU about the same time, so a long answer takes a few seconds to write. If the server waits for the last token, you look at an empty screen for all of that time. If it streams, it sends each token as soon as the model writes it. You can read the first words while the model is still busy with the rest. The answer takes the same time in total, but the wait feels much shorter. The first token shows how fast the system feels, and the last token shows how long the work takes. Servers stream in three common ways. Server-Sent Events keep one HTTP response open and add a small text event for each token. WebSockets turn the connection into a channel where both sides can send messages at any time. gRPC calls a remote function and gets back a stream of small binary messages over HTTP/2. All three carry the same tokens in the same order, and the model sets the pace. Pick the one that fits what your client must send back to the server."
tokens = re.findall(r" ?[A-Za-z]+| ?\d+|[^ A-Za-z\d]", ANSWER)
def varint(n):
out = b''
while True:
out += bytes([n % 128 + (128 if n >= 128 else 0)])
n //= 128
if n == 0:
return out
def message(i, text):
body = text.encode()
js = ('{"index":%d,"text":"%s"}' % (i, text)).encode()
if PROTO == "sse":
return b'data: ' + js + b'\n\n'
if PROTO == "ws":
head = bytes([0x81, len(js)]) if len(js) <= 125 else bytes([0x81, 126]) + len(js).to_bytes(2, 'big')
return head + js
pb = b'\x0a' + varint(len(body)) + body + (b'\x10' + varint(i) if i else b'')
grpc = b'\x00' + len(pb).to_bytes(4, 'big') + pb
return len(grpc).to_bytes(3, 'big') + b'\x00\x00\x00\x00\x00\x01' + grpc
setup = (3 if PROTO == "ws" else 2) * RTT # TCP + TLS (+ the WebSocket upgrade)
made0 = setup + RTT / 2 + PROMPT / TPS * 1000 # prefill makes the first token
made = [made0 + i * DECODE for i in range(len(tokens))]
msgs = [(i, ''.join(tokens[i:i + PER])) for i in range(0, len(tokens), PER)]
arrive = [made[min(i + PER, len(tokens)) - 1] + RTT / 2 for i, _ in msgs]
size = sum(len(message(i, t)) for i, t in msgs)
rest = 2 * RTT + RTT + PROMPT / TPS * 1000 + (len(tokens) - 1) * DECODE
print(len(tokens), "tokens in", len(msgs), "messages") # 218 tokens in 218 messages
print("first text at %.1f ms" % arrive[0]) # first text at 645.3 ms
print("last token at %.1f ms" % arrive[-1]) # last token at 6070.3 ms
print("plain REST reply at %.1f ms" % rest) # plain REST reply at 6070.3 ms
print(size, "bytes,", len(ANSWER.encode()), "of them text") # 7657 bytes, 1009 of them text
Copy it into a file and run it. It times R25's answer and counts its bytes.
Common mix-ups
MYTHStreaming makes the model write the answer faster.
FIXThe last token arrives at 6.07 s in both. Streaming only moves the first text from 6.07 s to 0.65 s.
MYTHStreaming tokens needs a WebSocket.
FIXServer-Sent Events stream over one normal HTTP response. A WebSocket helps only when the client must also send while the answer streams.
Takeaways
- Streaming moves the first text earlier, but the last token arrives no sooner.
- SSE streams one way over HTTP; WebSockets and gRPC can send both ways.
- Small messages show text sooner but spend more bytes on framing.