All Challenges
7 PointsExpert
00:00

Resilient WebSocket Client with Heartbeat, Auto-Reconnect & Offline Queue

Build an enterprise WebSocket connection manager featuring ping/pong heartbeat dead-socket detection, exponential jittered reconnection, and offline message queue replay.

### Problem Overview Raw WebSockets in web and mobile apps fail silently when moving across cell towers, Wi-Fi changes, or background tabs. Build a resilient WebSocket client wrapper that handles dirty disconnects, sends heartbeat probes, automatically reconnects with exponential backoff and jitter, and buffers messages while offline. ### Functional Requirements 1. **Heartbeat Protocol (Ping/Pong)**: - Periodically sends a ping message. - If no pong reply is received within `heartbeatTimeoutMs`, terminates the dead socket immediately and initiates reconnection. 2. **Exponential Reconnection with Jitter**: - Automatic reconnect with backoff: \( \min(\text{maxDelay}, \text{baseDelay} \times 2^{\text{attempt}}) + \text{jitter} \). 3. **Offline Message Outbox Queue**: - Messages sent while offline (`send(data)`) are stored in a persistent FIFO queue up to `maxQueueSize` and flushed automatically upon reconnection. 4. **Lifecycle Hooks**: - `on('open' | 'close' | 'message' | 'reconnecting' | 'error', callback)`. ### Non-Functional Requirements - **Memory Safety**: Clean up all event listeners, timers, and pending ping intervals on manual `disconnect()`. - **Duplicate Prevention**: Avoid race conditions where multiple reconnect loops run in parallel.
AI Review Rubric Dimensions (1–10 Points):
  • Ping/Pong heartbeat timeout handling
  • Offline message buffering and flush
  • Exponential backoff reconnect with jitter
  • Resource cleanup
solution.tsTYPESCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
34 lines•674 characters•
AI Review Ready