Course contentsShow
← C#
Lesson 1464 of 1,90813. Real-time Communication with SignalRFree lesson

Client-Side Reconnection Strategies

Configure exponential backoff and custom reconnection policies to ensure client robustness.

In this lesson, you will learn how to implement custom exponential backoff policies to ensure your SignalR client remains resilient during intermittent network instability.

By default, a SignalR client attempts to reconnect immediately upon failure, which can inadvertently create a "thundering herd" effect—where your server is overwhelmed by thousands of clients retrying simultaneously. To prevent this, you should implement an exponential backoff strategy, which gradually increases the delay between each reconnection attempt.

Configuring Exponential Backoff

In your C# client setup, you define this behavior by providing an implementation of IRetryPolicy when building your HubConnection. The RetryContext object allows you to inspect the number of attempts and the total elapsed time, enabling you to calculate custom wait intervals.

public class MyRetryPolicy : IRetryPolicy
{
    public TimeSpan? NextRetryDelay(RetryContext retryContext)
    {
        // If we've been trying for more than 30 seconds, give up
        if (retryContext.ElapsedTime > TimeSpan.FromSeconds(30))
        {
            return null;
        }

        // Exponential backoff: 0s, 2s, 4s, 8s, 16s...
        return TimeSpan.FromSeconds(Math.Pow(2, retryContext.PreviousRetryCount));
    }
}

// Applying the policy
var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/myhub")
    .WithAutomaticReconnect(new MyRetryPolicy())
    .Build();

Why Custom Policies Matter

The built-in default policy is sufficient for simple applications, but advanced scenarios require granular control. For example, if your application runs on mobile devices, a network-heavy retry loop can drain the battery. By using a custom policy, you can introduce "jitter" (randomizing the delay) to spread out the server load or stop retrying altogether once a specific ElapsedTime threshold is crossed, allowing your client to gracefully transition into a "disconnected" state where it can prompt the user to manually refresh.

When configuring these strategies, always consider the balance between user experience—waiting too long for a reconnect—and server stability. A well-designed policy ensures that your application remains robust without contributing to cascading failures under heavy traffic.

Key Takeaway: Implementing a custom IRetryPolicy with exponential backoff prevents server congestion and preserves client resources during periods of network instability.