All articles
Highload

WebSocket for charts and games: building reliable realtime systems

How to align snapshots with events, restore subscriptions after a disconnect, and avoid executing commands twice. WebSocket practices for charts and games: protocol design, queues, authorization, and scaling.

In a prototype, working with WebSocket looks simple: open a connection, send a message, and update the interface. With few users and a stable network, that may be enough.

The problems start later. A chart loses several trades after reconnection, a game action executes twice, a slow client accumulates a message queue, and an open connection remains alive only from one side's perspective.

WebSocket provides a bidirectional data channel. But the application must define its own rules for delivery, state recovery, and action processing.

First, decide whether you need WebSocket

Not every interface with live updates needs a persistent bidirectional connection.

If the client only needs notifications from the server, consider Server-Sent Events. If data changes infrequently, periodic HTTP requests may be simpler and cheaper to maintain.

WebSocket is useful when both sides send messages regularly: the client changes subscriptions and sends game commands, while the server delivers updates without separate requests.

However, WebSocket is not a universal transport for every networked game. It runs over TCP, so lost data delays delivery of subsequent data on that connection until transmission recovers. For fast-paced games, this can be a significant limitation.

That trade-off is acceptable for browser-based turn-based games, card games, trading interfaces, and many casual games. For competitive action games, evaluate alternatives separately, including WebTransport, WebRTC DataChannel, or a specialized networking stack outside the browser.

Choose a transport based on product requirements, not the assumption that “realtime always means WebSocket.”

Connections and subscriptions are different entities

An established connection does not mean the client should receive every event from the service.

A single connection can carry several logical subscriptions:

  • trades for the selected instrument;
  • candlestick updates;
  • game match state;
  • account notifications.

Each subscription needs clear parameters, permissions, and a lifecycle.

For example, when switching trading pairs, the client unsubscribes from the old instrument and subscribes to the new one. The server's response must make clear which subscription was confirmed and which stream a message belongs to.

This is especially important during rapid switching. If the user has already opened another chart, a delayed message from the previous subscription must not enter the current data series.

It helps to distinguish request identifiers, subscription identifiers, and event identifiers. They serve different purposes: matching requests to responses, identifying streams, and recognizing individual events.

You need an application protocol, not just JSON messages

Even a small realtime service benefits from an explicitly defined message format.

A protocol usually needs:

  • a message type;
  • a format version or agreed rules for changing it;
  • a request identifier for commands;
  • a subscription identifier for updates;
  • a sequence number or cursor if the stream supports recovery;
  • a payload;
  • a structured error.

Not every message needs every field. But each field's meaning must be unambiguous.

For example, a “command accepted” response may only mean the command was queued for processing, not that game state has already changed. If the interface treats it as the final result, the player sees success before the server confirms the action.

Define receipt acknowledgments, execution results, and state-change events separately. In a simple scenario they may coincide, but that must be a property of the protocol, not an accidental client assumption.

Validate incoming messages against a schema. An unknown type, oversized field, or invalid value should produce a controlled error, not an exception inside a handler.

Message ordering does not hold everywhere you expect

Messages are delivered in order within a single working WebSocket connection. That does not mean the entire system automatically preserves business-event order.

Events can originate from different processes, pass through a broker, and be processed asynchronously. The client can also apply them out of order if one message handler awaits an additional request while the next already changes state.

Define ordering at the level of a specific stream: an instrument, match, order book, or another entity.

A sequence number helps detect gaps or duplicates, but only if its rules are known. You need to understand:

  • where numbering starts;
  • which stream it applies to;
  • whether it can reset;
  • whether a gap means a lost event or an allowed omission due to filtering.

Reconnecting creates a new transport connection. The application resumes the previous stream using a cursor, event number, or a new state snapshot.

Snapshots and update streams must align

One of the most troublesome realtime interface bugs occurs between loading initial state and starting a subscription.

Consider a chart: the client requests history over HTTP, then opens a stream of new trades. Several more trades occur between those steps. The chart receives historical data and new events but loses the interval between them.

The reverse order also needs care. If you start receiving events first and then apply a snapshot without alignment, you can overwrite changes already received or count them twice.

A reliable design needs a synchronization point.

For example:

  • The client starts buffering stream events.
  • It receives a snapshot with a cursor corresponding to that snapshot's state.
  • It discards buffered events already reflected in the snapshot.
  • It applies the remaining events in the required order.
  • It continues processing the stream.

This works only if the data source actually supports that relationship between snapshots and events. An arbitrary timestamp is not a substitute for a coordinated cursor.

If the server cannot recover the missing segment, the client must obtain a new snapshot rather than continue with a state known to be incomplete.

Charts must distinguish event time from arrival time

A message may arrive now but describe a trade that occurred earlier.

Building candlesticks solely by arrival time puts late events into the wrong interval. You usually need event timestamps from the source and explicit rules for handling late data.

For a candlestick chart, define in advance:

  • interval boundaries and the time zone used;
  • which events determine price and volume;
  • how current and closed candles are distinguished;
  • whether a closed candle may be corrected;
  • how duplicate trades are excluded.

If the client receives precomputed candles, the protocol must explain whether a message contains the candle's complete current value or a change relative to its previous value.

This distinction is fundamental. Receiving full state again can safely replace the old value. Adding the same volume again corrupts the result.

An order book requires even more care. After a missed update, it must not continue to be shown as current: recovery according to the source's rules or a fresh snapshot is usually required.

Game commands and state need different delivery rules

Game messages cannot be handled identically just because they share a connection.

A position update, an item purchase command, and a match result have different importance and requirements.

For displaying movement, old state is often unnecessary once newer state arrives. But a game command that spends resources or changes persistent progress cannot simply be discarded.

It helps to distinguish:

  • player input and commands;
  • game state snapshots;
  • significant match events;
  • operations affecting persistent progress.

For each type, define whether messages may be coalesced, whether omissions are acceptable, and whether acknowledgment is required.

Input itself cannot be coalesced arbitrarily either. If the server must process button presses, movement duration, or individual actions sequentially, keeping only the latest command changes the game mechanics.

The delivery design must match the simulation model.

Reconnection must not become an endless retry loop

Many clients try to reconnect immediately after a network interruption. If the server has restarted, thousands of simultaneous attempts can prevent it from recovering.

Reconnection attempts therefore usually use increasing delays with random jitter. Cap the maximum delay and choose intervals according to product requirements.

But not every error should trigger a retry.

If access has been revoked or credentials are no longer valid, endlessly reconnecting with the same parameters is pointless. The client must distinguish a temporary network failure from a condition requiring renewed authorization or user action.

After the connection is restored:

  • revalidate access;
  • restore the required subscriptions;
  • reconcile state with the server;
  • resolve unacknowledged commands;
  • only then present the interface as fully up to date.

A “connected” indicator must not mean “data restored” while synchronization is still in progress.

Retrying a command must not repeat a purchase

The client sends a command, the server executes it, but the response is lost when the connection drops. After reconnecting, the client does not know whether the action happened.

Simply sending the same purchase as a new operation can charge the user twice.

Use an operation identifier for significant actions. A retry with the same identifier should return the result of the action already processed or safely resume its processing, rather than create a new action.

Remembering the identifier in the memory of a single connection is not enough. The guarantee must survive reconnection and, where necessary, process restarts.

Also define result retention time, the key's uniqueness scope, and what happens if a different request uses the same identifier.

WebSocket itself does not guarantee that a business operation executes exactly once. That guarantee is built through protocol design, storage, and transactional logic.

Slow clients must not accumulate unbounded queues

The server may produce messages faster than the client can receive and process them. A low-powered device, an overloaded tab, or an unstable network can cause this.

Without intervention, latency and memory usage grow. The connection technically works, but the user sees increasingly stale data.

You therefore need queue limits and a policy for overloaded connections.

For a quote stream, several updates can sometimes be coalesced into the latest value. For a chart, separate data reception from rendering frequency. For game state, reduce snapshot frequency.

Coalescing is not valid for every stream. If the client calculates volume from each trade or reconstructs an order book from sequential changes, arbitrarily dropping messages corrupts state.

In such cases, explicitly requesting resynchronization is better than silently displaying incorrect data.

The browser's WebSocket API has no full built-in mechanism for inbound flow control. The bufferedAmount value shows how much client-side data is waiting to be sent, but does not solve inbound queue problems. Load control must be designed at the application level.

Separate data frequency from rendering frequency

Receiving a hundred messages per second does not mean the interface should fully redraw the chart a hundred times.

Data can be received and processed independently of visual updates. Apply accumulated changes to the chart at an appropriate frequency, for example within the browser's rendering cycle.

This reduces unnecessary work without losing events needed for calculations.

A Web Worker can handle intensive processing. But moving computation to another thread does not remove the cost of transferring data and updating the interface. First, measure where the real bottleneck is.

A similar principle applies to games: network snapshot frequency, the simulation timestep, and frame rate do not have to align.

An open socket does not guarantee a live connection

After a network outage, one side may consider the connection open for some time. Proxies and load balancers may also close idle connections.

Liveness checks are used to detect these situations.

The WebSocket protocol includes Ping and Pong control frames. Browser JavaScript, however, cannot send these frames directly or handle them as regular messages. If an application needs its own liveness checks, it needs a separate heartbeat in its application protocol.

Align the interval and timeout with infrastructure and usage conditions. An overly short timeout will incorrectly disconnect clients during brief delays.

Also account for background tabs and mobile devices: the browser may throttle timers. This is especially important when heartbeats depend on client-side JavaScript running regularly.

Authorization does not end when the connection opens

An encrypted wss:// channel protects data in transit but does not resolve access control.

The server must check who connected, which streams they may subscribe to, and which commands they may execute.

For browser connections, validating the Origin header matters, especially with cookie-based authentication. Origin alone is not proof of client identity and does not replace authorization.

The browser's WebSocket API does not let you freely add an Authorization header. Choose a credential delivery method with that limitation in mind.

A long-lived token in the URL is risky: the address may appear in logs and monitoring systems. Alternatives include a short-lived, single-use ticket or authorization in the first message, with strict restrictions until it completes.

Also define what happens when a session expires, a user signs out, or permissions are revoked. An existing connection must not indefinitely retain access that is no longer authorized.

Scaling involves more than connections

The number of concurrently open sockets alone says little about actual load.

Message frequency, data size, subscription count, and the number of recipients per event matter. One popular trading pair or large game match can generate more load than many nearly idle connections.

When distributing across servers, decide:

  • where subscription state is stored;
  • how an event reaches the right node;
  • who is responsible for event ordering;
  • what happens when the broker is unavailable;
  • how clients migrate during service updates.

Ordinary Pub/Sub does not necessarily retain history. If a node misses an event, reconnecting to the broker may not recover the lost data.

Also distinguish the update stream from the service making game decisions. Scaling snapshot delivery and distributing an authoritative match simulation are different tasks.

What to measure before and after launch

Checking that “the connection opens” says almost nothing about the quality of a realtime service.

Useful metrics include:

  • time to establish a connection and confirm a subscription;
  • latency from event creation to application by the client;
  • queue sizes and the age of pending messages;
  • disconnection and reconnection counts;
  • the number of sequence gaps;
  • resynchronization frequency;
  • time to restore an up-to-date state;
  • the proportion of rejected and duplicate commands.

Estimating latency between devices requires accounting for clock skew. The difference between two timestamps does not always equal actual network latency.

Load tests should cover not only steady streams but also mass reconnections, slow clients, subscription changes, late events, and individual node failures.

Test prolonged operation separately. Leaking subscriptions or a queue that grows slowly but steadily can go unnoticed in a short test.

Where to start implementation

Reliable realtime starts with answers to a few questions:

  • Which data can be replaced by newer values, and which must not be lost?
  • How does the client know its state is current?
  • How are gaps detected?
  • What happens after reconnection?
  • How is a command with an unknown outcome handled?
  • How does the system handle a slow recipient?

Only then should you choose a library and configure the connection.

For a chart, preserving data correctness matters more than continuing to draw a line at any cost. For a game, consistent state and predictable action execution matter more than simply having a persistent channel.

WebSocket is a convenient transport. Reliable realtime emerges when it is paired with a clear protocol for recovery, load control, and operation execution.

What do you want to do?

Explain the idea in a couple of sentences. We'll come back with an estimate, deadlines and a plan - free of charge and under NDA.