Full answer
Real-time features (live results, notifications, chat) use a WebSocket. Connections drop on bad networks, laptop sleep, and server restarts, so reconnecting is part of the feature.
Design with RxJS:
- Source: RxJS
webSocket(url)returns aWebSocketSubject. It connects when subscribed, emits incoming messages, and closes the socket on unsubscribe. An error or an unexpected close ends the stream with an error or a complete. - Reconnect:
retryresubscribes to its source on error. To get a new socket on each attempt, build the source withdefer(() => webSocket(url)), since a closedWebSocketSubjectcannot be reused in some cases. - Backoff:
retry({ delay: (error, attempt) => timer(min(base * 2 ** (attempt - 1), max)) }). Add random jitter in production so thousands of clients do not reconnect at the same moment. - Reset: after a successful connection the attempt counter should return to 1, or a user who had five failures last week would wait the maximum delay today.
retry({ resetOnSuccess: true })resets the count when the source emits a value. - Clean close: a
completefrom the server (a normal close) can also triggerrepeat, if you want to reconnect, and an intentional close from the app is justunsubscribe. - Sharing:
share()makes one socket serve many subscribers, and closes it when the last one leaves.shareReplay({ bufferSize: 1, refCount: true })also gives late subscribers the latest message. - Component use:
toSignal(stream$), ortakeUntilDestroyed()withsubscribe, which closes the socket when the component is destroyed. - Connection state: expose a signal such as
connected, via theopenObserverandcloseObserveroptions ofwebSocket, so the UI can show "reconnecting...". Heartbeats (a ping every 30 seconds with a timeout) detect half-open connections that the browser does not report.
Security: use wss://, authenticate with a short-lived ticket in the first message or in a cookie, not with a long-lived token in the URL, since URLs end up in logs.
typescript
// file: reconnect.ts
import { Observable, defer, retry, timer } from 'rxjs';
export interface ReconnectOptions {
baseMs?: number;
maxMs?: number;
jitter?: boolean;
onWait?: (attempt: number, waitMs: number) => void;
}
export function reconnecting<T>(connect: () => Observable<T>, options: ReconnectOptions = {}): Observable<T> {
const { baseMs = 1000, maxMs = 30000, jitter = true, onWait } = options;
return defer(connect).pipe(
retry({
resetOnSuccess: true,
delay: (_error, attempt) => {
const exp = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
const wait = jitter ? Math.round(exp / 2 + Math.random() * (exp / 2)) : exp;
onWait?.(attempt, wait);
return timer(wait);
},
}),
);
}
// file: live-results.service.ts
import { Injectable, signal } from '@angular/core';
import { shareReplay } from 'rxjs';
import { webSocket } from 'rxjs/webSocket';
import { reconnecting } from './reconnect';
export interface ResultMessage {
student: string;
marks: number;
}
@Injectable({ providedIn: 'root' })
export class LiveResultsService {
readonly connected = signal(false);
readonly results$ = reconnecting<ResultMessage>(
() =>
webSocket<ResultMessage>({
url: 'wss://example.com/results',
openObserver: { next: () => this.connected.set(true) },
closeObserver: { next: () => this.connected.set(false) },
}),
{ baseMs: 1000, maxMs: 30000 },
).pipe(shareReplay({ bufferSize: 1, refCount: true }));
}
// file: main.ts
import { Observable, Subscriber } from 'rxjs';
import { reconnecting } from './reconnect.ts';
let attempts = 0;
const flakySource = (): Observable<string> =>
new Observable((subscriber: Subscriber<string>) => {
attempts++;
const current = attempts;
const timer = setTimeout(() => {
if (current < 3) {
subscriber.error(new Error(`connection ${current} dropped`));
} else {
subscriber.next(`message from connection ${current}`);
subscriber.complete();
}
}, 5);
return () => clearTimeout(timer);
});
reconnecting(flakySource, { baseMs: 10, maxMs: 100, jitter: false, onWait: (n, ms) => console.log(`attempt ${n} failed, waiting ${ms} ms`) }).subscribe({
next: (m) => console.log(m),
complete: () => console.log('done after', attempts, 'connections'),
});RxJS 7.8 and Angular 20.3. The `reconnecting` function is generic over its source. It was run in Node 24 against a fake source that fails twice and then emits, twice with the same output (delays 10, 20 ms). The `webSocket` usage in the Angular service is type-checked, but not run against a real server here.
Key points
- `defer` makes a fresh socket for each attempt.
- `retry` with a delay function gives exponential backoff. `resetOnSuccess` restarts the count after success. Add jitter.
- `share` or `shareReplay` with `refCount` serve many consumers with one socket and close it when unused.
- `takeUntilDestroyed` or `toSignal` handles cleanup. Add heartbeats and a connection state signal.
Common mistakes
- Retrying immediately in a loop with no delay, flooding the server.
- Reusing a closed socket for retry instead of creating a new one.
- Putting a long-lived token in the WebSocket URL.
Follow-ups
- How do you detect a half-open connection?
- How would you resend messages the client tried to send while disconnected?
- Why use `refCount: true` with `shareReplay`?
Tips
- Explain why `defer` is needed. Many candidates miss it.
- Name the reset problem (`resetOnSuccess`).
- Mention jitter and heartbeats.
Evaluation rubric
- Builds reconnect with backoff, reset, and cleanup.
- Shares one connection correctly.
- Considers state, heartbeats, and security.