Precision in Chaos: Managing WebSocket State
The illusion of "instantaneity" is the most expensive feature in modern software. To the user, a live election result or an AI response appears instantly. To the engineer, that data is a packet traversing a hostile network, subject to latency, packet loss, and race conditions.
In building the Third Party Results Collation System (TPRCS) for the 2024 elections, I learned that opening a WebSocket connection is easy. Keeping 10,000 clients mathematically synchronized without crashing the server is the actual engineering challenge.
The Fallacy of Event-Driven UI
Junior engineers treat WebSockets as "Event Emitters"—a firehose of events that the UI listens to directly. They push updates straight into the component state. This is a mistake. It leads to "State Tearing," where different parts of the UI show conflicting data because they processed events in a slightly different order.
The WebSocket is not a notification system. It is a state synchronization tunnel. Treat it as such.
The Store-First Architecture
To achieve precision, we must decouple the network layer from the view layer. In SvelteKit (or React), the component should never know a WebSocket exists. It should only subscribe to a Store.
- The Socket Worker: A dedicated background process handles the connection, heartbeats, and reconnection logic. It does not touch the UI.
- The Store: When a message arrives, the worker mutates a global Store (Single Source of Truth).
- The View: The UI components reactively update based on the Store. They are completely ignorant of the network.
Handling the Thundering Herd
The most dangerous moment in a real-time system is not peak traffic; it is recovery. If a network glitch disconnects 5,000 users simultaneously, and your client code immediately attempts to reconnect, you will DDoS your own server. This is the "Thundering Herd" problem.
The solution is "Exponential Backoff with Jitter." When a client disconnects, it shouldn't reconnect immediately. It should wait 100ms, then 200ms, then 400ms, adding a random "jitter" factor so that not all clients hit the server at the exact same millisecond.
Conclusion
Real-time features are not just about speed; they are about consistency. By treating the WebSocket as a synchronization mechanism rather than an event pipe, we build systems that remain precise even when the network is chaotic.