folkwaysDocs
Developer guides

How to build reliable WebSocket applications

Design real-time apps for network failure, reconnect backoff, offline publishing, bounded queues and explicit connection state.

Reliable WebSocket applications treat disconnection as routine. Use a connection state machine, backoff with jitter, bounded offline queues, idempotent writes and a recovery strategy tailored to the data. Not every real-time event needs durable history.

Choose delivery semantics before choosing a transport

A chat message needs ordered history. A location update usually needs the current value, not a backlog. A typing indicator can disappear when the connection is lost. Folkways exposes Stream for retained events, KV for latest state and Signal for ephemeral activity. Treat them differently in the UI and on reconnect.

Surface the connection state

The SDK handles reconnect backoff and can fall back to HTTP long-polling. Your app should display the state and distinguish temporary interruptions from permanent authorization failures. After configuring a segment and authenticated token endpoint, attach a connection listener before connecting.

Browser example · show connection transitions

import { Folkways } from '@folkwaysio/realtime';

const client = new Folkways.Realtime({
  url: 'https://rte.example.com',
  authUrl: '/api/realtime-token',
  offlineQueue: { maxSize: 100 },
});

client.connection.on('change', ({ current, reason }) => {
  console.log('Connection:', current, reason);
});
try {
  await client.connect();
} catch (error) {
  console.error('Initial connection did not complete:', error);
}

Bound memory and retry work

Do not allow an offline queue to grow without a limit. Reject or defer work when it is full and show whether a publish is pending, confirmed or failed. A publish retry must not create duplicate business actions. Apply idempotency at your application boundary as well as using the transport SDK.

Signals should be dropped while offline, not replayed later. Stale state should expire where useful. A persistent outbox is optional and still has an age limit; it is not a substitute for a business transaction log.

Plan for overloaded services and missed history

Use bounded message sizes, backpressure and rate limits. Let reconnect attempts back off instead of restarting every client simultaneously. If a stream cursor is outside retained history, recover from your authoritative data source. Do not silently skip missing events in critical workflows.

Test the unhappy paths

Test offline mode, browser reloads, blocked WebSocket connections, queue saturation, revoked credentials and server restarts. Observe time to recover, gaps, failed publishes and final application state. The right success criterion is a consistent application, not just a green connection indicator.

Create a free workspace and follow the quick start to try this pattern.

On this page