LESSON 11 OF 14

11. Reconnection, Error Handling, and a Resilient Client

Learn how to build a resilient SignalR JavaScript client with automatic reconnection, safe error handling, group rejoining, and missed-data synchronization.

55 dk 53

Introduction

A real-time application must not assume that a connection will remain open forever. A user may switch networks, a browser may suspend a background tab, a proxy may time out, or the server may restart. A resilient client detects these situations, communicates the current state clearly, retries at controlled intervals, and synchronizes application data after the connection returns.

In this lesson, you will configure SignalR automatic reconnection, implement a custom retry policy, distinguish connection failures from Hub operation failures, and safely expose expected errors to the user. You will also rejoin a project group and refresh missed task data after reconnection. The examples build on the task dashboard scenario introduced earlier in the course.

Understanding connection states

The JavaScript HubConnection normally moves through four important states:

StateMeaningRecommended application behavior
DisconnectedNo connection exists, or reconnect attempts have ended.Show a retry action or start a controlled retry loop.
ConnectingThe initial connection is being established.Disable operations that require the hub.
ConnectedThe client has an active connection to the server.Allow real-time operations.
ReconnectingThe connection was lost and the client is attempting to recover.Warn the user and temporarily queue or disable operations.

withAutomaticReconnect() uses default delays of 0, 2, 10, and 30 seconds for four reconnect attempts. It handles a dropped established connection, but it does not automatically retry a failed initial start() call. Initial startup failures need separate handling.

Basic client configuration

The following client updates a status element, disables the send button while disconnected, and refreshes the task view when the connection returns. Register handlers before calling start() so that messages cannot arrive before their handlers exist.

const statusElement = document.querySelector("[data-connection-status]");
const sendButton = document.querySelector("[data-send-button]");
const projectId = "project-42";

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/tasks")
    .withAutomaticReconnect()
    .configureLogging(signalR.LogLevel.Information)
    .build();

connection.on("TaskUpdated", task => {
    renderTask(task);
});

connection.onreconnecting(error => {
    setStatus("Connection lost. Reconnecting...", "warning");
    sendButton.disabled = true;
    console.warn("SignalR is reconnecting", error);
});

connection.onreconnected(async connectionId => {
    setStatus("Connection reestablished", "success");
    sendButton.disabled = false;
    await synchronizeAfterReconnect();
    console.info("New connection ID", connectionId);
});

connection.onclose(error => {
    setStatus("Connection closed. Refresh the page or try again.", "error");
    sendButton.disabled = true;
    console.error("SignalR connection closed", error);
});

During onreconnecting, the user should understand that displayed data may be stale. The onreconnected callback indicates that the client has a new connection. From the server's perspective, this is a new connection rather than a continuation of the old one. Previous group membership should therefore be restored explicitly.

Custom retry delays

Different applications need different retry behavior. An operational dashboard may reconnect quickly, while a mobile application may use longer delays to reduce battery and network consumption. Fixed delays can be supplied as an array:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/tasks")
    .withAutomaticReconnect([0, 2000, 10000, 30000])
    .build();

For more control, provide an object with a nextRetryDelayInMilliseconds method. This policy uses exponential backoff with random jitter and stops after 60 seconds:

const retryPolicy = {
    nextRetryDelayInMilliseconds: retryContext => {
        if (retryContext.elapsedMilliseconds >= 60000) {
            return null;
        }

        const baseDelay = Math.min(
            1000 * Math.pow(2, retryContext.previousRetryCount),
            8000
        );

        return Math.floor(Math.random() * baseDelay);
    }
};

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/tasks")
    .withAutomaticReconnect(retryPolicy)
    .build();

Returning null tells the client to stop reconnecting. Random jitter prevents many clients that lost connectivity at the same time from sending retry requests simultaneously and overloading the server.

Handling the initial connection failure

Automatic reconnect applies after an established connection is lost. If the server is unavailable when the page first loads, start() rejects its Promise. A controlled startup loop can handle that situation:

async function startConnection() {
    while (connection.state === signalR.HubConnectionState.Disconnected) {
        try {
            await connection.start();
            setStatus("Connected", "success");
            await synchronizeAfterReconnect();
            return;
        } catch (error) {
            setStatus("Unable to connect. Retrying soon.", "warning");
            console.error("Initial connection failure", error);
            await delay(5000);
        }
    }
}

function delay(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

Production applications should consider a maximum retry period, cancellation, and an offline mode. If the authentication session is invalid, retrying forever is not useful; the user should be sent through the sign-in or token-refresh flow instead.

Safe Hub error handling

When a Hub method fails, the client's invoke call returns a rejected Promise. The connection normally remains open. The client must distinguish an operation error from a connection error:

async function updateTask(taskId, title) {
    try {
        await connection.invoke("UpdateTask", {
            id: taskId,
            title: title
        });
        showToast("Task updated", "success");
    } catch (error) {
        showToast("The task could not be updated. Try again.", "error");
        console.error("UpdateTask failed", error);
    }
}

Use HubException for expected business-rule failures that are safe to communicate to the caller. Unexpected exceptions may contain database names, file paths, or stack traces and should not be exposed to clients.

using Microsoft.AspNetCore.SignalR;

public sealed class TasksHub : Hub
{
    public async Task UpdateTask(UpdateTaskRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Title))
        {
            throw new HubException("The task title cannot be empty.");
        }

        if (request.Title.Length > 120)
        {
            throw new HubException("The task title cannot exceed 120 characters.");
        }

        var task = await taskService.UpdateAsync(request);
        await Clients.Group($"project:{task.ProjectId}")
            .SendAsync("TaskUpdated", task);
    }
}

Keep client-visible messages short, stable, and written for users rather than developers. Detailed errors may be useful in a development environment, but enabling detailed exception messages in production creates an information disclosure risk. Unexpected failures should be logged on the server with a correlation ID while the client receives a generic message.

Rejoining a group after reconnection

SignalR groups are associated with connection IDs. After reconnecting, the client has a new connection, so previous group membership should not be assumed. Rejoin the selected project group from the reconnection flow.

async function joinProjectGroup() {
    await connection.invoke("JoinProject", projectId);
}

async function synchronizeAfterReconnect() {
    try {
        await joinProjectGroup();
        const snapshot = await connection.invoke("GetProjectSnapshot", projectId);
        renderProjectSnapshot(snapshot);
        setStatus("Data synchronized", "success");
    } catch (error) {
        setStatus("Connected, but the data could not be refreshed.", "warning");
        console.error("Synchronization failed", error);
    }
}

connection.onreconnected(async () => {
    await synchronizeAfterReconnect();
});

The server must still authorize the group operation. Never trust a project ID simply because it came from the client. The Hub method should verify that the authenticated user can access the project. This continues the authorization principles covered in the previous lesson.

Refreshing missed data

SignalR is not a durable event queue that stores every broadcast while a browser is disconnected. When the connection returns, showing only a “connected” message is not enough. The client should request a current snapshot or synchronize from a known version.

For a small application, a GetProjectSnapshot Hub method may be sufficient. For a larger system, the client can send the version or sequence number of the last event it processed:

const synchronizationRequest = {
    projectId,
    lastKnownVersion: Number(localStorage.getItem("project-version") || 0)
};

const result = await connection.invoke(
    "SynchronizeProject",
    synchronizationRequest
);

for (const change of result.changes) {
    applyChange(change);
}

localStorage.setItem("project-version", result.currentVersion);

If the server still has the requested change history, it can return only missing changes. If the history is no longer available, it should return a complete snapshot. In both cases, the client should apply changes idempotently. Receiving the same update twice must not create duplicate rows or inconsistent state.

Distinguishing transient and permanent failures

A transient failure may recover without user intervention: a temporary network outage, a proxy interruption, or a server restart are common examples. Automatic reconnect is appropriate for these situations. A permanent failure will not be fixed by retrying, such as an invalid JWT, a denied authorization decision, an incorrect Hub URL, or a removed application endpoint.

  • Transient failure: remain in Reconnecting, inform the user, and use backoff.
  • Authentication failure: attempt token refresh when appropriate; otherwise return to sign-in.
  • Authorization failure: show that the user lacks access instead of retrying indefinitely.
  • Business-rule failure: correct the input and do not automatically repeat the same invalid request.

Without this distinction, a client may repeatedly reconnect with an invalid token, wasting resources and making the user experience worse.

Common mistakes

  • Assuming automatic reconnect is enabled: ASP.NET Core SignalR requires the feature to be opted into explicitly.
  • Treating startup and reconnection as identical: a failed start() call needs its own retry logic.
  • Assuming groups survive reconnection: rejoin required groups after a new connection is established.
  • Rendering raw server errors as HTML: display messages as text and filter sensitive details.
  • Only re-enabling the send button: refresh missed data using a snapshot or version-based synchronization.
  • Using very short fixed retries: apply exponential backoff and jitter to control load.

Practice exercise

Extend the task dashboard with the following behavior:

  1. Configure the connection with withAutomaticReconnect and a custom retry policy.
  2. Show distinct status messages for onreconnecting, onreconnected, and onclose.
  3. Rejoin the selected project group after reconnecting.
  4. Request a project snapshot and replace the task list with the server's current state.
  5. Throw a HubException when a task title is empty and show a safe client-side message.
  6. Use browser developer tools to simulate offline mode, create a server-side change, restore the network, and verify that the client synchronizes the missed data.

The expected result is that the send control is disabled while disconnected, the group is restored after reconnection, and the task list matches the current server state instead of merely showing the last locally cached values.

Conclusion

A resilient SignalR client does more than attempt to reconnect. It exposes connection state, distinguishes transient failures from permanent failures, displays safe user-facing messages, restores group membership, and synchronizes application state after an outage. The onreconnecting, onreconnected, and onclose callbacks are the main UI integration points. HubException communicates expected business-rule failures without exposing unexpected exception details. Finally, snapshot or version-based synchronization ensures that a real-time application remains correct even when the network is unreliable.

Sources