Skip to Content
Client Lifecycle

Client Lifecycle

This page documents the lifecycle methods implemented in src/client.ts.

Construction

TS
import { createClient, Auth, type AuthProvider } from '@kalamdb/client'; const authProvider: AuthProvider = async () => {  const token = await myApp.getOrRefreshJwt();  return Auth.jwt(token);}; const client = createClient({  url: 'http://localhost:2900',  authProvider,  onConnect: () => {    console.log('realtime socket ready');  },  onConnectionError: (error) => {    console.error('cannot reach KalamDB:', error.message);  },});

Validation at construction time:

  • url is required
  • authProvider is required

See Authentication for the full auth guide.

WebSocket connection behavior

The SDK manages the WebSocket connection lifecycle automatically. connect() is public, but most applications only need it for eager connection or manual reconnect flows.

  • query() runs over HTTP and does not require a WebSocket connection.
  • live(), liveTable(), and liveEvents() automatically establish the WebSocket connection on first use.

Connect

TS
await client.connect();

connect() explicitly establishes or restores the shared WebSocket connection. It is safe to call more than once and deduplicates concurrent connection work. Existing subscription state is preserved in the underlying client so reconnecting the same instance can resume live queries.

Lifecycle handlers

createClient() and the KalamDBClient instance support three connection-lifecycle hooks:

  • onConnect(callback) fires when the shared realtime connection becomes healthy.
  • onConnectionError(callback) fires for connection and auth/bootstrap failures.
  • onError(callback) remains as a compatibility alias for connection-error handling.
TS
const client = createClient({  url: 'http://localhost:2900',  authProvider,  onConnect: () => {    console.log('connected to KalamDB');  },  onConnectionError: (error) => {    console.error(      `[${error.recoverable ? 'retryable' : 'fatal'}] ${error.message}`,    );  },}); client.onConnect(() => {  console.log('socket restored or connected');}); client.onConnectionError((error) => {  console.error('connection/auth problem:', error.message);});

Use onConnectionError for new code. onError still works, but it exists mainly so older code does not break.

If you do not register either handler, the SDK now logs connection/auth failures to the console by default instead of failing silently.

What reaches onConnectionError

The callback is used for both WebSocket connection failures and pre-connect failures that happen before the socket opens:

  • invalid or malformed server URLs
  • auth provider resolution failures
  • login or token refresh failures used during connection/bootstrap
  • unreachable server / refused connection cases

The event shape comes from the shared WASM client and includes:

  • message: normalized error message
  • recoverable: true when the failure can reasonably be retried, false for fatal configuration/auth issues

wsLazyConnect (default: true)

By default, the WebSocket connection is lazy: it is deferred until the first live(), liveTable(), or liveEvents() call. This avoids unnecessary connections when the client is only used for HTTP queries.

Set wsLazyConnect: false to establish the connection eagerly during initialization:

TS
const client = createClient({  url: 'http://localhost:2900',  authProvider: async () => Auth.jwt('<JWT_TOKEN>'),  wsLazyConnect: false, // connect immediately});

pingIntervalMs

Use pingIntervalMs to tune the WebSocket ping interval (default 5000).

TS
const client = createClient({  url: 'http://localhost:2900',  authProvider,  pingIntervalMs: 15_000,});

disableCompression

By default the server sends gzip-compressed binary WebSocket frames. During development you can disable compression to inspect raw JSON frames in browser DevTools or wscat:

TS
const client = createClient({  url: 'http://localhost:2900',  authProvider,  disableCompression: true, // appends ?compress=false to the WS URL});

When enabled the client appends ?compress=false to the WebSocket URL and the server responds with plain-text JSON frames for every message.

Do not use in production. Compression significantly reduces bandwidth for subscription payloads. Only enable for local debugging.

Initialization behavior

initialize():

  • loads WASM runtime (init(...))
  • resolves initial credentials from authProvider
  • creates underlying WASM KalamClient
  • wires authProvider callback into WASM for WebSocket auth resolution and reconnects
  • calls setDisableCompression(true) on WASM client when option is set
  • if wsLazyConnect: false, establishes the WebSocket connection immediately

If eager initialization hits a connection/auth/bootstrap failure, the SDK emits onConnectionError before rethrowing.

You usually don’t call it manually; most methods initialize lazily.

Disconnect

TS
await client.disconnect();

Notes:

  • disconnect() closes the WebSocket and clears SDK-side subscription tracking.
  • After disconnecting, the next subscribe() call will re-establish the connection.

Full teardown with shutdown()

TS
await client.shutdown();

Use shutdown() when you want to free the underlying WASM client and fully reset local SDK state. This is the stronger cleanup option for long-running Node.js processes, test suites, and explicit resource-management flows.

Reconnection controls

TS
client.setAutoReconnect(true);client.setReconnectDelay(1000, 30000);client.setMaxReconnectAttempts(10); // 0 means infinite console.log(client.getReconnectAttempts());console.log(client.isReconnecting());

setReconnectDelay(initial, max) is passed as BigInt to WASM.

Subscription state helpers

TS
client.getSubscriptionCount();client.getSubscriptions();client.isSubscribedTo('SELECT * FROM app.messages');client.getLastSeqId('<subscription-id>');

These are SDK-level convenience methods around subscription bookkeeping.

Cleanup pattern

TS
try {  // work} finally {  await client.unsubscribeAll();  await client.disconnect();}

Use this pattern in long-running services to avoid leaked subscriptions.

Last updated on