Skip to content

Frameworks & SDKsComparison

Server-Sent Events vs WebSockets for Streaming LLM Responses

Token streaming is one-way, so Server-Sent Events are usually enough. How SSE and WebSockets differ on the wire, the browser limits that bite in production, and when full-duplex is worth it.

AI Dev Hub Editorial

Automated quality gate

Published
Updated
Reading time
2 min read
  • 5 sources cited
  • 13 facts quote-verified

At a glance

Server-Sent EventsWebSockets
DirectionServer → clientBoth directions
TransportA long-lived HTTP response with text/event-streamAn upgraded connection (101 Switching Protocols)
Browser APIEventSourceWebSocket
ReconnectionBuilt in, resumes with Last-Event-IDYou implement it
PayloadUTF-8 textText or binary frames
Best forToken streams, progress, notificationsCollaboration, presence, realtime voice

For streaming a model's answer to a browser, Server-Sent Events (SSE) are usually the simpler and sturdier choice. The details below explain why — and when WebSockets earn their extra complexity.

Feature comparison

How Server-Sent Events work

The server responds with the text/event-stream MIME type and writes UTF-8 text events separated by blank lines. Fields such as data, event, id and retry control delivery 12. If the connection drops, the browser reconnects on its own and sends the last event id it saw in the Last-Event-ID header, so the server can resume where it left off 1. MDN describes EventSource as unidirectional: events flow from the server to the client 3.

code
event: token
data: {"text":"Hel"}

event: token
data: {"text":"lo"}

event: done
data: {}

How WebSockets work

A WebSocket connection starts as an HTTP request carrying Upgrade: websocket; the server replies 101 Switching Protocols, and from then on both sides exchange frames in either direction over the same connection 4. The protocol was published as RFC 6455 in December 2011 4, and browsers expose it through the WebSocket API 5.

Performance and operations

A model's response is a one-way stream of tokens, which maps directly onto an event stream. Because SSE is plain HTTP, your existing infrastructure keeps working: authentication, logging, compression rules and serverless functions that stream responses.

Two production details matter:

  1. You rarely use EventSource for LLM calls. Its constructor takes a URL plus an options object whose only setting is withCredentials 3, so it cannot send a JSON body or custom authorization headers. LLM requests are usually POSTs, so clients read the SSE-formatted stream with fetch() and parse the events themselves.
  2. Mind the HTTP/1.1 connection cap. When SSE is not served over HTTP/2, it is limited by the browser's maximum number of open connections — six, counted per browser and domain — which quickly hurts when users open several tabs 3. Serve streams over HTTP/2 or HTTP/3.

A minimal streaming endpoint using Web Streams (this shape works in Next.js route handlers and other fetch-based runtimes; generateTokens stands in for your model call):

ts
export async function POST(request: Request) {
  const { prompt } = await request.json();
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      for await (const token of generateTokens(prompt)) {
        controller.enqueue(encoder.encode(`event: token\ndata: ${JSON.stringify({ text: token })}\n\n`));
      }
      controller.enqueue(encoder.encode("event: done\ndata: {}\n\n"));
      controller.close();
    },
  });

  return new Response(stream, {
    headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" },
  });
}

And a client that reads it with fetch():

ts
export async function readEvents(prompt: string, onEvent: (data: unknown) => void) {
  const response = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ prompt }) });
  if (!response.body) throw new Error("No response body");
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = "";
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += value;
    const events = buffer.split("\n\n");
    buffer = events.pop() ?? "";
    for (const event of events) {
      const data = event
        .split("\n")
        .find((line) => line.startsWith("data: "))
        ?.slice(6);
      if (data) onEvent(JSON.parse(data));
    }
  }
}

When to choose which

  • One model response per request → SSE, read with fetch() and a small parser.
  • Server pushes updates to a dashboard → SSE with EventSource, using event ids for resumption 1.
  • Bidirectional, stateful sessions such as collaborative editing or multiplayer presence → WebSockets 45.
  • Binary audio or video → WebSockets, because an event stream carries UTF-8 text only 1.

WebSockets are worth it when the client must keep talking on the same connection. Budget for what you give up: reconnection, resumption and backpressure become your code.

Related reading: Structured Outputs in TypeScript with the AI SDK and Zod shows how to stream partial JSON objects instead of raw tokens.

Frequently asked questions

Can Server-Sent Events carry binary data?

No. An event stream carries UTF-8 text, so binary data has to be encoded (for example as base64). For binary audio or video, WebSockets are a better fit.

Does SSE reconnect automatically?

Yes. EventSource reconnects on its own and sends the last event id it received in the Last-Event-ID header so the server can resume the stream.

Why not use EventSource for LLM requests?

EventSource only takes a URL and a withCredentials option, so it cannot send a JSON body or custom authorization headers. Most LLM calls are POST requests, so clients read the stream with fetch instead.

Sources

Every factual claim above cites one of these documents, retrieved and snapshotted by our research pipeline.

  1. S1
    HTML Standard — Server-sent events
    WHATWGOfficialRetrieved Sep 30, 2026
  2. S2
    Using server-sent events
    MDN Web DocsHighRetrieved Sep 30, 2026
  3. S3
    EventSource
    MDN Web DocsHighRetrieved Sep 30, 2026
  4. S4
    RFC 6455: The WebSocket Protocol
    IETFOfficialRetrieved Sep 30, 2026
  5. S5
    The WebSocket API (WebSockets)
    MDN Web DocsHighRetrieved Sep 30, 2026

Frameworks & SDKsNews

OpenAI Python SDK v3.13.0 Introduces Agents API

OpenAI has released version 3.13.0 of its Python SDK, introducing a new Agents API. This update allows developers to integrate agent capabilities directly into their Python applications.

2 min readListen · 5 min