What is Server-Sent Events (SSE) and when is it a good fit?
Topic: microservices, Real-Time Communication. Level: Intermediate.
Answer
SSE is a standard for **server-to-client streaming** over a single long-lived HTTP connection using the `text/event-stream` content type. The server pushes messages as they occur; the browser's `EventSource` auto-reconnects and can resume via `Last-Event-ID`. It's one-directional (server→client only), text-based, and simpler than WebSocket (plain HTTP, works with existing infra). Ideal for feeds, notifications, live scores, or progress updates where the client only receives. For bidirectional/binary needs, use WebSocket.
```js
// Client — built-in reconnection, no library needed
const es = new EventSource('/api/stream')
es.onmessage = e => render(JSON.parse(e.data))
es.addEventListener('price', e => updatePrice(JSON.parse(e.data)))
```
```java
// Server (Spring) — push events over one connection
@GetMapping(value = "/api/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<Price>> stream() {
return prices.map(p -> ServerSentEvent.builder(p).event("price").id(p.id()).build());
}
```