> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/iii-hq/sdk/llms.txt
> Use this file to discover all available pages before exploring further.

# ReconnectionConfig

> Configure WebSocket reconnection behavior

The `ReconnectionConfig` type controls how the III SDK reconnects to the engine when the WebSocket connection is lost.

## Type Definition

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    interface ReconnectionConfig {
      initialDelayMs: number
      maxDelayMs: number
      backoffMultiplier: number
      jitterFactor: number
      maxRetries: number
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    @dataclass
    class ReconnectionConfig:
        initial_delay_ms: int = 1000
        max_delay_ms: int = 30000
        backoff_multiplier: float = 2.0
        jitter_factor: float = 0.3
        max_retries: int = -1
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    pub struct ReconnectionConfig {
        pub initial_delay_ms: u64,
        pub max_delay_ms: u64,
        pub backoff_multiplier: f64,
        pub jitter_factor: f64,
        pub max_retries: Option<u64>,  // None for infinite
        pub max_pending_messages: usize,
    }
    ```
  </Tab>
</Tabs>

## Fields

<ParamField name="initialDelayMs" type="number" default="1000">
  Starting delay in milliseconds before the first reconnection attempt.

  Each subsequent retry will use exponential backoff based on `backoffMultiplier`.
</ParamField>

<ParamField name="maxDelayMs" type="number" default="30000">
  Maximum delay cap in milliseconds between reconnection attempts.

  Even with exponential backoff, the delay will never exceed this value.
</ParamField>

<ParamField name="backoffMultiplier" type="number" default="2">
  Exponential backoff multiplier for calculating delay between retries.

  The delay is calculated as: `initialDelayMs * (backoffMultiplier ^ attempt)`

  **Example**: With `initialDelayMs=1000` and `backoffMultiplier=2`:

  * Attempt 1: 1000ms
  * Attempt 2: 2000ms
  * Attempt 3: 4000ms
  * Attempt 4: 8000ms
  * etc.
</ParamField>

<ParamField name="jitterFactor" type="number" default="0.3">
  Random jitter factor (0-1) to prevent thundering herd problem.

  Adds randomness to the delay: `delay ± (delay * jitterFactor * random(-1, 1))`

  **Example**: With `jitterFactor=0.3` and calculated delay of 4000ms:

  * Actual delay will be between 2800ms and 5200ms
</ParamField>

<ParamField name="maxRetries" type="number" default="-1">
  Maximum number of retry attempts before giving up.

  * `-1` or `None` (Rust): Infinite retries (never give up)
  * `0`: No retries (fail immediately)
  * `> 0`: Retry up to this many times
</ParamField>

<ParamField name="maxPendingMessages" type="number" default="1000">
  **Rust only**: Maximum number of messages to preserve across reconnects.

  Messages beyond this limit are dropped to prevent delivering stale data after a long disconnect.
</ParamField>

## Default Configuration

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const DEFAULT_RECONNECTION_CONFIG: ReconnectionConfig = {
      initialDelayMs: 1000,
      maxDelayMs: 30000,
      backoffMultiplier: 2,
      jitterFactor: 0.3,
      maxRetries: -1  // infinite
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    DEFAULT_RECONNECTION_CONFIG = ReconnectionConfig(
        initial_delay_ms=1000,
        max_delay_ms=30000,
        backoff_multiplier=2.0,
        jitter_factor=0.3,
        max_retries=-1  # infinite
    )
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    impl Default for ReconnectionConfig {
        fn default() -> Self {
            Self {
                initial_delay_ms: 1000,
                max_delay_ms: 30000,
                backoff_multiplier: 2.0,
                jitter_factor: 0.3,
                max_retries: None,  // infinite
                max_pending_messages: 1000,
            }
        }
    }
    ```
  </Tab>
</Tabs>

## Usage Examples

### Fast Reconnection

For local development or low-latency requirements:

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const iii = init('ws://localhost:49134', {
      reconnectionConfig: {
        initialDelayMs: 100,
        maxDelayMs: 5000,
        backoffMultiplier: 1.5,
        jitterFactor: 0.2,
        maxRetries: -1
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    iii = III('ws://localhost:49134', InitOptions(
        reconnection_config=ReconnectionConfig(
            initial_delay_ms=100,
            max_delay_ms=5000,
            backoff_multiplier=1.5,
            jitter_factor=0.2,
            max_retries=-1
        )
    ))
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    let reconnection = ReconnectionConfig {
        initial_delay_ms: 100,
        max_delay_ms: 5000,
        backoff_multiplier: 1.5,
        jitter_factor: 0.2,
        max_retries: None,
        max_pending_messages: 1000,
    };

    let config = OtelConfig {
        reconnection_config: Some(reconnection),
        ..Default::default()
    };

    let iii = III::new("ws://localhost:49134");
    iii.set_otel_config(config);
    ```
  </Tab>
</Tabs>

### Limited Retries

For batch jobs or scripts that should fail fast:

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const iii = init('ws://localhost:49134', {
      reconnectionConfig: {
        initialDelayMs: 1000,
        maxDelayMs: 10000,
        backoffMultiplier: 2,
        jitterFactor: 0.3,
        maxRetries: 5  // Give up after 5 attempts
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    iii = III('ws://localhost:49134', InitOptions(
        reconnection_config=ReconnectionConfig(
            initial_delay_ms=1000,
            max_delay_ms=10000,
            backoff_multiplier=2.0,
            jitter_factor=0.3,
            max_retries=5  # Give up after 5 attempts
        )
    ))
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    let reconnection = ReconnectionConfig {
        initial_delay_ms: 1000,
        max_delay_ms: 10000,
        backoff_multiplier: 2.0,
        jitter_factor: 0.3,
        max_retries: Some(5),  // Give up after 5 attempts
        max_pending_messages: 1000,
    };
    ```
  </Tab>
</Tabs>

### No Automatic Reconnection

For testing or manual connection management:

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const iii = init('ws://localhost:49134', {
      reconnectionConfig: {
        initialDelayMs: 1000,
        maxDelayMs: 1000,
        backoffMultiplier: 1,
        jitterFactor: 0,
        maxRetries: 0  // Never retry
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    iii = III('ws://localhost:49134', InitOptions(
        reconnection_config=ReconnectionConfig(
            initial_delay_ms=1000,
            max_delay_ms=1000,
            backoff_multiplier=1.0,
            jitter_factor=0.0,
            max_retries=0  # Never retry
        )
    ))
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    let reconnection = ReconnectionConfig {
        initial_delay_ms: 1000,
        max_delay_ms: 1000,
        backoff_multiplier: 1.0,
        jitter_factor: 0.0,
        max_retries: Some(0),  // Never retry
        max_pending_messages: 1000,
    };
    ```
  </Tab>
</Tabs>

## Connection State Monitoring

You can monitor connection state changes to react to reconnection events:

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    // Connection states: 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed'

    iii.onConnectionStateChange((state) => {
      console.log('Connection state:', state)
      
      if (state === 'reconnecting') {
        console.log('Attempting to reconnect...')
      } else if (state === 'connected') {
        console.log('Reconnected successfully!')
      } else if (state === 'failed') {
        console.error('Max retries exceeded, connection failed')
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    def on_state_change(state: str):
        print(f'Connection state: {state}')
        
        if state == 'reconnecting':
            print('Attempting to reconnect...')
        elif state == 'connected':
            print('Reconnected successfully!')
        elif state == 'failed':
            print('Max retries exceeded, connection failed')

    iii.on_connection_state_change(on_state_change)
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    // Connection state is tracked internally
    // Monitor via logs with the tracing crate
    ```
  </Tab>
</Tabs>

## Behavior During Reconnection

### Message Queueing

When the connection is lost:

1. Outgoing messages are queued in memory
2. On reconnect, all registrations (functions, triggers, services) are re-sent
3. Queued invocations are sent after reconnection
4. Duplicate registrations are automatically deduplicated

### Pending Invocations

Active function invocations during disconnect:

* **TypeScript/Python**: Remain pending, will timeout if not completed within `invocationTimeoutMs`
* **Rust**: Subject to `max_pending_messages` limit, excess messages are dropped

### State Preservation

* ✅ Function registrations
* ✅ Trigger registrations
* ✅ Service registrations
* ✅ Trigger type handlers
* ❌ Active WebSocket connections (channels)
* ❌ In-flight HTTP streaming responses

## Best Practices

1. **Production environments**: Use default config with infinite retries
2. **Development**: Reduce delays for faster feedback
3. **Batch jobs**: Limit retries to fail fast
4. **High-traffic**: Increase `jitterFactor` to prevent thundering herd
5. **Monitoring**: Always monitor connection state in production

## Related

* [InitOptions](/api/config/init-options)
* [Reconnection Guide](/guides/reconnection)
* [Error Handling](/guides/error-handling)
