Full answer
Clarify first: how fast must a notification arrive (seconds or a minute), how many users are connected, whether the client must send messages back, and what happens when the user is offline.
Transport choice:
- Polling (
timer(0, 30000)plus an HTTP call): simplest, works through every proxy and cache, easy to scale. Cost: delay and wasted requests. Good when a minute of delay is fine. - Server-sent events (SSE,
EventSource): one-way push over a normal HTTP connection. Browser reconnects automatically and sendsLast-Event-ID, so the server can resume. Works well through HTTP/2. Good for notifications and live feeds. Limits: text only, one direction, andEventSourcecannot set headers (use cookies or a token in the URL carefully). - WebSocket: two-way, low latency, binary support. Needs sticky routing or a message broker, heartbeats and manual reconnect. Choose it for chat, collaboration or when the client sends frequent messages.
Back end shape (briefly): the server writes notifications to a database, and publishes events to a broker (Redis, Kafka) so any instance can push to the user's connection. History and unread count come from normal REST endpoints.
Angular design:
NotificationService(root) owns the connection. It exposesunread = signal(0)andincoming$(Observable, shared). Components never open sockets.- Start the connection after login, close it on logout. Use RxJS
webSocket()or anObservablethat wrapsEventSource, withretryand exponential backoff and jitter, and a cap. - Initial state: load the last items and the unread count by HTTP, then merge live items (de-duplicate by id, because an item can arrive twice).
- UI: a bell button with
aria-live="polite"count, a panel with@forandtrack id, mark as read (optimistic update with rollback), and a "new items" toast throughLiveAnnouncerfor screen readers. - Efficiency: pause or slow down when the tab is hidden (
visibilitychange), run the socket outside the Angular zone if messages are frequent, and batch updates so the UI refreshes at most once per animation frame. - Multiple tabs: use
BroadcastChannelor aSharedWorkerto share one connection. - Failure: show a small "reconnecting" state, fall back to polling if the connection keeps failing, and replay missed items after reconnect using the last id.
Name the trade-offs openly: SSE is the simplest correct choice for one-way notifications, WebSocket is justified by two-way needs, and polling is a fine start.
import { Injectable, computed, signal } from '@angular/core';
import { Observable, Subscription, retry, timer } from 'rxjs';
export interface AppNotification {
id: number;
text: string;
read: boolean;
}
@Injectable({ providedIn: 'root' })
export class NotificationService {
private readonly items = signal<AppNotification[]>([]);
readonly list = this.items.asReadonly();
readonly unread = computed(() => this.items().filter((n) => !n.read).length);
private connection?: Subscription;
load(history: AppNotification[]): void {
this.items.set([...history].sort((a, b) => b.id - a.id));
}
connect(source: () => Observable<AppNotification>): void {
this.connection?.unsubscribe();
this.connection = source()
.pipe(retry({ delay: (_error, attempt) => timer(Math.min(30000, 500 * 2 ** attempt) + Math.random() * 250) }))
.subscribe((n) => this.add(n));
}
add(n: AppNotification): void {
this.items.update((list) => (list.some((x) => x.id === n.id) ? list : [n, ...list]));
}
markRead(id: number): void {
this.items.update((list) => list.map((n) => (n.id === id ? { ...n, read: true } : n)));
}
disconnect(): void {
this.connection?.unsubscribe();
}
}Angular 20.3 and RxJS 7.8, type-checked. The service logic (merge, de-duplicate, unread count) was run with a fake stream in a Karma test. No real WebSocket or EventSource server was available.
Key points
- Polling is simplest, SSE is one-way push with auto reconnect, WebSocket is two-way. Pick by need.
- One root service owns the connection and exposes a signal and a stream.
- Backoff with jitter, de-duplicate by id, resume with the last id, pause in hidden tabs.
- Load history by REST, and make the UI accessible with live regions.
Common mistakes
- Opening a WebSocket in every component.
- Reconnecting immediately in a tight loop after a failure.
- Showing duplicates after a reconnect.
Follow-ups
- How does `Last-Event-ID` help after a reconnect?
- How would you share one connection between browser tabs?
- When would you choose WebSocket over SSE?
Tips
- Ask about latency and direction first.
- Compare the three transports in one sentence each.
- Mention backoff, duplicates and accessibility.
Evaluation rubric
- Chooses a transport with reasons.
- Designs a service with state, reconnect and de-duplication.
- Covers UI, accessibility and efficiency.