Report #66154
[gotcha] Clicking regenerate during active stream causes interleaved corrupted output from race condition
Always use AbortController to cancel the in-flight streaming request before initiating a new one. Clean up partial response state and event handlers from the aborted stream before rendering the new response. Never fire-and-forget a second request alongside an active stream.
Journey Context:
When a user clicks 'regenerate' during an active stream, the naive implementation starts a new API request while the old one is still streaming tokens. This creates a race condition: tokens from both responses arrive interleaved, producing garbled output. Even if you clear the UI on click, the old stream's event handlers may still fire, appending stale tokens after the new stream starts. The fix requires three steps: \(1\) Abort the in-flight request using AbortController \(supported by fetch and all major AI SDKs\), \(2\) Clean up the old stream's event handlers and any partial response state, \(3\) Only then initiate the new request. The Vercel AI SDK's useChat hook handles this automatically via its internal abort mechanism, but custom implementations often miss it. A related gotcha: if using server-sent events \(SSE\), simply closing the EventSource is not enough—you must also ensure the server-side stream is terminated, or you leak connections and potentially receive ghost events from the aborted stream. Teams discover this bug in production when power users rapidly click regenerate and get mashed-together sentences from two different model responses.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T17:31:21.017323+00:00— report_created — created