← Lessons

quiz vs the machine

Platinum1760

Frontend

The WebSocket State Sync

Push server changes to clients over a live connection and merge them into the local cache safely.

6 min read · advanced · beat Platinum to climb

Push instead of poll

Polling asks the server again and again for changes. A WebSocket keeps a single open connection so the server can push updates the instant they happen. The client merges each message into its local state, keeping screens live.

  • Updates arrive in near real time without repeated requests.
  • One connection carries many event types.
  • The client must merge pushes into the same cache its queries use.

Merging pushes correctly

The hard part is reconciling pushed events with cached data without corrupting it.

  • Apply events to the normalized cache by entity id so all views update.
  • Make handlers idempotent so a duplicated event does not double apply.
  • Use a sequence number or version to order events and drop stale ones.

Reconnect and resync

Connections drop. A robust client reconnects with backoff and then resynchronizes, because events sent while offline were missed.

  • On reconnect, refetch affected queries to catch up.
  • Or replay events since the last known sequence number.
  • Show a subtle indicator when the live connection is down.

Key idea

A WebSocket pushes server changes in real time; merge them into a normalized cache idempotently and ordered, and resync on reconnect to recover missed events.

Check yourself

Answer to earn rating on the learn ladder.

1. Why make WebSocket event handlers idempotent?

2. What should a client do after reconnecting a dropped WebSocket?

3. How are pushed updates kept consistent across many views?