SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Long Polling
  • Server-Sent Events (SSE)
  • WebSockets
  • Webhooks
  • WebRTC
  • Short Polling
  • Push Notifications
  • MQTT
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Real-Time Communication

Server-Sent Events (SSE)

The server keeps one door open and pushes updates to you.

⏱ 11 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Server-Sent Events (SSE) let a server push updates to a browser over one long-lived HTTP connection. The browser opens the door once. The server keeps sending news through it.

  • One direction only: server to client.
  • Plain HTTP with the content type text/event-stream.
  • The browser reconnects by itself, and can ask to resume from the last event id.
  • Great for live feeds, scores, notifications and progress bars.

02Concept: What is it?

Normally, an HTTP response ends. With SSE, the server never finishes the response. It keeps writing small pieces of text. The browser reads each piece as an event, as soon as it arrives.

SSE in one picture
πŸ“±Browsernew EventSource('/events')
→↓GET /events
πŸ–₯️Serverkeeps the response open
→↓event, event, event...
πŸ“±Browseronmessage fires each time
Client Server Pushed events
The browser makes one request. The server answers with an endless stream.

What a message looks like

text/event-stream: plain text, one blank line ends each event
id: 42
event: score
data: SIX! India 187/4

id: 43
event: score
data: Single. India 188/4

: this is a comment, often used as a heartbeat
  • data: is the message. It can span several lines.
  • id: lets the browser remember where it stopped.
  • event: is an optional name, so different events can have different handlers.
  • retry: tells the browser how many milliseconds to wait before reconnecting.

03Real-Life Example

🍡The radio
A radio station broadcasts. You tune in once and the news keeps coming. You cannot talk back to the station through the radio. If the signal drops, you re-tune and you may say β€œI last heard the 9 o'clock news” so they continue from there.
Radio
SSE
Tuning in
Browser opens the connection (EventSource)
Radio station
Server
Programmes broadcast to you
Events pushed to the browser
You cannot talk back
One direction only
Signal drops, you tune in again
Automatic reconnect
'I last heard the 9 o'clock news'
Last-Event-ID header
Live cricket score
🏏Score feed
→↓
πŸ–₯️SSE server
→↓push to everyone
πŸ“±Fan 1
πŸ’»Fan 2
πŸ“±Fan 3
Thousands of fans keep one connection each. The server pushes each ball.

04Why Do We Need It?

Many features only need the server to talk: a live score, a stock price, a progress bar, a new notification. For these:

⚑Fast updates
News arrives the moment it exists. No polling delay.
πŸͺΆLight
One connection and small text messages. No repeated headers.
πŸ› οΈSimple
Browsers have EventSource built in. Reconnect is automatic.
🌐Plain HTTP
Works with normal auth, cookies, logging, and most proxies.
πŸ”Resume
Last-Event-ID lets the stream continue without gaps.
πŸ’ΈCheaper than WebSockets
If you do not need two-way talk, why build more?
If only the server needs to talk, SSE is often the simplest good answer.

05Where Do We Use It?

🏏Live scores
Sports, election results, auctions.
πŸ“ˆDashboards
Monitoring graphs and stock prices.
πŸ””Notifications
A new comment, a new order, a friend request.
πŸ“ŠProgress
Upload, build and report progress bars.
πŸ“°News feeds
Live blogs and timelines.
πŸ€–Streaming AI text
Many AI chat tools stream the reply word by word over a stream like this (general idea).

06Types / Parts / How It Works

How it works step by step

  1. 1
    Browser opens EventSource
    It sends GET /events with the header Accept: text/event-stream.
  2. 2
    Server replies and keeps the connection open
    Headers: Content-Type: text/event-stream, Cache-Control: no-cache. The body never ends.
  3. 3
    Server writes events as they happen
    Each event is a few lines of text followed by a blank line.
  4. 4
    Browser fires a handler for each event
    onmessage, or addEventListener('score', ...) for named events.
  5. 5
    If the connection drops
    The browser waits (retry:) and reconnects. It sends Last-Event-ID so the server can resume.
Reconnect with Last-Event-ID
  1. 1
    Browser has seen id 42
  2. 2
    Connection drops
    Wi-Fi blip, server restart or proxy timeout.
  3. 3
    Server creates events 43 and 44
    Nobody is listening.
  4. 4
    Browser reconnects with Last-Event-ID: 42
  5. 5
    Server replays 43 and 44, then continues live
Events 43 and 44 happened while offline. The server replays them.

Browser code

JavaScript
const es = new EventSource("/events");

es.onmessage = (e) => console.log("update:", e.data);
es.addEventListener("score", (e) => showScore(JSON.parse(e.data)));
es.onerror = () => console.log("lost it, browser will retry");
πŸ“Limits to know

SSE carries text only (send JSON as text). Over HTTP/1.1, browsers allow only about 6 connections per site, so many tabs can use them up. HTTP/2 shares many streams on one connection and removes this problem.

The plain EventSource cannot set custom headers, such as an Authorization header. People use cookies, or a fetch-based stream library.

VisualizerPush, drop, reconnect, resumeWatch events arrive, then drop the connection. Try with and without Last-Event-ID.
When the browser reconnects
πŸ“±BrowserEventSource Β· last id 0
←one open HTTP connection, server β†’ browser
πŸ–₯️Servernewest event id 0
What travels down the wire (text/event-stream)
: waiting for the first event
Last reconnect request
(none yet: drop the connection to see one)
Server events
0
Browser received
0
Lost
0
Status
Open
Connected. The server pushes one event every second, all on one open connection.

07How to Use It / Steps / Implementation

Build a good SSE endpoint

  1. Set the headers: Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive on HTTP/1.1.
  2. Give every event an id that grows with time. Keep a short history to replay.
  3. Send a heartbeat comment line (: ping) every 15 to 30 seconds. It stops proxies from closing an idle connection.
  4. Read Last-Event-ID on connect. Replay what the client missed, then switch to live events.
  5. Turn off buffering in proxies (for example NGINX proxy_buffering off), or events will arrive in clumps.
  6. Plan for scale. Each client is one open connection. Use async servers, and a pub/sub bus (such as Redis) so any server can feed its own clients.
  7. Authenticate with cookies or short-lived tokens in the URL, and check permissions on every connect.
  8. Close cleanly on deploys, and add jitter so clients do not all reconnect at once.
Scaling SSE to many users
πŸ“±
πŸ’»
πŸ“±
→↓open streams
βš–οΈLoad balancerno buffering, long timeout
→↓
SSE servers
πŸ–₯️
πŸ–₯️
↔fan-out
πŸ“£Pub/sub

08Key Terms to Know

TermMeaning in easy words
EventSourceThe browser object that opens an SSE connection and handles reconnects
text/event-streamThe content type that tells the browser this is an SSE stream
EventOne message: lines like id, event, data, ended by a blank line
Last-Event-IDA request header the browser sends on reconnect, to resume after the last id it saw
retryA field that sets how many milliseconds the browser waits before reconnecting
HeartbeatA tiny comment line sent often so the connection does not look idle
PushThe server sends data without being asked each time
Fan-outSending one event to many connected clients
Proxy bufferingA proxy holding data until it has a full chunk. It breaks live streams

09Pros, Cons and Trade-offs

βœ… Pros
  • Very simple on the browser: EventSource does the work
  • Automatic reconnect and resume with ids
  • Plain HTTP: works with normal logging, auth, and HTTP/2
  • Low overhead after connecting
  • Great for one-way live data
⚠️ Cons
  • One direction only (client must use normal requests to send)
  • Text only. No binary data
  • Plain EventSource cannot send custom headers
  • HTTP/1.1 limits about 6 connections per site
  • Every user holds an open connection, so servers need to be built for it

SSE vs WebSockets vs long polling

Long pollingSSEWebSockets
DirectionServer to clientServer to clientBoth ways
Data typeAnything over HTTPTextText and binary
ReconnectYou build itBuilt inYou build it
Resume after dropYou build itBuilt in (Last-Event-ID)You build it
Overhead per messageHighLowLowest
Works through proxiesBestGood (turn off buffering)Sometimes blocked
Choose it forFallbackFeeds, alerts, progressChat, games, editors

10Common Problems and Mistakes

Common mistakes

  1. Proxy buffering. Events arrive late in big batches. Turn buffering off.
  2. No heartbeat. An idle connection is closed by a proxy after 60 seconds or so.
  3. No event ids. After a reconnect, events are lost.
  4. Using SSE for chat that needs fast two-way talk. You will end up with a second channel for sending.
  5. Forgetting the 6-connection limit on HTTP/1.1 when users open many tabs.
  6. Reconnect storm. After a deploy, all clients reconnect together. Use retry values with jitter.
  7. Memory per connection ignored. A million open streams need a plan: async I/O, many servers, and limits.
⚠️Security
Do not put long-lived secrets in the URL (they appear in logs). Use cookies, or short-lived tokens, and check permissions again on every reconnect.

11Real-World Examples

πŸ€–AI chat streaming
Many AI APIs and chat tools send the answer in small chunks over an SSE-style stream (general idea).
πŸ“ˆLive dashboards
Monitoring and trading pages that update every second.
πŸ””Notification feeds
Browser pages that show new alerts without refresh.
πŸ§ͺBuild and deploy logs
Streaming logs line by line while a job runs.
Pick SSE when...
  • Only the server needs to talk
  • You want simple code and auto-reconnect
  • Messages are text or JSON
  • You are happy with plain HTTP
Pick WebSockets when...
  • Both sides send often
  • You need binary data or very low delay
  • Games, chat, shared editing
  • You can manage the extra complexity

12Related Topics to Read Next

Long Polling→

The simpler cousin: repeated held requests.

WebSockets→

Two-way messages when SSE is not enough.

Webhooks→

Server-to-server push, instead of server-to-browser.

HTTP / HTTPS→

SSE is an HTTP response that never ends.

Pub/Sub→

How many servers fan out one event to many connections.

What are Load Balancers?β†’

They must allow long, unbuffered connections.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: one long-lived HTTP response that keeps pushing events to the browser.
  • βœ”Format: text/event-stream with id, event and data lines, and a blank line between events.
  • βœ”Direction: server to client only.
  • βœ”Built in: EventSource, auto-reconnect, Last-Event-ID resume.
  • βœ”Always: add ids, send heartbeats, turn off proxy buffering, plan for many open connections.
  • βœ”Use for: feeds, alerts, dashboards, progress, AI text streams.
  • βœ”One line: β€œSSE is a radio broadcast from the server to the browser.”
← Previous
Long Polling
Next β†’
WebSockets