Skip to main content

Automatic Reconnect

The HiveMQ MQTT client provides automatic reconnection functionality that allows the client to automatically recover from unexpected disconnections. This feature is disabled by default and must be explicitly enabled.

Enabling Automatic Reconnect​

var options = new HiveMQClientOptionsBuilder()
.WithBroker("broker.hivemq.com")
.WithAutomaticReconnect(true)
.Build();

var client = new HiveMQClient(options);
await client.ConnectAsync();

Backoff Strategy​

The automatic reconnect uses an exponential backoff strategy:

AttemptDelay
1st5 seconds
2nd10 seconds
3rd20 seconds
4th40 seconds
5th+60 seconds (maximum)

The client will continue attempting to reconnect indefinitely until successful.

Monitoring Reconnection​

Use events to track reconnection status:

var client = new HiveMQClient(options);

// Triggered when reconnected successfully
client.AfterConnect += (sender, args) =>
{
Console.WriteLine($"Connected/Reconnected: {args.ConnectResult.ReasonCode}");
};

// Triggered when disconnected (before reconnect attempts begin)
client.AfterDisconnect += (sender, args) =>
{
if (!args.CleanDisconnect)
{
Console.WriteLine("Unexpected disconnection - reconnection will be attempted");
}
};

await client.ConnectAsync();

Re-subscribing After Reconnect​

Important

After reconnection, you may need to re-subscribe to topics depending on your session configuration. If using CleanStart = true, subscriptions are not preserved across reconnections.

client.AfterConnect += async (sender, args) =>
{
// Re-subscribe after reconnection
await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery);
};

When to Use​

ScenarioRecommendation
IoT devices with unstable networksEnable
Long-running servicesEnable
Short-lived connectionsUsually not needed
Custom reconnect logic requiredDisable and implement your own

See Also​