Frontend System Design: Notification System (Facebook-style)

interviewNovember 16, 2026ยท 13 min read

"Design a notification system" sounds like the softest question in the loop โ€” a badge and a dropdown. Then the interviewer asks: "you have the site open in five tabs. You read a notification in one. What happens to the badge in the other four?"

The junior answer assumes the system is the dropdown. The senior answer knows a notification system is a cross-context state-sync problem wearing a UI: events arrive on the server faster than any inbox can show them, the unread badge must be identical in every tab and on every device, and two different UIs โ€” transient toasts and a durable inbox โ€” consume the same stream without double-showing anything.

A production notification system is five systems stacked: a data model (what is a notification, and how do 200 likes become one row?), a delivery channel (SSE, WebSocket, or polling โ€” and how do you survive reconnects?), an unread count (derived state that stays honest across tabs, devices, and pagination), multi-tab consistency (who owns the socket?), and presentation routing (toast or inbox, and never both). Let's design all five.

Requirements โ€” the questions that split junior from senior

Before drawing anything, ask:

  • Delivery surfaces? In-app only, or also push/email/SMS? This changes the architecture completely โ€” in-app means the client is pulling or streaming; push means the server is waking devices that aren't even running your code. For this design, in-app with a note on where push hooks in.
  • Real-time degree? Does the badge update within a second of the event, or on next refresh? Real-time means a persistent channel and a catch-up protocol for the gaps.
  • Aggregation semantics? When 200 people like your photo, is that 200 notifications or one? This single question decides whether the inbox is usable. Get the answer before the data model.
  • Read semantics? Per-item read state, mark-all-as-read, or Facebook-style "see new" (a watermark, not flags)? Each implies a different unread-count mechanism.
  • Multi-tab? Five tabs, one badge โ€” who owns the connection, and how do reads in one tab propagate?
  • Retention? How long does the inbox keep read notifications? This breaks naive badge math โ€” I'll show where.

I'll assume the full production version: in-app real-time (SSE-class), server-side aggregation with client rendering of the aggregate, per-item read state plus a materialized unread counter, multi-tab consistency via a single connection owner, toasts for urgent items, and a paginated inbox with 30-day retention of read items.

The naive answer โ€” and exactly where it dies

The junior design: a useNotifications hook that polls GET /notifications every 30 seconds, stores the array in component state, and renders the badge as items.filter(n => !n.read).length.

Four failure modes, each with a name:

  1. The badge lies between polls. For up to 30 seconds, every tab shows a stale unread count โ€” and with five tabs open, you're paying for five polling loops. Polling latency isn't a tuning knob; it's the design's ceiling.
  2. Tabs drift. Each tab computed its own unread count from its own snapshot, at its own time. Read something in one tab, and the other four still show it unread until their next poll. The badge โ€” the single most visible number in the product โ€” disagrees with itself.
  3. No aggregation. A viral post generates 200 rows in the inbox, each with its own unread flag. The user's notification experience becomes triage. Aggregation isn't a nice-to-have; it's the difference between an inbox and a spam feed.
  4. Delivery leaks into presentation. Toasts render from the same array the inbox reads, so after every route change the last five notifications pop up again as toasts. Delivery state and presentation state share a store, so neither can behave correctly.

Every one of these has a structural fix. Let's build it.

Data model โ€” what a notification actually is

A notification is not "an event." An event is "X liked your photo"; a notification is a rendered, aggregated, user-facing claim derived from events. Keep them separate:

// Server-side: raw events arrive at high frequency
interface NotificationEvent {
  eventId: string;        // globally unique, for exactly-once delivery
  actorId: string;
  verb: 'liked' | 'commented' | 'mentioned' | 'tagged' | ...;
  objectId: string;       // the photo/post
  targetUserId: string;   // recipient
  createdAt: string;      // ISO instant
}

// User-facing: what the inbox reads (already aggregated)
interface Notification {
  id: string;             // stable id โ€” the aggregate's identity
  aggregateKey: string;   // e.g. "liked:photo:42" โ€” groups collapsing events
  actorIds: string[];     // sample of actors, newest first
  actorCount: number;     // 200 likes โ†’ actorCount: 200
  verb: string;
  objectId: string;
  snippet?: string;       // comment text, mention context
  createdAt: string;      // newest event in the aggregate
  readAt: string | null;
}

The aggregate key is the design's hinge: verb + object (and sometimes target). All events mapping to one key collapse into one notification โ€” the server merges them inside a short window (say 30 seconds), updates actorCount and rotates the actor sample, and bumps createdAt. One row per aggregate; "A, B, and 198 others liked your photo."

On the client, hold notifications in a normalized store keyed by id, and treat lists (inbox page 1, unread slice) as queries over the store, not stored arrays. This is the same discipline as the email client and data table designs: one source of truth, views derived from it.

Delivery โ€” SSE, WebSocket, or polling?

The decision matrix, stated crisply:

  • Polling: simplest, works everywhere, but latency equals interval, cost equals interval ร— clients, and every tab polls separately. Acceptable only as a fallback.
  • WebSocket: bidirectional, ideal when you already run one for chat or presence. Running one just for notifications means building reconnection, heartbeats, and backpressure for a firehose you only ever read.
  • SSE (Server-Sent Events): one-way server-to-client, native auto-reconnect, Last-Event-ID resumability built into the protocol, plain HTTP. For a stream you only consume, this is the default answer.

Notifications are a read-only stream โ€” SSE is the honest fit. If the app already has a WebSocket (the chat app in this series), multiplex notifications onto it by channel; don't build two persistent connections.

The part interviews actually probe: what happens when the connection drops? The stream guarantees live delivery, not complete delivery. So every event carries a monotonically increasing cursor, and the client's reconnect protocol is:

1. Stream drops (SSE auto-reconnects; resume with Last-Event-ID if the server supports it)
2. On reconnect: GET /notifications?since=<lastSeenCursor> โ€” fetch the gap
3. Upsert by id (eventId dedupe makes replays harmless)
4. Resume the stream; server acks the cursor watermark

Delivery is therefore at-least-once with idempotent application โ€” the same contract as the collaborative editor's sync handshake. The client never trusts "the socket is open, so I have everything"; it trusts the cursor watermark.

Unread count โ€” derived, but not the way you think

Here's the trap: badge = inbox.filter(n => !n.readAt).length. It breaks the moment the inbox paginates. The badge says 3, the user opens the dropdown, the first page shows 25 read items and the unread ones are on page 2 โ€” the badge and the list are computing over different slices of history.

The senior design separates the two concerns:

  • Per-item readAt โ€” ground truth for rendering read/unread styling in the list.
  • A materialized unreadCount counter โ€” maintained server-side, transactionally incremented on delivery and decremented on read. It is the badge, delivered over the same SSE stream, and it does not care about pagination or retention.
// The badge update rides the same stream as notifications
interface BadgeEvent { type: 'unread-count'; count: number; cursor: number }

// Client: server count is truth; local reads are optimistic deltas
function applyReadLocal(state: State, ids: string[]): State {
  const currentlyUnread = ids.filter(id => !state.byId[id].readAt).length;
  return {
    ...state,
    byId: ids.reduce((m, id) => ({ ...m, [id]: { ...state.byId[id], readAt: now() } }), state.byId),
    badge: Math.max(0, state.badge - currentlyUnread), // optimistic
  };
}
// The next unread-count event from the server reconciles any drift.

Mark-all-as-read is a server operation that zeroes the counter and stamps readAt on the visible page optimistically โ€” the rest of history is stamped lazily server-side. Never ask the client to enumerate every unread id; it can't, because it only has one page.

Multi-tab โ€” one socket, five consistent tabs

Five tabs must not open five SSE connections (server cost, duplicated work, and โ€” worse โ€” five independent caches that drift). One tab (or a worker) owns the connection; the others subscribe to it. Two good architectures:

  • SharedWorker: the worker holds the SSE connection and the notification store; every tab talks to the worker over postMessage. One connection, one store, tabs are thin views. Caveat: Safari's support has been historically shaky โ€” feature-detect.
  • Leader tab + BroadcastChannel: the first tab opens the stream and becomes leader; it rebroadcasts every event (and badge updates, and read-receipts) over a BroadcastChannel. Non-leader tabs listen. If the leader closes, the next tab claims leadership via a heartbeat-election on the same channel.

I've covered the mechanics of cross-tab messaging in depth in the BroadcastChannel guide โ€” the design decision here is ownership: exactly one context streams from the network, everything else subscribes locally. Reads propagate the same way: mark-as-read happens in tab 3, the leader applies the optimistic delta and rebroadcasts, all badges move together, and the server reconciliation lands on every tab identically.

One detail that shows product judgment: don't mark items read merely because they streamed in while visible. Read state should mean the user saw it โ€” apply read on open/click, or on inbox visibility (via document.visibilityState) with a dwell threshold, never on arrival.

Optimistic read โ€” the tap must not wait

Tapping a notification navigates and marks it read. The network round-trip must not sit between the tap and the badge decrement:

  1. Tap โ†’ apply optimistic read locally (badge down, row restyles) โ†’ navigate.
  2. Fire POST /notifications/read with an idempotency key (the batch of ids + a client-generated key), fire-and-forget with retry via the outbox pattern from the email client design.
  3. On failure: roll back the badge delta, surface a subtle "couldn't sync" affordance โ€” never a modal for a badge.

The rollback math must be delta-based (decrement by the number that were actually unread, captured before the optimistic write), not absolute โ€” otherwise a concurrent mark-all from another tab double-decrements. This is the same optimistic-with-rollback discipline as the kanban board's move op; the difference is only that reads are idempotent server-side, so replay is always safe.

Toasts vs inbox โ€” one stream, two consumers

Toasts and the inbox are two views of one stream, never two stores. The routing happens at presentation:

function routeNotification(n: Notification): 'toast' | 'inbox' {
  if (n.verb === 'mentioned' || n.verb === 'tagged') return 'toast';  // urgent, social
  if (isViewedContextPresent(n)) return 'inbox';                       // ambient โ†’ inbox only
  return 'inbox';
}

Rules that separate a toy from a product:

  • Toast is for urgency only โ€” mentions, tags, live events. Everything lands in the inbox; only a subset may also toast. If a class of notification is not urgent today, it must not toast by default tomorrow.
  • Deduplicate and cap: a toast queue with a max of 3 concurrent, identical aggregate keys collapsed into one ("3 new mentions"), oldest auto-dismissed. Five stacked toasts for one viral post is a design failure.
  • No toast replay: toasts fire exactly once, at delivery, from the stream consumer. They are never derived from stored state โ€” that's naive failure mode #4. Route change re-renders the inbox; it must not re-toast.
  • Dwell and dismissal: auto-dismiss ~5s, pause on hover/focus, explicit close button; the item remains in the inbox regardless.
  • Visibility gating: if the tab is hidden, skip toasts entirely and let the badge carry the signal โ€” unmuting into a stack of stale popups is worse than a badge.

Retention, pagination, and the badge that must survive both

The inbox paginates by (createdAt, id) cursor โ€” stable under insertion, unlike offset pagination (a page of 20 shifts when three notifications arrive mid-scroll). Read items older than 30 days are compacted server-side; the unread counter survives because it never depended on list contents.

Aggregates keep mutating after first render โ€” "A and B liked" becomes "A, B and 12 others liked." The client upserts by notification id (the aggregate identity is stable even as its contents change), which means the inbox re-renders a row in place instead of re-sorting the list. Sort order is by the aggregate's createdAt at fetch time; live re-sorting mid-scroll is disorienting โ€” snapshot the order, surface "new notifications" as a divider, and re-sort on next open. The nested comments design calls this the snapshot-sort tradeoff; it applies here identically.

Accessibility โ€” the badge is not the signal

  • Live regions: toasts render into an aria-live="polite" region (assertive only for genuinely destructive/urgent events). Screen readers hear mentions, not every like.
  • Unread state must not be color-only: bold weight + dot + text ("New"), so it survives color blindness and high-contrast modes.
  • Focus management: opening the inbox moves focus to the list with a clear name ("Notifications, 3 unread"); closing returns focus to the bell. Escape closes. Arrow keys navigate items โ€” this is a listbox pattern, not a div pile.
  • Badge for everyone: pair the counter with aria-label on the bell ("Notifications, 3 unread"), updated with the same events that drive the visual badge.

Interview gotchas โ€” the quick-fire round

  • Why is the badge not list.filter(unread).length? Pagination + retention truncate the list; the badge is a server-materialized counter, delivered over the stream.
  • SSE or WebSocket? One-way stream โ†’ SSE (auto-reconnect, Last-Event-ID). Already have a socket for chat โ†’ multiplex. Polling only as last-resort fallback.
  • What happens on reconnect? Fetch since=<cursor> to backfill the gap; dedupe by event id; the cursor watermark is the completeness guarantee, not "socket is open."
  • 200 likes, one notification โ€” where? Server-side aggregation on verb + object aggregate keys inside a short window; client renders count + actor sample; the row upserts in place.
  • Five tabs, one badge โ€” how? One connection owner (SharedWorker or leader tab), events rebroadcast via BroadcastChannel; reads propagate as optimistic deltas to all tabs, reconciled by the server counter.
  • When does a notification become read? On open/click, or on visible dwell (visibility-gated) โ€” never on arrival, never on render.
  • Toast appears again on route change โ€” why did it happen and how do you prevent it? Toasts were derived from stored state; they must fire exactly once from the stream consumer and never be re-derived.
  • Idempotency where? Read-receipt POSTs carry idempotency keys; event application upserts by id. Retries and replays must be harmless everywhere.
  • Do toasts mark items read? No. Display is not a read-receipt; otherwise dismissing a toast silently clears the badge and the inbox signal.

Putting it together

A production notification system design:

  • Data model: events โ‰  notifications; aggregate on verb + object server-side; normalized client store; lists are queries
  • Delivery: SSE for the stream (WebSocket only if one already exists); cursor watermark + since backfill for reconnects; at-least-once delivery, idempotent application
  • Unread count: server-materialized counter as the badge, readAt per item for styling; optimistic local deltas reconciled by stream events
  • Multi-tab: one connection owner (SharedWorker or leader election), BroadcastChannel fan-out to tabs; reads propagate everywhere instantly
  • Presentation: toasts are a routed, capped, fire-once view; inbox is the durable store view; visibility gates toasts
  • Ops: cursor pagination, 30-day compaction, idempotency keys on read-receipts, delta-based optimistic rollback
  • A11y: polite live regions, non-color unread signals, listbox semantics, focus management

The dropdown is the easy 20%. The product is the counter that never lies across tabs and time, and the aggregation that turns a viral spike into one readable row. Get the cursor watermark and the aggregate key right, and the notification system designs itself.

The Series: Frontend System Design Interview Questions

Donate
ยฉ 2024, Built with Gatsby