Log inStart free
LESSON 33.02 · 5 STAGES · 3 CONTROLS · 3 CHECKS

Streaming tokens: SSE, WebSockets and gRPC

Watch one chat answer reach the screen as a stream of small messages.


EXPLAINER · 33.02 · STREAM BAY
01
Stage 1 of 5 · Ask and wait
The client sends one HTTP request to a REST path. The whole reply arrives at 6.07 s, after the last token.
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.

requestprefill, setuptokens, messagesplain reply
Toy: R25 from 33.C4, 608 prompt and 218 answer tokens
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
SSE
How the server sends the tokens.
1 token
How many tokens go in one message.
80 ms
The time for a message to go and come back.
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
tall=s+r2+p+(n−1) d+r2\sy{t}{out}{t_{\text{all}}} = \sy{s}{param}{s} + \tfrac{\sy{r}{param}{r}}{2} + \sy{p}{param}{p} + (\sy{n}{out}{n}-1)\,\sy{d}{param}{d} + \tfrac{\sy{r}{param}{r}}{2}
6070.3=160+40+405.3+217⋅25+40 ms6070.3 = 160 + 40 + 405.3 + 217 \cdot 25 + 40\ \text{ms}

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.

Predict, then reveal
0 / 3 REVEALED
Q01If the server packs 16 tokens in each message, does the first text arrive sooner or later?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02At a 200 ms round trip, how much later is a WebSocket's first text than SSE's?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03Compared with SSE, do the bytes for the whole answer go up or down with gRPC?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. Streaming moves the first text earlier, but the last token arrives no sooner.
  2. SSE streams one way over HTTP; WebSockets and gRPC can send both ways.
  3. Small messages show text sooner but spend more bytes on framing.