Skip to content

    Frontend System Design

    Server-Sent Events in Depth

    How Server-Sent Events work on the client: the stream format, parsing rules, EventSource reconnection with Last-Event-ID, its limits, and a lab model.

    By Published 12 min read

    • frontend-system-design
    • real-time
    • server-sent-events
    • eventsource
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Polling, Server-Sent Events and WebSockets

    What you'll learn: By the end of this lesson you will be able to read a text/event-stream response line by line, explain which rule turns lines into events, say what an EventSource does when the connection breaks and which answers make it stop for good, use id and Last-Event-ID to resume without losing events, and name the limits (one direction, GET only, connection counts) that make you reach for something else.

    Think of a numbered newsletter that arrives by one long delivery that never quite finishes. Each issue is a few lines, ended by a blank line, and has a number on top. If the delivery is interrupted, you phone and say "the last one I have is number 41". The publisher can answer only if it kept the recent issues. That is the whole mechanism: a response that does not end, a text format with a blank line between events, and a number you hand back to resume.

    The running example is a merchant dashboard that shows live order counts for a shop. The numbers, timings and names in it are made up for the lesson. The server is only a model here; for the server side see WebSockets, SSE and Long Polling.

    The core idea

    1. SSE is an ordinary HTTP response that stays open. The server answers 200 with the media type text/event-stream and keeps writing. The browser reads the body as it arrives.
    2. The parsing rules, not the server, decide what an event is. Lines are fields, a blank line dispatches, and where the network cut the text does not matter.
    3. Recovery is a pair: id out, Last-Event-ID back. It resumes exactly as far as the server kept events, no further.

    Three illustrations run through the lesson: a minimal example (a three-event stream), a realistic example (the dashboard reconnecting after a drop) and a failure example (a client that was away longer than the server's replay window).

    The wire format

    The format is UTF-8 text in lines. A line ends with CRLF, LF or a lone CR. A line starting with a colon is a comment. Otherwise a line is field: value, where exactly one space after the colon is dropped.

    Field What it does
    data Appends the value and a newline to the data buffer. Several data lines make a multi-line payload.
    event Sets the event type for the next event. Without it the type is message.
    id Sets the last event ID buffer. Ignored if the value contains a NUL character.
    retry Sets the reconnection time in milliseconds, but only if the value is digits only.
    anything else Ignored. Names are compared literally, so DATA is not data.

    A line with no colon is treated as a field name with an empty value. A blank line ends the event and dispatches it.

    A minimal stream (illustrative):

    retry: 2000
    
    id: 41
    event: price
    data: 19.99
    
    id: 42
    data: first line
    data: second line

    The first block only sets the reconnection time. The second dispatches a price event with data 19.99. The third dispatches a message event with the two lines joined by a newline.

    Figure 1. From server writes to page code

    Event stream path: the server writes text, the browser's parser turns it into events, page code handles themOrder events to Event endpoint (publish); Event endpoint to EventSource (text/event-stream); EventSource to Dashboard (message events)Order events: numbered 1, 2, 3Order eventsnumbered 1, 2, 3Event endpoint: keeps a replay windowEvent endpointkeeps a replaywindowEventSource: parser, last event IDEventSourceparser, lastevent IDDashboard: event handlersDashboardevent handlerspublishtext/event-streammessage events

    How to read this: the flow is one way, left to right. The only thing the client sends is the request that opens the stream, and a later one that reopens it.

    How the parser decides

    Figure 2. What happens to each line

    flowchart TD accTitle: How one line of an event stream is handled accDescr: An empty line dispatches the event if the data buffer is not empty. A line starting with a colon is ignored. Any other line is split at the first colon into a field and a value. The fields event, data, id and retry update their buffers or the reconnection time, and any other field is ignored. L["A line ends"] --> E{"Empty?"} E -->|"yes"| D["Dispatch: type, data, last event ID"] E -->|"no"| C{"Starts with a colon?"} C -->|"yes"| I["Ignore (comment)"] C -->|"no"| S["Split at the first colon:
    field and value"] S --> F{"Field"} F -->|"data"| A["Append value and newline"] F -->|"event"| T["Set event type"] F -->|"id"| N["Set last event ID buffer"] F -->|"retry"| R["Set reconnection time if digits"] F -->|"other"| X["Ignore"]

    How to read this: a line never does two things. State lives in a few buffers, and only the blank line turns the buffers into an event.

    Three details trip up hand-written parsers, and the lab's tests pin each one:

    • An empty data buffer does not dispatch. A block with only event: ping or only id: 5 produces no event. The standard still sets the last event ID string at that point, so an id-only block moves the resume point without waking any handler.
    • The id persists. An event with no id field still reports the previous last event ID. An id field with no value resets it to the empty string.
    • An unfinished event is lost. When the stream ends, anything not closed by a blank line is discarded. A server that dies mid-event costs the client that event, not a corrupt half.

    Chunks do not matter. Network reads can end anywhere: inside a word, between the CR and the LF of a CRLF, after data:. The parser keeps its buffers between reads, and the lab's test cuts a stream at every position, and one character at a time, and gets identical events each time. If you decode bytes yourself, TextDecoder.decode takes a stream option, a flag saying "additional data will follow in subsequent calls", for processing data in chunks. A decoder that is not told this treats each chunk as complete.

    EventSource: what the browser adds

    new EventSource(url) opens the connection and runs the parser for you.

    • readyState is CONNECTING (0), OPEN (1) or CLOSED (2).
    • Events without an event field arrive as message events. With one, you listen for that name with addEventListener.
    • open fires when the connection opens, error when a connection failed to open or is lost.
    • close() stops it. After that the object does nothing, and events still in flight are dropped.
    • The options in the sources read for this lesson hold one entry, withCredentials, which controls whether cross-origin requests carry credentials. The request is a plain GET and the page cannot send data back on it. MDN says plainly: "This is a one-way connection, so you can't send events from a client to a server." A message from the page goes in a separate request.

    Reconnection and Last-Event-ID

    When an open stream ends, or a connection attempt fails, the browser goes back to CONNECTING, fires error, waits the reconnection time, and tries again. The standard calls the default "implementation-defined", probably a few seconds, and lets the client wait longer. A retry field from the server replaces it. If the last event ID string is not empty, the new request carries Last-Event-ID with that value.

    Figure 3. The dashboard loses its connection and resumes

    sequenceDiagram accTitle: Reconnecting with Last-Event-ID accDescr: The dashboard opens an event stream and receives events 1 and 2. The connection drops. Event 3 is published while the client is away. After the reconnection time the client sends a new request with Last-Event-ID 2. The server replays event 3 and then continues with live events. participant D as Dashboard participant S as Event endpoint D->>S: GET /events S-->>D: retry 2000, id 1, id 2 Note over D,S: the connection drops S->>S: event 3 happens, kept in the log D->>D: wait the reconnection time D->>S: GET /events, Last-Event-ID 2 S-->>D: replay id 3, then live events

    How to read this: the client never asks for "event 3". It says what it has, and the server decides what follows. That is why the server must number events and keep a window of them.

    Failing for good. A reconnect is not unconditional. In the standard's processing model a status other than 200, or a media type other than text/event-stream, fails the connection, and a failed EventSource does not try again. The standard's introduction says a server can tell the client to stop with a 204 No Content. A network error, by contrast, triggers a reconnect. A server that wants clients to stop retrying (the endpoint is retired, the user's session ended) must answer one of those; an error that you want retried must be a dropped connection, not a 500. See HTTP Semantics for the Front End for what the statuses mean.

    Figure 4. The states of an EventSource

    stateDiagram-v2 accTitle: EventSource states accDescr: The object starts in connecting. A 200 response with the event stream media type moves it to open. A stream that ends or a network failure moves it back to connecting and it reconnects after the reconnection time. Another status, a wrong media type, or a call to close moves it to closed, which is final. [*] --> CONNECTING CONNECTING --> OPEN: 200 and text/event-stream OPEN --> CONNECTING: stream ends, error fires CONNECTING --> CONNECTING: network failure, wait and retry CONNECTING --> CLOSED: other status or wrong type OPEN --> CLOSED: close() CONNECTING --> CLOSED: close() CLOSED --> [*]

    How to read this: CLOSED has no way out. If the page wants a live feed again after a failure, it must create a new EventSource.

    The limits

    • One direction, GET only. Sending from the page uses a separate request. If you need a body, a header such as Authorization, or a different method, EventSource does not offer it in the sources read here, so you read the response yourself: fetch gives response.body as a ReadableStream, and read() returns { value, done } chunks. You then own the parser, the decoding and the reconnection, which is what the lab's model shows.
    • Connection counts. MDN warns that without HTTP/2, SSE is limited by the number of open connections, a limit that is per browser and "a very low number (6)", which hurts with many tabs. Over HTTP/2 the number of simultaneous streams is negotiated and defaults to 100. The standard suggests a shared worker for pages that open many connections. See HTTP Protocols.
    • Idle connections. Proxies may drop a silent connection. The standard suggests a comment line "every 15 seconds or so".
    • Text only. The standard requires UTF-8, so binary data needs an encoding such as Base64, which costs size (a design consequence, not a rule of the standard).

    Choosing

    Figure 5. When SSE is the right transport

    flowchart TD accTitle: Choosing a transport for server pushes accDescr: If the page only receives updates and plain GET is enough, use EventSource. If it needs headers or a body but still only receives, read a fetch stream and own the parser. If it must also send low-latency messages, use a WebSocket. If updates are rare, polling is enough. Q{"Does the server push often?"} -->|"no"| P["Polling is enough"] Q -->|"yes"| W{"Does the page also send
    frequent messages?"} W -->|"yes"| WS["WebSocket"] W -->|"no"| H{"Need headers, a body
    or a method other than GET?"} H -->|"no"| ES["EventSource"] H -->|"yes"| FS["fetch stream + your own parser"]

    How to read this: SSE fits "server talks, page listens". The moment the page must talk a lot, or customise the request, pick another branch.

    Choice Gain Cost
    EventSource Parser, reconnect and resume built in GET only, no custom headers, one direction
    Fetch stream plus own parser Any method, headers and body You write parsing, decoding, reconnect and backoff
    Short window plus a resync signal Little server memory The client must reload its state when told

    Build it: parse, reconnect, resume, and fall behind

    Goal. Run a model of the event-stream parser, an EventSource, and a server with a bounded replay window through five situations.

    Setup. The lab sse-event-stream is in the course's example workspace (Node 26.13.1). It is pure logic: no browser and no network, and a virtual clock replaces time.

    cd examples/frontend
    pnpm install
    cd labs/sse-event-stream
    pnpm test           # 30 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In section 1, find the block colour: blue followed by a line data. The unknown field is ignored, and the bare data line makes an event with empty data. The id: 42 block produces no event but moves the last event ID.
    3. In section 3, check the timing: no request at 1999 ms after the drop, one at 2000 ms, carrying Last-Event-ID: 2.
    4. In section 4, the server keeps only ids 6 to 8, so the client with last ID 4 gets a resync event instead of a replay.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    === 1. Parsing: what the standard's rules make of a few lines
    the last block, data: never finished, is cut off before its blank line
      event: price "19.99" lastEventId="41"
      event: message "line one\nline two" lastEventId="41"
      event: message "" lastEventId="41"
      retry values accepted: [1500]
      last event ID string at the end: "42" (set by an id-only block, no event for it)
    
    === 2. The same stream cut into chunks everywhere
    CRLF version, 159 two-chunk splits: 159 give identical events
    one character per chunk gives identical events: true
    events found: 3

    Expected output, captured from a real run (the rest of section 3 and all of section 4 of the same demo):

    t=    0  request 1: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache"}
    t=    0  open
    t=    0  reconnection time learned from the retry field: 2000 ms
    t=    0  event message "packed" (last event ID 1)
    t=    0  event message "out for delivery" (last event ID 2)
    t=  500  the connection drops
    t=  500  error: stream ended; will reconnect: true
    t= 2499  1999 ms after the drop: 1 request so far
    t= 2500  request 2: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache","Last-Event-ID":"2"}
    t= 2500  open
    t= 2500  event message "arriving soon" (last event ID 3)
    t= 2500  event message "delivered" (last event ID 4)
    received in order, once each: ["packed","out for delivery","arriving soon","delivered"]
    
    === 4. Away too long: the replay window has moved on
    t= 2500  the connection drops
    t= 2500  error: stream ended; will reconnect: true
    t= 2500  server keeps only ids 6, 7, 8; the client's last ID is "4"
    t= 4500  request 3: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache","Last-Event-ID":"4"}
    t= 4500  open
    t= 4500  event resync "replay window starts at 6" (last event ID 8)
    t= 4500  closed: readyState 2

    What the lab does not show. No real HTTP, proxies or buffering, and no byte decoding: the parser takes text. The 3000 ms default wait, the numbering from 1 and the resync event are this lab's design, not the standard's. The standard's processing model is followed in the order the lab implements it, but the lab was not compared with any browser.

    Break it. In src/client.ts, change the condition before headers["Last-Event-ID"] so the header is never sent. Five client tests fail. Revert it.

    In practice: a merchant dashboard that quietly fell behind

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A merchant dashboard shows today's order count and the newest five orders. A product manager wants it live. Updates are small, arrive a few times a minute, and only go from server to page. Merchants keep the dashboard open on an office screen for days, and laptops sleep overnight.

    Starting architecture

    Figure 6. Starting point: polling every 30 seconds

    Starting architecture: the dashboard polls an orders endpoint on a timerDashboard to Orders API (GET on a timer); Orders API to Order store (read)Dashboard: timer, 30 s (illustrative)Dashboardtimer, 30 s(illustrative)Orders API: returns the latest stateOrders APIreturns thelatest stateOrder storeOrder storeGET on a timerread

    How to read this: every poll repeats the whole read. Updates reach the page up to one interval late.

    Options considered

    Option What it fixes What it costs Risk
    Poll every few seconds Nothing to build Load grows with open dashboards Still not live
    WebSocket Two-way, low latency Own protocol for order, acks, reconnect More than a one-way feed needs
    SSE with EventSource One-way push, built-in reconnect GET only, replay window to run Silent gaps after a long absence

    The decision

    Field Decision record
    Context One-way updates a few times a minute to dashboards that stay open for days.
    Decision Use EventSource on one endpoint. Number every event, send id, keep the last N events, and send a named resync event when a client's last ID is older than the window. On resync, the dashboard reloads its state with one normal request.
    Consequences, good Live updates, no custom client protocol, resume after short drops.
    Consequences, bad The server keeps a replay log, and the client has two paths: apply events and reload state.
    Revisit when The page must send frequent messages (consider a WebSocket) or the stream needs custom headers (read a fetch stream).

    Rollout and verification

    1. Start with tests for chunk splits, id persistence, 204 and 500.
    2. Ship behind a flag and compare the live count with the polled count for a week.
    3. Test the long absence on purpose: pause the dashboard longer than the replay window and confirm it reloads.

    The 2 a.m. failure

    Monday morning a merchant reports the dashboard shows Friday's order count. The laptop slept all weekend. On wake the browser reconnected with Last-Event-ID set to a Friday id that was long gone from the server's window. The server, written for the happy path, replayed nothing and sent only new events, so the page showed new orders added to an old total (illustrative).

    First three checks: (1) compare the Last-Event-ID in the request with the oldest id the server holds; (2) check whether the server tells a client that its id is too old; (3) check whether the client has a code path for "reload everything". Mitigation: send a resync event when the id is older than the window, and have the page reload state on it. Follow-up: reload on visibilitychange after a long hidden period, count resync events in monitoring, and test the long absence in CI.

    Architect's notes

    • Number every event from the start. Without ids there is nothing to resume from.
    • Decide the window and say it out loud. "Resume works for N events" is a product statement.
    • Always give the client a way to start over. A signal plus a reload path beats silent drift.
    • Pick the failure status on purpose. A 204 or an error status stops the client; a dropped connection makes it retry.

    Common mistakes

    • Writing a parser that splits on \n\n. It breaks on CRLF and lone CR, and on a chunk that ends mid-line.
    • Treating id as optional. The reconnect then replays nothing.
    • Returning 500 to make clients back off. A failed EventSource never retries.
    • Putting long-lived secrets in the query string to work around the missing headers. URLs are often logged.

    Key takeaways

    • SSE is an open HTTP response in text/event-stream, UTF-8, read line by line.
    • A blank line dispatches; empty data does not; id persists; unfinished events are discarded.
    • Where the network splits the text must never change the events.
    • EventSource reconnects after the reconnection time, sends Last-Event-ID when it has one, and stops for good on a non-200 answer, a wrong media type or close().
    • It is one-way and GET only; for headers or a body, read a fetch stream and write your own parser.
    • Resume is only as good as the server's replay window; design the "too old" answer.

    Practice exercises

    Exercise 1, Starter (45 min): Write five streams by hand (CRLF line ends, a comment, a two-line data, a bad retry, an id with no data) and predict the events.

    Exercise 2, Intermediate (2 hours): Add backoff to the lab's client: double the wait after each failed attempt up to a cap, and reset it after a stream delivers an event. Write tests with the virtual clock.

    Exercise 3, Advanced (half day): Write a fetch-based reader that feeds a TextDecoder (with stream: true) into the parser, and make it send a custom header. List what you now own that EventSource owned before.

    In this course:

    Planned lessons in this module, named here as plain text: Polling, SSE and WebSockets compares the transports; Reconnection and Message Ordering goes further on resuming and ordering.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments