# Reconnection (/sdks/python/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 gRPC channel. 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 setting `auto_reconnect=True` on `ClientConfig` along with `reconnect_initial_delay_ms`, `reconnect_backoff_multiplier`, `reconnect_max_delay_ms`, and `max_reconnect_attempts` to shape the backoff curve. A `KeepAliveConfig` with periodic pings detects a dead connection promptly, so the reconnect logic triggers right away instead of waiting for the next operation to time out. &#x2A;*Gotchas:** `max_reconnect_attempts` is a hard cap — once exhausted, the client raises rather than retrying forever, so size it (or set it high) for how long you expect outages to last; in-flight calls made during the outage window still fail immediately, since the policy governs the *connection*, not individual publishes or requests; and keep-alive pings add background traffic, so tune `ping_interval_in_seconds` down for faster failure detection only if the extra load is acceptable.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Python SDK installed (`pip install kubemq`)

## Code [#code]

```python title="reconnection.py"
"""Example: Reconnection — demonstrate auto-reconnect configuration."""

from __future__ import annotations

import asyncio

from kubemq import ClientConfig, KeepAliveConfig
from kubemq import AsyncPubSubClient, EventMessage


async def main() -> None:
    # Configure client with aggressive reconnection settings
    config = ClientConfig(
        address="localhost:50000",
        client_id="python-error-handling-reconnection-client",
        auto_reconnect=True,
        reconnect_interval_seconds=2,
        max_reconnect_attempts=5,
        reconnect_initial_delay_ms=500,
        reconnect_max_delay_ms=10_000,
        reconnect_backoff_multiplier=2.0,
        keep_alive=KeepAliveConfig(
            enabled=True,
            ping_interval_in_seconds=10,
            ping_timeout_in_seconds=5,
        ),
    )

    try:
        async with AsyncPubSubClient(config=config) as client:
            info = await client.ping()
            print(f"Connected to {info.host}")
            print(f"Auto-reconnect: {config.auto_reconnect}")
            print(f"Max reconnect attempts: {config.max_reconnect_attempts}")
            print(f"Reconnect interval: {config.reconnect_interval_seconds}s")

            # Normal operation
            await client.publish_event(
                EventMessage(
                    channel="python-error-handling.reconnection",
                    body=b"message with reconnection configured",
                )
            )
            print("Message sent successfully")

            # If the server goes down and comes back, the client will
            # automatically reconnect up to max_reconnect_attempts times
            print("Client configured for automatic reconnection on failure")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    asyncio.run(main())

```

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

`ClientConfig` centralizes all reconnection tuning. `auto_reconnect=True` enables automatic gRPC channel recovery. `reconnect_initial_delay_ms` is the first backoff delay; subsequent delays are multiplied by `reconnect_backoff_multiplier` up to `reconnect_max_delay_ms`. `max_reconnect_attempts=5` caps the total number of retries before the client raises. The `KeepAliveConfig` detects dead connections via periodic pings so the reconnect logic triggers promptly after a network partition rather than waiting for the next operation to time out.

## Related [#related]

* [Python SDK Reference](/sdks/python/reference)
* [Connection Error](/sdks/python/how-to/error-handling/connection-error)
* [Graceful Shutdown](/sdks/python/how-to/error-handling/graceful-shutdown)
