DEV Community

desgh white
desgh white

Posted on

Defensive Coding for Real-Time Scoreboard Components

Live scoreboards look simple — a number, a timer, maybe a dot for possession — until the WebSocket drops mid-event and the UI freezes on a stale score. Most scoreboard bugs are not render bugs; they are state-reconciliation failures.

Heartbeat timeout

If the socket sends no message for N seconds, assume the connection is stale and trigger a full state refetch instead of waiting for the browser's built-in close event (which can take 30+ seconds):

let last = Date.now();
socket.onmessage = (ev) => { last = Date.now(); handle(ev); };
setInterval(() => {
  if (Date.now() - last > 8000) refetchState();
}, 4000);
Enter fullscreen mode Exit fullscreen mode

Optimistic display, pessimistic state

Render the latest message optimistically but keep a confirmed state separately. If a correction message arrives (scores do get revised during VAR reviews), roll back the optimistic render:

interface ScoreState {
  confirmed: Score;
  optimistic: Score | null;
}
Enter fullscreen mode Exit fullscreen mode

A platform like Tenobet that covers dozens of live matches at once cannot afford to show a wrong score even briefly — the trust cost is higher than the latency cost of waiting for confirmation.

Clock sync

Server timestamps drift from client clocks. Never compute match time from Date.now() - kickoff; instead, use the server's elapsed-seconds field and increment it locally between messages. When a fresh message arrives, snap the local clock to the server value — the user won't notice a sub-second jump.

Takeaway

Scoreboards are deceptively simple. The hard part is not drawing the number; it is knowing which number is still true.

Top comments (0)