Sub topic 7
Parsing events that split across chunks
This chapter assumes you know the Server-Sent Events (SSE) wire format from the previous chapter: data: lines, comment lines, and a blank line that ends each event. It also assumes you can read Python and JSON.
Why chunk boundaries are a problem
A network read returns whatever bytes have arrived. It does not return one event, or even one line. The server may send data: {"delta": "Hello"}\n\n as a single write. Between the server and your code, TCP segmentation, TLS records, proxies, and HTTP chunked encoding can cut those bytes at any position.
Your parser can therefore receive any of these:
- Several complete events in one chunk.
- Half of a JSON payload in one chunk and the rest in the next.
- A chunk that ends between the two newlines that terminate an event.
- A chunk that ends in the middle of a multi-byte UTF-8 character such as
éor an emoji. - A chunk that ends between the
\rand\nof a\r\nline ending.
Code that calls json.loads(chunk) or chunk.split("\n\n") on each read works on a fast local test and fails intermittently in production. The failures depend on timing, so they are hard to reproduce.
The three layers of buffering
A correct parser keeps state at three levels. Each level holds back only what it cannot yet interpret.
- Bytes to text. Decode with an incremental decoder. It keeps the leading bytes of an unfinished character and returns them once the rest arrives. Decoding each chunk independently with
chunk.decode("utf-8")raises an error or inserts replacement characters when a split lands inside a character. - Text to lines. Append decoded text to a buffer. Remove only lines that end with a line terminator. Whatever follows the last terminator stays in the buffer.
- Lines to events. Collect
data:lines in a list. A blank line closes the event: join the list with\nand emit it. Comment lines and unknown fields are skipped.
The SSE specification allows \n, \r\n, and a lone \r as line terminators. A chunk that ends in \r is ambiguous. If the next chunk starts with \n, the two characters form one terminator. If the parser treated \r as a complete line ending, it would see a second, empty line and emit an event early. The code below holds back a trailing \r until it can tell.
A chunk-safe parser
This class takes raw bytes. It returns a list of data payloads from each call to feed.
import codecs
import json
import re
LINE_END = re.compile(r"\r\n|\r|\n")
class SSEParser:
def __init__(self):
self.decoder = codecs.getincrementaldecoder("utf-8")()
self.buffer = ""
self.data_lines = []
def feed(self, chunk: bytes):
"""Accept raw bytes and return the payloads of any completed events."""
self.buffer += self.decoder.decode(chunk)
payloads = []
while True:
match = LINE_END.search(self.buffer)
if match is None:
break
if match.group() == "\r" and match.end() == len(self.buffer):
break # may be the first half of "\r\n"; wait for more data
line = self.buffer[: match.start()]
self.buffer = self.buffer[match.end():]
payload = self._handle_line(line)
if payload is not None:
payloads.append(payload)
return payloads
def _handle_line(self, line):
if line == "":
if self.data_lines:
payload = "\n".join(self.data_lines)
self.data_lines = []
return payload
return None
if line.startswith(":"):
return None # comment, often a keep-alive
field, _, value = line.partition(":")
if value.startswith(" "):
value = value[1:]
if field == "data":
self.data_lines.append(value)
return None # event, id, and retry are ignored here
raw = (
'data: {"delta": "caf\u00e9 "}\n\n'
": keep-alive\n\n"
'data: {"delta": "\U0001F600"}\r\n\r\n'
"data: [DONE]\n\n"
).encode("utf-8")
def collect(chunk_size):
parser = SSEParser()
text = ""
for i in range(0, len(raw), chunk_size):
for payload in parser.feed(raw[i : i + chunk_size]):
if payload == "[DONE]":
return text
text += json.loads(payload)["delta"]
return text
expected = "caf\u00e9 \U0001F600"
for size in range(1, len(raw) + 1):
assert collect(size) == expected, size
print(collect(1)) # café 😀The loop at the bottom is the important part. It feeds the same bytes in every chunk size from one byte up to the whole stream, and every size must produce the same text. Chunk size 1 is the harshest case, because every boundary falls everywhere at once. Write a test like this for any stream parser you build.
Behavior to check in your own parser
| Situation | Correct behavior |
|---|---|
| Chunk ends in the middle of a JSON payload | Keep the partial line in the buffer. Do not call `json.loads` until the event is closed. |
| Chunk contains several events | Emit each one in order, then keep any leftover text. |
| Chunk ends between `\n` and the second `\n` | Keep the `data:` lines collected so far. The event is not closed yet. |
| Chunk ends in the middle of a multi-byte character | Let the incremental decoder hold the partial bytes. |
| Event has two `data:` lines | Join them with `\n` into one payload. |
| Line starts with `:` | Skip it. It is a comment. |
| Stream ends without a final blank line | Discard the unfinished event. The specification does the same, because the event was never completed. |
Applying this in the browser
In JavaScript, response.body.pipeThrough(new TextDecoderStream()) gives you the incremental decoder from layer 1. You still own layers 2 and 3. The fetch example from the code samples for this tutorial keeps the incomplete tail of the buffer by using buffer.split("\n\n") followed by events.pop(). That works when the server uses \n line endings. If your server or a proxy in between may use \r\n, normalize the buffer first with buffer.replace(/\r\n/g, "\n"). Be careful with a trailing \r, for the same reason as in the Python parser.
Common mistakes
- Treating one read as one event. This is the most common bug, and it passes tests on
localhost. - Decoding each chunk separately. Text in English rarely exposes this. Text in Japanese, or text containing emoji, exposes it quickly.
- Parsing
[DONE]as JSON. OpenAI-style streams end with the literal[DONE]. Check for it before callingjson.loads. - Dropping the tail at end of stream. If a provider closes the connection without a final blank line, the last event may be incomplete. Decide on purpose whether to discard it or report an error, as the next chapters on accumulation and mid-stream errors discuss.
- Using
readlineon a buffered stream without checking its behavior. Some HTTP libraries read ahead, which delays delivery. Prefer the library's own iterator over bytes or lines.
Exercise
A chunk arrives ending in data: {"delta": "Hel. The next chunk is lo"}\n\ndata: {"delta": " there"}\n\n. What should the parser emit after each chunk, and why?
Show answer
After the first chunk it emits nothing. The text has no line terminator, so the line stays in the buffer. After the second chunk the buffer holds data: {"delta": "Hello"}, which is a complete line, followed by a blank line. The parser emits the payload {"delta": "Hello"}, and then {"delta": " there"} after the second blank line. It emits two payloads from the second chunk, and each is complete valid JSON.
Exercise
Why does the parser above hold back a \r that is the last character in its buffer?
Show answer
A \r may be the first half of a \r\n terminator whose \n has not arrived. If the parser treated the \r as a full line ending, the \n that arrives next would look like a second, empty line. That empty line would close an event too early.