Avoid rescanning SSE delimiter buffers#1913
Open
camdencheek wants to merge 1 commit into
Open
Conversation
Mamalimashayekh
approved these changes
Jun 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changes being requested
Modify
iterSSEChunksto skip already-scanned bytes so streaming in small chunks does not causefindDoubleNewlineIndexto get called with more data than is necessary.Additional context & links
In many of our profiles,
findDoubleNewlineIndexwas consuming a large amount of CPU. In some cases, even pushing our event loop utilization to 100%. This was surprising to me since that should be a pretty cheap operation.It seems the issue is not
findDoubleNewlineIndexitself, but rather that it is re-scanning bytes that it has already checked. Whenever a network chunk comes in, it gets appended todatathen that full buffer is searched for a double newline. This means that, in the pathological case of streaming one byte at a time, finding the double newline scans1 + 2 + ... + n = n * (n + 1) / 2bytes.When we measured this in our service, roughly 95% of the bytes scanned were redundantly scanned.
This fixes the issue by skipping the prefix we know can't contain any double newline (or partial double newline) and only scanning new bytes. We've patched this on our end, and it dropped byte scans here by 95% in our production env (as expected).