Long-Polling vs WebSocket: Test Patterns for Both

Long-Polling vs WebSocket: Test Patterns for Both

Long-polling and WebSocket solve the same problem — real-time server-to-client data delivery — but they have fundamentally different failure modes, different test strategies, and different monitoring requirements.

Understanding the differences helps you write tests that catch actual bugs rather than testing implementation details that don't matter.

What You're Actually Testing

Long-Polling Architecture

In long-polling, the client sends an HTTP request. The server holds the request open until it has data to return (or a timeout occurs). The client immediately sends a new request upon receiving a response.

Client → HTTP GET /poll?since=1234
         [server holds request open for up to 30s]
Server → 200 OK with event data (or 204 No Content on timeout)
Client → HTTP GET /poll?since=5678  [immediately repeats]

The key behaviors to test:

  • Server holds open requests correctly (doesn't return early)
  • Server returns immediately when data is available
  • Server returns 204 (or empty response) after timeout
  • Client uses the returned cursor/sequence for the next poll
  • Client handles 204 and immediately polls again
  • Client handles errors and retries with backoff

WebSocket Architecture

WebSocket establishes a persistent bidirectional connection. The server can push data at any time without the client requesting it.

Client → HTTP Upgrade request
Server → 101 Switching Protocols
[persistent connection]
Server → data frame (any time)
Client → data frame (any time)

Key behaviors to test:

  • Connection establishment and authentication
  • Server pushes arrive at the client (not request-driven)
  • Connection state management (reconnection on drop)
  • Heartbeat/ping-pong to detect dead connections

Testing Long-Polling

Basic Poll Cycle

describe('long-polling endpoint', () => {
  test('returns 204 when no events within timeout', async () => {
    const start = Date.now();
    const response = await fetch('http://localhost:3000/poll?since=999999999', {
      signal: AbortSignal.timeout(35000), // longer than server timeout
    });
    
    const elapsed = Date.now() - start;
    
    expect(response.status).toBe(204);
    // Server should have waited at least 25s (±tolerance)
    expect(elapsed).toBeGreaterThanOrEqual(25000);
    // But not longer than 35s
    expect(elapsed).toBeLessThan(35000);
  });
  
  test('returns immediately when events are available', async () => {
    // Create a pending event first
    await fetch('http://localhost:3000/events', {
      method: 'POST',
      body: JSON.stringify({ type: 'test', data: 'hello' }),
      headers: { 'Content-Type': 'application/json' },
    });
    
    const start = Date.now();
    const response = await fetch('http://localhost:3000/poll?since=0');
    const elapsed = Date.now() - start;
    
    expect(response.status).toBe(200);
    expect(elapsed).toBeLessThan(500); // Should return near-instantly
    
    const events = await response.json();
    expect(events).toHaveLength(1);
    expect(events[0].data).toBe('hello');
  });
  
  test('returns events published during the hold period', async () => {
    // Start polling (will hold until events arrive)
    const pollPromise = fetch('http://localhost:3000/poll?since=current');
    
    // Wait a bit, then publish an event
    await sleep(500);
    await publishEvent({ type: 'delayed', data: 'I arrived late' });
    
    const response = await pollPromise;
    expect(response.status).toBe(200);
    
    const events = await response.json();
    expect(events.some(e => e.data === 'I arrived late')).toBe(true);
  });
});

Cursor Integrity

Long-polling depends on cursors (sequence numbers, timestamps, or offsets) to prevent duplicate delivery and missed events. Test cursor handling explicitly:

describe('cursor integrity', () => {
  test('cursor advances after each response', async () => {
    await publishEvent({ data: 'event 1' });
    
    const res1 = await fetch('/poll?since=0');
    const events1 = await res1.json();
    const cursor1 = res1.headers.get('X-Next-Cursor');
    
    await publishEvent({ data: 'event 2' });
    
    const res2 = await fetch(`/poll?since=${cursor1}`);
    const events2 = await res2.json();
    
    // First poll should return event 1, second should return event 2
    expect(events1.map(e => e.data)).toContain('event 1');
    expect(events2.map(e => e.data)).toContain('event 2');
    expect(events2.map(e => e.data)).not.toContain('event 1'); // No duplicates
  });
  
  test('replaying from old cursor returns all missed events', async () => {
    const originalCursor = await getCurrentCursor();
    
    // Publish 5 events
    for (let i = 1; i <= 5; i++) {
      await publishEvent({ sequence: i });
    }
    
    // Poll from original cursor
    const response = await fetch(`/poll?since=${originalCursor}`);
    const events = await response.json();
    
    expect(events).toHaveLength(5);
    expect(events.map(e => e.sequence)).toEqual([1, 2, 3, 4, 5]);
  });
  
  test('invalid cursor returns 400', async () => {
    const response = await fetch('/poll?since=not-a-valid-cursor');
    expect(response.status).toBe(400);
  });
});

Concurrent Poll Handling

Many implementations limit clients to one active poll at a time. Test this:

test('second poll from same client supersedes first', async () => {
  const poll1Promise = fetch('/poll?since=0&clientId=test-client');
  await sleep(100); // Let first poll establish
  
  const poll2Promise = fetch('/poll?since=0&clientId=test-client');
  
  const [res1, res2] = await Promise.all([poll1Promise, poll2Promise]);
  
  // Implementation-dependent: first might be closed, or second might be queued
  // But server should not crash or deadlock
  expect([200, 204, 409]).toContain(res1.status);
  expect([200, 204]).toContain(res2.status);
});

Testing WebSocket

Connection State Transitions

describe('WebSocket states', () => {
  test('readyState transitions correctly', (done) => {
    const states = [];
    const ws = new WebSocket('ws://localhost:3000');
    
    // CONNECTING = 0
    states.push(ws.readyState);
    
    ws.on('open', () => {
      states.push(ws.readyState); // OPEN = 1
      ws.close();
    });
    
    ws.on('close', () => {
      states.push(ws.readyState); // CLOSED = 3
      expect(states).toEqual([0, 1, 3]);
      done();
    });
  });
  
  test('closing state is 2 during graceful close', (done) => {
    const ws = new WebSocket('ws://localhost:3000');
    
    ws.on('open', () => {
      ws.close();
      // Immediately after calling close(), state should be CLOSING
      expect(ws.readyState).toBe(2); // CLOSING
    });
    
    ws.on('close', done);
  });
});

Heartbeat Testing

Production WebSocket connections need heartbeats to detect dead connections. Test that ping/pong works:

describe('WebSocket heartbeat', () => {
  test('server sends ping within configured interval', (done) => {
    const ws = new WebSocket('ws://localhost:3000');
    const pingReceived = false;
    
    ws.on('ping', (data) => {
      ws.pong(data); // Respond to ping
      ws.close();
      done();
    });
    
    // If no ping received within interval + buffer, fail
    setTimeout(() => {
      if (!pingReceived) done(new Error('No ping received within 35s'));
    }, 35000);
  });
  
  test('server closes connection when pong not received', (done) => {
    const ws = new WebSocket('ws://localhost:3000');
    
    ws.on('open', () => {
      // Override pong to not send it
      ws._socket.removeAllListeners('data');
    });
    
    ws.on('close', (code) => {
      // Server should close with 1001 or 4001 after missing pong
      expect([1001, 4001]).toContain(code);
      done();
    });
  });
});

Comparing Failure Modes

Understanding failure modes guides what to test in each approach.

Long-Polling Failure Modes

Failure Symptom Test
Server closes too early Client polls endlessly Assert hold duration ≥ configured timeout
Missing cursor in response Client re-fetches duplicates Assert cursor header present on every 200
Client doesn't re-poll on 204 Real-time stops E2E test: publish after 204 and verify delivery
Connection dropped mid-hold Client hangs Test network interruption during hold
Database query per poll Server overload at scale Load test: N concurrent polls
test('client handles network drop during long poll', async () => {
  const client = new LongPollingClient('/poll');
  const received = [];
  client.on('event', (e) => received.push(e));
  
  client.start();
  await sleep(1000); // Let first poll start
  
  // Simulate network drop
  await simulateNetworkFailure(500);
  
  // Publish event during recovery
  await publishEvent({ data: 'recovery event' });
  
  // Client should recover and receive the event
  await waitFor(() => received.length > 0, 10000);
  expect(received[0].data).toBe('recovery event');
  
  client.stop();
});

WebSocket Failure Modes

Failure Symptom Test
No reconnection logic Single disconnect kills real-time Kill connection, verify auto-reconnect
State lost on reconnect Missed events after reconnect Reconnect and verify event replay
Heartbeat not implemented Dead connections pile up Simulate unresponsive client, verify cleanup
Message queued while disconnected Messages dropped Disconnect, queue events, reconnect
test('queued messages delivered after reconnection', async () => {
  const client = new ReconnectingWebSocketClient('ws://localhost:3000');
  const received = [];
  client.on('message', (m) => received.push(m));
  
  await client.connect();
  
  // Force disconnect
  client._socket.terminate();
  
  // Publish while disconnected
  await sleep(200); // Before reconnection completes
  await publishServerEvent({ data: 'queued during disconnect' });
  
  // Wait for reconnection
  await waitForReconnect(client, 5000);
  
  // Event should arrive after reconnect (if your server queues by session)
  await waitFor(() => received.some(m => m.data === 'queued during disconnect'), 3000);
});

Performance Testing Both Approaches

Long-polling and WebSocket have very different performance characteristics:

// k6 load test: long-polling throughput
import http from 'k6/http';
import { sleep, check } from 'k6';

export const options = {
  scenarios: {
    long_polling: {
      executor: 'constant-vus',
      vus: 1000,
      duration: '5m',
    },
  },
};

export default function () {
  // Long-polling: each VU is one concurrent connection
  const response = http.get('http://api.yourapp.com/poll?since=0', {
    timeout: '35s',
  });
  
  check(response, {
    'status 200 or 204': (r) => [200, 204].includes(r.status),
    'response under 35s': (r) => r.timings.duration < 35000,
  });
  
  // No sleep — client immediately re-polls
}
// k6 load test: WebSocket connection count
import ws from 'k6/ws';
import { check } from 'k6';

export const options = {
  scenarios: {
    websocket_connections: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 5000 },  // Ramp to 5000 concurrent connections
        { duration: '5m', target: 5000 },  // Hold
        { duration: '1m', target: 0 },
      ],
    },
  },
};

export default function () {
  const url = 'wss://api.yourapp.com/ws';
  
  const res = ws.connect(url, {}, function (socket) {
    socket.on('message', (data) => {
      check(JSON.parse(data), {
        'valid message format': (m) => m.type !== undefined,
      });
    });
    
    socket.setTimeout(() => socket.close(), 60000);
  });
  
  check(res, { 'WebSocket connected': (r) => r && r.status === 101 });
}

Monitoring Both in Production

Long-Polling Metrics to Watch

  • Poll rate per client: should be ~1 req/30s under normal conditions; spike indicates issues
  • Hold duration: histogram of how long polls are held; sudden drop means events are flooding
  • 204 rate: high 204 rate is normal; 0% means events are arriving too fast
  • Server-side connections: number of held requests; should equal active users

WebSocket Metrics to Watch

  • Active connections: should grow with users, drop when users leave
  • Connection duration: average session length
  • Reconnection rate: high rate indicates instability
  • Messages per connection per minute: traffic rate for capacity planning
*** Test Cases ***
Long-Polling Health Check
    [Documentation]    Verify long-polling endpoint delivers events
    ${response}=    POST    /api/test-events    {"type": "health", "data": "check"}
    ${poll_response}=    GET    /api/poll?since=0    timeout=5s
    Status Code Should Be    ${poll_response}    200
    ${events}=    Parse JSON    ${poll_response.body}
    Events Should Contain Type    ${events}    health

WebSocket Health Check
    [Documentation]    Verify WebSocket endpoint is functional
    ${ws}=    Connect WebSocket    wss://api.yourapp.com/ws
    Send Message    ${ws}    {"type": "ping"}
    ${response}=    Receive Message    ${ws}    timeout=3s
    ${data}=    Parse JSON    ${response}
    Should Be Equal    ${data}[type]    pong
    Close WebSocket    ${ws}

Choosing What to Test

Test long-polling for:

  • Timeout duration (server holds long enough, but not too long)
  • Cursor integrity (no duplicates, no gaps)
  • Immediate return when data is available
  • Client re-poll behavior (including error recovery)
  • Concurrency (multiple clients, one connection per client)

Test WebSocket for:

  • Connection lifecycle (connect, disconnect, reconnect)
  • Authentication (at connection time and per-message if needed)
  • Message delivery in both directions
  • Heartbeat and dead connection detection
  • Connection limit behavior at scale
  • Message ordering guarantees

Both approaches need load testing at 10x expected concurrent users. Long-polling servers hold connections open — at 1000 concurrent users with 30s polls, you need a server that handles 1000 simultaneous open HTTP connections. WebSocket servers need the same, but the connections are much longer-lived.

The test that catches the most bugs in real-world deployments: connect 100 simultaneous clients, kill the server, restart it, and verify all 100 clients reconnect and receive the next event. Most real-time implementations break at this boundary.

Read more

Start now free