# 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.

- Published: 2026-09-25
- Updated: 2026-10-07
- Category: Frameworks & SDKs
- Type: comparison
- Tags: llm, sse, streaming, websockets
- Sources: 5
- Canonical: https://rajatxautomatedcontent.vercel.app/articles/server-sent-events-vs-websockets-llm-streaming

---

## At a glance

|              | Server-Sent Events                                  | WebSockets                                         |
| ------------ | --------------------------------------------------- | -------------------------------------------------- |
| Direction    | Server → client                                     | Both directions                                    |
| Transport    | A long-lived HTTP response with `text/event-stream` | An upgraded connection (`101 Switching Protocols`) |
| Browser API  | `EventSource`                                       | `WebSocket`                                        |
| Reconnection | Built in, resumes with `Last-Event-ID`              | You implement it                                   |
| Payload      | UTF-8 text                                          | Text or binary frames                              |
| Best for     | Token streams, progress, notifications              | Collaboration, 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 [S1][S2]. 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 [S1]. MDN describes `EventSource` as unidirectional: events flow from the server to the client [S3].

```text
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 [S4]. The protocol was published as RFC 6455 in December 2011 [S4], and browsers expose it through the `WebSocket` API [S5].

## 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` [S3], so it cannot send a JSON body or custom authorization headers. LLM requests are usually `POST`s, 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 [S3]. 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 [S1].
- **Bidirectional, stateful sessions** such as collaborative editing or multiplayer presence → WebSockets [S4][S5].
- **Binary audio or video** → WebSockets, because an event stream carries UTF-8 text only [S1].

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](/articles/structured-outputs-typescript-ai-sdk-zod) shows how to stream partial JSON objects instead of raw tokens.

## FAQ

**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

- [S1] HTML Standard — Server-sent events — WHATWG. <https://html.spec.whatwg.org/multipage/server-sent-events.html> (retrieved 2026-09-30, trust: official)
- [S2] Using server-sent events — MDN Web Docs. <https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events> (retrieved 2026-09-30, trust: high)
- [S3] EventSource — MDN Web Docs. <https://developer.mozilla.org/en-US/docs/Web/API/EventSource> (retrieved 2026-09-30, trust: high)
- [S4] RFC 6455: The WebSocket Protocol — IETF. <https://www.rfc-editor.org/rfc/rfc6455> (retrieved 2026-09-30, trust: official)
- [S5] The WebSocket API (WebSockets) — MDN Web Docs. <https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API> (retrieved 2026-09-30, trust: high)

---

Source: AI Dev Hub — https://rajatxautomatedcontent.vercel.app/articles/server-sent-events-vs-websockets-llm-streaming
