Imagine a SaaS app adding a bell icon. The first version works in a demo: a notifications table, a count query, and a WebSocket that pushes new rows. Then real use begins. The badge says 3 while the list shows 5. A second tab still shows 7 after everything was read in the first. A user is notified about a comment that was rolled back. An announcement to a 20,000-person tenant takes minutes to insert. And six months later the table is the largest in the database.
A notification center looks like a small feature, but it touches data modeling, counting, real-time delivery, multi-tenancy, and retention all at once.
A design that holds up usually comes down to a few decisions:
- Store read state per recipient, and keep "seen," "read," and "done" distinct if your product needs them.
- Create notifications only for changes that actually committed.
- Count unread items with an index-friendly query and cap what the badge shows.
- Implement "mark all as read" with a timestamp watermark, not thousands of updates.
- Push updates in real time, and resync over REST whenever the connection is re-established.
- Share one live connection across browser tabs.
- Scope every query by tenant, and plan cleanup from day one.
Model the notification and the recipient separately
Two things are easy to mix up: the event ("Dana commented on Invoice 42") and each person's relationship to it (delivered to you, read by you, dismissed by you). Keeping them separate makes the rest of the design simpler:
- An event or content record holds what happened: type, actor, target object, a short payload, and when it happened.
- A recipient row holds one user's state for that event: tenant, user, event reference, created time, and read or archived timestamps.
Be clear about which states you need. GitHub's notifications API is a useful real-world model: marking a thread as read and marking it as done are separate operations. Many products also distinguish "seen" (the user opened the panel, so the badge clears) from "read" (the user opened that item). Pick the states your UI actually shows and model exactly those.
Timestamps such as read_at work better than a boolean is_read. They record when something happened, and a NULL means "not yet."
Fan-out on write or on read
When one event concerns many users, you can fan out in two ways:
- On write: create a recipient row for every user when the event happens. Reads are simple and fast, and each row carries its own read state. The cost is paid at write time, and it grows with audience size.
- On read: store the event once and work out each user's list when they open it. Writes are cheap, but reads are more complex, and read state has to live somewhere else.
LinkedIn's engineering post on FollowFeed describes this trade-off for feeds and explains why LinkedIn built its feed at read time. A notification center usually lands somewhere in between. Most notifications target one or a few people and suit fan-out on write. Broadcasts such as a tenant-wide announcement or a maintenance notice can be stored once and merged into each user's list at read time, with a small per-user record created only when someone reads or dismisses one.
If you do fan out on write to a large audience, do it in a background job in batches rather than inside the request that triggered it.
Only notify about changes that committed
A notification created in the same request as the change it describes can go wrong in both directions. If the transaction rolls back after the notification is sent, users are told about something that didn't happen. If the change commits but the notification step fails, they're never told.
The transactional outbox pattern solves this: write an outbox record in the same transaction as the business change, and have a separate process create and deliver notifications from it. For lower-stakes notifications, creating them in a queued job that runs after the commit is often enough.
Unread counts that stay correct
The badge is the most visible number in the feature, so it's where inconsistency gets noticed.
A plain COUNT(*) over a large table isn't free in PostgreSQL. The PostgreSQL wiki page on slow counting explains that because of how PostgreSQL handles row visibility, it has to examine rows to count them. That cost depends on how many rows match, which suggests two practical moves:
- Index only what you count. PostgreSQL supports partial indexes that cover only rows matching a condition. An index on the user's unread rows, with a condition like
read_at IS NULLand the tenant and user columns first, keeps the count proportional to unread items rather than all history. PostgreSQL's docs on multicolumn indexes note they work best when queries constrain the leading columns. - Cap the number you display. Showing "99+" is a common design choice. It also means you can stop counting at 100, which bounds the work even for a user with thousands of unread items.
Some teams keep a counter column instead and update it on every insert and read. That makes the badge cheap, but counters drift when a code path forgets to update them or a retry runs twice. If you use one, treat it as a cache: recompute it periodically from the recipient rows, and recompute it on demand when the user opens the panel.
Either way, return the count from the same endpoint as the first page of the list, so the badge and the list come from the same moment.
Mark as read, and mark all as read
Marking one item as read is a simple update. Make it idempotent: setting read_at only if it's still empty means a double click or a retry does no harm.
"Mark all as read" is where naive designs struggle, because updating thousands of rows on one click is slow. GitHub's API shows a better approach. Its mark-all endpoint takes a last_read_at timestamp, and anything updated after that time isn't marked as read. GitHub may also accept the request and process it asynchronously, returning 202.
You can apply the same idea with a per-user watermark:
- Store a "read everything up to" timestamp for each user.
- Treat any notification created at or before the watermark as read, unless you track individual read times for it.
- Set the watermark to the newest notification the user actually saw, not the server's current time, so an item that arrived a moment later isn't silently marked as read.
Real-time updates with a REST resync
Real-time delivery is what makes the bell feel alive, but it shouldn't be the source of truth. Connections drop, laptops sleep, and deploys restart servers. The list must be correct even if every live event is missed.
Server-sent events are often enough. Notifications flow one way, from server to browser, which is exactly what server-sent events (SSE) are for. MDN's SSE guide describes how the browser's EventSource reconnects automatically, how the server can suggest a reconnection delay with the retry field, and how an id field lets the browser resume. The HTML specification says the browser sends the last event ID in a Last-Event-ID header when it reconnects, and suggests sending a comment line about every 15 seconds to keep proxies from closing idle connections. In NestJS, the SSE technique uses the @Sse() decorator on a route that returns an Observable. If you already run WebSocket gateways for other features, sending notifications over them is also fine.
Resync on every (re)connect, in the right order. When the client connects, it should:
- open the live stream first,
- then fetch the latest list and count from the REST API, including everything since the last item it has,
- then apply live events on top, ignoring any it already has by ID.
Doing it in this order means nothing that happens between the fetch and the subscription is lost. PostgreSQL's own LISTEN documentation recommends the same order for its notifications: start listening, then check the current state, then rely on notifications.
Across several API instances, a user's stream may be connected to a different server than the one that created the notification. A message bus such as Redis pub/sub, or PostgreSQL's NOTIFY, can tell every instance to push it. NOTIFY payloads must be shorter than 8,000 bytes and are delivered only when the transaction commits, only to sessions currently listening. The docs also note that notifications are visible to all users of the database, so send IDs, not notification content, and let each instance load the content with the right permissions.
Polling is a fine fallback. GitHub's notifications API is polled, using Last-Modified and 304 Not Modified responses, with an X-Poll-Interval header telling clients how often they may ask. A short poll with conditional requests is simple and survives any proxy.
Many tabs, one connection
Users open the app in several tabs, and each one wants live updates. MDN's EventSource page warns that over HTTP/1.1, browsers limit open SSE connections to six per browser and domain, and Chrome and Firefox have marked the issue as "won't fix." Over HTTP/2 the number of streams is negotiated, with a default of 100, but one connection per tab still multiplies server load.
Two browser APIs help:
- BroadcastChannel lets same-origin tabs send messages to each other, per MDN. When one tab marks items as read or receives an event, it broadcasts the change so the other tabs update their badge without asking the server. You can also elect one tab to hold the live connection and relay events to the rest.
- Page Visibility lets a tab know when it's hidden, per MDN. Pause polling in hidden tabs and resync when the tab becomes visible again.
Paginate with a cursor
Notification lists are newest-first and keep growing while users scroll, which breaks offset pagination: new items push old ones onto the next page, so users see duplicates. Use a keyset cursor on the creation time plus the ID as a tiebreaker. PostgreSQL's row comparison lets you compare the pair in one condition, evaluated left to right, and an index on the tenant, user, creation time, and ID keeps each page fast.
Scope everything by tenant
In a multi-tenant app, a notification shown to the wrong tenant is a data leak. Put the tenant ID on every recipient row, include it as the leading column of your indexes, and include it in every query, live channel name, and cache key.
PostgreSQL row-level security adds a second layer. Once enabled on a table, rows are hidden unless a policy allows them, so a forgotten filter returns nothing instead of another tenant's data. Two catches matter. Superusers and roles with the BYPASSRLS attribute always skip row-level security. Table owners skip it too, unless the table is altered to force row-level security. If your app connects as a superuser or as the table owner without that setting, the policies may not apply at all.
Grouping, deduplication, and preferences
Group repetitive events. Twenty likes on a post should be one notification that updates, not twenty rows. A grouping key, such as type plus target plus recipient, lets you upsert a single unread notification. PostgreSQL's INSERT documentation describes ON CONFLICT DO UPDATE as guaranteeing an atomic insert-or-update outcome, which is what grouping needs.
Let users choose. Store preferences per notification type and channel, so a user can keep in-app notifications for mentions but turn off email for them. In the US, the FTC's CAN-SPAM guide applies to commercial email messages. Transactional messages are exempt from most of its provisions, but the FTC reads those categories narrowly. That's a concern for your email channel rather than the in-app list, but it's a good reason to model channels separately.
Retention and cleanup
Notifications pile up quickly, and most are worthless after a few weeks. Decide how long to keep them before launch.
Partition by time. PostgreSQL's partitioning documentation notes that removing old data by dropping or detaching a partition is far faster than a bulk delete, and avoids the VACUUM overhead a large DELETE creates. Monthly partitions on the creation time let you drop a whole month at once. Dropping a partition takes a strong lock on the parent table, while detaching it concurrently takes a lighter one, which matters on a busy table.
Otherwise, delete in batches. If partitioning is too much for now, a scheduled job that deletes old read notifications in small batches avoids long locks.
For EU users, retention isn't only a performance question. GDPR's storage limitation principle, in Article 5(1)(e) of the regulation, says personal data should be kept no longer than necessary for its purpose. It doesn't set a number of days; choose one you can justify and enforce it automatically.
Accessibility
A badge that changes silently is invisible to screen reader users. MDN's guide to live regions recommends polite announcements in most cases, using assertive ones only when an interruption is essential. It also notes the live region should exist in the page's initial markup, so assistive technology is already listening when content changes.
In practice:
- Announce briefly, such as "3 new notifications," and combine bursts into one announcement rather than reading every event.
- Give the bell button an accessible name that includes the count.
- Make the notification list keyboard-navigable, with a clear way to mark items as read.
Build or buy
Hosted services such as Novu and Knock provide inbox components, preferences, and multi-channel delivery. Push services such as Firebase Cloud Messaging and Amazon SNS deliver push and messaging, but they don't give you an in-app list with read state. Building it yourself keeps data in your database and under your tenant rules; buying saves time if you need many channels quickly. The design questions above apply either way.
Checklist
- Separate events from recipient state, and choose your states: seen, read, done.
- Fan out on write for small audiences, and at read time for broadcasts.
- Create notifications only for committed changes, via an outbox or a post-commit job.
- Index unread rows with a partial index, and cap the badge count.
- Treat any counter column as a cache and recompute it.
- Use a watermark for mark-all-as-read.
- Subscribe, then resync over REST, then apply live events, deduplicating by ID.
- Send IDs, not content, over cross-instance channels.
- Share one connection across tabs and pause hidden tabs.
- Paginate with a cursor on creation time and ID.
- Scope by tenant everywhere, and check that row-level security actually applies to your app's role.
- Group repeated events and store preferences per type and channel.
- Partition by time and set a retention period you can justify.
- Announce politely and give the bell an accessible name.



