Web Development
Next.jsReal-timeWebSocketsSSEArchitectureReact QuerySWR

Real-Time Notifications in Next.js (App Router): SSE vs WebSockets, Fanout, and Delivery Guarantees

AO
Adrijan Omićević
·16 min read

# What You’ll Build and Why It Matters#

"Next.js real-time notifications" sounds simple until you hit production constraints: serverless timeouts, fanout costs, reconnection storms, and users who miss events while offline.

This guide shows a pragmatic architecture that works with the Next.js App Router: real-time delivery via SSE or WebSockets, persistence via an inbox table, read states, and a fallback polling strategy using React Query or SWR. You’ll also learn how to choose between SSE and WebSockets for notification delivery and presence-like features, including scaling constraints.

If you want a broader overview of real-time options in Next.js, read Next.js real-time features with WebSockets, SSE, and Supabase Realtime.

# Prerequisites#

RequirementVersionNotes
Next.js14 or 15App Router examples assume modern route handlers
Node.js18+20+ recommended in 2026 for performance and security updates
DatabasePostgres recommendedNeeded for inbox persistence and read state
Cache or pub-subRedis or managed pub-subUsed for fanout across instances
Basic authAnyExamples assume you can identify a user ID on the server

# Architecture Overview: Don’t Ship Notifications as “Just Events”#

Real-time transport is not the product. Notifications are a product feature with UX and reliability requirements.

A production-ready model usually includes:

  1. 1
    Durable inbox for every user, backed by a database table.
  2. 2
    Real-time transport to reduce perceived latency.
  3. 3
    Idempotent delivery so reconnects do not create duplicates.
  4. 4
    Read/unread state with timestamps and optional per-device semantics.
  5. 5
    Fallback polling for environments where real-time connections fail.
  6. 6
    Observability so you can debug missed notifications and latency.

🎯 Key Takeaway: Real-time transport is an optimization. Delivery guarantees come from persistence plus reconciliation.

# SSE vs WebSockets for Next.js Real-Time Notifications#

SSE and WebSockets solve different problems. Notifications are usually server-to-client, bursty, and tolerant to small delays. Presence-like features are bidirectional and require frequent client-to-server heartbeats.

Comparison Table: Notifications, Presence, and Scaling Constraints#

CriteriaSSEWebSockets
DirectionServer to clientFull duplex
Best forNotifications, feeds, status updatesPresence, chat, collaborative cursors, typing indicators
Browser supportExcellentExcellent
Proxy friendlinessVery good, uses HTTPSometimes problematic with corporate proxies
Reconnect behaviorBuilt-in retry and Last-Event-ID patternsYou must implement backoff and resubscribe logic
Message framingText only by defaultBinary and text
Cost profileOne HTTP connection per clientOne socket per client, often more infra
Serverless compatibilityDepends on platform support for streaming responsesOften requires specialized WS support or managed service
Presence accuracyLimitedStrong, via heartbeats and server-side state
Delivery guaranteesNot built inNot built in

SSE for Notifications: Why It Often Wins#

SSE is typically the simplest way to ship "Next.js real-time notifications" when you only need server-to-client events:

  • Runs over HTTP, usually plays nicely with load balancers and proxies.
  • Automatic reconnect behavior in browsers makes it resilient.
  • The mental model is closer to "stream of events" than a socket protocol.

Where SSE can hurt:

  • Scaling: you still maintain one open connection per client, which affects memory and file descriptors.
  • Multi-instance fanout: you need a shared pub-sub layer, otherwise each instance only knows about its own connected clients.
  • Presence: without client-to-server heartbeats, SSE alone cannot reliably track online status.

WebSockets for Presence and Interactive Real-Time#

Use WebSockets when you need:

  • Presence, last-seen, and accurate "online now" indicators
  • Two-way events like "mark as read" without additional HTTP calls
  • High-frequency client events, like collaborative updates

Where WebSockets can hurt:

  • Infrastructure complexity: sticky sessions or shared state, plus careful backpressure handling.
  • Serverless limitations: long-lived sockets do not fit basic serverless request lifecycles.
  • Reconnection semantics: you must design resubscribe flows, replay, and idempotency.

⚠️ Warning: If you implement WebSockets and ship ephemeral events only, users will miss notifications when offline. Always add an inbox and reconcile on reconnect.

# Delivery Guarantees: What You Can and Can’t Promise#

Most teams want “exactly once delivery.” In real-world networks, "exactly once" is expensive and often not needed.

A pragmatic target is:

  • At least once to the inbox: persisted notification exists once, uniquely identified.
  • At least once real-time: the UI may receive duplicates, but the client deduplicates by ID.
  • Eventually consistent read state: read/unread is correct after retries and reconciliation.

Define Your Notification States Explicitly#

If you do not model delivery, you cannot debug delivery.

Common states and timestamps:

FieldTypeWhy it matters
created_attimestampSorting and auditing
delivered_attimestamp nullableOptional, indicates a device saw it
read_attimestamp nullableUnread count and UX
archived_attimestamp nullableOptional, for inbox cleanup
client_last_seen_idbigint or uuidHelps reconcile missed events

# Data Model: Inbox Table and Read State Patterns#

A single "notifications" table is not enough when multiple users can receive the same event (fanout), and when read state is per recipient.

A proven approach:

  • notification_events stores the canonical event payload once.
  • notification_inbox stores per-user delivery and read state.
TableKey columnsPurpose
notification_eventsid, type, payload, created_atImmutable event data
notification_inboxid, user_id, event_id, read_at, created_atPer-user inbox row
notification_devices (optional)id, user_id, device_id, last_seen_atPer-device read sync and delivery metrics

Example Postgres DDL (Minimal)#

SQL
CREATE TABLE notification_events (
  id uuid PRIMARY KEY,
  type text NOT NULL,
  payload jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
 
CREATE TABLE notification_inbox (
  id uuid PRIMARY KEY,
  user_id uuid NOT NULL,
  event_id uuid NOT NULL REFERENCES notification_events(id),
  read_at timestamptz NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (user_id, event_id)
);
 
CREATE INDEX notification_inbox_user_created_idx
  ON notification_inbox (user_id, created_at DESC);

This enables:

  • Deduplication per user via UNIQUE (user_id, event_id)
  • Fast unread counts with WHERE read_at IS NULL
  • Replay from DB when the client reconnects

💡 Tip: Keep notification_events.payload compact. Large payloads inflate both DB and network costs. Store IDs and fetch details lazily when the user opens the notification.

# Fanout Patterns: How Notifications Reach Many Users#

Fanout means one event might be delivered to thousands of inboxes.

You have three common options:

Option A: Fanout on Write (Immediate Inbox Insert)#

When an event happens:

  1. 1
    Insert into notification_events
  2. 2
    Insert one notification_inbox row per recipient user
  3. 3
    Publish a real-time signal per recipient or per channel

Pros:

  • Simple reads: inbox query is direct.
  • Reliable: the DB is the source of truth.

Cons:

  • Heavy write amplification for large recipient sets.
  • Needs background jobs for very large fanout.

Option B: Fanout on Read (Dynamic Querying)#

Store only the event, and compute recipients at read time.

Pros:

  • Low write amplification.

Cons:

  • Complex queries, harder to track read state per user.
  • Difficult to reason about delivery guarantees.

Option C: Hybrid with Background Jobs#

Write the event, enqueue fanout inserts, and publish a real-time hint.

Pros:

  • Scales better with big audiences.
  • Lets you rate-limit and batch inserts.

Cons:

  • More moving parts: queue, retries, idempotency keys.

For most B2B apps, Option A is fine up to moderate scale. If you regularly notify more than 10,000 users per event, you want Option C with batching and backpressure.

# Implementing SSE in Next.js App Router#

SSE is built on streaming a response and writing data: lines. Next.js route handlers can do this on Node runtimes that support streaming.

SSE Route Handler Example#

TypeScript
// app/api/notifications/stream/route.ts
export const runtime = "nodejs";
 
export async function GET() {
  const stream = new ReadableStream({
    start(controller) {
      const encoder = new TextEncoder();
      const send = (obj: unknown) => {
        controller.enqueue(encoder.encode(`data: ${JSON.stringify(obj)}\n\n`));
      };
 
      send({ type: "connected", ts: Date.now() });
 
      const interval = setInterval(() => {
        send({ type: "ping", ts: Date.now() });
      }, 25000);
 
      const cleanup = () => clearInterval(interval);
 
      // No request abort signal in this minimal snippet
      // In production, stop on disconnect and unsubscribe from pub-sub
      return cleanup;
    },
  });
 
  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache, no-transform",
      Connection: "keep-alive",
    },
  });
}

This example only pings. In production you will subscribe to a pub-sub channel for the authenticated user, and write notifications to the stream.

Client Subscription Example#

TypeScript
// client-side
export function connectNotifications() {
  const es = new EventSource("/api/notifications/stream");
  es.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    console.log("notification stream message", msg);
  };
  es.onerror = () => {
    es.close();
  };
  return () => es.close();
}

Scaling SSE: Connection Limits and Instance Fanout#

SSE scaling constraints are often ignored until you have a few thousand concurrent users.

Important constraints to plan for:

  • Each open connection consumes memory and file descriptors.
  • You need cross-instance fanout via Redis pub-sub, NATS, Kafka, or a managed real-time service.
  • If you deploy on serverless where instances scale up and down, connected clients can churn aggressively.

If you need help choosing the right real-time stack and deployment model, the tradeoffs are discussed in Next.js real-time features with WebSockets, SSE, and Supabase Realtime.

# Implementing WebSockets in Next.js: Presence and Bidirectional Actions#

Pure Next.js route handlers are not enough for classic WebSocket servers on many platforms. Common approaches are:

  • Managed WebSocket providers
  • Running a separate Node server for sockets
  • Using platform-specific WebSocket support

Presence-like features require:

  • Heartbeats from client to server
  • A server-side presence store with TTL
  • A strategy for reconnect storms and stale sessions

Presence Model (Practical Minimum)#

FieldStored inTTLMeaning
user_idRedis key60 to 120 secondsUser is online if key exists
last_seen_atDBnoneUpdated on disconnect or periodic flush
connection_idRedis hashsame as TTLDebugging and multi-device

Presence accuracy depends on heartbeat intervals and TTL. For example, a 30-second heartbeat and a 90-second TTL tolerates brief network drops while keeping online status reasonably fresh.

ℹ️ Note: If you deploy behind a proxy that kills idle connections, presence over WebSockets must include ping frames or app-level heartbeats. Otherwise users will “ghost” as online.

# Reconciling Missed Notifications: The Inbox Sync API#

Even with real-time transport, clients will miss events:

  • Device was offline
  • Tab was in background
  • Corporate proxy buffered the stream
  • User switched networks

Your UI should always start by fetching the inbox delta since the last seen ID.

Minimal Inbox API Contract#

EndpointPurposeReturns
GET /api/notifications?after={{cursor}}Fetch new inbox itemsItems plus next cursor
POST /api/notifications/{{id}}/readMark as readUpdated unread count
GET /api/notifications/unread-countFast header badgeNumber

Next.js Route Example: Fetch Inbox Delta#

TypeScript
// app/api/notifications/route.ts
export const runtime = "nodejs";
 
export async function GET(request: Request) {
  const url = new URL(request.url);
  const after = url.searchParams.get("after");
 
  // Replace with your auth and DB calls
  const userId = "user-id";
 
  // Example: cursor-based pagination by created_at and id
  // Keep it deterministic to avoid duplicates
  const items = [
    { id: "n1", createdAt: Date.now(), title: "Invoice paid", readAt: null },
  ];
 
  return Response.json({ items, nextCursor: "cursor-value" });
}

The transport (SSE or WS) should only be responsible for prompting the client to refresh, or sending notification IDs that the client can reconcile against the inbox.

# Read States: Single Source of Truth vs Optimistic UI#

Unread badges are one of the highest-visibility notification surfaces. If they drift, users lose trust.

Recommended approach:

  • DB is the source of truth for read state.
  • Client can optimistically mark as read, but must reconcile on next fetch.

Two common patterns:

Pattern 1: Per-Notification Read Timestamp#

  • Each inbox row has read_at.
  • Unread count is COUNT(*) WHERE read_at IS NULL.

This is simple and supports partial reads.

Pattern 2: High-Water Mark for “Read Up To”#

  • Store last_read_at or last_read_notification_id per user.
  • Everything older than that is treated as read.

This is faster for bulk reads, but breaks if users read out of order or across devices without careful handling.

For most apps, start with per-notification read_at. You can add a high-water mark later for performance, but keep the inbox rows as the audit trail.

Some environments will not keep a stable stream. Your app should remain correct without real-time.

Polling is not “old-school,” it’s a safety net. A 30 to 60-second polling interval is often enough for notifications, and the cost is predictable.

React Query Polling Example#

TypeScript
import { useQuery, useQueryClient } from "@tanstack/react-query";
 
export function useNotifications() {
  return useQuery({
    queryKey: ["notifications"],
    queryFn: async () => {
      const res = await fetch("/api/notifications");
      if (!res.ok) throw new Error("Failed to load notifications");
      return res.json();
    },
    refetchInterval: 30000,
    staleTime: 15000,
  });
}
 
export function useNotificationStreamBridge() {
  const qc = useQueryClient();
 
  return () => {
    const es = new EventSource("/api/notifications/stream");
    es.onmessage = () => {
      qc.invalidateQueries({ queryKey: ["notifications"] });
    };
    return () => es.close();
  };
}

This pattern keeps the stream dumb and robust: stream triggers invalidation, inbox API remains authoritative.

SWR Polling Example#

TypeScript
import useSWR from "swr";
 
const fetcher = (url: string) => fetch(url).then((r) => r.json());
 
export function useNotifications() {
  return useSWR("/api/notifications", fetcher, {
    refreshInterval: 30000,
    dedupingInterval: 5000,
  });
}

For SWR, you can also call mutate("/api/notifications") when your SSE or WS message arrives.

💡 Tip: Use exponential backoff when the stream fails, but keep polling steady. This avoids reconnect storms during incidents.

# Choosing Between SSE and WebSockets: Practical Decision Matrix#

Use this decision matrix to avoid architecture churn.

RequirementRecommended transportWhy
Notifications only, server to clientSSESimple, resilient reconnects, fewer moving parts
Notifications plus interactive actionsSSE plus HTTP for actionsKeeps real-time channel simple and debuggable
Presence, typing indicators, collaborative featuresWebSocketsRequires bidirectional low-latency messaging
Highly restricted enterprise networksSSEOften more proxy-friendly
Mobile app with background delivery needsPush notifications plus inboxReal-time sockets cannot run reliably in background
Need to support millions of connectionsManaged real-time serviceSelf-hosting becomes costly without specialized infra

If you still need presence but want SSE for notifications, you can do hybrid:

  • SSE for notifications
  • A lightweight WebSocket channel only for presence and heartbeats

This reduces message volume on the socket while keeping presence accurate.

# Observability: Debug Missed Notifications and Latency#

Real-time systems fail silently if you don’t instrument them. Add visibility before you scale.

Track these metrics:

MetricWhy it mattersTypical alert trigger
Stream connection countCapacity planningSudden drop greater than 30 percent
Reconnect rateNetwork or platform issuesSpike greater than 3x baseline
Inbox insert latencyBackpressure and DB healthp95 greater than 500 ms
Time to first notificationUX and correctnessp95 greater than 2 s
Unread count mismatch rateState bugsAny sustained increase

For a full instrumentation approach, read Web app observability guide: logging, metrics, tracing and the Next.js-specific setup in Next.js logging and monitoring with Sentry and OpenTelemetry on Vercel.

⚠️ Warning: Logging every notification payload in production can leak PII. Log IDs, types, and timings, and sample aggressively.

# Common Pitfalls (and How to Avoid Them)#

Treating real-time as the database#

If you don’t persist to an inbox, users lose notifications when offline. Always persist first, then notify.

Not deduplicating events on the client#

Reconnects and retries will cause duplicates. Deduplicate by event_id or inbox id in your state store.

Per-recipient fanout in the request path#

If a single action triggers 5,000 inbox inserts in the same HTTP request, your p95 latency will explode. Move fanout to a background job when recipient counts grow.

No fallback when streams fail#

Corporate proxies and mobile networks are not friendly to long-lived connections. Always keep polling enabled.

# Key Takeaways#

  • Choose SSE for most notification-only use cases, and WebSockets when you need presence-like features or high-frequency bidirectional events.
  • Build delivery guarantees with a durable inbox table plus reconciliation, not by trusting SSE or WebSockets to be reliable.
  • Model read state explicitly with per-user inbox rows and read_at, and deduplicate with a unique constraint on (user_id, event_id).
  • Plan fanout early: start with fanout-on-write for moderate scale, and move large recipient fanout into background jobs with batching.
  • Always implement fallback polling with React Query or SWR, and let real-time messages trigger cache invalidation instead of being the only source of truth.
  • Add observability for reconnect rate, inbox insert latency, and unread mismatches to catch failures before users report them.

# Conclusion#

Real-time delivery improves UX, but durable notifications require persistence, clear state modeling, and a fallback path. Start with an inbox-first design, add SSE for simple real-time updates, and reach for WebSockets only when presence and two-way interactions justify the complexity.

If you want Samioda to design or implement a production-ready Next.js real-time notifications system, including scaling and observability, contact us and we’ll review your requirements and propose an architecture that fits your traffic and hosting constraints.

FAQ

Share
A
Adrijan OmićevićFounder & Senior Developer

Founder & Senior Developer at Samioda. 8+ years building React, Next.js, Flutter and n8n automation solutions for clients across Europe.

Need help with your project?

We build custom solutions using the technologies discussed in this article. Senior team, fixed prices.