Dev tools

Server-Sent Events vs WebSockets for AI Streaming

Server-sent events vs WebSockets: how each works, why LLM APIs stream with SSE, when WebSockets win, and how to stream AI responses to the browser.

By OmniAI Editorial · Nov 20, 2026 · 10 min read

Server-sent events vs WebSockets is a common choice when you build anything that streams data from a server, and it matters especially for AI apps that show answers word by word as the model writes them. Server-sent events (SSE) send a one-way stream from server to browser over ordinary HTTP. WebSockets open a two-way channel where both sides can send messages at any time. Most LLM APIs stream with SSE, but voice assistants and other real-time apps often need WebSockets.

This guide explains how each technology works, compares them side by side, shows why SSE became the standard for streaming LLM responses, explains when WebSockets are the better fit, and includes short code examples.

Server-Sent Events vs WebSockets at a Glance

Server-sent events (SSE)WebSockets
DirectionOne way: server to clientTwo way: both sides send any time
ProtocolPlain HTTP responseStarts as HTTP, then upgrades to the WebSocket protocol
Data formatText (UTF-8)Text or binary
Browser APIEventSource (or fetch streaming)WebSocket
ReconnectionBuilt in, with resume via last event IDYou build it yourself
Works with HTTP infrastructureYes, mostly as-isNeeds proxies and load balancers that support upgrades
Typical AI useStreaming chat answers from an LLMReal-time voice, interruptions, collaborative apps

The short version of SSE vs WebSocket: use SSE when the server streams and the client mostly listens; use WebSockets when both sides need to talk continuously.

What Are Server-Sent Events?

Server-sent events are a web standard for streaming updates from a server over a normal HTTP connection. The client makes a request, and instead of sending one response and closing, the server keeps the connection open and writes events as they happen.

The response uses the text/event-stream content type. Each event is a few lines of text, ending with a blank line:

event: message
data: {"text": "Hello"}

data: {"text": " world"}
id: 42

The standard fields are data (the content), event (an optional event name), id (an ID for resuming) and retry (how long to wait before reconnecting).

In browsers, the built-in EventSource API handles all of this. It opens the connection, parses the events and reconnects automatically if the connection drops, sending the last event ID it received so the server can resume.

As MDN puts it, unlike WebSockets, server-sent events are unidirectional: data flows from the server to the client only. To send something back, the client makes a separate ordinary HTTP request.

What Are WebSockets?

WebSockets, defined in RFC 6455, provide a full two-way connection between client and server. The connection starts as an HTTP request with an "upgrade" header. If the server agrees, the same connection switches to the WebSocket protocol and stays open. Addresses look like ws:// or, encrypted, wss://.

After that, either side can send messages, called frames, at any moment, as text or binary data. There's no request-response pattern: it's a continuous conversation.

That flexibility comes with more work. WebSockets don't reconnect automatically in browsers; you write that logic yourself, including heartbeats to detect dead connections and a way to resume missed messages. And because the connection isn't a normal HTTP response, every proxy, firewall and load balancer in the path must support WebSocket upgrades.

Split by a dotted divider: on the left, a grey server box with three ink arrows pointing right to a grey browser window; on the right, a grey server box and browser window joined by arrows pointing both ways, with one arrow in orange.
SSE streams one way from the server; WebSockets carry messages in both directions.

Why LLM APIs Stream With SSE

When you ask a chatbot a question, the pattern is simple: one request goes in, and a stream of tokens comes back. The client doesn't need to say anything while the answer is being written. That's exactly what SSE is built for.

Major LLM APIs, including those from OpenAI and Anthropic, deliver streaming responses as server-sent events. Each event carries the next piece of text or a status update, and a final event marks the end.

SSE fits LLM streaming well because:

  • It's just HTTP. The request can be a normal POST with headers for authentication, and it passes through standard web infrastructure.
  • It's simple. No upgrade handshake, no custom protocol, easy to debug with ordinary tools.
  • It's stateless between requests. Each answer is its own stream, which suits horizontally scaled servers.
  • Text is all you need. Tokens are text, so SSE's text-only format is no limit.

If you're building a chatbot, SSE is usually the right default for showing answers as they're generated.

When WebSockets Win

WebSockets are the better choice when both sides need to talk at the same time:

  • Real-time voice assistants. Audio streams up from the microphone while audio and text stream back, and the user can interrupt mid-sentence. Real-time voice APIs commonly use WebSockets or WebRTC for this. Our guide to AI voice agents covers the architecture.
  • Interactive agents. If the user can stop, redirect or approve steps while an agent is working, a two-way channel avoids juggling many separate requests.
  • Collaborative apps. Shared documents, whiteboards and multiplayer features need constant updates in both directions.
  • Binary data. WebSockets carry binary frames directly; SSE needs binary data encoded as text.

SSE vs WebSocket: Performance and Scaling

For typical AI streaming, both are fast enough: the model's generation speed is the bottleneck, not the transport. The differences show up in operations.

Connection limits. Over HTTP/1.1, browsers allow only a small number of connections per domain. MDN notes that without HTTP/2, SSE is limited to 6 open connections per browser and domain, shared across all tabs. Over HTTP/2, many streams share one connection (the default limit negotiated is typically 100), so this stops being a problem. Serve SSE over HTTP/2 or HTTP/3.

Proxies and buffering. Some reverse proxies buffer responses, holding back the stream until it's finished, which destroys the streaming effect. Disable buffering for SSE endpoints. With nginx, for example, the response header X-Accel-Buffering: no turns it off for that response.

Timeouts. Load balancers often close idle connections. Long AI answers with pauses, or long-lived WebSocket connections, may need longer timeouts or periodic keep-alive messages.

State. A WebSocket connection is long-lived and tied to one server, so scaling out often needs sticky sessions or a shared message layer. SSE streams for LLM answers are usually short-lived, one per request, which makes them easier to spread across servers.

Streaming LLM Responses: Code Examples

Server: an SSE endpoint in Python

With FastAPI, a streaming response with the text/event-stream media type sends events as the model produces them:

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

def generate():
    for token in ["Hello", " from", " the", " model"]:  # replace with your LLM stream
        yield f"data: {token}\n\n"
    yield "data: [DONE]\n\n"

@app.get("/stream")
def stream():
    return StreamingResponse(generate(), media_type="text/event-stream")

Client: EventSource or fetch?

EventSource is the easiest client, but it only makes GET requests and can't set custom headers such as an Authorization token. For chat apps, where you POST a conversation and authenticate, most developers read the stream with fetch instead:

const res = await fetch("/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ message: "Hello" }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  console.log(decoder.decode(value, { stream: true }));
}

The chunks you read don't always line up with events, so split the text on blank lines and parse each data: line. You also lose EventSource's automatic reconnection, which is usually fine for a single chat answer.

A grey browser window with three ink text lines of decreasing length, the newest and shortest line in orange, and an ink arrow coming in from a grey server box on the left.
Streaming shows an AI answer piece by piece as the server sends it.

What About Long Polling and Streamable HTTP?

Long polling is the older technique: the client asks for updates, the server holds the request open until it has something, responds, and the client immediately asks again. It works everywhere but adds overhead and delay. SSE and WebSockets replaced it in most new apps, though it's still a useful fallback in restrictive networks.

Streamable HTTP is the transport used by the Model Context Protocol for remote servers. It replaced MCP's earlier HTTP+SSE transport. Clients send messages as HTTP POST requests, and the server can reply with a single JSON response or open an SSE stream for multiple messages. It's a good example of SSE being used inside a newer design rather than disappearing. Our guide to the Model Context Protocol explains how MCP fits into AI apps.

What About Webhooks and gRPC?

Two other options come up in the same comparisons.

Webhooks are HTTP requests one server sends to another when something happens, such as a payment provider calling your backend when a charge succeeds. They're for server-to-server notifications, not for streaming to a browser. In AI apps, webhooks are useful for long jobs: start a batch or a long-running agent task, then let the provider call your webhook when it's done instead of holding a stream open for minutes.

gRPC is a framework for calls between services over HTTP/2. It supports server streaming, client streaming and two-way streaming, with compact binary messages, which makes it popular between backend services, including some model-serving systems. Browsers can't speak native gRPC directly; they need a gRPC-Web proxy, which supports a narrower set of streaming patterns. For streaming AI answers to a browser, SSE or WebSockets are simpler.

Server-Sent Events vs WebSockets: How to Choose

Ask these questions:

  1. Does the client only need to receive a stream after sending a request? Use SSE. This covers most LLM chat interfaces.
  2. Do both sides need to send messages continuously or interrupt each other? Use WebSockets (or WebRTC for audio and video).
  3. Do you need binary data? WebSockets handle it natively.
  4. Is your infrastructure plain HTTP with proxies you don't control? SSE is less likely to break.
  5. Do you need automatic reconnection and resume? SSE with EventSource gives it to you for free.

For notifications, such as "your report is ready", SSE is usually enough: the server pushes, the browser listens. For chat, SSE works well when each message triggers one streamed answer; WebSockets fit better when many users chat live with each other in the same room. Many AI apps use both: SSE for streaming text answers, and WebSockets only for real-time voice or live collaboration features.

FAQ

What is the difference between server-sent events and WebSockets?

Server-sent events stream data one way, from server to client, over a normal HTTP response, with built-in reconnection. WebSockets open a two-way connection where both sides can send text or binary messages at any time, but you must handle reconnection yourself and your infrastructure must support WebSocket upgrades.

Is SSE better than WebSocket for LLM streaming?

Usually, yes. LLM chat follows a request-then-stream pattern, which SSE handles simply over standard HTTP. That's why major LLM APIs use it. WebSockets are better when the user needs to talk while the model is responding, as in real-time voice assistants.

Does ChatGPT use SSE or WebSockets?

OpenAI's API streams text responses as server-sent events. Real-time voice features need two-way streaming, which is where WebSockets or WebRTC come in. The exact transport used inside a consumer app can change and isn't always documented.

Are server-sent events deprecated?

No. Server-sent events are part of the HTML standard and supported by all major browsers, and major LLM APIs use them for streaming. The confusion comes from the Model Context Protocol, which replaced its older HTTP+SSE transport with Streamable HTTP. Streamable HTTP can still use SSE to stream messages; only the old MCP transport design was retired.

What is the connection limit for SSE?

Over HTTP/1.1, browsers limit open connections per domain, and MDN notes a limit of 6 SSE connections per browser and domain across all tabs. Over HTTP/2, many streams share one connection, so the practical limit is much higher. Serving SSE over HTTP/2 or HTTP/3 avoids the problem.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog