← Back to Blog
AI EngineeringLLMsDeveloper Productivity

Streaming LLM Responses in Production: SSE, Cancellation, and Partial JSON Done Right

Streaming makes an 8-second answer feel like it starts in under a second, until a proxy buffers it, a closed tab keeps billing tokens, or half a JSON object crashes your UI. Here's the end-to-end setup that holds up in production.

By JoinloopΒ·1 October 2026Β·11 min read
ShareLinkedInXReddit
🌊

A non-streaming LLM call that takes 8 seconds feels broken. The same call streamed, with the first words showing up in 400ms, feels fast, even though the total time hasn't changed. That's why every chat product streams, and why "add streaming" is one of the first tickets on any AI feature.

The demo version takes about twenty lines. The production version is where teams lose a week, because the problems only appear under real conditions:

  • It streams on localhost but arrives in one lump on staging, because a proxy or compression layer is buffering the response.
  • A user closes the tab, but the server keeps generating (and paying for) 3,000 tokens nobody will read.
  • Tokens go missing now and then, because an SSE frame was split across two network reads and the parser dropped it.
  • A structured response renders as {"title": "Quar and the UI throws.
  • The model fails 40 seconds in, after a 200 OK was already sent, so there's no status code left to carry the error.

This post walks through the full path, from model API to server to browser, and shows how to handle each one.

Why streaming is different from a normal request

A normal HTTP request has three clear moments: a request, a status code, and a body. Streaming breaks that up. You commit to 200 OK before you know whether generation will succeed, and the body arrives in pieces over seconds or minutes. Three things follow from that:

  1. Errors become part of the payload. Once headers are sent, the only way to report a failure is an in-band event that the client knows how to read.
  2. Every layer has to pass bytes through as they arrive. Load balancers, reverse proxies, CDNs, compression middleware, and framework response helpers all like to buffer. One buffering layer anywhere in the chain turns your stream back into a batch response.
  3. Lifetimes are tied together. The browser connection, your server handler, and the upstream model request should live and die together. If you don't wire that up, they won't.

Choosing a transport

Transport Direction Good for Watch out for
SSE (text/event-stream) Server β†’ client Chat, completions, agent progress EventSource only does GET, so most apps use fetch + a manual parser
Chunked fetch (NDJSON) Server β†’ client Simple token or JSON-line streams You define the framing yourself; no standard reconnect
WebSocket Both ways Voice, collaborative editing, interrupting mid-generation Sticky sessions, more infrastructure, harder to cache or route

For text generation, SSE over a fetch POST is the default choice. Anthropic, OpenAI, and Google all stream this way, it works through most infrastructure, and the framing (event: / data: lines ending in a blank line) is simple to parse correctly. Use WebSockets only when the client has to send data mid-stream, for example in voice interfaces.

The server: stream, frame, and propagate aborts

Here's a Next.js-style route handler in TypeScript using the Anthropic SDK. The pattern carries over to any provider and any framework that can return a web Response with a ReadableStream.

// app/api/chat/route.ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const encoder = new TextEncoder();

function sse(event: string, data: unknown): Uint8Array {
  return encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}

export async function POST(req: Request) {
  const { messages } = await req.json();

  const body = new ReadableStream<Uint8Array>({
    async start(controller) {
      // Ties the upstream model call to the browser connection.
      const stream = client.messages.stream(
        { model: "claude-sonnet-5", max_tokens: 2048, messages },
        { signal: req.signal },
      );

      // Keep-alive so idle proxies don't kill long-thinking requests.
      const heartbeat = setInterval(() => {
        controller.enqueue(encoder.encode(": ping\n\n"));
      }, 15_000);

      try {
        for await (const event of stream) {
          if (
            event.type === "content_block_delta" &&
            event.delta.type === "text_delta"
          ) {
            controller.enqueue(sse("delta", { text: event.delta.text }));
          }
        }
        const final = await stream.finalMessage();
        controller.enqueue(
          sse("done", { stop_reason: final.stop_reason, usage: final.usage }),
        );
      } catch (err) {
        if (!req.signal.aborted) {
          // Headers are already sent, so report the error in-band.
          controller.enqueue(sse("error", { message: "generation_failed" }));
          console.error("stream failed", err);
        }
      } finally {
        clearInterval(heartbeat);
        controller.close();
      }
    },
  });

  return new Response(body, {
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      Connection: "keep-alive",
      "X-Accel-Buffering": "no", // tells nginx not to buffer
    },
  });
}

What each piece is for:

  • signal: req.signal is the most important line. When the browser disconnects, the request signal aborts, the SDK cancels the upstream HTTP call, and generation stops. Without it, every abandoned tab keeps generating tokens you pay for. Check that your runtime actually fires req.signal on client disconnect. Most modern runtimes do, but some serverless adapters haven't historically, so test it.
  • Named events (delta, done, error) give the client a clear protocol. The done event is how the client tells "finished" apart from "connection dropped". Without it, a truncated stream looks like a complete answer.
  • Heartbeat comments (lines starting with :) are ignored by SSE parsers but keep idle-timeout proxies from closing the connection while a reasoning model is thinking before its first token.
  • no-transform and X-Accel-Buffering: no ask intermediaries not to compress or buffer. They aren't guaranteed to work, which is why the checklist below includes testing through your real edge.

SDK event shapes and helper names change between versions, so check your provider's current streaming docs for the exact delta types, especially for tool use and thinking blocks.

The client: a parser that doesn't drop tokens

EventSource doesn't support POST bodies or custom headers, so most apps read the stream with fetch. The usual bug is splitting each network chunk on \n\n and assuming every chunk contains whole events. TCP makes no such promise. A chunk can end halfway through an event, or halfway through a multi-byte UTF-8 character.

type Handlers = {
  onDelta: (text: string) => void;
  onDone: (meta: unknown) => void;
  onError: (msg: string) => void;
};

export async function streamChat(
  messages: unknown[],
  handlers: Handlers,
  signal: AbortSignal,
) {
  const res = await fetch("/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages }),
    signal,
  });
  if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);

  // TextDecoderStream handles UTF-8 characters split across chunks.
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = "";
  let finished = false;

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += value;

    // Only process complete events; keep the remainder for the next read.
    let sep: number;
    while ((sep = buffer.indexOf("\n\n")) !== -1) {
      const raw = buffer.slice(0, sep);
      buffer = buffer.slice(sep + 2);

      let event = "message";
      const dataLines: string[] = [];
      for (const line of raw.split("\n")) {
        if (line.startsWith(":")) continue; // heartbeat comment
        if (line.startsWith("event:")) event = line.slice(6).trim();
        else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
      }
      if (dataLines.length === 0) continue;
      const data = JSON.parse(dataLines.join("\n"));

      if (event === "delta") handlers.onDelta(data.text);
      else if (event === "done") { finished = true; handlers.onDone(data); }
      else if (event === "error") { finished = true; handlers.onError(data.message); }
    }
  }

  if (!finished && !signal.aborted) handlers.onError("stream_truncated");
}

The Stop button is then just controller.abort() on an AbortController you created per request. The abort travels from fetch to req.signal to the SDK to the provider, so one click stops the whole chain.

This parser assumes \n line endings, which is what your own server sends. A fully spec-compliant SSE parser also handles \r\n and id:/retry: fields. If you consume third-party SSE streams, use a maintained library such as eventsource-parser instead of writing your own.

Rendering without melting the browser

Fast models can emit hundreds of tokens per second. If each delta calls setState and re-runs a markdown parser over the whole message, the tab will lag on long answers. Two fixes cover most cases:

  1. Batch to animation frames. Add deltas to a ref and flush to state once per requestAnimationFrame. That's 60 renders per second at most, no matter how fast tokens arrive.
  2. Memoise finished blocks. Split the markdown into blocks (paragraphs, code fences) and re-render only the last, still-growing block. Blocks that are complete don't change.

Also pin scroll to the bottom only if the user is already there. If they've scrolled up to reread something, jumping them back down on every token is the most common streaming UX complaint.

Streaming structured output

When the model returns JSON (a generated form, a list of extracted entities, a card UI), the in-progress text is never valid JSON until the final brace. You have three options:

Approach How it works Best when
Wait for completion Buffer and parse once at done Output is short, or partial data is useless
Partial JSON parsing Re-parse the buffer on each delta with a tolerant parser that closes open strings and brackets Fields can render progressively (title first, then items)
NDJSON / one object per line Prompt or schema asks for one JSON object per line; parse each complete line Lists of independent items (search results, extracted rows)

For partial parsing, use a maintained library such as partial-json or the partial-JSON helpers in the Vercel AI SDK. Don't write a regex. Two rules apply whichever you choose:

  • Validate only the final object. Partial objects will fail your Zod schema because required fields are missing. Render partial data optimistically, then run strict validation at done and handle failures there.
  • Treat the last string field as unstable. "status": "approv may become "approved" or "approval_pending". Don't trigger side effects (routing, API calls, analytics) on fields that are still streaming.

Production checklist

  • Upstream model call receives the request's abort signal, and you've confirmed generation stops when a tab closes (check provider usage or logs)
  • Explicit done and error events; client treats a stream without done as truncated
  • Heartbeat every 10–20s for reasoning models with long time-to-first-token
  • Tested through the real CDN, load balancer, and proxy, not just localhost (curl -N against staging and watch the chunks arrive)
  • Compression disabled or flushed per event on the streaming route
  • Client parser buffers partial events and decodes UTF-8 as a stream
  • Renders batched per animation frame; completed markdown blocks memoised
  • Time-to-first-token and total duration logged separately, plus abort rate
  • Final assistant message persisted server-side on done, not by the client after the fact

Common pitfalls

Measuring only total latency. For streamed features, time-to-first-token (TTFT) is what users notice. A change that cuts total time by 20% but doubles TTFT, such as adding a retrieval step before the call or turning up reasoning effort, can make the product feel slower. Track both, and set the TTFT budget per feature.

Retrying a stream that half-succeeded. If the connection drops after 600 tokens, blindly retrying sends the user a second, different answer that gets appended to the first. Either discard the partial text visibly ("Connection lost β€” regenerating") or design resumable streams with event IDs and a server-side buffer. Most teams should pick the first.

Persisting from the client. If the browser is responsible for saving the finished message, every closed tab loses it. Save on the server when done fires, and save partial text with a truncated flag when the client aborts.

Forgetting serverless time limits. Many serverless platforms cap function duration. A long agent run that streams for minutes may be killed partway through. Check your platform's limits for streaming responses, or move long agent runs to a background job that streams progress events.

Streaming tool calls straight to the UI. When the model is building tool-call arguments, those deltas are partial JSON for your backend, not text for the user. Show a status indicator ("Searching orders…") and execute the tool only once its arguments are complete and validated.

For PMs: what to ask for

Streaming is partly a product decision. Ask the team three things: what's our p50 and p95 time-to-first-token, what does the user see between pressing Enter and the first token (an empty bubble, a "thinking" indicator, a retrieval status), and what happens when a stream fails partway through. If nobody has designed that third case, users will be the first to find it.

Next steps

Start by testing against your staging URL with curl -N and checking whether tokens trickle in or arrive all at once. If they trickle in, close a tab mid-generation and confirm in your provider's usage logs that billing stopped. Those two checks catch most of the production streaming bugs we've seen.

If you want to build production-grade LLM features like this, with code review from practitioners who have shipped them, that's what Joinloop's AI engineering cohort covers.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.