skip to content

In the SignalR JavaScript and .NET clients, what does withAutomaticReconnect() do by default, and what does a reconnect not give back?

level: middleimportance: must knowfreq 60%

answer

  1. off unless you opt in
  2. 0, 2, 10, 30 seconds, then stop
  3. Reconnecting state and onreconnecting
  4. onreconnected gets a new connectionId
  5. first start() is never retried

basics

~20 s

SignalR clients do not reconnect unless you call withAutomaticReconnect(). By default it waits 0, 2, 10 and 30 seconds before four attempts, then closes. A successful reconnect is a new connection with a new connection id; pending calls and server-side per-connection state are gone.

solid answer

~40 s

Without `withAutomaticReconnect()` (`WithAutomaticReconnect()` in .NET) a dropped connection goes straight to `Disconnected` and fires `onclose` / `Closed`. With it, the client moves to `Reconnecting`, fires `onreconnecting` / `Reconnecting`, and retries after 0, 2, 10 and 30 seconds; on success it returns to `Connected` and fires `onreconnected` / `Reconnected` with the new connection id, otherwise it ends in `Disconnected` and fires `onclose`. Delays can be an array of milliseconds (a `TimeSpan[]` in .NET) or an `IRetryPolicy` whose `nextRetryDelayInMilliseconds` / `NextRetryDelay` returns `null` to stop. What a reconnect does not restore: invocations that were pending, which were rejected; messages sent while it was down; and anything the server tied to the old connection id, such as group membership, which the client must re-establish in `onreconnected`. It also never retries a failed initial `start()`.

code

javascript · 18 lines
javascript
const connection = new signalR.HubConnectionBuilder()
  .withUrl("/ticker")
  .withAutomaticReconnect()          // 0, 2, 10, 30 s, then onclose
  .build();

connection.onreconnecting(error => {
  setBanner("Reconnecting...");
  markPricesStale();
});

connection.onreconnected(async connectionId => {
  setBanner("");
  // New connection: server-side state is gone, so rejoin and refetch.
  const snapshot = await connection.invoke("Subscribe", watchedSymbols);
  render(snapshot);
});

connection.onclose(() => setBanner("Disconnected. Reload to retry."));

go deeper

for a junior

Remember that reconnecting is off until you call withAutomaticReconnect(), and that the defaults try four times, at 0, 2, 10 and 30 seconds.

for a middle

Walk through the Reconnecting, Connected and Disconnected transitions with their callbacks, and how arrays or IRetryPolicy change the schedule.

for a senior

List what is lost across a reconnect (connection id, server state, pending calls, missed pushes) and design rejoin, refetch and first-start retry around it.

for a principal

Decide the reconnect budget per client type: an interactive page may give up and ask for a reload, a kiosk must retry forever with back-off.

## Off by default A SignalR client that loses its connection does **not** try again on its own. Without configuration, the `HubConnection` moves to `Disconnected` and fires its close callbacks (`onclose` in JavaScript, the `Closed` event in .NET). Opting in is one builder call: ```javascript const connection = new signalR.HubConnectionBuilder() .withUrl("/ticker") .withAutomaticReconnect() .build(); ``` The .NET client uses `.WithAutomaticReconnect()` on `HubConnectionBuilder`. ## The default schedule With no arguments, the client waits **0, 2, 10 and 30 seconds** before its four attempts (the JavaScript default policy is `[0, 2000, 10000, 30000, null]`; the trailing `null` means stop). The sequence of events: 1. The transport drops. Pending `invoke` calls are rejected. 2. The connection enters **`Reconnecting`** and fires `onreconnecting(error)` / `Reconnecting`. It does **not** fire `onclose` yet. 3. Each attempt runs the whole start again: negotiate, transport, handshake. 4. On success: back to **`Connected`**, and `onreconnected(connectionId)` / `Reconnected` fires with the **new** connection id. The server sees an entirely new connection. 5. After the last failed attempt: **`Disconnected`**, and `onclose` / `Closed` fires. ## Custom schedules | Form | JavaScript | .NET | |---|---|---| | fixed delays | `withAutomaticReconnect([0, 1000, 5000])` | `WithAutomaticReconnect(new[] { TimeSpan.Zero, ... })` | | a policy object | `IRetryPolicy.nextRetryDelayInMilliseconds(retryContext)` | `IRetryPolicy.NextRetryDelay(RetryContext)` returning `TimeSpan?` | The retry context carries `previousRetryCount`, `elapsedMilliseconds` and `retryReason` (`PreviousRetryCount`, `ElapsedTime` and `RetryReason` in .NET). Returning `null` stops reconnecting. A policy can retry forever with a capped, jittered back-off, or give up after a time budget. ## What a reconnect does not give back - **The connection id.** The new connection has a new id, so anything keyed by the old id on the server is stale. - **Server-side per-connection state**: `Context.Items`, group membership and any presence record keyed by connection id. The usual pattern is to rejoin in `onreconnected` by calling a hub method such as `Subscribe(symbols)`; how the server tracks groups is a server-side topic. - **Pending calls.** In-flight `invoke` calls were rejected when the connection closed; nothing replays them. - **Missed pushes.** Prices the server sent while the client was away are not buffered for it. The dashboard should fetch a fresh snapshot after reconnecting. Stateful reconnect (an opt-in .NET 8 feature) narrows this gap for short WebSocket drops. ## What it never covers: the first start `withAutomaticReconnect()` applies only to a connection that was once `Connected`. If the initial `start()` / `StartAsync()` fails, it throws and the connection stays `Disconnected`. Wrap the first start in a loop: ```csharp while (true) { try { await connection.StartAsync(token); break; } catch when (!token.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(5), token); } } ``` And after the policy gives up, `Closed` is the place to schedule a fresh `StartAsync`, which is how an unattended kiosk keeps trying all day. ## States across the two clients Both clients expose `state` / `State` with `Disconnected`, `Connecting`, `Connected` and `Reconnecting`; the JavaScript enum also has `Disconnecting`. The UI should key off these: in the ticker dashboard, `onreconnecting` greys out prices and shows "reconnecting", `onreconnected` refetches and rejoins, and `onclose` offers a reload.

  • How would you make an unattended .NET kiosk retry forever without hammering the server?
    Implement `IRetryPolicy.NextRetryDelay(RetryContext)` to return an exponential delay based on `PreviousRetryCount`, capped at a minute or two, plus random jitter, and never `null`. Pass it to `WithAutomaticReconnect(policy)`. Separately loop the first `StartAsync`, which the policy never covers, and restart from the `Closed` handler if the connection ever stops.
  • Why does onreconnected receive a connection id at all?
    Because it is a new one: the server treats a reconnect as a brand-new connection and assigns a new id. Code that registered the old id with the server, or that excludes itself by id, must use the new value. The JavaScript docs note the id is `undefined` when negotiation is skipped.

Automatic reconnect is a phone that redials after the call drops: it tries a few times on a fixed schedule, but each successful redial is a brand-new call, so the other side does not remember what was said or who was on the conference line.

  • SignalR clients reconnect automatically even without withAutomaticReconnect().
  • withAutomaticReconnect() keeps retrying forever by default.
  • After a reconnect the client keeps its old connection id.
  • Group membership survives a reconnect because the user is the same.
  • withAutomaticReconnect() also retries a failed initial start().