Sub topic 7
Parsing events that split across chunks
This chapter assumes you know the Server-Sent Events (SSE) format from the previous chapter and can read Python and JavaScript. It also assumes you know the basics of async code.
Why chunks do not match events
The network delivers bytes in chunks. SSE defines events as text ending in a blank line. These two units are unrelated. A single chunk can hold half an event, exactly one event, or three events plus the start of a fourth. The chunk size depends on TCP, proxies, and the server's flush behavior.
A parser that treats each chunk as one event works on your laptop and then fails in production. The failure shows up as json.loads errors on truncated payloads, or as silently dropped text.
The buffer pattern
Keep a buffer of text you have received but not yet processed. For each new chunk:
- Append the chunk to the buffer.
- While the buffer contains a blank-line terminator, cut off one complete event and handle it.
- Leave the remainder in the buffer for the next chunk.
The JavaScript client from the previous chapter does the same thing with buffer.split("\n\n") followed by buffer = events.pop(). The last item of the split is always the incomplete tail, so it goes back into the buffer.
A Python version that survives any split
The chunks in the example below are bytes. A multi-byte UTF-8 character such as é can be cut in half between chunks, and decoding each chunk on its own would raise an error. An incremental decoder holds the partial bytes until the rest arrive.
import codecs
import json
def iter_events(byte_chunks):
decoder = codecs.getincrementaldecoder("utf-8")()
buffer = ""
for chunk in byte_chunks:
buffer += decoder.decode(chunk)
buffer = buffer.replace("\r\n", "\n")
while "\n\n" in buffer:
raw, buffer = buffer.split("\n\n", 1)
data = [
line[5:].removeprefix(" ")
for line in raw.split("\n")
if line.startswith("data:")
]
if data:
yield "\n".join(data)
stream = 'data: {"delta": "caf\u00e9"}\n\ndata: [DONE]\n\n'.encode("utf-8")
chunks = [stream[i:i + 7] for i in range(0, len(stream), 7)]
for payload in iter_events(chunks):
if payload == "[DONE]":
break
print(json.loads(payload)["delta"]) # caféThe 7-byte chunks cut through the middle of é and through the middle of the JSON. The output is still correct.
Common errors
- Parsing per chunk. Never call
json.loadson a chunk. Parse only after you have a complete event. - Decoding each chunk separately. This breaks on non-ASCII text. Use an incremental decoder, or
TextDecoderStreamin the browser. - Mixed line endings. Servers may send
\r\n. Normalize them after appending to the buffer, so a\rat the end of one chunk and a\nat the start of the next still join. - Dropping the tail. If the stream ends with leftover text in the buffer, the server was cut off. Treat that as an error. Do not parse the fragment.
Exercise
A chunk ends with data: {"delta": "Hel and the next chunk begins with lo"}\n\n. What does a correct parser do after the first chunk, and what does it emit after the second?
Show answer
After the first chunk it emits nothing, because the buffer holds no blank line. It keeps the text in the buffer. After the second chunk the buffer contains a complete event, so it emits the payload {"delta": "Hello"}.