# Reconnection (/sdks/nodejs/how-to/error-handling/reconnection)



## Overview [#overview]

Production connections drop for reasons that have nothing to do with your application code: the broker restarts during a rolling upgrade, a load balancer fails over, a network blip severs the connection. Without built-in reconnection, every client in your fleet needs its own hand-rolled retry-connect loop, and it's easy to get the backoff wrong — too aggressive and you hammer a recovering broker, too slow and you leave the application dark longer than necessary. Automatic reconnection moves that logic into the client itself, so the connection self-heals without any code the application has to write or maintain.

It works by passing a `reconnect` option to `KubeMQClient.create()` — `initialDelayMs`, `multiplier`, `maxDelayMs`, `maxAttempts`, and `jitter: 'full'` to randomize retry timing and avoid a thundering herd when many clients reconnect at once. The client emits lifecycle events (`'connected'`, `'disconnected'`, `'reconnecting'`, `'reconnected'`, `'stateChange'`, `'closed'`) that the application can subscribe to via `client.on(...)` for diagnostics, and `client.state` exposes the current state on demand. &#x2A;*Gotchas:** event handlers run on the client's event loop, so blocking work inside one stalls further processing; in-flight `sendEvent` calls made during the outage window still fail immediately — the policy governs the *connection*, not individual calls; and `maxAttempts: -1` (unlimited) will retry forever against a broker that's gone for good, so pair it with alerting on the `'reconnecting'` event's attempt counter rather than assuming it will eventually succeed.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Node.js SDK installed (`npm install kubemq-js`)

## Code [#code]

```typescript title="reconnection.ts"
/**
 * Example: Automatic Reconnection with Backoff
 *
 * Demonstrates how the SDK automatically reconnects when the connection
 * is lost. The reconnection policy uses exponential backoff with jitter
 * to avoid thundering herd problems.
 *
 * Prerequisites:
 *   - KubeMQ server running on localhost:50000
 *
 * Run: npx tsx examples/error-handling/reconnection.ts
 */
import { KubeMQClient, ConnectionState, createEventMessage } from 'kubemq-js';

async function main(): Promise<void> {
  const client = await KubeMQClient.create({
    address: 'localhost:50000',
    clientId: 'js-error-handling-reconnection-client',
    // Configure reconnection behavior.
    reconnect: {
      maxAttempts: 10, // -1 for unlimited attempts
      initialDelayMs: 500, // first retry after ~500ms
      maxDelayMs: 30_000, // cap backoff at 30 seconds
      multiplier: 2.0, // double delay each attempt
      jitter: 'full', // randomize to avoid thundering herd
    },
  });

  try {
    // Listen for connection lifecycle events.
    client.on('connected', () => {
      console.log('[Event] Connected');
    });

    client.on('disconnected', () => {
      console.log('[Event] Disconnected');
    });

    client.on('reconnecting', (attempt: number) => {
      console.log(`[Event] Reconnecting (attempt ${attempt})...`);
    });

    client.on('reconnected', () => {
      console.log('[Event] Reconnected successfully');
    });

    client.on('stateChange', (state: ConnectionState) => {
      console.log(`[Event] State changed to: ${state}`);
    });

    client.on('closed', () => {
      console.log('[Event] Client closed');
    });

    // Publish some events to verify the connection is working.
    for (let i = 1; i <= 3; i++) {
      await client.sendEvent(
        createEventMessage({
          channel: 'js-error-handling.reconnection',
          body: `heartbeat-${i}`,
        }),
      );
      console.log(`Published heartbeat #${i}`);
    }

    console.log('\nConnection is active. Current state:', client.state);
    console.log('If the server restarts, the SDK will automatically reconnect.');
    console.log('Waiting 10 seconds to observe any reconnection events...');

    await new Promise((resolve) => setTimeout(resolve, 10_000));
  } finally {
    await client.close();
    console.log('Client closed. Final state:', client.state);
  }
}

main().catch(console.error);

```

## How It Works [#how-it-works]

* The `reconnect` option on `KubeMQClient.create()` enables automatic exponential-backoff reconnection: `initialDelayMs` sets the first retry wait, `multiplier` doubles it each attempt, and `jitter: 'full'` adds randomization to prevent thundering-herd storms.
* The SDK emits lifecycle events (`'connected'`, `'disconnected'`, `'reconnecting'`, `'reconnected'`, `'stateChange'`, `'closed'`) so the application can log diagnostics without polling `client.state`.
* `client.on('reconnecting', (attempt) => ...)` passes the zero-based attempt counter, letting you implement adaptive alerting (e.g. warn after attempt 3, page after attempt 7).
* When `maxAttempts: -1` (unlimited), the SDK keeps retrying indefinitely — useful in long-running services that must survive extended server outages.

## Related [#related]

* [Node.js SDK Reference](/sdks/nodejs/reference)
* [Connection Error](/sdks/nodejs/how-to/error-handling/connection-error)
* [Graceful Shutdown](/sdks/nodejs/how-to/error-handling/graceful-shutdown)
