Real-time Notifications and Multi-Channel Delivery: WebSockets, Push, Email, and Beyond
Delivery patterns for WebSocket, push, email, SMS and webhook channels: cross-instance routing, safe provider failover, payload limits and signed webhooks
A notification system has to reach the same person through channels that share almost nothing: a socket that lives for minutes, a push token that can go stale between two sends, an email address that may already be on a suppression list.
Connection drain on WebSockets, token invalidation on push, bounce handling on email: every mechanism carries its own limits, failure modes, and latency expectation. WebSockets need sub-second delivery, while a few minutes is acceptable for email. What follows are the delivery patterns for each channel, the coordination layer that decides which one fires when, and the provider limits each channel runs into.
WebSocket Connection Management#
Storing Connection State#
The manager below, written against an ioredis client, keeps the user-to-socket mapping in Redis, so an instance that does not own the connection can still find it:
interface ConnectionMetadata {
userId: string;
deviceId?: string;
userAgent: string;
connectedAt: Date;
lastPing: Date;
subscriptions: Set<string>;
metadata: Record<string, any>;
}
class WebSocketConnectionManager {
private connections: Map<string, {
socket: WebSocket;
metadata: ConnectionMetadata;
}> = new Map();
private userConnections: Map<string, Set<string>> = new Map();
private heartbeatInterval?: NodeJS.Timeout;
constructor(private redis: Redis, private serverId: string) {}
// Awaited before the server accepts sockets: peers read a missing key as a crash
async start(): Promise<void> {
await this.beat();
this.heartbeatInterval = setInterval(() => {
this.beat().catch((error) => console.error('Heartbeat failed:', error));
}, 30_000);
}
private async beat(): Promise<void> {
const pipeline = this.redis.pipeline();
// Liveness key: expires three missed heartbeats after this process dies
pipeline.set(`ws:server:${this.serverId}`, '1', 'EX', 90);
// Rewrite this server's rows, so a row a peer removed during a Redis blip comes back
for (const [connectionId, { metadata }] of this.connections) {
pipeline.hset(`ws:connections:${metadata.userId}`, connectionId, this.connectionRecord(metadata));
}
await pipeline.exec();
// ... ping local sockets, close the ones whose lastPing is too old
}
private connectionRecord(metadata: ConnectionMetadata): string {
return JSON.stringify({
serverId: this.serverId,
connectedAt: metadata.connectedAt,
deviceId: metadata.deviceId
});
}
async handleConnection(socket: WebSocket, request: IncomingMessage): Promise<void> {
const connectionId = this.generateConnectionId();
try {
// Extract user info from JWT token or session
const userInfo = await this.authenticateConnection(request);
if (!userInfo) {
socket.close(1008, 'Authentication required');
return;
}
const metadata: ConnectionMetadata = {
userId: userInfo.userId,
deviceId: userInfo.deviceId,
userAgent: request.headers['user-agent'] || '',
connectedAt: new Date(),
lastPing: new Date(),
subscriptions: new Set(),
metadata: {}
};
// Store connection
this.connections.set(connectionId, { socket, metadata });
// Update user connection mapping
if (!this.userConnections.has(userInfo.userId)) {
this.userConnections.set(userInfo.userId, new Set());
}
this.userConnections.get(userInfo.userId)!.add(connectionId);
// Store connection info in Redis for multi-instance support
await this.redis.hset(
`ws:connections:${userInfo.userId}`,
connectionId,
this.connectionRecord(metadata)
);
// Setup event handlers
this.setupConnectionHandlers(connectionId, socket, metadata);
// Send connection acknowledgment
await this.sendMessage(connectionId, {
type: 'connection_ack',
data: { connectionId, timestamp: new Date() }
});
console.log(`WebSocket connection established for user ${userInfo.userId}`);
} catch (error) {
console.error('WebSocket connection setup failed:', error);
socket.close(1011, 'Internal server error');
}
}
private setupConnectionHandlers(
connectionId: string,
socket: WebSocket,
metadata: ConnectionMetadata
): void {
socket.on('message', async (data) => {
try {
const message = JSON.parse(data.toString());
await this.handleMessage(connectionId, message);
} catch (error) {
console.error('Message handling error:', error);
await this.sendError(connectionId, 'Invalid message format');
}
});
socket.on('pong', () => {
metadata.lastPing = new Date();
});
socket.on('close', async (code, reason) => {
await this.handleDisconnection(connectionId, code, reason);
});
socket.on('error', async (error) => {
console.error(`WebSocket error for ${connectionId}:`, error);
await this.handleDisconnection(connectionId, 1011, 'Connection error');
});
}
// Entry point for producers: local sockets first, then the servers that own the rest
async sendNotificationToUser(userId: string, notification: NotificationEvent): Promise<void> {
await this.deliverLocally(userId, notification);
const entries = await this.redis.hgetall(`ws:connections:${userId}`);
const targets = new Set<string>();
for (const [connectionId, raw] of Object.entries(entries)) {
const { serverId } = JSON.parse(raw) as { serverId: string };
if (serverId === this.serverId) continue;
// A server that stopped refreshing its liveness key crashed: drop its leftovers
if (!(await this.redis.exists(`ws:server:${serverId}`))) {
await this.redis.hdel(`ws:connections:${userId}`, connectionId);
continue;
}
targets.add(serverId);
}
// One message per owning server, on that server's own channel
for (const serverId of targets) {
await this.redis.publish(
`ws:notification:${serverId}`,
JSON.stringify({ userId, notification })
);
}
}
// Entry point for the cluster subscriber: touches local sockets only and never publishes,
// so a notification makes at most one hop between servers
async deliverLocally(userId: string, notification: NotificationEvent): Promise<void> {
const connectionIds = Array.from(this.userConnections.get(userId) ?? []);
const results = await Promise.allSettled(
connectionIds.map((connectionId) =>
this.sendMessage(connectionId, { type: 'notification', data: notification })
)
);
// Clean up connections whose send failed
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to send notification to ${connectionIds[index]}:`, result.reason);
void this.handleDisconnection(connectionIds[index], 1011, 'Send failed');
}
});
}
}
The producer side and the subscriber side call different methods on purpose. If the subscriber ran the producer path, the receiving server would publish back to every other server holding a socket for that user, and the message would bounce between them without end. The liveness key covers the other gap: handleDisconnection removes a socket’s row on a clean close, but a crashed process never runs it, so its rows stay in the hash until a sender notices that ws:server:<id> has expired. The key has to exist before the first socket arrives. A new server that waited for its first interval would look crashed to its peers for 30 seconds, and they would delete the rows of every user who connected in that time, so start() writes it once before the server accepts connections. Each heartbeat also rewrites the server’s own rows, which repairs a row that a peer deleted while the key had briefly expired.
Coordinating Across Instances#
Horizontal scaling breaks the assumption that the sender and the connection live in the same process. Redis pub/sub closes that gap, with each server listening on a channel named after itself:
class WebSocketCluster {
private subscriber: Redis;
constructor(
private connectionManager: WebSocketConnectionManager,
private redis: Redis,
private serverId: string
) {
// A RESP2 connection in subscribed state only accepts (UN)SUBSCRIBE-family
// commands, PING, RESET and QUIT, so subscriptions get their own connection
this.subscriber = redis.duplicate();
this.setupClusterCommunication();
}
private setupClusterCommunication(): void {
// Each server listens on its own channel plus the shared broadcast channel
void this.subscriber.subscribe(`ws:notification:${this.serverId}`, 'ws:broadcast');
this.subscriber.on('message', async (channel, message) => {
try {
const data = JSON.parse(message);
if (channel === 'ws:broadcast') {
await this.handleBroadcast(data);
} else {
// Addressed to this server: deliver, never re-publish
await this.connectionManager.deliverLocally(data.userId, data.notification);
}
} catch (error) {
console.error('Cluster message handling error:', error);
}
});
}
async broadcastSystemMessage(message: unknown): Promise<void> {
await this.redis.publish('ws:broadcast', JSON.stringify({
message,
senderId: this.serverId,
timestamp: new Date()
}));
}
}
Redis pub/sub delivers at most once: a message published while the target server restarts is gone. That is acceptable only because the socket is not the record of truth. The delivery row from Part 1 and the in-app inbox still hold the notification, and the client fetches what it missed when it reconnects. A channel that must not lose messages needs Redis Streams or a queue instead.
Push Notification Delivery#
Multi-Platform Push Service#
iOS and Android should be treated as completely different systems, even though they’re both “push notifications”:
import { createHash } from 'node:crypto';
interface PushProvider {
sendNotification(
tokens: string[],
payload: PushPayload,
options?: PushOptions
): Promise<PushResult[]>;
validateToken(token: string): Promise<boolean>;
getInvalidTokens(results: PushResult[]): string[];
}
interface PushPayload {
title: string;
body: string;
data?: Record<string, string>; // FCM's data map is string-to-string
badge?: number;
sound?: string;
icon?: string;
color?: string; // Android icon color, #rrggbb
image?: string;
}
// APNs (non-VoIP) and FCM both refuse payloads above 4096 bytes
const MAX_PUSH_PAYLOAD_BYTES = 4096;
// Example: types whose updates replace each other, such as a build or order status
const COLLAPSIBLE_TYPES = new Set(['build_status', 'order_status']);
// apns-collapse-id allows 64 bytes, and a SHA-256 hex digest is exactly 64
function collapseKeyFor(type: string, entityId: string): string {
const key = `${type}:${entityId}`;
return Buffer.byteLength(key, 'utf8') <= 64
? key
: createHash('sha256').update(key).digest('hex');
}
class UnifiedPushService {
private providers: Map<PushPlatform, PushProvider> = new Map();
private tokenStore: TokenStore;
private analytics: PushAnalytics;
constructor() {
this.providers.set('ios', new APNSProvider());
this.providers.set('android', new FCMProvider());
this.providers.set('web', new WebPushProvider());
}
async sendPushNotification(
userId: string,
notification: NotificationEvent
): Promise<PushDeliveryResult> {
try {
// Get all push tokens for user
const userTokens = await this.tokenStore.getUserTokens(userId);
if (userTokens.length === 0) {
return {
success: false,
reason: 'no_tokens',
deliveries: []
};
}
// Group tokens by platform
const tokensByPlatform = this.groupTokensByPlatform(userTokens);
// Prepare platform-specific payloads
const payloads = await this.createPlatformPayloads(notification);
// Send to each platform
const deliveryPromises = Object.entries(tokensByPlatform).map(
([platform, tokens]) => this.sendToPlatform(
platform as PushPlatform,
tokens,
payloads[platform as PushPlatform],
notification
)
);
const results = await Promise.allSettled(deliveryPromises);
// Process results and clean up invalid tokens
const deliveries = await this.processDeliveryResults(results, userTokens);
// Track analytics
await this.analytics.trackPushDelivery(notification.id, deliveries);
return {
success: deliveries.some(d => d.success),
deliveries
};
} catch (error) {
console.error('Push notification delivery failed:', error);
return {
success: false,
reason: 'send_error',
error: error.message,
deliveries: []
};
}
}
private async sendToPlatform(
platform: PushPlatform,
tokens: PushToken[],
payload: PushPayload,
notification: NotificationEvent
): Promise<PlatformDeliveryResult> {
const provider = this.providers.get(platform);
if (!provider) {
throw new Error(`No provider for platform ${platform}`);
}
const ttl = notification.expiresAt
? Math.floor((notification.expiresAt.getTime() - Date.now()) / 1000)
: 3600; // 1 hour default
if (ttl <= 0) {
// Expired while queued: a stale alert is worse than none
return { platform, tokens: [], results: [], invalidTokens: [], skipped: 'expired' };
}
const entityId = notification.data.entityId;
const options: PushOptions = {
priority: this.mapPriorityToPlatform(notification.priority, platform),
ttl: Math.min(ttl, 2_419_200), // FCM's maximum TTL is 4 weeks
// Collapse updates to the same entity only, and only for types listed as collapsible
collapseKey: COLLAPSIBLE_TYPES.has(notification.type) && typeof entityId === 'string'
? collapseKeyFor(notification.type, entityId)
: undefined,
apnsTopic: platform === 'ios' ? process.env.APNS_TOPIC : undefined
};
const tokenStrings = tokens.map(t => t.token);
const results = await provider.sendNotification(tokenStrings, payload, options);
// Clean up invalid tokens
const invalidTokens = provider.getInvalidTokens(results);
if (invalidTokens.length > 0) {
await this.tokenStore.markTokensInvalid(notification.userId, invalidTokens);
}
return {
platform,
tokens: tokenStrings,
results,
invalidTokens
};
}
private async createPlatformPayloads(
notification: NotificationEvent
): Promise<Record<PushPlatform, PushPayload>> {
const user = await this.getUser(notification.userId);
const template = await this.templateService.getTemplate(
notification.type,
'push',
user.locale
);
const rendered = await this.templateService.render(template, notification.data);
// The push carries a pointer; the app loads the full notification by id
const data: Record<string, string> = {
notificationId: notification.id,
type: notification.type
};
if (typeof notification.data.deepLink === 'string') {
data.deepLink = notification.data.deepLink;
}
const payloads: Record<PushPlatform, PushPayload> = {
ios: {
title: rendered.subject || '',
body: rendered.body,
data,
badge: await this.getBadgeCount(notification.userId),
sound: this.getSoundForNotificationType(notification.type)
},
android: {
title: rendered.subject || '',
body: rendered.body,
data,
icon: 'ic_notification',
color: '#007AFF'
},
web: {
title: rendered.subject || '',
body: rendered.body,
data,
icon: '/icons/notification-icon.png',
image: notification.data.imageUrl
}
};
for (const payload of Object.values(payloads)) {
// Approximation: providers add their own envelope, so keep headroom below the limit
const bytes = Buffer.byteLength(JSON.stringify(payload), 'utf8');
if (bytes > MAX_PUSH_PAYLOAD_BYTES - 512) {
throw new Error(`Push payload too large: ${bytes} bytes`);
}
}
return payloads;
}
}
The payload shape follows from three provider rules. APNs refuses any non-VoIP notification above 4 KB, and FCM applies the same 4096-byte ceiling to both its message types, so spreading notification.data into the push makes the whole send fail once one event carries a large field. FCM’s data is a map of strings, which is why the payload holds only an id, a type and a deep link. A collapse key tells the provider to keep only the latest message in its group. Keyed by notification type, an update to project B would replace a pending update to project A, so the key names one entity. FCM stores at most four collapse keys per device, so only the types listed in COLLAPSIBLE_TYPES get a key: status updates where the latest one makes the earlier ones useless. Everything else goes out without one. APNs caps the same key at 64 bytes in apns-collapse-id, so a longer key is replaced by its SHA-256 hex digest.
Push Token Management#
class PushTokenStore {
constructor(private db: Database, private redis: Redis) {}
async registerToken(
userId: string,
token: string,
platform: PushPlatform,
deviceId: string
): Promise<void> {
try {
// Validate token format
if (!this.isValidTokenFormat(token, platform)) {
throw new Error('Invalid token format');
}
// Check if token already exists for another user
const existingToken = await this.db.query(
'SELECT user_id FROM push_tokens WHERE token = $1',
[token]
);
if (existingToken.length > 0 && existingToken[0].user_id !== userId) {
// Token moved to new user, update it
await this.db.query(
'UPDATE push_tokens SET user_id = $1, updated_at = NOW() WHERE token = $2',
[userId, token]
);
} else {
// Insert or update token
await this.db.query(`
INSERT INTO push_tokens (user_id, token, platform, device_id, is_active, created_at, updated_at)
VALUES ($1, $2, $3, $4, true, NOW(), NOW())
ON CONFLICT (token)
DO UPDATE SET
user_id = $1,
is_active = true,
updated_at = NOW()
`, [userId, token, platform, deviceId]);
}
// Invalidate, never patch: the next read rebuilds the full list from the database
const staleKeys = [`push_tokens:${userId}`];
if (existingToken.length > 0 && existingToken[0].user_id !== userId) {
staleKeys.push(`push_tokens:${existingToken[0].user_id}`); // the device left that user
}
await this.redis.del(...staleKeys);
console.log(`Registered push token for user ${userId} on ${platform}`);
} catch (error) {
console.error('Push token registration failed:', error);
throw error;
}
}
async markTokensInvalid(userId: string, tokens: string[]): Promise<void> {
if (tokens.length === 0) return;
await this.db.query(
'UPDATE push_tokens SET is_active = false, updated_at = NOW() WHERE token = ANY($1)',
[tokens]
);
await this.redis.del(`push_tokens:${userId}`);
console.log(`Marked ${tokens.length} tokens as invalid for user ${userId}`);
}
async getUserTokens(userId: string): Promise<PushToken[]> {
const key = `push_tokens:${userId}`;
const cached = await this.redis.get(key);
if (cached !== null) {
return JSON.parse(cached) as PushToken[];
}
const tokens: PushToken[] = await this.db.query(`
SELECT token, platform, device_id, created_at
FROM push_tokens
WHERE user_id = $1 AND is_active = true
ORDER BY updated_at DESC
`, [userId]);
// Cache the complete list (an empty one included), never a subset.
// The short TTL bounds how long a list written by a racing read can stay stale
await this.redis.set(key, JSON.stringify(tokens), 'EX', 300); // 5 minutes
return tokens;
}
}
The cache holds the whole token list or nothing. Adding a single token to a set that had already expired would recreate it with that one token, and every later read would treat the set as complete and skip the user’s other devices. Deleting the key on every write moves that decision back to the database. One race remains. A getUserTokens call that queried the database just before a new token was inserted can write its older list after registerToken deleted the key, and the new device then misses sends until that entry expires. The five-minute TTL keeps that window short, where a 24-hour TTL would hide a new phone for a day.
Email Deliverability and Bounce Handling#
Email Service with Provider Failover#
Email providers can fail, get rate limited, or have deliverability issues. A second provider adds redundancy, but only if a failed call is classified before the next provider is tried. A timeout does not mean the message was not sent:
// What a failed send tells us about the message
type FailureKind =
| 'safe_to_failover' // provider refused before accepting: another provider may send it
| 'permanent' // bad address or rejected content: every provider will refuse it
| 'unknown'; // timed out mid-request: the provider may already have sent it
function classifySendError(error: { status?: number; code?: string }): FailureKind {
if (error.status === undefined) {
// No response. Only a connection that never opened proves nothing was sent
return error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND'
? 'safe_to_failover'
: 'unknown';
}
if ([401, 403, 429, 503].includes(error.status)) return 'safe_to_failover';
if (error.status >= 400 && error.status < 500) return 'permanent';
return 'unknown'; // 500, 502, 504: acceptance cannot be ruled out
}
interface EmailProvider {
sendEmail(email: EmailMessage): Promise<EmailResult>;
handleWebhook(payload: any): Promise<WebhookResult>;
getDeliverabilityScore(): Promise<number>;
}
class EmailDeliveryService {
// Priority order; a provider's sendEmail throws on any non-2xx response
private providers: EmailProvider[] = [
new SendGridProvider(),
new AmazonSESProvider(),
new PostmarkProvider()
];
async sendEmail(
userId: string,
notification: NotificationEvent
): Promise<EmailDeliveryResult> {
try {
// Get user email and preferences
const user = await this.getUserWithEmailPrefs(userId);
if (!user.email || !user.emailEnabled) {
return {
success: false,
reason: 'email_disabled',
attempts: []
};
}
// Check if user is on suppression list
if (await this.isUserSuppressed(user.email)) {
return {
success: false,
reason: 'user_suppressed',
attempts: []
};
}
// Render email content
const emailContent = await this.renderEmailContent(notification, user);
// Prepare email message
const emailMessage: EmailMessage = {
to: user.email,
from: this.getFromAddress(notification.type),
subject: emailContent.subject,
html: emailContent.html,
text: emailContent.text,
metadata: {
userId,
notificationId: notification.id,
notificationType: notification.type
},
tags: [notification.type, `user:${userId}`],
unsubscribeUrl: this.generateUnsubscribeUrl(userId, notification.type)
};
// Providers in priority order; move on only when the last one provably did not send
const attempts: EmailAttemptResult[] = [];
for (const provider of this.providers) {
const attempt = await this.attemptDelivery(provider, emailMessage);
attempts.push(attempt);
// Every attempt lands on the delivery row, so a retry worker sees what was tried
await this.storeDeliveryAttempt(notification.id, 'email', attempt);
if (attempt.success || attempt.failure !== 'safe_to_failover') break;
console.warn(`${attempt.providerId} refused the message, trying the next provider`);
}
const last = attempts[attempts.length - 1];
return {
success: last.success,
// 'unknown' waits for the provider's delivery or bounce event instead of a resend
status: last.success ? 'sent' : last.failure,
attempts,
providerId: last.providerId,
messageId: last.messageId
};
} catch (error) {
console.error('Email delivery failed:', error);
return {
success: false,
reason: 'delivery_error',
error: error.message,
attempts: []
};
}
}
private async attemptDelivery(
provider: EmailProvider,
email: EmailMessage
): Promise<EmailAttemptResult> {
const startTime = Date.now();
try {
const result = await provider.sendEmail(email);
const duration = Date.now() - startTime;
return {
providerId: provider.constructor.name,
success: true,
messageId: result.messageId,
duration,
response: result.response
};
} catch (error) {
const duration = Date.now() - startTime;
return {
providerId: provider.constructor.name,
success: false,
duration,
error: error.message,
failure: classifySendError(error)
};
}
}
private async renderEmailContent(
notification: NotificationEvent,
user: User
): Promise<EmailContent> {
// Get email template
const template = await this.templateService.getTemplate(
notification.type,
'email',
user.locale
);
// Render with user data and notification data
const context = {
user,
...notification.data,
unsubscribeUrl: this.generateUnsubscribeUrl(user.id, notification.type),
preferencesUrl: this.generatePreferencesUrl(user.id)
};
const rendered = await this.templateService.render(template, context);
// Convert markdown to HTML if needed
const html = this.markdownToHtml(rendered.body);
const text = this.htmlToText(html);
return {
subject: rendered.subject,
html,
text
};
}
}
The unknown branch is where duplicates come from. A timeout after the request left the process may still end in a sent email, and failing over at that point gives the user two copies. Deduplication has to live on this side: the SES SendEmail request has no idempotency-key parameter, so a resend must not happen while an earlier attempt is still unresolved. The notificationId in the message metadata ties the provider’s later delivery or bounce event back to the delivery row, and that event settles the unknown status.
A standby provider also has to be able to deliver on the day it takes over. Each provider signs with keys it manages (SES Easy DKIM, for example, generates its own key pair), so the sending domain publishes DKIM and SPF records for every provider in the list, the standby ones included. A dedicated IP needs a warm-up period before mailbox providers trust it, which SES puts at around two weeks for some providers and up to six weeks for others. A secondary that only sends during an outage never warms up, so it should carry a small share of regular traffic.
Email Bounce and Complaint Handling#
Handling bounces, complaints, and unsubscribes properly is critical for deliverability:
// Policy choice, not a provider rule: tune it against your own bounce history
const SOFT_BOUNCE_LIMIT = 5;
class EmailWebhookHandler {
constructor(
private db: Database,
private suppressionService: SuppressionService
) {}
async handleWebhook(
provider: string,
payload: any
): Promise<WebhookProcessResult> {
try {
const events = this.parseProviderWebhook(provider, payload);
for (const event of events) {
await this.processEmailEvent(event);
}
return { success: true, eventsProcessed: events.length };
} catch (error) {
console.error('Webhook processing failed:', error);
return { success: false, error: error.message };
}
}
private async processEmailEvent(event: EmailEvent): Promise<void> {
// Update delivery record
await this.db.query(`
UPDATE notification_deliveries
SET status = $1, delivered_at = $2, error_message = $3, provider_response = $4
WHERE provider_id = $5
`, [
event.status,
event.timestamp,
event.error,
JSON.stringify(event.rawData),
event.messageId
]);
// Handle specific event types
switch (event.type) {
case 'bounce':
await this.handleBounce(event);
break;
case 'complaint':
await this.handleComplaint(event);
break;
case 'unsubscribe':
await this.handleUnsubscribe(event);
break;
case 'delivered':
await this.handleDelivery(event);
break;
}
}
private async handleBounce(event: EmailEvent): Promise<void> {
const bounceType = event.bounceType || 'unknown';
if (bounceType === 'permanent') {
// Suppress permanently bounced email
await this.suppressionService.addSuppression({
email: event.recipient,
reason: 'permanent_bounce',
source: 'webhook',
metadata: {
bounceSubType: event.bounceSubType,
messageId: event.messageId
}
});
console.log(`Permanently suppressed ${event.recipient} due to hard bounce`);
} else if (bounceType === 'temporary') {
// Track temporary bounces, suppress after threshold
const bounceCount = await this.incrementBounceCount(event.recipient);
if (bounceCount >= SOFT_BOUNCE_LIMIT) {
await this.suppressionService.addSuppression({
email: event.recipient,
reason: 'repeated_soft_bounces',
source: 'auto_suppression',
metadata: { bounceCount }
});
console.log(`Auto-suppressed ${event.recipient} after ${bounceCount} soft bounces`);
}
}
}
private async handleComplaint(event: EmailEvent): Promise<void> {
// Immediately suppress users who mark emails as spam
await this.suppressionService.addSuppression({
email: event.recipient,
reason: 'spam_complaint',
source: 'webhook',
metadata: {
messageId: event.messageId,
complaintType: event.complaintSubType
}
});
// Also switch email off on the account, so the preference screen shows the opt-out
await this.db.query(`
UPDATE users SET email_enabled = false
WHERE email = $1
`, [event.recipient]);
console.log(`Suppressed ${event.recipient} due to spam complaint`);
}
}
The two suppression paths protect different things. SES computes the account bounce rate from hard bounces only: at 5% it places the account under review, and at 10% it may pause sending. Complaints weigh far more, with review at 0.1% and a possible pause at 0.5%. That asymmetry is why a hard bounce or a complaint suppresses at once, while soft bounces only count toward a local limit.
SMS and Webhook Channels#
SMS Delivery Service#
SMS is billed per segment, and the segment size depends on the encoding. A message that fits GSM-7 gets 160 characters in one segment and 153 per segment once it is split. A single character outside GSM-7 switches the whole message to UCS-2, which drops those numbers to 70 and 67. The Turkish letters ş, ğ, ı and lowercase ç are outside the GSM-7 basic set, so a Turkish template usually costs more segments than its English twin:
const GSM7_BASIC =
'@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?' +
'¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà';
const GSM7_EXTENDED = '^{}\\[~]|€\f'; // each costs two septets
function smsSegments(text: string): { encoding: 'GSM-7' | 'UCS-2'; segments: number } {
let septets = 0;
for (const ch of text) {
if (GSM7_BASIC.includes(ch)) {
septets += 1;
} else if (GSM7_EXTENDED.includes(ch)) {
septets += 2;
} else {
// One character outside GSM-7 (ş, ğ, ı, ç, an emoji) moves the whole message to UCS-2
const units = text.length; // UTF-16 code units
return { encoding: 'UCS-2', segments: units <= 70 ? 1 : Math.ceil(units / 67) };
}
}
return { encoding: 'GSM-7', segments: septets <= 160 ? 1 : Math.ceil(septets / 153) };
}
The service below enforces a segment budget per template and fails over only when the first provider provably did not send, using the same classifySendError as email:
class SMSDeliveryService {
private provider: SMSProvider;
private fallbackProvider: SMSProvider;
constructor() {
this.provider = new TwilioProvider();
this.fallbackProvider = new AmazonSNSProvider();
}
async sendSMS(
userId: string,
notification: NotificationEvent
): Promise<SMSDeliveryResult> {
try {
const user = await this.getUserWithSMSPrefs(userId);
if (!user.phone || !user.smsEnabled) {
return { success: false, reason: 'sms_disabled' };
}
// SMS content should be concise
const content = await this.renderSMSContent(notification, user);
const message = {
to: user.phone,
message: content,
metadata: { userId, notificationId: notification.id }
};
let result = await this.attemptSMS(this.provider, message);
await this.storeDeliveryAttempt(notification.id, 'sms', result);
// A timeout here may already have cost a paid message: never resend on 'unknown'
if (!result.success && result.failure === 'safe_to_failover') {
result = await this.attemptSMS(this.fallbackProvider, message);
await this.storeDeliveryAttempt(notification.id, 'sms', result);
}
return result;
} catch (error) {
console.error('SMS delivery failed:', error);
return { success: false, error: error.message };
}
}
private async renderSMSContent(
notification: NotificationEvent,
user: User
): Promise<string> {
const template = await this.templateService.getTemplate(
notification.type,
'sms',
user.locale
);
const rendered = await this.templateService.render(template, {
user,
...notification.data
});
// Fail at render: cutting the text could split a code or a link in half
const { encoding, segments } = smsSegments(rendered.body);
if (segments > template.maxSegments) {
throw new Error(
`Template ${template.id} needs ${segments} ${encoding} segments, budget is ${template.maxSegments}`
);
}
return rendered.body;
}
// Inbound webhook from the SMS provider
async handleInboundSMS(from: string, body: string): Promise<void> {
const keyword = body.trim().toUpperCase();
if (OPT_OUT_KEYWORDS.has(keyword)) {
await this.db.query('UPDATE users SET sms_enabled = false WHERE phone = $1', [from]);
} else if (OPT_IN_KEYWORDS.has(keyword)) {
// Twilio unblocks the number on these, so the local flag follows
await this.db.query('UPDATE users SET sms_enabled = true WHERE phone = $1', [from]);
}
}
}
// Twilio's default English opt-out keywords
const OPT_OUT_KEYWORDS = new Set([
'STOP', 'UNSUBSCRIBE', 'END', 'QUIT', 'STOPALL', 'REVOKE', 'OPTOUT', 'CANCEL'
]);
// Twilio's reserved opt-in keywords, which cannot be removed
const OPT_IN_KEYWORDS = new Set(['START', 'UNSTOP']);
Because the budget check throws at render time, a test that renders every template with sample data catches an over-budget template before release, where someone can still shorten it. Truncation would instead ship it to users cut in the middle of a one-time code. The opt-out handler matters even when the provider blocks the number itself. Twilio rejects later messages to an opted-out number with error 21610, but the local sms_enabled flag is what keeps the preference screen accurate and stops the service from attempting sends that can only fail. The reverse path needs the same mirror: when the user replies START or UNSTOP, Twilio removes the number from its block list, and the flag has to turn back on with it. Twilio lets the opt-out keyword list differ per country, and other sending rules vary by destination as well, so they belong in a per-country rule table that the SMS service reads.
Webhook Delivery for Integrations#
A webhook URL is user input that the server will call, which makes it a server-side request forgery (SSRF) path into the internal network. The client below resolves DNS inside the connection itself and refuses private, loopback and link-local addresses, including the cloud metadata address 169.254.169.254. Because the check runs at connect time, a DNS answer that changes between validation and request cannot slip through. Signing follows the Standard Webhooks scheme, which binds the message id, a timestamp and the exact body bytes:
import { createHmac } from 'node:crypto';
import { lookup as dnsLookup } from 'node:dns';
import { request } from 'node:https';
import { BlockList, isIP, type LookupFunction } from 'node:net';
// Destinations a customer-supplied URL must never reach.
// IPv4 rules also match IPv4-mapped IPv6 addresses (::ffff:10.0.0.1)
const blocked = new BlockList();
blocked.addSubnet('0.0.0.0', 8, 'ipv4');
blocked.addSubnet('10.0.0.0', 8, 'ipv4');
blocked.addSubnet('100.64.0.0', 10, 'ipv4');
blocked.addSubnet('127.0.0.0', 8, 'ipv4');
blocked.addSubnet('169.254.0.0', 16, 'ipv4'); // link-local, includes 169.254.169.254
blocked.addSubnet('172.16.0.0', 12, 'ipv4');
blocked.addSubnet('192.168.0.0', 16, 'ipv4');
blocked.addAddress('::', 'ipv6');
blocked.addAddress('::1', 'ipv6');
blocked.addSubnet('fc00::', 7, 'ipv6'); // unique local
blocked.addSubnet('fe80::', 10, 'ipv6'); // link-local
// Runs when the socket connects, so the address that passed the check
// is the address the request uses
const safeLookup: LookupFunction = (hostname, options, callback) => {
dnsLookup(hostname, { ...options, all: true }, (err, addresses) => {
if (err) return callback(err, '');
const denied = addresses.length === 0 || addresses.some((a) =>
blocked.check(a.address, a.family === 6 ? 'ipv6' : 'ipv4'));
if (denied) return callback(new Error(`Blocked webhook destination: ${hostname}`), '');
if (options.all) return callback(null, addresses);
callback(null, addresses[0].address, addresses[0].family);
});
};
function postWebhook(url: URL, body: string, headers: Record<string, string>): Promise<number> {
return new Promise((resolve, reject) => {
const req = request(url, {
method: 'POST',
headers: { ...headers, 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
lookup: safeLookup,
timeout: 10_000,
}, (res) => {
res.resume(); // redirects are not followed: a 3xx counts as a failure
resolve(res.statusCode ?? 0);
});
req.on('timeout', () => req.destroy(new Error('Webhook timed out')));
req.on('error', reject);
req.end(body);
});
}
// Standard Webhooks signature: HMAC-SHA256 over "id.timestamp.body",
// with a base64 secret carried behind the whsec_ prefix
function signWebhook(secret: string, msgId: string, timestamp: number, body: string): string {
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const signature = createHmac('sha256', key)
.update(`${msgId}.${timestamp}.${body}`)
.digest('base64');
return `v1,${signature}`;
}
class WebhookDeliveryService {
// A BullMQ queue: its worker calls deliverToWebhook again and throws only when
// the result has shouldRetry, so a permanent 4xx ends the job and the job's
// attempts and backoff settings drive the retries
constructor(private retryQueue: Queue) {}
async sendWebhook(
userId: string,
notification: NotificationEvent
): Promise<WebhookDeliveryResult> {
try {
// Get user's webhook configurations
const webhookConfigs = await this.getWebhookConfigs(userId, notification.type);
if (webhookConfigs.length === 0) {
return { success: false, reason: 'no_webhooks_configured' };
}
// Send to each configured webhook
const deliveryPromises = webhookConfigs.map(config =>
this.deliverToWebhook(config, notification)
);
const results = await Promise.allSettled(deliveryPromises);
// Retryable failures go to the queue; the retry reuses the same msgId
await Promise.all(results.map((r, i) =>
r.status === 'fulfilled' && r.value.shouldRetry
? this.retryQueue.add(
'webhook-retry',
{ configId: webhookConfigs[i].id, notificationId: notification.id },
{ attempts: 5, backoff: { type: 'exponential', delay: 30_000 } }
)
: undefined
));
const successful = results.filter(r =>
r.status === 'fulfilled' && r.value.success
).length;
return {
success: successful > 0,
delivered: successful,
total: webhookConfigs.length,
results: results.map(r =>
r.status === 'fulfilled' ? r.value : { success: false, error: r.reason }
)
};
} catch (error) {
console.error('Webhook delivery failed:', error);
return { success: false, error: error.message };
}
}
private async deliverToWebhook(
config: WebhookConfig,
notification: NotificationEvent
): Promise<WebhookResult> {
const url = new URL(config.url);
// Literal IPs skip DNS and with it safeLookup, so only https hostnames pass
if (url.protocol !== 'https:' || isIP(url.hostname.replace(/^\[|\]$/g, '')) !== 0) {
return { success: false, error: 'invalid_webhook_url', shouldRetry: false };
}
// Stable across retries: receivers deduplicate on it
const msgId = `msg_${notification.id}_${config.id}`;
const body = JSON.stringify({
id: msgId,
type: notification.type,
userId: notification.userId,
data: notification.data,
occurredAt: (notification.scheduledAt ?? new Date()).toISOString()
});
// Fresh on every attempt: receivers reject timestamps outside their tolerance
const timestamp = Math.floor(Date.now() / 1000);
try {
const status = await postWebhook(url, body, {
'webhook-id': msgId,
'webhook-timestamp': String(timestamp),
'webhook-signature': signWebhook(config.secret, msgId, timestamp, body),
'user-agent': 'NotificationSystem/1.0'
});
return {
success: status >= 200 && status < 300,
statusCode: status,
shouldRetry: status === 429 || status >= 500
};
} catch (error) {
return {
success: false,
error: error.message,
shouldRetry: !error.message.startsWith('Blocked')
};
}
}
}
The receiver verifies the signature over the raw request bytes before parsing JSON, rejects a webhook-timestamp outside a tolerance of a few minutes, and stores webhook-id to drop repeats. All three rules go into the integration docs. A retry after a lost response delivers the same event twice, and only the stable id lets the receiver recognize it. The lookup check is one layer. The Standard Webhooks spec also recommends sending through an egress proxy that filters internal addresses and running webhook workers in a subnet that cannot reach internal services.
Channel Coordination and Delivery Logic#
Preferences have one owner. The Part 1 resolver turns them into one ChannelPlan per enabled channel: send now, defer to the end of quiet hours, or collect into a daily or weekly digest. Deferred and digest rows belong to the Part 1 sweeper, and rate limits apply later, when send runs. In Part 1 the engine claims a delivery row for every plan and sends the now-mode rows directly. The orchestrator takes over that send. The engine still claims the rows and passes each plan with its row, and the orchestrator never reads preferences again. Its only job is ordering within that set: which channel fires at once, which waits briefly, and which fires only if the others did not reach the user.
interface DeliveryPlan {
immediate: Delivery[];
delayed: { delivery: Delivery; delayMs: number; skipIfRead: boolean }[];
escalation: { delivery: Delivery; afterMs: number; skipIfAcknowledged: boolean }[];
}
const EMAIL_READ_WINDOW_MS = 5 * 60_000; // example values: tune per product
const SMS_ESCALATION_MS = 2 * 60_000;
const LEASE_MS = 5 * 60_000; // the lease Part 1's claim and sweeper use
class MultiChannelDeliveryOrchestrator {
// claimed: the Part 1 resolver's plans for this user and type,
// each with the delivery row the engine claimed for it
async deliverNotification(
notification: NotificationEvent,
claimed: { plan: ChannelPlan; delivery: Delivery }[]
): Promise<void> {
// Defer and digest rows stay with the Part 1 sweeper
const rows = claimed.filter((c) => c.plan.mode === 'now').map((c) => c.delivery);
if (rows.length === 0) return;
const plan = this.createDeliveryPlan(notification, rows);
// Push each held row past its wait, so the sweeper does not send it
// when the claim's lease runs out
await Promise.all([
...plan.delayed.map((d) => this.deliveries.reschedule(d.delivery.id, d.delayMs + LEASE_MS)),
...plan.escalation.map((e) => this.deliveries.reschedule(e.delivery.id, e.afterMs + LEASE_MS))
]);
const results = await this.executeDeliveryPlan(notification, plan);
await this.analytics.trackMultiChannelDelivery(notification.id, results);
}
// executeDeliveryPlan calls this when a read or an acknowledgment cancels a held row
private async closeSkipped(delivery: Delivery): Promise<void> {
// The sweeper only picks up pending rows, so a skipped row never sends
await this.db.query(
`UPDATE notification_deliveries
SET status = 'skipped', next_retry_at = NULL
WHERE id = $1 AND status = 'pending'`,
[delivery.id]
);
}
private createDeliveryPlan(
notification: NotificationEvent,
rows: Delivery[]
): DeliveryPlan {
const plan: DeliveryPlan = { immediate: [], delayed: [], escalation: [] };
const critical = notification.priority === 'critical';
const hasRealtime = rows.some((d) => d.channel === 'push' || d.channel === 'in_app');
for (const delivery of rows) {
switch (delivery.channel) {
case 'in_app':
case 'push':
case 'webhook':
plan.immediate.push(delivery);
break;
case 'email': {
// A short wait lets an in-app read cancel the email; critical events skip it
const waitForRead = hasRealtime && !critical;
plan.delayed.push({
delivery,
delayMs: waitForRead ? EMAIL_READ_WINDOW_MS : 0,
skipIfRead: waitForRead
});
break;
}
case 'sms':
// The paid channel fires only when the free ones did not reach the user
plan.escalation.push({
delivery,
afterMs: hasRealtime ? SMS_ESCALATION_MS : 0,
skipIfAcknowledged: hasRealtime
});
break;
}
}
return plan;
}
}
Both waiting states have a concrete exit. A delayed email checks the delivery rows when its timer fires: if the user already read the notification in the app, the email is dropped, and otherwise it goes out on its own. Collecting several notifications into one email is the digest mode, which stays with Part 1. An escalation checks for an acknowledgment from push or in-app (a tap or a read receipt) and sends SMS only when none arrived. Neither exit may leave the row to Part 1’s sweeper, which sends any pending row once its 5-minute claim lease ends. Each held row’s next_retry_at therefore moves past its wait before the timer starts, and a dropped email or SMS row is closed as skipped. A sent row leaves the queue through markSent as before. If the process dies while it holds a row, the sweeper sends that row once the moved time passes: the read or acknowledgment check is lost, the notification is not. Critical priority sends the email at once and skips the read check, matching Part 1, where critical events already bypass quiet hours and digests. SMS still waits for the escalation window, because sending a critical event to every channel at once means paying for an SMS the user may already have seen as a push.
Channel Limits Worth Designing Around#
Each provider sets limits that the code above has to respect. A self-hosted WebSocket server has no published ceiling, so its connection count per instance has to be measured under your own load; the managed API Gateway row shows the limits that replace it.
| Channel | Limits worth knowing | Where it breaks | Cost driver |
|---|---|---|---|
| WebSocket (API Gateway) | 128 KB message, 32 KB frame, 10-minute idle timeout, 2-hour maximum connection, 500 new connections per second per account and Region (adjustable) | Clients that do not reconnect after the 2-hour cut; reconnect bursts after a deploy | Connection minutes and messages |
| APNs | 4 KB payload (5 KB for VoIP), 64-byte apns-collapse-id; apns-expiration of 0 means one attempt and no storage | Oversized payload is refused outright | Your own sender fleet |
| FCM | 4096-byte payload, string-only data map, 4 stored collapse keys per device, 4-week maximum TTL, 600k messages per minute per project, 240 per minute and 5,000 per hour to one Android device | 429 RESOURCE_EXHAUSTED when the project quota runs out | FCM itself is no-cost |
| Email (SES) | Account review at 5% hard bounces or 0.1% complaints; possible pause at 10% or 0.5%; 2 to 6 weeks to warm a dedicated IP | Reputation, long before throughput | Volume sent, plus dedicated IPs as an add-on |
| SMS | 160 GSM-7 or 70 UCS-2 characters per single segment; 153 or 67 once split | Opted-out numbers fail (Twilio error 21610) | Every segment sent |
| Webhook | Set by each receiver | Slow or dead endpoints filling the retry queue | Your own egress and queue |
Failure Modes Worth Designing For#
Connections drop, and critical state needs to live outside the socket so a reconnect can rebuild the session. Push tokens go stale occasionally. An invalid-token response is routine cleanup, and the device gets re-registered once it reconnects. A successful send call only starts the email process. The suppression list, the bounce classification, and whether a warmed-up second provider is on standby decide whether the message actually lands.
Every provider here enforces rate limits, which is why backoff belongs in the delivery path from the start. Preference changes and opt-outs need to take effect on the very next send, since deliverability degrades otherwise. Monitoring stays per channel because connection counts, push delivery rates, email bounce rates, and SMS costs all move independently.
The next part of the series covers debugging and monitoring these channels in production.
References#
- API Gateway WebSocket APIs - AWS Documentation (opens in new tab) - Official AWS guide to building bidirectional real-time WebSocket APIs for persistent client connections in notification systems
- Use @connections commands in your backend service - AWS Documentation (opens in new tab) - How to push messages from a backend Lambda or service to connected WebSocket clients
- RFC 6455 - The WebSocket Protocol - IETF (opens in new tab) - The foundational IETF standard defining the WebSocket protocol, framing, and connection lifecycle
- Firebase Cloud Messaging - firebase.google.com (opens in new tab) - Multi-platform push notification delivery covering Android, iOS, and web with topic messaging and reliability guarantees
- Sending notification requests to APNs - Apple Developer (opens in new tab) - Apple’s official documentation for transmitting push payloads to iOS devices including authentication and retry behavior
- Using dead-letter queues in Amazon SQS - AWS Documentation (opens in new tab) - SQS dead-letter queue setup for capturing failed message deliveries and triggering retry workflows
- Quotas for configuring and running a WebSocket in API Gateway - AWS Documentation (opens in new tab) - Message and frame size, idle timeout, maximum connection duration and new-connection rate for WebSocket APIs
- Amazon API Gateway pricing - AWS (opens in new tab) - WebSocket APIs are billed for messages and connection minutes
- Redis Pub/Sub - Redis Documentation (opens in new tab) - At-most-once delivery semantics and the commands a RESP2 client may issue while subscribed
- Generating a remote notification - Apple Developer (opens in new tab) - APNs payload size limits: 4 KB for regular notifications, 5 KB for VoIP
- Firebase Cloud Messaging message types - Firebase (opens in new tab) - The 4096-byte payload limit shared by notification and data messages
- Non-collapsible and collapsible messages - Firebase (opens in new tab) - How collapse keys replace pending messages and the four-key limit per device
- FCM HTTP v1 projects.messages reference - Firebase (opens in new tab) - The string-to-string
datamap, Android TTL with its 4-week maximum, and collapse key fields - FCM throttling and quotas - Firebase (opens in new tab) - Project-wide sending quota, per-device rate limits and the
429 RESOURCE_EXHAUSTEDresponse - Firebase pricing - Firebase (opens in new tab) - Lists Cloud Messaging among the no-cost products
- SendEmail - Amazon SES API v2 Reference (opens in new tab) - Full request syntax of the SES send call, which has no idempotency-key parameter
- Reputation metrics messages - Amazon SES Developer Guide (opens in new tab) - Bounce and complaint rate thresholds for account review and sending pause
- Warming up dedicated IP addresses - Amazon SES Developer Guide (opens in new tab) - Why new IPs need a gradual ramp and how long warm-up takes
- Authenticating email with DKIM in Amazon SES - AWS Documentation (opens in new tab) - Easy DKIM, BYODKIM and manual signing options
- Amazon SES pricing - AWS (opens in new tab) - Volume-based email pricing with dedicated IPs as an add-on
- What is the SMS character limit? - Twilio (opens in new tab) - GSM-7 and UCS-2 segment sizes and per-segment billing
- What is GSM-7 character encoding? - Twilio (opens in new tab) - The GSM-7 basic character table and escape characters that count double
- Advanced Opt-Out - Twilio (opens in new tab) - Default opt-out keywords, the reserved START and UNSTOP opt-in keywords, per-country keyword configuration and error 21610 for opted-out numbers
- Retrying failing jobs - BullMQ Documentation (opens in new tab) - The
attemptsand exponentialbackoffjob options used by the webhook retry queue - Standard Webhooks specification - GitHub (opens in new tab) - Webhook id, timestamp and HMAC signature headers, idempotency on retries, and SSRF guidance
Building a Scalable User Notification System
Part 2 of 4A comprehensive 4-part series covering the design, implementation, and production challenges of building enterprise-grade notification systems. From architecture and database design to real-time delivery, debugging at scale, and performance optimization.
All posts in this series
Related posts
AppSync subscriptions fire only on mutations. This explores bridging downstream BFF events into a NONE-data-source mutation with EventBridge and CDK.
aws · graphql · serverless +4
One default shape for long-running work across a browser SPA and a mobile app, with the cases where it should be overridden.
api-design · real-time · webhooks +4
A production guide to feature flags in distributed systems, comparing LaunchDarkly, Unleash, and AWS AppConfig with examples for rollouts and A/B testing.
feature-flags · devops · ci-cd +5
Building scalable real-time APIs with AWS AppSync: JavaScript resolvers, subscription filtering, caching strategies, and infrastructure as code patterns.
aws · graphql · serverless +4
A technical comparison of MQTT, AMQP, ZeroMQ, CoAP, and DDS for IoT logistics: fleet tracking, cold chain monitoring, and real-time device communication.
messaging · industry-trends · real-time +2