← Blog

How to Handle Streaming Responses in LLM Apps

2026-11-23 · 5 min read · SubToAPI Team

How to handle streaming responses in LLM apps

Streaming is how you turn a 10-second wait into something that feels instant. Instead of waiting for a full completion and dumping it on the screen, you read the response token by token (or chunk by chunk) as the model generates it, and render it incrementally. The core pattern is always the same: open a connection, read a continuous stream of events over HTTP, parse each event, append it to your output, and handle disconnects or malformed chunks gracefully.

Most LLM providers expose streaming over Server-Sent Events (SSE) on top of a normal HTTP connection. You don't need WebSockets, a message queue, or any special infrastructure — you need a client that can read a response body incrementally and a bit of state to track partial messages. The rest of this article walks through the moving parts you actually need to get right: parsing, buffering, backpressure, errors, and UI updates.

Why streaming is different from a normal HTTP call

A non-streaming LLM call is just fetch → wait → JSON. Streaming breaks that mental model in three ways:

Reading the stream

On the client (browser, Node, or server-side proxy), you read the response body as a stream of bytes and decode it incrementally. In Node or a browser with fetch, that looks like this:

const response = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "claude-sonnet-4",
    stream: true,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Summarize this ticket in two sentences." }]
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

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

  let lines = buffer.split("\n");
  buffer = lines.pop(); // keep the last (possibly incomplete) line

  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const payload = line.slice(6);
    if (payload === "[DONE]") continue;
    const event = JSON.parse(payload);
    handleEvent(event);
  }
}

The key detail most people miss: chunks from the network don't align with event boundaries. A single read() call might give you half a data: line. That's why you buffer everything and only process complete lines, pushing the remainder back for the next iteration. Skip this step and you'll get intermittent JSON parse errors that are maddening to debug because they only happen under certain network conditions.

Handling event types

Streaming APIs typically emit several distinct event types in a single response: a start event, repeated content deltas, tool-use argument deltas, and a final stop event with usage metadata. Your handleEvent function needs a switch statement, not a single code path:

function handleEvent(event) {
  switch (event.type) {
    case "content_block_delta":
      appendToUI(event.delta.text);
      break;
    case "message_stop":
      finalizeMessage(event.usage);
      break;
    case "error":
      showRecoverableError(event.error.message);
      break;
  }
}

If the model is using tools, argument fragments arrive as partial JSON strings across multiple events. Don't try to JSON.parse each fragment individually — concatenate them and only parse once you see the matching "stop" event for that content block. See /docs/tools and /docs/streaming for the exact event shapes if you're building against SubToAPI.

Backpressure and rendering performance

If you append every single delta directly to the DOM, you'll cause layout thrashing on fast streams. Batch UI updates instead:

let pending = "";
let scheduled = false;

function appendToUI(text) {
  pending += text;
  if (!scheduled) {
    scheduled = true;
    requestAnimationFrame(() => {
      outputEl.textContent += pending;
      pending = "";
      scheduled = false;
    });
  }
}

This keeps rendering smooth regardless of how fast tokens arrive, and it generalizes to non-browser contexts too — if you're piping a stream to a WebSocket or a terminal, batch writes on a short interval rather than per-token.

Handling disconnects and partial responses

Streams fail mid-way more often than full requests fail outright — proxies time out, mobile connections drop, tabs get backgrounded. Decide upfront what "partial success" means for your product:

let lastEventTime = Date.now();
const STALL_MS = 15000;

setInterval(() => {
  if (Date.now() - lastEventTime > STALL_MS) {
    reader.cancel();
    showStallError();
  }
}, 1000);

Server-side proxying

If your frontend can't hold a direct connection to the LLM provider (auth, CORS, or you want to log usage), you'll proxy the stream through your own backend. The rule is the same on the server: read the upstream stream, forward chunks as you receive them, and don't buffer the entire response before responding — that defeats the purpose of streaming and adds latency that users notice immediately.

This is also where centralizing access pays off. If you're already issuing scoped application keys through SubToAPI, your backend proxy can just forward the stream from /v1/messages with stream: true, log the final usage event for billing, and never hold the whole response in memory. Get started details are in /docs/quickstart, and the full event reference is in /docs/messages.

questions

Do I need WebSockets to stream LLM responses? No. Server-Sent Events over a standard HTTP response is sufficient and is what most providers use. WebSockets add complexity (connection management, reconnection logic) that streaming text generation doesn't require.

What happens if the connection drops halfway through a response? You lose the rest of that specific generation — there's no resume-from-token mechanism. Render what arrived, mark it incomplete in your UI, and let the user retry the full request rather than silently failing.

How do I avoid parsing errors on partial JSON chunks? Buffer incoming bytes and only parse complete lines or events, holding back any incomplete trailing data for the next read. Never call JSON.parse on a chunk boundary you haven't verified is a full event.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →