← Back to Angular, page 10

angular-0190 · Hard senior

Design a real-time notification feature (bell icon with unread count, live updates, history). How do you choose between WebSocket, server-sent events and polling, and how is it built in Angular?

Choose the transport by need: polling is simplest, server-sent events give one-way push over HTTP with automatic reconnect, and WebSocket gives two-way messages. In Angular, one service owns the connection, exposes a signal for the unread count and a stream for new items, reconnects with backoff, pauses when the tab is hidden, and loads history over normal HTTP.

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 sends Last-Event-ID, so the server can resume. Works well through HTTP/2. Good for notifications and live feeds. Limits: text only, one direction, and EventSource cannot 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:

  1. NotificationService (root) owns the connection. It exposes unread = signal(0) and incoming$ (Observable, shared). Components never open sockets.
  2. Start the connection after login, close it on logout. Use RxJS webSocket() or an Observable that wraps EventSource, with retry and exponential backoff and jitter, and a cap.
  3. 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).
  4. UI: a bell button with aria-live="polite" count, a panel with @for and track id, mark as read (optimistic update with rollback), and a "new items" toast through LiveAnnouncer for screen readers.
  5. 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.
  6. Multiple tabs: use BroadcastChannel or a SharedWorker to share one connection.
  7. 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.

typescript
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.