Managing WebSocket State

1. Tracking Connection State

State SliceStorage
Connection statusState machine: idle/connecting/open/closing/closed
SubscriptionsSet of topics
OutboxQueue of pending sends
Inflight RPCsMap of id → handler
Last seqFor resume

2. Storing Client Data

Example: Attach context

wss.on("connection", (ws, req) => {
  ws.ctx = { userId: req.user.id, subs: new Set(), connectedAt: Date.now() };
});
StorageUse
Attached to ws objectPer-connection
WeakMap<ws, ctx>Cleaner ownership
RedisCross-node shared state

3. Synchronizing State

ApproachDetail
SnapshotSend full state on connect
Delta + seqSend changes after snapshot
Resync triggerClient requests on gap detection

4. Handling State Recovery

Example: Resume protocol

{ "type": "resume", "lastSeq": 4218 }
{ "type": "resumed", "from": 4219, "to": 4235, "events": [ /* ... */ ] }
{ "type": "snapshot", "state": { /* full */ }, "seq": 4500 }
Server ResponseCondition
resumedBuffer still has from lastSeq+1
snapshotBuffer rolled past; full state needed

5. Implementing State Snapshots

DetailRecommendation
FormatCompact (msgpack/protobuf for large)
VersionedSchema version + seq
ChunkedSplit if > 64KB
TriggerOn connect, on resync, periodic

6. Implementing Delta Updates

Example: JSON Patch (RFC 6902)

{ "type": "patch", "seq": 4501, "ops": [
  { "op": "replace", "path": "/users/u1/status", "value": "online" },
  { "op": "add", "path": "/messages/-", "value": { "id": "m9", "text": "hi" } }
]}
FormatLib
JSON Patchfast-json-patch
JSON Merge PatchRFC 7396
Custom opsDomain-specific

7. Using Operational Transformation

AspectDetail
ConceptTransform concurrent ops against each other
UsesGoogle Docs-style text editing
Server roleCentral source-of-truth ordering
LibraryShareDB, ot.js

8. Implementing CRDT

CRDT TypeUse
LWW-RegisterSingle value, last-write-wins
G-CounterMonotonic counter
OR-SetAdd/remove element set
Yjs / AutomergeRich text, JSON CRDT libraries
Note: CRDTs allow peer-to-peer merges without a central authority. WebSocket transports their update messages but isn't part of the algorithm.

9. Validating State Consistency

CheckDetail
Hash comparePeriodic SHA of state; resync on mismatch
Seq monotonicityDetect gaps / duplicates
Schema invariantsRe-validate after each patch

10. Persisting State

StorageUse
IndexedDBBrowser-local persistence
localStorageSmall KV (<5MB)
RedisServer-side ephemeral
PostgresDurable source-of-truth