IoT Bricks Blog Try challenge Sign in

From database to screen with Server-Sent Events

The data is in the database. Now someone wants to watch it change on a screen. There are three common ways to do it.

Polling, WebSockets or SSE

Polling: the browser asks "anything new?" every few seconds. It is simple, but most requests return nothing, and the screen is always a little late.

WebSockets: a two-way channel. Powerful, but you must handle the protocol upgrade, framing and your own reconnection logic, and a dashboard rarely needs the browser to talk back.

Server-Sent Events (SSE): one ordinary HTTP response that never ends. The server writes lines as events happen, and the browser reads them. It is one-way, which is exactly what a live view needs.

What SSE looks like

The response has the type text/event-stream, and each event is a few lines ended by a blank line:

id: 1042
event: reading
data: {"device":"greenhouse-3","value":21.4}

In the browser, new EventSource("/stream") is enough. If the connection drops, the browser reconnects by itself and sends the id of the last event it received in a Last-Event-ID header. The server can then replay what was missed, which is why the event identity from the ingestion brick pays off again here.

What the gateway has to get right

Closing the loop

A reading published by a sensor, delivered by the broker, validated by ingestion, stored by the time-series database and pushed by the gateway reaches a screen in a fraction of a second. When one of those steps misbehaves, you will know where to look, because you built each one.