KubeMQ
Client SDKsC#How-to guidesError Handling

Reconnection

Automatically reconnect a KubeMQ C# client after a disconnection, restoring messaging without manual intervention.

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 setting ReconnectOptions on KubeMQClientOptionsInitialDelay, BackoffMultiplier, MaxDelay, and MaxAttempts shape the backoff curve. The client.StateChanged event fires on every transition with PreviousState, CurrentState, and a Timestamp, giving a full audit trail without polling client.State. Gotchas: StateChanged handlers run synchronously on the client's internal thread, so blocking work inside one stalls reconnection itself; in-flight calls issued during the outage window still fail immediately — the policy governs the connection, not individual requests; and MaxAttempts is a hard cap — once exhausted, reconnection stops and the application must surface the error and decide whether to reconnect manually, rather than assuming the client will keep trying forever.

Prerequisites

  • KubeMQ server running on localhost:50000
  • C# SDK installed (dotnet add package KubeMQ.SDK.CSharp)

Code

Program.cs
// KubeMQ .NET SDK — ErrorHandling: Reconnection
//
// This example demonstrates the auto-reconnection behavior.
// The SDK can automatically reconnect when the connection is lost,
// using configurable backoff. The StateChanged event reports transitions.
//
// Prerequisites:
//   - KubeMQ server running on localhost:50000
//   - dotnet run
//   - (Optional) stop/restart the server to observe reconnection behavior

using KubeMQ.Sdk.Client;
using KubeMQ.Sdk.Config;

var options = new KubeMQClientOptions
{
    Address = "localhost:50000",
    ClientId = "csharp-errorhandling-reconnection-client",

    // Configure auto-reconnection
    Reconnect = new ReconnectOptions
    {
        Enabled = true,
        MaxAttempts = 10,
        InitialDelay = TimeSpan.FromSeconds(1),
        MaxDelay = TimeSpan.FromSeconds(15),
        BackoffMultiplier = 2.0,
    },
};

await using var client = new KubeMQClient(options);

// Subscribe to connection state changes
client.StateChanged += (_, args) =>
{
    Console.WriteLine($"[State] {args.PreviousState} -> {args.CurrentState} at {args.Timestamp:HH:mm:ss}");
    if (args.Error is not null)
    {
        Console.WriteLine($"  Error: {args.Error.Message}");
    }
};

try
{
    await client.ConnectAsync();
    Console.WriteLine($"Connected. Current state: {client.State}");
    Console.WriteLine("Monitoring connection state for 15 seconds...");
    Console.WriteLine("(Stop/restart the KubeMQ server to observe reconnection)");

    await Task.Delay(TimeSpan.FromSeconds(15));
    Console.WriteLine($"Final state: {client.State}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Console.WriteLine("Done.");

How It Works

  • client.StateChanged is a C# event that fires on every connection state transition; args.PreviousState, args.CurrentState, and args.Timestamp give a full audit trail.
  • ReconnectOptions.BackoffMultiplier = 2.0 doubles the delay after each failed attempt, capped at MaxDelay; this prevents overwhelming a recovering server.
  • MaxAttempts = 10 stops reconnection after 10 consecutive failures, allowing the application to surface the error rather than retry indefinitely.
  • Stop and restart the KubeMQ server process while the program is running to observe the StateChanged transitions in real time.

Was this page helpful?

On this page