Real-time Dashboard — Realtime

Mrs. Rini's realtime dashboard computes its numbers (orders per status, total kilos, revenue = kilos × $7) from the order list. The server pushes data over…

Here is what you will build: a dashboard at Mrs. Rini's front counter. It shows the number of orders per status, total kilos today and revenue (the total price of all orders). Its numbers change as soon as the data changes, with no refresh. A screen of numbers that updates by itself is called a realtime dashboard.

It works much like the scoreboard at a football match. The scorekeeper does not repaint the whole board for every goal. They only change the number that changed. A fan who arrives in the second half reads the board first, then follows the next goals, and the match minute tells them whether they missed anything. On a dashboard, that first reading is called a snapshot, each change after it is a delta, and the match minute is a sequence number for each change.

The dashboard's numbers are computed from the order list

The dashboard keeps the list of orders, and every number is computed from that list. The rate is $7 per kilo.

const STATUS = ['Queued', 'Washing', 'Ironing', 'Ready for pickup']

function compute(orders) {
  const perStatus = Object.fromEntries(STATUS.map((s) => [s, 0]))
  let kg = 0
  for (const o of orders) {
    perStatus[o.status]++
    kg += o.kg
  }
  return { perStatus, kg, revenue: kg * 7 }
}

An example order list:

Order Kg Status
#12 Mr. Darto 3 Washing
#13 Ms. Wulan 2 Ironing
#14 Mr. Yoga 5 Ready for pickup
#15 Mrs. Tini 4 Queued

The result: 1 order per status, 3 + 2 + 5 + 4 = 14 kg, and revenue 14 × $7 = $98. The numbers are always computed again from the list, not added and subtracted one by one, so they cannot go wrong.

Snapshot or delta

For a live chart, the server pushes data over SSE (enough when data only flows from the server to the browser) or WebSocket, and the frontend updates its chart. Polling every second wastes requests even when nothing changed. The question is: what does the server send?

In the Lab, the 40 changes of the busy morning (from the starting state) = 1,904 bytes as deltas, 22,448 bytes as snapshots. A delta carries the new value (status: 'Washing'), not a relative change like "+1 Washing, -1 Queued". So the same delta received twice still gives the right numbers.

This function on the realtime server sends a delta to every staff screen:

// realtime server, namespace /staff
function changeStatus(id, status) {
  seq += 1
  orders.get(id).status = status
  staff.emit('board:delta', { seq, id, status })
}

Collect first, draw once

Redrawing is expensive (layout, charts, animation), and no eye can read 20 changes a second. So incoming deltas are collected first, then drawn at most once per 250 ms. In the browser, staff is the socket to the /staff namespace, applyDelta puts one delta into the order list, and draw redraws the dashboard:

let batch = []
let timer = null

staff.on('board:delta', (d) => {
  batch.push(d)
  if (timer) return                 // a draw is already scheduled
  timer = setTimeout(() => {
    timer = null
    for (const x of batch) applyDelta(x)
    batch = []
    draw()                          // once for everything collected
  }, 250)
})

The first delta sets a 250 ms timer. Deltas that arrive before that timer ends are only collected.

Guess first: a busy morning, 40 changes arrive within 2 seconds. Redrawing on every message means 40 draws. With the code above, how many times?

Measured in Chromium 147 with 40 random messages over 2,000 ms: drawing on every message = 40 times, collected per 250 ms = 7 times. With 200 messages within 1 second: 200 times against 4. No message is lost. All of them are applied, just drawn together. The server can also collect before sending: one message every 250 ms, carrying several deltas, so the number of messages drops too.

Late joiners: a snapshot, then numbered deltas

At 10:00 Mrs. Rini opens the dashboard on her phone. The phone needs the current state (a snapshot), then the changes after it (deltas). The phone fetches the snapshot with GET /api/dashboard, and receives deltas after it subscribes (starts listening to board:delta). The order matters. This table compares both ways, while Eko changes one order at 150 ms and another at 900 ms:

Time Snapshot first, then subscribe Subscribe first, then snapshot
0 ms GET /api/dashboard subscribe to board:delta, then GET /api/dashboard
150 ms Eko: #15 Washing (seq 58), the phone has not subscribed: missed delta 58 is queued
300 ms snapshot seq 57 arrives, now it subscribes the snapshot arrives (built after the change: seq 58), delta 58 is dropped because it is already inside
900 ms delta seq 59 arrives: seq jumps from 57 to 59 delta 59 is applied

This is the phone's code, in the order of the right-hand column. orders is null while there is no snapshot yet, and queue holds the deltas during that time:

let orders = null      // null: no snapshot yet
let lastSeq = 0
let queue = []

function applyDelta(d) { // { seq, id, status } or { seq, added: order }
  if (d.added) orders.push(d.added)
  else orders.find((o) => o.id === d.id).status = d.status
  lastSeq = d.seq
}

staff.on('board:delta', (d) => {
  if (!orders) return queue.push(d)          // no snapshot yet: queue it
  if (d.seq <= lastSeq) return               // already in the snapshot
  if (d.seq !== lastSeq + 1) return reload() // something was missed
  applyDelta(d)
  draw()
})

async function reload() {
  orders = null
  const snap = await fetch('/api/dashboard').then((r) => r.json()) // { seq, orders }
  orders = snap.orders
  lastSeq = snap.seq
  for (const d of queue.splice(0)) if (d.seq > lastSeq) applyDelta(d)
  draw()
}
reload() // called after the listener is attached

Charts that do not redraw everything

The dashboard's chart has one bar per status. The delta #15 Queued to Washing changes only two bars: Queued and Washing. Keep the numbers per status, and let bars whose number did not change skip the redraw. In React, you do it with memo:

const Bar = memo(function Bar({ status, count, max }) {
  return <div className="bar" style={{ width: `${(count / max) * 100}%` }}>{status}: {count}</div>
})

With memo, React skips the bars whose props (the data given to a component) did not change. Chart libraries have a similar way: change the data, then ask the chart to update itself once per group of deltas, instead of building a new chart. When the tab is hidden (document.visibilityState === 'hidden'), skip drawing, then draw once when the tab is visible again.

⚠️ A dashboard that stutters or shows the wrong numbers

TL;DR: Mrs. Rini's realtime dashboard computes its numbers (orders per status, total kilos, revenue = kilos × $7) from the order list. The server pushes data over SSE or WebSocket. It sends a small delta (only what changed) with a sequence number seq, such as {"seq":58,"id":15,"status":"Washing"} (37 bytes), not a snapshot (the whole state) that keeps growing. 40 changes: 1,904 against 22,448 bytes. Collect messages and draw at most once per 250 ms: 40 messages in 2 seconds are drawn 7 times, not 40. A phone that opens the dashboard late subscribes first (starts listening to deltas) and queues deltas, then fetches a snapshot with its seq. Deltas whose seq the snapshot already includes are dropped, and when the seq jumps, the phone fetches the snapshot again. With memo in React, only the chart bars whose number changed are redrawn.

⚡ The server pushes

Meaning: A realtime dashboard is a screen of numbers, like the one at Mrs. Rini's front counter, that changes with no refresh. For a live chart, the server pushes data over SSE (enough when data only flows from the server to the browser) or WebSocket, and the frontend updates its chart. Polling every second wastes requests even when nothing changed.

⚡ Send deltas, not snapshots

Write:

// realtime server, namespace /staff
function changeStatus(id, status) {
  seq += 1
  orders.get(id).status = status
  staff.emit('board:delta', { seq, id, status })
}

Meaning: This function runs on the server when Eko changes an order's status. The server sends a delta, only what changed, to every staff screen (staff): about 37 bytes however many orders there are. A snapshot (the whole state) grows with the number of orders. seq is the sequence number of the change. The delta carries the new value, not "+1 Washing, -1 Queued", so a delta received twice still gives the right numbers.

⚡ Collect first, draw once

Guess first: a busy morning, 40 changes (deltas) arrive at the dashboard within 2 seconds. If messages are collected and drawn at most once per 250 ms, how many times does the dashboard draw?

7 times (measured, random timing), not 40. No message is lost: all of them are applied, just drawn together.

Meaning: Redrawing is expensive, and no eye can read 20 changes a second.

⚡ Late joiners

Meaning: A phone that opens the dashboard late needs a snapshot, then the deltas after it. Subscribe (start listening to deltas) first, queue, then fetch the snapshot. If you fetch the snapshot first, the changes in between are missed. A delta whose seq is ≤ the snapshot's seq is dropped, and when the seq jumps, fetch the snapshot again.

What you will learn