Skip to main content

How to Push Live Updates to the Browser

In this guide, we build a small live poll, "tabs or spaces?", where every open browser sees the vote totals change the moment anyone votes, without reloading the page. We build it twice: once with server-sent events, where the server streams the totals and the browser votes with ordinary HTTP requests, and once with a WebSocket, where votes and totals travel over one connection. By the end, you will know which of the two fits your page and have a working server for each.

We start with the choice itself, then share the poll state between connections with a SubscriptionRef, and finally write the two servers on top of that shared state.

The Problem​

A browser only learns about new data when it asks for it. A page that shows changing data, such as vote totals, a build status or a price, therefore often polls: a timer sends a request every second and redraws the page with the answer:

setInterval(async () => {
const response = await fetch('/tally');
const tally = await response.json();
document.getElementById('tabs').textContent = tally.tabs;
document.getElementById('spaces').textContent = tally.spaces;
}, 1000);

Polling is simple, but it trades freshness for load. With a one-second timer, every open page sends 3,600 requests an hour, almost all of them answered with "nothing changed", and a change still takes up to a second to appear. A shorter timer makes updates faster and the load worse; a longer one does the opposite. With many open pages, most of the server's work goes into answering questions whose answer has not changed.

The fix is to turn the direction around: the browser opens one long-lived connection, and the server pushes data down it only when something changes. Browsers have two standard ways to do this, server-sent events and WebSockets, and zio-http supports both.

Choose Between Server-Sent Events and WebSockets​

Both keep a connection open and let the server send data whenever it wants. They differ in what the browser can send back and in how much the browser does for you:

ConcernServer-sent eventsWebSockets
DirectionServer to browser only; the browser sends data with normal requestsBoth directions over the same connection
On the wireA normal HTTP response with type text/event-stream that stays openAn HTTP request upgraded to the WebSocket protocol
Browser APIEventSourceWebSocket
DataText events; zio-http encodes each event's data with its SchemaText or binary frames, encoded by your code
Dropped connectionsEventSource reconnects by itselfThe page has to open a new socket itself
zio-http APIServerSentEvent, Response.fromServerSentEventsHandler.webSocket, WebSocketChannel, WebSocketFrame

The rule of thumb follows from the first row. If the browser mostly listens, as with dashboards, notifications, progress bars and feeds, use server-sent events: the server side is one streaming response, and the browser reconnects for free. If the browser also talks a lot, as with chat, multiplayer games and collaborative editing, or if you need binary data, use a WebSocket.

Our poll sits in between: the browser mostly listens, and it sends a vote now and then. That makes it a good example for both, so we build both and you can compare the code.

Prerequisites​

Both servers need only zio-http. The poll's model also derives a Schema, which needs zio-schema's derivation module:

libraryDependencies ++= Seq(
"dev.zio" %% "zio-http" % "3.12.0",
"dev.zio" %% "zio-schema-derivation" % "1.9.2",
)

This guide assumes you can define routes and handlers. If not, start with Routes and Handler.

Share the Poll State with SubscriptionRef​

The poll is a pair of counters. Tally#vote adds one vote for a choice and ignores any other text, so a stray request cannot break the totals. The derived Schema lets zio-http and zio-schema encode a Tally as JSON, which the page reads:

import zio.schema.{DeriveSchema, Schema}

case class Tally(tabs: Int, spaces: Int) {
def vote(choice: String): Tally = choice match {
case "tabs" => copy(tabs = tabs + 1)
case "spaces" => copy(spaces = spaces + 1)
case _ => this
}
}

object Tally {
val empty: Tally = Tally(0, 0)

implicit val schema: Schema[Tally] = DeriveSchema.gen
}

Every open page needs the same totals, and every page needs to hear about every vote. ZIO's SubscriptionRef from zio.stream does both jobs. It is a Ref, so SubscriptionRef#update changes the value safely from any number of requests at once, and its SubscriptionRef#changes stream emits the current value first and then every later value. Each connection runs its own changes stream, so a page that connects late, or reconnects, receives the current totals straight away and then each new vote.

Both servers create one SubscriptionRef[Tally] with SubscriptionRef.make(Tally.empty) when they start, and pass it to every route that reads or changes the totals.

Stream Updates with Server-Sent Events​

A server-sent event stream is an HTTP response that never finishes: the server writes one event at a time, each ending with a blank line, and the browser's EventSource calls a function for each one. In zio-http, an event is a ServerSentEvent[T], and Response.fromServerSentEvents turns a ZStream of events into such a response.

The page is a few elements and a short script. We write it with zio-http's HTML templates; script.inlineJs puts the JavaScript into the page as it is. The script opens an EventSource on /tally, parses the JSON of each event and writes the numbers into the page. The buttons send the votes with fetch:

import zio._
import zio.stream.SubscriptionRef
import zio.http._
import zio.http.template2._

val ssePage: Dom =
html(
head(title("Tabs or spaces?")),
body(
h1("Tabs or spaces?"),
p("Tabs: ", span(id := "tabs", "0"), ", spaces: ", span(id := "spaces", "0")),
button(id := "vote-tabs", "Vote for tabs"),
button(id := "vote-spaces", "Vote for spaces"),
script.inlineJs(
"""
const events = new EventSource('/tally');
events.onmessage = (event) => {
const tally = JSON.parse(event.data);
document.getElementById('tabs').textContent = tally.tabs;
document.getElementById('spaces').textContent = tally.spaces;
};
for (const choice of ['tabs', 'spaces']) {
document.getElementById('vote-' + choice).onclick = () =>
fetch('/vote/' + choice, { method: 'POST' });
}
""",
),
),
)

On the server, the /tally route maps each value of the changes stream to an event. Response.fromServerSentEvents needs a Schema for the data type: a primitive type such as String is written as text, and any other type, such as Tally, as JSON. Votes arrive as plain POST /vote/<choice> requests that update the SubscriptionRef; the stream then carries the new totals to every open page, including the page that voted:

def sseRoutes(poll: SubscriptionRef[Tally]): Routes[Any, Response] =
Routes(
Method.GET / Root -> handler(Response.html(ssePage)),
Method.GET / "tally" -> handler {
Response.fromServerSentEvents(poll.changes.map(tally => ServerSentEvent(tally)))
},
Method.POST / "vote" / string("choice") -> handler { (choice: String, _: Request) =>
poll.update(_.vote(choice)).as(Response.ok)
},
)

We serve the routes with one shared SubscriptionRef:

object ServerSentEventsPoll extends ZIOAppDefault {
def run =
SubscriptionRef
.make(Tally.empty)
.flatMap(poll => Server.serve(sseRoutes(poll)))
.provide(Server.default)
}

Open http://localhost:8080 in two browser windows and vote in one: both update at once. You can also watch the raw stream with curl -N, which prints the response as it arrives, and vote from a second terminal with curl -X POST http://localhost:8080/vote/tabs:

$ curl -i -N http://localhost:8080/tally
HTTP/1.1 200 OK
content-type: text/event-stream
transfer-encoding: chunked

data: {"tabs":0,"spaces":0}

data: {"tabs":1,"spaces":0}

data: {"tabs":1,"spaces":1}

The first event is the current totals, sent as soon as the connection opens; each later event is one vote. The response has no content-length because it has no end: zio-http sends it in chunks, one or more events at a time, for as long as the browser keeps the connection open.

tip

The zio-http server keeps a quiet connection open: its idle timeout is off by default. A proxy or load balancer between the server and the browser may still close a stream that sends nothing for a while. To keep the stream busy, merge in ServerSentEvent.heartbeat, a comment event that EventSource ignores, on a schedule. It is a ServerSentEvent[String], so it merges into a stream of string events; for the poll, encode each Tally to a JSON string first, as the WebSocket server below does:

import zio.stream.ZStream

def withHeartbeat(
events: ZStream[Any, Nothing, ServerSentEvent[String]],
): ZStream[Any, Nothing, ServerSentEvent[String]] =
events.merge(ZStream.tick(15.seconds).as(ServerSentEvent.heartbeat))
Runnable version, with the model from Tally.scala: ServerSentEventsPoll.scala
zio-http-example/src/main/scala/example/liveupdates/Tally.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"

package example.liveupdates

import zio.schema.{DeriveSchema, Schema}

/**
* The vote totals of a "tabs or spaces?" poll, shared by every browser that has
* the page open.
*/
case class Tally(tabs: Int, spaces: Int) {
def vote(choice: String): Tally = choice match {
case "tabs" => copy(tabs = tabs + 1)
case "spaces" => copy(spaces = spaces + 1)
case _ => this
}
}

object Tally {
val empty: Tally = Tally(0, 0)

implicit val schema: Schema[Tally] = DeriveSchema.gen
}
zio-http-example/src/main/scala/example/liveupdates/ServerSentEventsPoll.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"
//> using file Tally.scala
// Run from this folder: scala-cli run ServerSentEventsPoll.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.liveupdates.ServerSentEventsPoll"

package example.liveupdates

import zio._

import zio.stream.SubscriptionRef

import zio.http._
import zio.http.template2._

/**
* Push Live Updates to the Browser — Stream Updates with Server-Sent Events
*
* Every browser that opens http://localhost:8080 subscribes to `/tally`, a
* stream of server-sent events. A vote is an ordinary `POST /vote/<choice>`
* request, and each vote pushes the new totals to every open page.
*/
object ServerSentEventsPoll extends ZIOAppDefault {

val page: Dom =
html(
head(title("Tabs or spaces?")),
body(
h1("Tabs or spaces?"),
p("Tabs: ", span(id := "tabs", "0"), ", spaces: ", span(id := "spaces", "0")),
button(id := "vote-tabs", "Vote for tabs"),
button(id := "vote-spaces", "Vote for spaces"),
script.inlineJs(
"""
const events = new EventSource('/tally');
events.onmessage = (event) => {
const tally = JSON.parse(event.data);
document.getElementById('tabs').textContent = tally.tabs;
document.getElementById('spaces').textContent = tally.spaces;
};
for (const choice of ['tabs', 'spaces']) {
document.getElementById('vote-' + choice).onclick = () =>
fetch('/vote/' + choice, { method: 'POST' });
}
""",
),
),
)

def routes(poll: SubscriptionRef[Tally]): Routes[Any, Response] =
Routes(
Method.GET / Root -> handler(Response.html(page)),
Method.GET / "tally" -> handler {
Response.fromServerSentEvents(poll.changes.map(tally => ServerSentEvent(tally)))
},
Method.POST / "vote" / string("choice") -> handler { (choice: String, _: Request) =>
poll.update(_.vote(choice)).as(Response.ok)
},
)

def run =
SubscriptionRef
.make(Tally.empty)
.flatMap(poll => Server.serve(routes(poll)))
.provide(Server.default)
}

Send and Receive over a WebSocket​

A WebSocket starts as an HTTP request that the server upgrades to a two-way connection. After that, either side can send a message, called a frame, at any time. In zio-http, Handler.webSocket takes a function that receives the connection as a WebSocketChannel and returns a WebSocketApp. WebSocketApp#toResponse turns it into the response that accepts the upgrade, so a WebSocket is served from an ordinary route.

WebSocketChannel#receiveAll handles every event on the connection, one at a time, until the connection closes. Two events matter for the poll:

  • UserEventTriggered(UserEvent.HandshakeComplete) arrives once, when the connection is ready. We then start sending the totals: a fiber runs the changes stream and sends each Tally as a JSON text frame. We start it with fork because it runs for as long as the connection is open, while receiveAll goes on handling events.
  • Read(WebSocketFrame.Text(choice)) is a text frame from the browser, which is a vote. We update the SubscriptionRef, and every connection's fiber sends the new totals to its page.

Unlike Response.fromServerSentEvents, a WebSocket frame carries text or bytes, not a typed value, so we encode the Tally ourselves with zio-schema's JsonCodec:

import zio.http.ChannelEvent.{Read, UserEvent, UserEventTriggered}
import zio.schema.codec.JsonCodec

val tallyEncoder = JsonCodec.jsonEncoder(Tally.schema)

def votesSocket(poll: SubscriptionRef[Tally]): WebSocketApp[Any] =
Handler.webSocket { channel =>
channel.receiveAll {
case UserEventTriggered(UserEvent.HandshakeComplete) =>
poll.changes.runForeach { tally =>
val json = tallyEncoder.encodeJson(tally, None).toString
channel.send(Read(WebSocketFrame.text(json)))
}.fork
case Read(WebSocketFrame.Text(choice)) =>
poll.update(_.vote(choice))
case _ =>
ZIO.unit
}
}

When the browser closes the page, receiveAll returns, the handler's effect ends, and ZIO interrupts the forked fiber with it, so a closed connection leaves no fiber behind. The case _ line ignores the other events, such as pings and binary frames.

warning

The function passed to Handler.webSocket must keep running for as long as the connection is in use, which receiveAll does. If it only forks work and returns, ZIO interrupts the forked fibers as soon as it returns, and nothing handles the connection's events from then on.

The page differs from the server-sent events page only in its script. It opens a WebSocket on /votes, reads the totals from each message and sends a vote as a text frame over the same socket:

val webSocketPage: Dom =
html(
head(title("Tabs or spaces?")),
body(
h1("Tabs or spaces?"),
p("Tabs: ", span(id := "tabs", "0"), ", spaces: ", span(id := "spaces", "0")),
button(id := "vote-tabs", "Vote for tabs"),
button(id := "vote-spaces", "Vote for spaces"),
script.inlineJs(
"""
const socket = new WebSocket('ws://' + location.host + '/votes');
socket.onmessage = (event) => {
const tally = JSON.parse(event.data);
document.getElementById('tabs').textContent = tally.tabs;
document.getElementById('spaces').textContent = tally.spaces;
};
for (const choice of ['tabs', 'spaces']) {
document.getElementById('vote-' + choice).onclick = () => socket.send(choice);
}
""",
),
),
)

The routes serve the page and the socket, and the server is built the same way as before:

object WebSocketPoll extends ZIOAppDefault {
def routes(poll: SubscriptionRef[Tally]): Routes[Any, Response] =
Routes(
Method.GET / Root -> handler(Response.html(webSocketPage)),
Method.GET / "votes" -> handler(votesSocket(poll).toResponse),
)

def run =
SubscriptionRef
.make(Tally.empty)
.flatMap(poll => Server.serve(routes(poll)))
.provide(Server.default)
}

Open http://localhost:8080 in two browser windows and vote in either: both update at once. Here is what two WebSocket clients, A and B, received when each voted and A then left:

B received {"tabs":0,"spaces":0}
A received {"tabs":0,"spaces":0}
A sends tabs
B received {"tabs":1,"spaces":0}
A received {"tabs":1,"spaces":0}
B sends spaces
B received {"tabs":1,"spaces":1}
A received {"tabs":1,"spaces":1}
A closes
B sends tabs
B received {"tabs":2,"spaces":1}

Each client first receives the current totals, then every vote, its own included. After A closes, B goes on voting and receiving totals.

A browser's WebSocket does not reconnect on its own. If the connection drops, the page has to open a new socket, for example from the socket's onclose handler. Because the server sends the current totals first on every new connection, a page that reconnects catches up straight away.

Runnable version, with the model from Tally.scala: WebSocketPoll.scala
zio-http-example/src/main/scala/example/liveupdates/WebSocketPoll.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"
//> using file Tally.scala
// Run from this folder: scala-cli run WebSocketPoll.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.liveupdates.WebSocketPoll"

package example.liveupdates

import zio._

import zio.stream.SubscriptionRef

import zio.schema.codec.JsonCodec

import zio.http.ChannelEvent.{Read, UserEvent, UserEventTriggered}
import zio.http._
import zio.http.template2._

/**
* Push Live Updates to the Browser — Send and Receive over a WebSocket
*
* Every browser that opens http://localhost:8080 opens one WebSocket to
* `/votes`. The browser sends its votes over the socket, and the server sends
* the new totals back over the same socket to every open page.
*/
object WebSocketPoll extends ZIOAppDefault {

val page: Dom =
html(
head(title("Tabs or spaces?")),
body(
h1("Tabs or spaces?"),
p("Tabs: ", span(id := "tabs", "0"), ", spaces: ", span(id := "spaces", "0")),
button(id := "vote-tabs", "Vote for tabs"),
button(id := "vote-spaces", "Vote for spaces"),
script.inlineJs(
"""
const socket = new WebSocket('ws://' + location.host + '/votes');
socket.onmessage = (event) => {
const tally = JSON.parse(event.data);
document.getElementById('tabs').textContent = tally.tabs;
document.getElementById('spaces').textContent = tally.spaces;
};
for (const choice of ['tabs', 'spaces']) {
document.getElementById('vote-' + choice).onclick = () => socket.send(choice);
}
""",
),
),
)

private val tallyEncoder = JsonCodec.jsonEncoder(Tally.schema)

def socket(poll: SubscriptionRef[Tally]): WebSocketApp[Any] =
Handler.webSocket { channel =>
channel.receiveAll {
case UserEventTriggered(UserEvent.HandshakeComplete) =>
poll.changes.runForeach { tally =>
val json = tallyEncoder.encodeJson(tally, None).toString
channel.send(Read(WebSocketFrame.text(json)))
}.fork
case Read(WebSocketFrame.Text(choice)) =>
poll.update(_.vote(choice))
case _ =>
ZIO.unit
}
}

def routes(poll: SubscriptionRef[Tally]): Routes[Any, Response] =
Routes(
Method.GET / Root -> handler(Response.html(page)),
Method.GET / "votes" -> handler(socket(poll).toResponse),
)

def run =
SubscriptionRef
.make(Tally.empty)
.flatMap(poll => Server.serve(routes(poll)))
.provide(Server.default)
}

Running the Examples​

All runnable code from this guide is in zio-http-example/src/main/scala/example/liveupdates/. Run either server from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.liveupdates.<ObjectName>". Each example starts a server on port 8080; open http://localhost:8080 in two browser windows and vote.

Going Further​

  • Response lists the other server-sent event constructors, such as Response.fromServerSentEvent for a single event.
  • Endpoint shows how to declare a server-sent event stream with Endpoint#outStream, so the stream appears in the generated OpenAPI documentation.
  • Socket and WebSocketFrame cover the WebSocket API in depth, including every frame and channel event.
  • Client shows how to consume server-sent events and WebSockets from a zio-http client, for example in tests.
  • Building a Real-time Chat with Datastar builds a larger live application on server-sent events, with the Datastar library updating the page.