Design a Notification Center – Frontend System Design

We’ll walk through the frontend system design for an in-app notification center: the bell, the inbox, the unread badge, and the live updates that keep them honest. You’ll see why the badge is not a count of the rows on screen, why grouping belongs on the server, how to pick between a stream and a poll, and how a mark-all-read click races the mention that arrives in the same millisecond.
The interviewer phrases it as “design the notifications dropdown”. A list of toasts is a junior answer. The real product is an inbox that survives pagination, two open tabs, a muted thread, a deep link to a deleted issue, and a screen reader that should not hear every like.
Problem Statement
Design the frontend for an in-app notification center, like GitHub, Linear, or LinkedIn.
Requirements:
- A bell with an unread badge, a popover inbox, and a full-page inbox
- Unread counts that stay correct across tabs and after mark-read
- Grouping (“Priya and 4 others liked your post”)
- Live updates while the app is open
- Per-category preferences, mutes, and quiet hours
- Clicks resolve to the right place in the app
Describe the client architecture, the unread model, the delivery channel, and the mark-read protocol.
Interviewers are checking three things. Do you keep unread as its own versioned value, or do you derive it from whatever page is mounted? Can you explain a mark-read race with a watermark instead of waving at “eventual consistency”? And do you treat the live region and the badge as different surfaces, so a screen reader is not spammed?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | In-app inbox, OS push, email, or all three? | In-app is required. Email and web push exist as preference channels. Lock-screen push is out of scope unless you have time. |
| 2 | How many notifications does a heavy user get? | Tens to low hundreds a day. Two years of history stay readable. Unread is usually under a few hundred. |
| 3 | Must the inbox update live? | Yes while the tab is visible. A few seconds of lag after focus is fine. Instant lock-screen delivery is not the bar. |
| 4 | Do we group? | Yes for high-churn types (likes, new comments on one thread). Mentions stay as their own rows. |
| 5 | Cross-device and multi-tab? | Unread and read state follow the user. Two desktop tabs must not fight. |
| 6 | What does a click open? | The target resource in this app (issue, comment, review). External URLs are not stored on the row. |
| 7 | Which browsers? | Evergreen desktop and mobile. Installed / home-screen badge is a plus, not a requirement. |
Question 2 kills offset pagination and any design that loads the whole inbox to count unread. Question 3 decides the transport: a stream in the foreground, a snapshot on focus, not a 5-second poll on top of a socket. Question 4 means grouping is a write-time groupKey, not a reduce after fetch. Question 6 rules out putting a raw href on the row and navigating to it.
Requirements
Functional
- Bell button shows a badge (blank, a number, or 99+). Opening it shows the latest page, grouped, with All / Unread / Mentions filters.
- Each row shows actor, action, target title, relative time, and an unread affordance that is not color alone.
- Clicking a row marks it read and routes to the target. Mark one, mark visible, and mark all are all supported. Mark-as-unread exists for a single row.
- A group updates in place and jumps to the top when a new member arrives. Expanding it lists members. Marking the group read marks every member.
- Preferences: in-app / email / push per category, mute a target, quiet hours for email and push (in-app still arrives).
- A full
/inboxroute shares the store with the popover. The URL can restore filter and cursor.
Non-Functional
- Opening the popover paints the last cached page in one frame, then reconciles.
- Unread is correct after a mark-read, a mark-all, a new event, and a second tab, with no bounce through zero unless it really is zero.
- A focused tab sees a new notification within about a second. A tab that was hidden catches up on focus without waiting for the next poll.
- The inbox is keyboard reachable. The bell’s accessible name includes the count. Incoming items are not all announced.
- Notification bodies never execute HTML. Deep links never leave the app origin through a stored URL.
The unread invariant is the requirement that shapes the design. If the badge can lie, everything downstream (title prefix, app badge, mark-all) is untrustworthy. Treat unread as a small, versioned document. The list is a cursor window over the same user’s rows.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| Rows per heavy user | ~36,000 | 50/day × 365 × 2 years | Never fetch to count. Cursor pages of 20. Virtualize the full page. |
| Unread (typical) | 0–200 | People clear, or they don’t | A 32-bit counter plus a version is enough. Do not scan. |
| First page payload | ~12 KB | 20 rows × ~600 B JSON | Fine over REST. Bundle the unread snapshot on the same response. |
| Live events, busy user | ~1–5 / min | Likes and comments in a working hour | SSE or the existing product socket. Not a dedicated WS fleet. |
| Poll fallback | ~2 KB / min | 60 s interval, If-None-Match often 304 |
Acceptable when there is no stream. Wasteful as a second live path. |
| Two tabs | 2 connections | One stream per visible tab | Pause the stream when hidden. Fan-out read state on a BroadcastChannel. |
Architecture
The client has a UI shell and a small domain layer. The important boundary is that the inbox view never owns the unread number.
| Layer | Owns | Runs on | Talks to |
|---|---|---|---|
| UI shell | Bell, popover, /inbox, preferences, badge surfaces |
React, main thread | Reads store + counter, sends intents |
| NotificationStore | Rows by id, groups by key, page cursors | Client singleton | Transport, inbox view, router |
| UnreadCounter | Snapshot, version, optimistic overlay | Client singleton | Bell, title, App Badge, live region, other tabs |
| Transport | Stream, catch-up GET, poll fallback | Main thread | API, realtime gateway |
| DeepLink router | Allowlisted type + id → route |
Client | App router, never window.location = href |
React renders the chrome. It does not hold a useState(unread) that every event mutates. The popover and /inbox subscribe to the same two stores, so the full page does not refetch what the popover just showed.
“The list is a cursor page. The badge is a versioned counter. If you derive one from the other, a 47-unread user who loaded 20 rows shows 3.”
Pages are keyed by cursor, not one array you append to forever. A live upsert updates a row you have, prepends onto page 1, or only bumps the counter if the user is on page 4.
Data Model
Each recipient gets their own row. That is what makes read, mute, and delete per-user. The actor’s “I commented” event is not the same record as your inbox item.
type NotificationId = string;
type Category = "mention" | "comment" | "assign" | "review" | "like" | "system";
interface Actor {
readonly id: string;
readonly name: string;
readonly avatarUrl: string;
}
interface TargetRef {
readonly type: "issue" | "comment" | "review" | "post";
readonly id: string;
readonly title: string;
}
interface Notification {
readonly id: NotificationId;
readonly category: Category;
readonly actor: Actor;
readonly target: TargetRef;
readonly body: string;
readonly groupKey: string | null;
readonly createdAt: string;
readAt: string | null;
}
interface NotificationGroup {
readonly key: string;
readonly category: Category;
readonly target: TargetRef;
actors: Actor[];
latestAt: string;
unreadCount: number;
memberIds: NotificationId[];
}
interface UnreadSnapshot {
readonly total: number;
readonly byCategory: Readonly<Partial<Record<Category, number>>>;
readonly version: number;
readonly watermark: NotificationId | null;
}
interface Preference {
readonly category: Category;
readonly inApp: boolean;
readonly email: boolean;
readonly push: boolean;
readonly mutedTargets: readonly string[];
}
interface CursorPage {
readonly items: readonly Notification[];
readonly nextCursor: string | null;
readonly unread: UnreadSnapshot;
}
Four choices are worth defending.
No href on the row. The target is { type, id }. The client maps that through an allowlist to a route. A stored URL is an open redirect the first time someone puts https://evil.example/ in a title-derived link. The displayed title is plain text, not HTML.
groupKey is assigned at write time. Likes of post 42 share like:post:42. The inbox has one row for that key. A new like appends an actor, bumps latestAt, and the row jumps to the top. Mentions get groupKey: null so they never collapse. Client-side grouping of adjacent rows breaks as soon as a different type sits between two likes.
Unread is a snapshot with a monotonic version. Every mutating response and every live event carries a full snapshot, not “+1”. The client applies a delta only when event.version === local.version + 1. A gap means refetch. Guessing from the list is how badges drift.
The first page returns the snapshot. One round trip to open the popover. You do not fire GET /inbox and GET /unread and hope they describe the same instant.
Inbox, Filters, and Grouping
The popover and /inbox are the same view with a different max height. Virtualize the full page. Twenty popover rows do not need it; two years of history do. Filters are query params (/inbox?filter=unread), each with its own cursor. Reusing the All cursor on Unread skips rows. The popover stores the same params so it reopens on the last filter.
The store keeps rows normalized and groups as a derived index. Walk page 1 in order; the first time you see a groupKey, emit the group and skip later members.
The inbox store holds two maps: rows by id and groups by groupKey. Upserting a row stores it by id. A row with no group key is prepended as a singleton. A grouped row joins its group, or creates the group on first sight. Joining adds the member id if it is new, puts the actor at the front of a list capped at three faces, sets latestAt, recomputes the group’s unread count from its members, and moves the group to the top. Because upsert is keyed by id, a duplicate event or a replay after reconnect changes nothing.
A group is unread if any member is unread. Marking it read is POST /notifications/read with every memberId, not a fake group id. A live like on page 1 moves the group to the top; on page 4 only the counter changes. Prepending onto an old page looks like a row appearing in last Tuesday.
Relative times come from one 30-second clock for the open view, not a timer per row. Screen readers get the absolute datetime on a <time>.
Unread Counts
Unread is a per-user document: total, optional byCategory, a monotonic version, and a watermark (the newest id the server has attributed to this snapshot). The client has two layers on top of it.
- Authoritative. The last snapshot the server sent (REST or stream).
- Overlay. Optimistic decrements for in-flight mark-read calls, keyed by notification id so they are idempotent.
The rendered badge is max(0, authoritative.total + overlay), capped at 99+ for display. When a server snapshot arrives, drop any overlay ids that the snapshot already shows as read, then recompute.
The unread model is a small module with an authoritative snapshot and a set of in-flight read ids.
- Displayed total is the snapshot total minus the in-flight set size, floored at zero.
- Adopt rejects a snapshot older than the current version. Otherwise it replaces the snapshot, drops in-flight ids whose rows are now read, and publishes.
- Apply event ignores an event older than the current version, asks for a resync if the event skips a version, and adopts it when it is exactly the next one.
- Mark read locally stamps
readAton the row, adds its id to the in-flight set, and publishes. Rows that are missing or already read are a no-op.
Three rules keep this from oscillating.
Never increment locally from a list length. A create event carries a snapshot. If the stream omitted the snapshot, treat that as a protocol bug and refetch. Local +1 on every toast is how two tabs, or a retry, double-count.
A version gap is a refetch, not a skip. You missed an event while the laptop slept. Applying the latest delta on top of an old total is how you land on 4 when the truth is 7.
In-flight reads are a set, not a number. The user can click the same row twice, or mark-all can include an id you already marked. A set makes both no-ops.
Category counts (Mentions vs Everything) are the same snapshot, not a second endpoint. The Mentions tab badge is byCategory.mention. If the server does not break it out, the tab has no badge. Do not count mention rows on page 1 and pretend that is the filter.
Realtime vs Poll
Notifications are one-way. The client does not send presence on this channel. That makes SSE the default live transport: the browser handles reconnect, and Last-Event-ID resumes the stream. If the product already has a WebSocket (chat, presence, document sync), multiplex inbox events on it. Do not open a second socket for the bell.
| Transport | Use when | Resume | Cost |
|---|---|---|---|
| SSE (or existing WS) | Signed-in app, tab visible | Last-Event-ID or lastVersion on reconnect |
One cheap connection |
| Catch-up GET | Tab becomes visible, or version gap | Full snapshot + page 1 | One request per focus |
| Poll 45–60s | No stream (proxy, failure, old browser) | If-None-Match on the unread version |
Tiny when idle, only while visible |
| Web Push | Background / lock screen | Service worker push |
Permission, not a live inbox |
A 5-second poll and a socket is the common overdesign. Pick one live path. Poll is what you do when that path is missing.
A delivery controller owns the transport and exposes one start function that takes an event handler and a gap handler, and returns a stop function.
- Visible: run a catch-up fetch, then open an
EventSourcewith the current unread version. Each message goes through apply-event. A resync result calls the gap handler. Anything else goes to the event handler. - Stream error: close it and fall back to a 60-second catch-up poll while the tab is visible. Browsers without
EventSourceuse the poll from the start. - Hidden: close the stream and stop polling.
Hidden tabs drop the stream so six open tabs are not six idle sockets. On visible, catch up immediately: that is what stops “I came back and the badge was stale for a minute”. The gap handler is GET /api/notifications?unread=1, then adopt the snapshot from that page. Keep in-flight reads so a pending mark-read does not flash the row unread.
Web Push is for when the tab is gone. The payload is a notification id, not the body, so a phone that already read it does not show a lock-screen ghost. iOS web push needs a Home Screen app (16.4+). Mention it, then return to the inbox.
Mark-Read Races
This is the part most candidates skip. There are three races, and they all yield to one protocol: every write carries a watermark, every response carries a snapshot, the client adopts the snapshot.
1. Mark-all vs a brand-new row
The user has 12 unread. The newest id they have seen is n100. They click Mark all. In the same moment the server inserts mention n101.
A request body of {} means “every unread row for this user”, including n101. The mention is born read. The optimistic badge goes to 0. The live event then tries to upsert an already-read row, and the user never sees it.
Send the watermark.
Mark all in the unread model does four things. It reads the current watermark. It saves a copy of the in-flight set. It adds every unread row it knows about to the set and publishes, which drops the badge optimistically. Then it posts { before: watermark } to /notifications/read-all and adopts the snapshot from the response. On failure it restores the saved set and publishes, so the badge returns to its true value instead of staying at zero.
The server runs UPDATE ... WHERE user_id = ? AND id <= before AND read_at IS NULL, then recomputes unread (the leftover n101) and bumps version. Tab A adopts { total: 1, version: 84 }. It never paints 0. Tab B receives the same snapshot on the stream and does the same.
If the client has no watermark yet (first paint, empty inbox), send the server’s clock from the snapshot response, not Date.now(). Device clocks lie.
2. Mark-one vs the create event
The user clicks a row that the stream is also delivering. Order is not guaranteed.
- If mark-read acks first, the create event arrives with
readAtset (or with a snapshot that already excludes it). Upsert is a no-op for unread. - If create arrives first, the row is unread, then mark-read overlays it. The in-flight set prevents the create path from incrementing again: the create path skips the increment when the id is in flight or the row already has
readAt.
Idempotency is on the id, not on “we already decremented once this session”.
3. Two tabs mark different rows
Tab A marks n40. Tab B marks n41. Each has an overlay of −1 on a snapshot of 12. If they only trusted the overlay, both would show 11, then 10, and a refetch would snap to 10. That happens to work for decrements. It fails for mark-all in one tab and a create in the other.
So tabs do not share overlays. They share snapshots. On adopt, post the snapshot to a BroadcastChannel("inbox"). The other tab calls adopt and drops its own overlay ids that the snapshot already read. Same-tab React subscriptions are not enough: the other tab’s counter is a different JS heap.
Each tab opens a BroadcastChannel named inbox. Every publish renders the badges from the displayed total and posts the authoritative snapshot (never the overlay) to the channel. A message from another tab runs through adopt, so the version check ignores older snapshots and the in-flight cleanup happens on both sides.
Do not broadcast overlays. A failed mark-read in tab A must not flicker tab B.
When to mark read
Mark on open (click or keyboard), not on scroll. Intersection Observer “seen” clears the badge as people skim. Offer “Mark visible as read” as a batch POST of ids. Undo for mark-all keeps the previous snapshot and ids for about five seconds, then POST /notifications/unread. After that the watermark has moved on.
Preferences
Preferences are a per-category matrix plus mutes, stored on the user, not the device. In-app still arrives during quiet hours; email and push do not. The client does not enforce email or push. It does drop a leaked in-app event for a muted target or disabled category, and it does not touch unread. The server should not have sent it.
Mute is target.type + ":" + target.id. Future comments on that thread stop landing; history stays, usually marked read. Say that rule out loud. Writes are PATCH /api/me/notification-preferences. Optimistic toggle, rollback on 409 if another device has a newer server updatedAt. Device clocks are not an order.
Deep Links
A click is two intents: mark read, then navigate. Do them in that order locally so the row does not sit unread while the issue page loads. The POST can finish in the background. If it fails, the overlay rolls back and the user is still on the issue, which is fine.
Navigation goes through a static route table keyed by target type: issue, comment, review, and post each map an id to an internal path. One function, openNotification, handles every click. It marks the row read locally, fires the read POST in the background and adopts its snapshot, then looks up the route. A known type navigates inside the app. An unknown type shows a tombstone. No branch ever navigates to a string from the payload.
Unknown type is a tombstone, not a home redirect. A 404 target is the issue page’s problem. A 410 on the row itself becomes “This item is no longer available” and stays markable so the badge can clear.
OS-push and in-app clicks share openNotification. The push payload is { id }; the worker focuses a client and posts it. Two code paths is how push opens a raw URL and skips mark-read. Restore ?filter= on /inbox. Do not put bodies in the query string.
Badge Surfaces
One counter, four places it can show up. Drive them from the displayed total, not from four independent states.
One render function owns every surface. It formats the label (empty at zero, 99+ past 99), writes it to the bell’s data attribute, sets the document title to (label) base title (captured once with any old prefix stripped), and calls navigator.setAppBadge or clearAppBadge when the API exists. A sibling function builds the bell’s accessible name: “Notifications”, “Notifications, 7 unread”, or “Notifications, more than 99 unread”.
The title prefix is the desktop badge that works everywhere. Update it while focused so people can scan the tab strip. Do not flash “!!! New mention !!!” on an interval.
setAppBadge is Chromium and Safari for installed / Home Screen apps. Feature-detect, ignore failures, pass the real number; the OS caps display. A favicon overlay is optional and ugly on dark themes. The bell’s accessible name is the badge for assistive tech: an aria-label change, not a live announcement.
API
// REST
GET /api/notifications?filter=all|unread|mention&cursor=&unread=1
// 200 { items, nextCursor, unread: UnreadSnapshot }
POST /api/notifications/read // { ids: NotificationId[] } → { unread }
POST /api/notifications/unread // { ids } → { unread }
POST /api/notifications/read-all // { before: NotificationId | ISO } → { unread }
GET /api/me/notification-preferences
PATCH /api/me/notification-preferences // { category, inApp?, email?, push?, muteTarget? }
// SSE: GET /api/notifications/stream?lastVersion=83
// Content-Type: text/event-stream
// id: 84
// data: { "type": "upsert", "notification": { ... }, "unread": { "total": 13, "version": 84, ... } }
type InboxEvent =
| { type: "upsert"; notification: Notification; unread: UnreadSnapshot }
| { type: "read"; ids: NotificationId[]; unread: UnreadSnapshot }
| { type: "read_all"; before: NotificationId; unread: UnreadSnapshot }
| { type: "delete"; ids: NotificationId[]; unread: UnreadSnapshot };
Every mutating endpoint returns the snapshot, so a client that missed the stream still converges. The SSE id is the unread version; reconnect sends Last-Event-ID: 84. If the journal no longer has 84, the server sends a snapshot and the client runs onGap. Page 1 is an empty cursor. The next cursor is opaque (createdAt + id), never an offset. Unread is readAt IS NULL on the server, not “rows the client has not painted”. Cap ids at about 100; a keyboard user will burst.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Popover feels empty | Session cache of page 1 + snapshot | Paint cached rows, then reconcile |
| Long inbox jank | Virtualized list, stable keys (id or groupKey) |
Only visible rows mount |
| Refetch on every open | Reuse the store; catch-up only on version or focus | No duplicate GET |
| Hidden-tab sockets | Close stream on hidden |
One live connection per visible tab |
| Poll noise | ETag = unread version, 304 |
Empty responses while idle |
| Avatar storms | Shared image cache, lazy avatars in the virtual window | No 40 requests on open |
| Mark-all of 200 unread | Watermark update, not 200 ids | One write, one snapshot |
Cache page 1 in sessionStorage. Skip a long-lived localStorage inbox unless asked; this product is online-first and already has a catch-up GET. Coalesce live upserts in a 50ms window so a burst of likes is one group render. Adopt snapshots in order so versions do not skip inside the batch.
Handling Edge Cases
- Empty inbox. Distinguish “none at all” from “Unread is empty, 12 in All”.
- Partial batch read. The snapshot is truth. One 404 of 20 does not roll the rest back.
- Deleted target. Tombstone the row, keep it markable so the badge can clear.
- Clock skew. Use server
createdAt. A few seconds in the future is “just now”, not “in 8 seconds”. - Duplicates. Same id upserted twice is a replace. A backwards version is ignored.
- Stream flap. After two EventSource failures, poll and show “Live updates paused” in the panel, not a toast.
- Signed out. 401 clears stores, closes the channel, and
clearAppBadge(). No leftover “(12)” on login. - Vacation unread (1,000+). Badge shows 99+. Mark-all still uses the watermark, not 1,000 ids.
Accessibility and Security
Accessibility
- The bell is a button named
bellAriaLabel(total). That is how a screen-reader user learns there is unread mail without opening the panel. - The popover is a dialog or disclosure: focus moves in on open, back to the bell on close, Escape dismisses. Same contract as Design a Modal Dialog.
- Rows are links or buttons in a list. Unread is the word “unread” plus a dot, not a tint alone.
aria-live="polite"announces a new item only while the panel is open. Closed, the bell name is enough. Assertive is for errors, never inbound likes.- Keyboard:
j/kmove,Enteropens,rtoggles read. Do not steal those keys from an input. Honorprefers-reduced-motionon the badge pop and jump-to-top.
Security
- Bodies, titles, and actor names are user-generated text. No
dangerouslySetInnerHTML. - Deep links go through the allowlisted
type + idmap. Drop any storedhref. Open-redirects on notification clicks are a classic. - Avatars come from your CDN, not an actor-supplied URL.
Referrer-Policy: no-referrerif they can ever hit a third party. - SSE auth matches REST. A query token expires; URLs leak into logs. Row ids are ULIDs, and every query is scoped to the session user.
- Mark-read is POST, not GET, so a tracking pixel cannot clear the inbox. Preference PATCH is CSRF-protected like the rest of the app.
An inbox is a per-user feed, not a room; see Chat Application Frontend System Design for presence. For a heavier personal list, see Design an Email Client.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Unread | Count the unread rows in state | Versioned snapshot + overlay; gap → refetch; badge is not the page |
| Delivery | “Use a WebSocket” | SSE or the existing socket while visible, catch-up on focus, poll only as fallback |
| Mark-all | Set everything read locally | Watermark before, adopt the leftover snapshot, never paint a fake 0 |
| Grouping | groupBy after fetch |
Write-time groupKey, one row, mark group = mark members |
| Click | <a href={n.url}> |
Allowlisted type + id, shared with push, tombstone on unknown |
| A11y | A red dot | Named bell, dialog, polite live only when open, no assertive spam |
Conclusion: How to Design a Notification Center
Start with the split: a cursor-paginated inbox of per-recipient rows, and a tiny versioned unread document that every badge reads. Group at write time. One live channel while visible, a snapshot on focus, a poll only if the stream is gone.
Then make every write converge. Mark-read and mark-all send a watermark, the server returns a snapshot, the client adopts it, and other tabs hear it on a BroadcastChannel. If you can explain why a bare mark-all eats the mention that arrived in the same millisecond, and why the live region stays quiet while the bell’s name updates, you have shown you have shipped an inbox.
