Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 144/ 160
08. Backend

Streaming with SSE

Server-Sent Events for token streams from backend to browser.

IntermediateSSE · Event Stream3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

SSE keeps a web connection open so the server can send little pieces of an answer as soon as they are ready, and if the connection breaks, the browser reconnects and says where it left off.

Think of it like…

A radio broadcast over a single open channel. The station keeps transmitting numbered segments; if your signal drops, your radio tunes back in and tells the station the last segment it heard, and a faint carrier tone (heartbeat) keeps the line from being treated as dead air.

Where you’ve seen it

A chat endpoint streams a 420-token answer at 150 tokens a second, so generation takes 2.8 seconds after a 0.6-second time to first token. Each event looks like id: 17, event: token, data: {"t":"Hello"} plus a blank line, about 26 bytes for a short token, so the whole answer is roughly 420 × 26 ≈ 11 KB. Writing and flushing 150 times a second is wasteful, so the server batches tokens into 50 ms flushes of about 7.5 tokens, 20 flushes a second. The response headers include Cache-Control: no-cache, Connection: keep-alive and X-Accel-Buffering: no so that nginx passes bytes through immediately. Because EventSource only issues GET without custom headers, and the chat needs a POST body and a bearer token, the front end uses fetch with a streaming body reader and an SSE parser instead, adding its own reconnect logic. A proxy closes connections idle for 60 seconds, so the server sends a comment line : keep-alive every 15 seconds, four heartbeats per timeout window, which matters when the model is thinking or a tool call is slow. Events have types (token, tool_call, usage, error, done); if the provider fails after the first event, the server emits event: error with a request_id and closes, since the HTTP status 200 was already sent. To resume after a drop, the server stores the partial output per request id in Redis for five minutes: a client reconnecting with Last-Event-ID: 210 receives events 211 onwards from the buffer, or a clean restart event if the buffer expired. Capacity follows Little's law: 100 new streams per second × 3.4 seconds is about 340 open connections, a few tens of KB each on an async server.

Words you’ll hear

text/event-stream
The media type that tells the client to treat the body as an SSE stream.
Last-Event-ID
A request header the browser sends on reconnect naming the last event it received.
Heartbeat
A periodic comment or ping that keeps proxies from closing an idle connection.
Proxy buffering
Intermediaries holding bytes back, which breaks streaming unless disabled.

Visual diagram

Loading interactive diagram

Theory & deep dive

The wire format and client behaviour

An SSE response is UTF-8 text. Each event is a block of field: value lines ended by a blank line: id: sets the last-event ID, event: names the event type (default message), data: carries the payload (multiple data: lines are joined by newlines) and retry: suggests a reconnect delay in milliseconds. Lines beginning with : are comments, ideal for heartbeats such as : keep-alive. A typical token event is id: 17, event: token, data: {"t":"Hello"} and a blank line, about 26 bytes, so 420 tokens cost roughly 11 KB. Use JSON payloads so you can add fields later.

EventSource handles parsing and automatic reconnects, sending Last-Event-ID on retry, but it only supports GET, no custom headers and a fixed credential model (cookies). Chat products usually need a POST with a JSON body and a bearer token, so they use fetch and read response.body as a stream with a small SSE parser (or a library), implementing their own reconnect with backoff. Browsers also limit HTTP/1.1 to six connections per origin, so multiple open tabs can starve one another; HTTP/2 multiplexes many streams over one connection and removes that limit.

Event framing

id: 17 / event: token / data: {"t":"Hello"} / blank line. Heartbeat: : keep-alive / blank line. Final event: event: done with data: {"usage":{"in":3100,"out":420}}. About 26 bytes per short token, so 420 tokens ≈ 11 KB.

Key takeaway: SSE is plain-text framing over HTTP; use fetch-based clients when you need POST and headers, and HTTP/2 to avoid connection limits.

Production concerns: buffering, heartbeats, errors and resume

Buffering: set Cache-Control: no-cache, disable compression for the stream (or flush correctly), add X-Accel-Buffering: no for nginx and check CDNs and API gateways; if tokens arrive in one lump at the end, something is buffering. Flush cadence: batching 50 ms of output (about 7.5 tokens at 150 tokens a second) gives 20 writes a second instead of 150 with no visible change. Heartbeats: intermediaries often close idle connections after 60 seconds, so send a comment every 15 seconds, four per timeout window, especially while a model reasons or a tool runs. Errors: the HTTP status is committed when the headers are sent, so report later failures with event: error (including a request_id and whether retrying is safe) and then close; log them as failed requests.

Resuming: give every event an id, buffer the partial output per request in Redis with a short TTL (5 minutes) and, when a client reconnects with Last-Event-ID: 210, replay events 211 onwards. If the buffer has expired or the generation was cancelled, send a restart event so the client can offer a retry rather than splice mismatched text. Stop generation when the client disconnects to avoid paying for unused tokens, unless you are buffering for resume. Capacity: open streams equal arrival rate × duration (100 per second × 3.4 seconds ≈ 340) and each consumes a connection and a small buffer; set per-user stream limits, idle and total duration caps and monitor open connections, time to first byte and stream error rates.

Resume after a drop

Client has events up to id 210 when the network drops. It reconnects with Last-Event-ID: 210. The server reads the Redis list for the request, replays ids 211–420 immediately, then continues live if generation is still running. After 5 minutes the buffer is gone and the server answers with event: restart.

Key takeaway: Disable buffering, heartbeat below the idle timeout, report failures in-band and keep a short replay buffer for resume.

How it works, step by step

Step 1 of 4
Backend engineer

1. Define events and headers

Choose event types and a JSON payload shape, and set the streaming headers including buffering off.

token · tool_call · usage · error · done
Key numbers at this step
Header
text/event-stream

When to use it & trade-offs

What it is

Server-Sent Events (SSE) is a simple protocol for pushing a one-way stream of messages from server to browser over a normal HTTP response. The server replies with Content-Type: text/event-stream and keeps the connection open, writing events in a plain-text format: optional event: and id: lines, one or more data: lines and a blank line to end the event. Browsers expose it through EventSource, which reconnects automatically and sends the last seen id in a Last-Event-ID header. For LLM products SSE carries token deltas, tool-call notices, usage totals, errors and a final done event, and it works through ordinary proxies as long as buffering is disabled and idle connections are kept alive with heartbeats.

Why it matters: The protocol details decide whether streaming works in production. Proxies that buffer responses hide tokens until the end, idle timeouts of 60 seconds silently drop quiet streams, EventSource cannot send an Authorization header or a POST body, browsers limit HTTP/1.1 connections per origin to six and a dropped connection mid-answer wastes a paid generation unless the client can resume. Getting these right turns a demo into a dependable feature.

When to reach for it

  • Chat token streaming to web clients
  • Progress and status events for agent runs
  • Live logs and long-running job updates

When to avoid or be careful

  • Streaming through proxies with response buffering enabled
  • EventSource when you need POST bodies or custom headers
  • Silent streams with no heartbeat

Streaming transports

SSE
Best for: One-way token streams to browsers

Strengths: Simple; works over HTTP; built-in reconnect.

Watch out: Server-to-client only; text format.

WebSockets
Best for: Two-way, low-latency interaction

Strengths: Full duplex; binary frames.

Watch out: More infrastructure; custom reconnect.

Long polling
Best for: Environments that block streaming

Strengths: Works almost everywhere.

Watch out: Chunky updates; higher overhead.

Interview signals & numbers to know

When this topic comes up

  • “Why do tokens arrive all at once in production?”
  • SSE versus WebSockets
  • How a client resumes a dropped stream
  • Heartbeats and idle timeouts
  • Error handling after a 200

Benchmarks & rules of thumb

≈ 26 bytes / 11 KB -
one short token event, and a 420-token answer
15 s vs 60 s -
heartbeat interval against a typical idle timeout
6 -
HTTP/1.1 connections per origin in browsers

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting X-Accel-Buffering and compression flush settings.
  • Using GET-only EventSource for an authenticated POST endpoint.
  • Continuing to generate after the user has left.

Likely interviewer follow-ups

  • How would you resume a stream that dropped halfway?
  • How do you report an error after streaming started?
  • What limits the number of simultaneous streams?
Interview tip: Mention Last-Event-ID and the replay buffer; resumable streams are what separates a demo from a service.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Streaming with SSE with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Async and Await
Next topic
WebSockets