Optimizing Performance

1. Minimizing Message Size

TechniqueSaving
Short keysReplace "timestamp" with "t"
Binary formatMessagePack/Protobuf vs JSON
Delta vs fullPatches, not snapshots
Omit defaultsSkip null/zero fields
Dictionary IDsSend enum int instead of string

2. Batching Messages

TriggerLatency Impact
10-20ms windowImperceptible
N messagesBounded throughput
Byte thresholdNetwork-efficient
Note: Batching converts many small frames into one larger frame, amortizing TLS/framing overhead.

3. Using Binary Format

FormatSize (vs JSON)
MessagePack50-70%
CBOR50-70%
Protobuf20-40%
FlatBuffers20-40% (zero-copy)
Custom TLVSmallest possible

4. Implementing Message Throttling

Example: requestAnimationFrame throttle

let pending = null;
function throttleSend(cursor) {
  pending = cursor;
  if (throttleSend.scheduled) return;
  throttleSend.scheduled = true;
  requestAnimationFrame(() => {
    ws.send(JSON.stringify({ "type":"cursor", "pos": pending }));
    throttleSend.scheduled = false;
  });
}
ApproachUse
throttle (leading)Fixed-rate updates
debounce (trailing)Quiet-after typing
rAFUI sync (cursor, scroll)

5. Optimizing JSON Parsing

TechniqueDetail
Avoid double parseParse once, share parsed
Lazy fieldsDefer heavy decode
simdjson (Node)SIMD-accelerated parser
Pre-validate lengthReject oversized before parse

6. Reusing Buffers

Example: Buffer pool

const pool = [];
function get(size) { return pool.pop() ?? new Uint8Array(size); }
function release(buf) { if (pool.length < 64) pool.push(buf); }
StrategyUse
Pool by sizeAvoid alloc churn
Reset (zero) on releaseSecurity if reused across users
Bounded poolPrevent memory hoarding

7. Reducing Event Listener Overhead

Anti-patternFix
Many handlers per WSSingle router
Closures per handlerHoist + bind
Re-create on reconnectReuse via AbortController

8. Implementing Lazy Parsing

TechniqueDetail
Parse envelope onlyDefer payload until needed
Type-based dispatchSkip if no handler
Streaming JSONFor very large messages

9. Profiling WebSocket Performance

ToolInsight
Chrome PerformanceMain-thread cost
clinic.js flameNode CPU hot spots
0xFlamegraphs
perf / dtraceSystem-level

10. Load Testing Connections

ToolUse
k6 (xk6-websocket)Scriptable, modern
ArtilleryYAML scenarios, WS plugin
TsungDistributed load
autocannon-ws (custom)Quick benchmarks