Mental model
Parallel stream orchestration merges independently produced assistant outputs into one interface while preserving each stream’s identity, local order, cancellation state, and failure status. A merge should never mistake arrival order for causal order: tag chunks with a stream ID and sequence, bound queued data, and let one failed stream terminate independently when partial results remain useful.
Learning outcomes
- Explain which ordering guarantees belong to an individual stream and which do not exist across streams.
- Estimate the latency benefit of independent work and identify when a dependency changes the critical path.
- Design cancellation, backpressure, partial-failure, and user-status behavior for a multi-stream interface.
Theory
Each producer should have a stable identity within one request, such as “retrieval”, “draft”, or “verification”. Every emitted frame needs that identity and a sequence number that increases within its own stream. The UI can then append a delta to the correct message and reject duplicates or late frames from an older request. Arrival time can interleave independent streams, but it does not establish a meaningful total order among their content. If verification depends on retrieval, represent that dependency in an explicit step or event rather than inferring it from whichever chunk arrived first.
The AI SDK UI stream protocol illustrates this distinction by framing message starts, text deltas, tool input, and completion as typed events. Keeping those event types matters: a tool result is not text to concatenate, and a final message boundary is not just another token. A client can multiplex frames onto one transport while retaining each producer’s local order. The transport’s ordering guarantee only applies to the frames it delivered; it cannot repair a producer that labels an old chunk with the wrong request or sequence.
For independent streams started together, the response is ready when the slowest required stream finishes. Let be dispatch time in seconds, the completion time of stream after dispatch in seconds, and the final merge time in seconds. With no dependencies, the critical-path estimate is:
Suppose retrieval takes 1.4 s, drafting takes 1.9 s, and verification takes 1.1 s; dispatch costs 0.26 s and assembling the final view costs 0.12 s. The parallel path is about s. Running the same three tasks serially takes about s. This estimate assumes the tasks are independent, overlap fully, and do not contend for a shared rate limit or worker pool. If verification waits for the draft, the work is a dependency graph, and the longest path through that graph replaces the simple maximum.
Fast producers can outrun the browser. A readable stream has a queueing strategy, but combining many readers does not create a global memory limit by itself. Keep at most one outstanding read per producer, consume the merged async iterator at the speed of the renderer, cap each source’s high-water mark, and stop or slow a producer when its queue reaches budget. The built-in ReadableStream tee operation needs special care: when one branch lags, unread chunks may accumulate for that branch without bounding memory. For fan-out to logging and UI, use bounded queues with a defined drop, pause, or durable-spool policy instead of silently retaining an unlimited copy.
Cancellation is a lifecycle decision. A user pressing Stop should cancel the request’s producers, release their readers, and prevent late frames from mutating a new turn. Cancelling one optional agent can leave the others useful; cancelling the parent request should usually stop all children. Give every run a fresh request ID and AbortController so a new turn cannot accidentally reuse the old signal. When one reader errors, report a stream-local failure with a stable code and keep other readers active if the product can still return a coherent partial result.
Progress also has an accessibility budget. A visual pane may update on every delta, while a polite live region announces only meaningful milestones such as “Draft ready” or “Verification failed”. Repeating every token through a screen reader creates noise and competes with the user’s current task. Pair color with a textual stream label and status, preserve keyboard access to each result, and announce the final partial or complete outcome.
Trade-offs
Parallel work can reduce time to a complete answer, but it consumes concurrent provider capacity and can make the interface harder to follow. Start only tasks with independent value, assign each a visible purpose, and cancel work whose result is no longer needed. A speculative draft may appear first and later be revised; present that as provisional instead of letting users mistake early arrival for authority.
A single multiplexed channel simplifies connection management and keeps per-request frame order. Separate channels can isolate a slow or failed producer and make cancellation more precise, but require more sockets, bookkeeping, and reconnection logic. Whatever transport is selected, define stream IDs, sequence handling, terminal events, and retry semantics at the application boundary. Server-Sent Events provide a useful one-way event channel; they do not replace application-level correlation IDs or make an interrupted generation resumable on their own.
Strict fairness prevents a chatty source from monopolizing rendering, but adds scheduling delay to small updates. A simple arrival-order merge often works for two or three streams. For a larger set, batch a short time window, rotate among ready producers, or prioritize a required source while enforcing a maximum burst. Measure time to first useful result, time to all required results, queue bytes, cancellations, and partial failures; optimizing only average completion time can hide poor tail latency or a producer that never finishes.
Failure modes and misconceptions
- Interleaving is read as chronology. Two independent streams can race. Preserve sequence inside each stream, and display source labels or explicit dependencies rather than claiming a cross-stream order.
- The fastest stream fills memory. A producer may continue adding chunks while the UI paints slowly. Bound its queue, expose queue depth, and choose backpressure, pause, or a documented truncation policy.
- A failed optional stream erases all results. Catch errors per reader and surface a partial outcome. If the failed stream is required for correctness, mark the whole response incomplete and block any action that depends on it.
- Cancellation leaves stale updates behind. Abort the parent and child operations, then compare each arriving frame’s request ID with the active request before applying it.
- A tee is assumed to provide safe backpressure. One slow branch can buffer independently. Avoid unbounded fan-out or give the slow consumer an explicit budget and overflow behavior.
- Every token is announced. Per-chunk screen-reader updates are overwhelming. Announce state changes and completion, with a control for inspecting each stream’s full text.
Decision scenario
An assistant launches a retrieval stream, a draft stream, and a verifier stream. Retrieval returns a useful source list, the draft completes, and the verifier stalls until its 8 s deadline. The UI already has enough evidence to show a provisional answer, but the product requires verification before it can label the result “checked”.
Keep the retrieval and draft visible with their own statuses, mark verification as timed out, and label the assembled answer provisional. Do not convert the missing verification result into a pass or discard the other completed work. Offer a retry that starts a new verifier child under the same parent run, with a new child ID and a clear deadline. If the user cancels the whole request during that retry, abort every child and ignore any late delta from the old run. Track the verifier timeout separately from first-token latency so the team can improve the slow dependency without hiding the failure.
Implementation pattern
This async generator reads each producer independently, emits deltas with per-stream sequence numbers, turns a local read error into a stream-local failure frame, and cancels remaining readers when the caller stops consuming or aborts the run. Each input stream should be constructed with an appropriate queue budget.
typescripttype Frame =| { streamId: string; sequence: number; kind: "delta"; text: string }| { streamId: string; sequence: number; kind: "done" }| { streamId: string; sequence: number; kind: "error"; code: "stream_failed" };type ReaderState = {streamId: string;reader: ReadableStreamDefaultReader<string>;sequence: number;pending: Promise<ReadableStreamReadResult<string>>;};export async function* mergeStreams(streams: Record<string, ReadableStream<string>>,signal: AbortSignal,): AsyncGenerator<Frame> {const active: ReaderState[] = Object.entries(streams).map(([streamId, stream]) => {const reader = stream.getReader();return { streamId, reader, sequence: 0, pending: reader.read() };});if (active.length === 0) throw new RangeError("At least one stream is required.");const cancelAll = () => {for (const item of active) void item.reader.cancel().catch(() => undefined);};signal.addEventListener("abort", cancelAll, { once: true });try {while (active.length > 0 && !signal.aborted) {const settled = await Promise.race(active.map((item) =>item.pending.then((result) => ({ item, result }),() => ({ item, failed: true as const }),),));const index = active.indexOf(settled.item);if ("failed" in settled) {active.splice(index, 1);await settled.item.reader.cancel().catch(() => undefined);settled.item.reader.releaseLock();yield { streamId: settled.item.streamId, sequence: settled.item.sequence++, kind: "error", code: "stream_failed" };} else if (settled.result.done) {active.splice(index, 1);settled.item.reader.releaseLock();yield { streamId: settled.item.streamId, sequence: settled.item.sequence++, kind: "done" };} else {settled.item.pending = settled.item.reader.read();yield { streamId: settled.item.streamId, sequence: settled.item.sequence++, kind: "delta", text: settled.result.value };}}} finally {signal.removeEventListener("abort", cancelAll);await Promise.all(active.map(async ({ reader }) => {await reader.cancel().catch(() => undefined);reader.releaseLock();}));}}