Skip to main content
WebSocket

Auto-Reconnection

SubscribeValidateMedium

What you will learn

  • Exponential backoff for reconnect attempts โ€” 1s, 2s, 4s, 8s, capped at 30s. Reset on successful connection
  • On reconnect, resume state via Last-Event-ID or similar โ€” server must replay missed events within retention window
  • Test silent network drop (pull cable) vs explicit close (1000) โ€” clients behave differently, both must recover

Description

Implement automatic reconnection with exponential backoff on connection failure.

Test Scenario

// Test: Reconnection logic
let attempts = 0;
const maxAttempts = 3;

function connect() {
  const ws = new WebSocket('wss://echo.websocket.org');

  ws.onerror = () => {
    attempts++;
    if (attempts < maxAttempts) {
      setTimeout(connect, Math.pow(2, attempts) * 1000);
    }
  };

  ws.onopen = () => {
    console.log('Connected after', attempts, 'retries');
  };
}

connect();

Testing Tips

  • โ€ขTrack connection attempts
  • โ€ขUse exponential backoff (1s, 2s, 4s, ...)
  • โ€ขSet max retry limit
// Playwright API Testing - WebSocket
import { test, expect } from '@playwright/test';
test('WebSocket connection', async ({ page }) => {
// Listen for WebSocket connections
const wsPromise = page.waitForEvent('websocket');
await page.goto('/websocket-demo');
const ws = await wsPromise;
expect(ws.url()).toContain('ws://');
// Wait for message
const framePromise = ws.waitForEvent('framereceived');
const frame = await framePromise;
expect(frame.payload).toBeDefined();
});

Challenge ID: ws-reconnect

2 frameworks available