Building a Scalable User Notification System: Architecture and Database Design
Event routing, idempotent delivery rows in PostgreSQL, quiet hours that defer delivery, and per-channel Redis rate limits for a multi-channel notification system
Multi-channel notification systems fail when teams model them as template-plus-send pipelines. A notification is a per-user routing decision: it may fan out, coalesce, suppress, or defer across email, SMS, push, and in-app channels. Without an explicit router layer, delivery guarantees collapse, user preferences get ignored, and compliance auditability becomes impossible.
The default worth starting from is an event-driven pipeline with a dedicated channel router. Producers emit events, the engine resolves preferences and rate limits, and the router owns every channel-specific decision. Three supporting pieces cannot be skipped: a PostgreSQL schema that separates events from delivery attempts and allows one delivery row per event and channel, preference resolution with timezone-aware quiet hours, and a correlation ID on every record so failures stay debuggable before they reach the user.
The Hidden Complexity of “Simple” Notifications#
The initial mental model for notifications is: trigger event → send message → done. The production reality is a complex orchestration of user preferences, delivery channels, rate limiting, retry logic, template management, analytics tracking, and regulatory compliance.
The complexity becomes apparent during a first major product launch. With 10,000 users suddenly receiving welcome emails, password resets, and activity notifications simultaneously, the email service starts throttling, the database connection pool maxes out, and users start complaining about duplicate notifications.
System Architecture#
The architecture below separates event intake, policy resolution, and channel delivery. Each component maps to a distinct failure mode: the event bus absorbs bursts, the preference manager and rate limiter decide when work reaches a provider (now, after quiet hours, in a digest, or after the limit window) before any provider is called, and the router keeps a failure in one channel from touching the others.
Event-Driven Architecture#
Notifications are not request-response operations. They are fire-and-forget events that require asynchronous processing. The following event structure works reliably across multiple systems:
interface NotificationEvent {
id: string;
userId: string;
type: NotificationType;
templateId?: string;
data: Record<string, any>;
priority: 'low' | 'normal' | 'high' | 'critical';
scheduledAt?: Date;
expiresAt?: Date;
metadata: {
source: string;
correlationId: string;
};
}
enum NotificationType {
PROJECT_UPDATE = 'project_update',
SECURITY_ALERT = 'security_alert',
FEATURE_ANNOUNCEMENT = 'feature_announcement',
SYSTEM_MAINTENANCE = 'system_maintenance',
USER_ACTIVITY = 'user_activity',
INTEGRATION_UPDATE = 'integration_update'
}
The metadata section is crucial: the correlation ID enables tracing notification flows across distributed systems and is essential for debugging delivery failures. Retry counters are deliberately absent. Attempts belong to the delivery rows further down, one per channel, so retrying a failed email never runs the push again.
The Events Table as the Bus#
The bus in this design is the notification_events table itself, which keeps the whole pipeline inside one PostgreSQL database. Producers insert a row with an ID they generate, so a producer retry hits ON CONFLICT (id) DO NOTHING and creates no second event. Workers claim due rows with FOR UPDATE SKIP LOCKED, the locking mode PostgreSQL documents for several consumers reading a queue-like table without waiting on each other.
-- Producer: the event ID comes from the producer, so a retry is safe
INSERT INTO notification_events
(id, user_id, notification_type, priority, data, correlation_id)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (id) DO NOTHING;
-- Worker: claim a batch. The lease moves scheduled_at forward, so an
-- event whose worker dies becomes due again after five minutes.
UPDATE notification_events
SET scheduled_at = now() + interval '5 minutes'
WHERE id IN (
SELECT id FROM notification_events
WHERE status = 'pending' AND scheduled_at <= now()
ORDER BY scheduled_at
LIMIT 20
FOR UPDATE SKIP LOCKED
)
RETURNING *;
-- After processEvent returns
UPDATE notification_events
SET status = 'processed', processed_at = now()
WHERE id = $1;
The lease means an event can be processed twice: a worker can crash after sending, or take longer than five minutes. The engine below is written for that case. The same property makes a later move to Amazon SQS cheap, because standard queues deliver at least once and AWS asks consumers to be idempotent. Switch to a broker when several services consume the same event (SNS fans one message out to several SQS queues) or when polling the table becomes the bottleneck; the engine itself does not change.
The Notification Engine: Heart of the System#
The notification engine is where most of the complexity lives. In the implementation below, the order of the checks matters as much as the checks themselves: cheap rejections happen before any template is rendered or any provider is called.
class NotificationEngine {
constructor(
private users: UserRepository,
private deliveries: DeliveryStore,
private templateService: TemplateService,
private preferenceManager: PreferenceManager,
private rateLimiter: RateLimiter,
private channelRouter: ChannelRouter,
private analytics: AnalyticsService
) {}
async processEvent(event: NotificationEvent): Promise<void> {
try {
// Check if user exists and is active
const user = await this.users.findById(event.userId);
if (!user?.isActive) {
await this.analytics.trackSkipped(event.id, 'user_inactive');
return;
}
// Every enabled channel comes back as send now, defer, or digest
const plans = await this.preferenceManager
.resolveChannels(event.userId, event.type, event.priority);
if (plans.length === 0) {
await this.analytics.trackSkipped(event.id, 'all_channels_disabled');
return;
}
// Process each channel independently
const results = await Promise.allSettled(
plans.map(plan => this.processChannel(event, plan, user))
);
await this.analytics.trackDeliveryResults(event.id, results);
} catch (error) {
await this.handleProcessingError(event, error);
}
}
private async processChannel(
event: NotificationEvent,
plan: ChannelPlan,
user: User
): Promise<DeliveryOutcome> {
// Claim the (event, channel) pair before anything else. A redelivered
// event finds the row already there and stops before any provider call.
const delivery = await this.deliveries.claim(event.id, plan);
if (!delivery) return 'duplicate';
// Quiet hours and digests: the row waits for the sweeper
if (plan.mode !== 'now') return 'deferred';
return this.send(delivery, event, user);
}
// Also called by the sweeper for deferred rows and retries
async send(
delivery: Delivery,
event: NotificationEvent,
user: User
): Promise<DeliveryOutcome> {
if (event.priority !== 'critical') {
const limit = await this.rateLimiter
.tryConsume(user.id, event.type, delivery.channel);
if (!limit.allowed) {
await this.deliveries.reschedule(delivery.id, limit.retryAfterMs);
return 'deferred';
}
}
try {
const template = await this.templateService.getTemplate(
event.type,
delivery.channel,
user.locale
);
const content = await this.templateService.render(template, event, user);
const result = await this.channelRouter.deliver(
delivery.channel,
user,
content,
{
correlationId: event.metadata.correlationId,
idempotencyKey: delivery.id
}
);
await this.deliveries.markSent(delivery.id, result.providerMessageId);
return 'sent';
} catch (error) {
// Schedules a retry with backoff, or marks the row failed
await this.deliveries.markFailed(delivery.id, error);
throw error;
}
}
}
Promise.allSettled is deliberate. A failing channel must not cancel the others, and each channel result is recorded separately, so a bounced email and a delivered push for the same event stay distinguishable in the delivery table.
Here the engine sends the now-mode rows itself, which keeps the flow complete in one place. Part 2 replaces that last step: the engine still claims every row, then hands each now-mode plan with its claimed row to a MultiChannelDeliveryOrchestrator, which only decides the order in which channels fire. Deferred and digest rows stay with the sweeper below.
The claim is what removes the duplicate notifications from the launch scenario. notification_deliveries has a unique constraint on (event_id, channel), and INSERT ... ON CONFLICT DO NOTHING RETURNING returns a row only when the insert happened. A second run of the same event gets nothing back and stops before rendering.
One window stays open. A worker that crashes after the provider accepted the message, but before markSent, leaves the row pending, and the sweeper retries it when the lease runs out. Passing delivery.id as the provider’s idempotency key closes that window where the provider supports one. Resend, for example, reads an Idempotency-Key header, keeps keys for 24 hours, and answers a repeated request with the same payload with the original response, without sending the email again; a different payload under the same key is rejected. A provider without such a key leaves this window open, and it is the cost of at-least-once delivery.
Delivery Rows: Claim, Send, Retry#
Every delivery attempt goes through one store, so the row always reflects what happened:
class DeliveryStore {
constructor(private db: Pool) {}
// Returns null when an earlier run already claimed this (event, channel)
async claim(eventId: string, plan: ChannelPlan): Promise<Delivery | null> {
const { rows } = await this.db.query<Delivery>(
`INSERT INTO notification_deliveries
(event_id, channel, next_retry_at, digest_frequency)
VALUES ($1, $2, COALESCE($3, now() + interval '5 minutes'), $4)
ON CONFLICT (event_id, channel) DO NOTHING
RETURNING id, event_id AS "eventId", channel`,
[
eventId,
plan.channel,
plan.mode === 'now' ? null : plan.sendAt, // null: a 5-minute lease
plan.mode === 'digest' ? plan.frequency : null
]
);
return rows[0] ?? null;
}
async markSent(id: string, providerMessageId: string): Promise<void> {
await this.db.query(
`UPDATE notification_deliveries
SET status = 'sent', sent_at = now(), provider_id = $2,
attempt_count = attempt_count + 1, next_retry_at = NULL
WHERE id = $1`,
[id, providerMessageId]
);
}
// Backoff of 30 s, then 60 s, doubling until max_attempts (3 by default), then 'failed'
async markFailed(id: string, error: unknown): Promise<void> {
await this.db.query(
`UPDATE notification_deliveries
SET attempt_count = attempt_count + 1,
error_message = $2,
status = CASE WHEN attempt_count + 1 >= max_attempts
THEN 'failed' ELSE 'pending' END,
failed_at = CASE WHEN attempt_count + 1 >= max_attempts
THEN now() END,
next_retry_at = CASE WHEN attempt_count + 1 >= max_attempts THEN NULL
ELSE now() + make_interval(secs => 30 * 2 ^ attempt_count)
END
WHERE id = $1`,
[id, error instanceof Error ? error.message : String(error)]
);
}
async reschedule(id: string, delayMs: number): Promise<void> {
await this.db.query(
`UPDATE notification_deliveries
SET next_retry_at = now() + make_interval(secs => $2)
WHERE id = $1`,
[id, delayMs / 1000]
);
}
}
A row starts as pending, with next_retry_at set either to a lease or to the deferred send time. markSent moves it to sent; delivered and bounced arrive later from provider webhooks, which Part 2 handles. Part 2 also closes a held email or SMS row as skipped when the user already read or acknowledged the notification on another channel. markFailed keeps the row pending with a growing delay, and after max_attempts sets it to failed, where it waits for a person instead of another retry. A rate-limited send stays pending too: reschedule only moves its time.
Database Design: Schema and Indexing Strategy#
The schema splits into three concerns: what to send (events and templates), who wants it (preferences), and what happened (deliveries and metrics). Keeping the third separate from the first is what makes per-channel retries and audit queries cheap.
Core Tables#
-- Users table (assuming it exists)
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
phone VARCHAR(20),
display_name VARCHAR(100),
locale VARCHAR(10) DEFAULT 'en',
timezone VARCHAR(50) DEFAULT 'UTC', -- IANA name, e.g. 'Europe/Berlin'
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- The channels each type may use, and their defaults
CREATE TABLE notification_type_channels (
notification_type VARCHAR(100) NOT NULL,
channel VARCHAR(50) NOT NULL,
enabled_by_default BOOLEAN NOT NULL,
default_frequency VARCHAR(20) NOT NULL DEFAULT 'immediate',
PRIMARY KEY (notification_type, channel)
);
-- The preference system - this gets complex fast
CREATE TABLE notification_preferences (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
notification_type VARCHAR(100) NOT NULL,
channel VARCHAR(50) NOT NULL,
enabled BOOLEAN DEFAULT true,
frequency VARCHAR(20) DEFAULT 'immediate', -- immediate, daily, weekly
quiet_hours_start TIME DEFAULT '22:00:00',
quiet_hours_end TIME DEFAULT '08:00:00',
metadata JSONB DEFAULT '{}', -- for channel-specific settings
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id, notification_type, channel)
);
-- Template management - localization is crucial
CREATE TABLE notification_templates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
notification_type VARCHAR(100) NOT NULL,
channel VARCHAR(50) NOT NULL,
locale VARCHAR(10) DEFAULT 'en',
subject VARCHAR(500),
body TEXT NOT NULL,
variables JSONB DEFAULT '{}', -- declared variables: all a template can read
is_active BOOLEAN DEFAULT true,
version INTEGER DEFAULT 1,
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(notification_type, channel, locale, version)
);
Event Storage and Tracking#
Event storage is the area most prone to scaling surprises. The schema below addresses the most common failure modes:
-- Main event table - this gets HUGE
CREATE TABLE notification_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- SET NULL keeps an anonymous audit trail when a user is erased
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
notification_type VARCHAR(100) NOT NULL,
template_id UUID REFERENCES notification_templates(id),
priority VARCHAR(20) DEFAULT 'normal',
data JSONB DEFAULT '{}',
scheduled_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
status VARCHAR(20) DEFAULT 'pending', -- pending, processed
processed_at TIMESTAMP WITH TIME ZONE,
correlation_id VARCHAR(255), -- for tracing
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- PostgreSQL has no inline INDEX clause; indexes are separate statements
CREATE INDEX idx_notification_events_correlation
ON notification_events(correlation_id);
-- Delivery tracking - separate for performance
CREATE TABLE notification_deliveries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID REFERENCES notification_events(id) ON DELETE CASCADE,
channel VARCHAR(50) NOT NULL,
status VARCHAR(20) DEFAULT 'pending', -- pending, sent, delivered, failed, bounced, skipped
attempt_count INTEGER DEFAULT 0,
max_attempts INTEGER DEFAULT 3,
-- Next time a worker should act: a lease, a retry, quiet-hours end, or digest time
next_retry_at TIMESTAMP WITH TIME ZONE,
digest_frequency VARCHAR(20), -- NULL: send on its own; daily, weekly: digest
sent_at TIMESTAMP WITH TIME ZONE,
delivered_at TIMESTAMP WITH TIME ZONE,
failed_at TIMESTAMP WITH TIME ZONE,
error_code VARCHAR(50),
error_message TEXT,
provider_id VARCHAR(255), -- external provider message ID
provider_response JSONB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- One row per event and channel: the claim depends on it
UNIQUE (event_id, channel)
);
-- Analytics aggregation table - direct queries time out at millions of events
CREATE TABLE notification_metrics (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
date DATE NOT NULL,
hour SMALLINT NOT NULL, -- 0-23
notification_type VARCHAR(100) NOT NULL,
channel VARCHAR(50) NOT NULL,
status VARCHAR(20) NOT NULL,
count INTEGER DEFAULT 1,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(date, hour, notification_type, channel, status)
);
The unique constraint brings its own B-tree index on (event_id, channel), so lookups by event need no separate index.
Indexing Strategy#
The indexes below follow the three query patterns the system runs most: user timelines, the event queue, and the delivery queue that holds retries and deferred sends.
-- Critical indexes based on query patterns
CREATE INDEX idx_events_user_type_created
ON notification_events(user_id, notification_type, created_at DESC);
CREATE INDEX idx_events_processing_queue
ON notification_events(scheduled_at)
WHERE status = 'pending';
CREATE INDEX idx_deliveries_retry_queue
ON notification_deliveries(channel, next_retry_at)
WHERE status = 'pending' AND next_retry_at IS NOT NULL;
-- Append-only history: BRIN stays small where a btree would not
CREATE INDEX idx_events_created_brin
ON notification_events USING BRIN (created_at);
-- For analytics queries
CREATE INDEX idx_metrics_time_type
ON notification_metrics(date, hour, notification_type);
Two details decide whether these indexes hold up. A partial index predicate has to be immutable, so a rolling window such as NOW() - INTERVAL '7 days' is rejected outright; time-ordered history belongs in a BRIN index instead. The queue indexes stay small only because their WHERE clauses exclude rows that already reached a terminal status.
User Preference Management#
User preferences look like a boolean until quiet hours, timezones, and frequency windows enter the picture. PostgreSQL does the time zone arithmetic: AT TIME ZONE turns the current instant into the user’s wall clock and turns a local time back into an instant. The function below returns the next instant at which a user’s clock shows a given time:
-- Next instant at which the wall clock in `tz` shows `t`.
-- 'weekly' moves to the next Monday; anything else means today or tomorrow.
CREATE FUNCTION next_local_time(tz TEXT, t TIME, frequency TEXT DEFAULT 'daily')
RETURNS TIMESTAMPTZ
LANGUAGE sql STABLE
AS $$
SELECT (CASE
WHEN frequency = 'weekly'
THEN local_now::date + (8 - extract(isodow FROM local_now)::int)
WHEN local_now::time < t THEN local_now::date
ELSE local_now::date + 1
END + t) AT TIME ZONE tz
FROM (SELECT now() AT TIME ZONE tz AS local_now) AS s
$$;
The resolver applies preferences in a fixed order, so the same event always produces the same plan. Each enabled channel comes back as one of three modes: send now, defer to the end of quiet hours, or collect into a digest.
type ChannelPlan =
| { channel: NotificationChannel; mode: 'now' }
| { channel: NotificationChannel; mode: 'defer'; sendAt: Date }
| { channel: NotificationChannel; mode: 'digest'; sendAt: Date; frequency: 'daily' | 'weekly' };
interface PreferenceRow {
channel: NotificationChannel;
enabled: boolean;
frequency: 'immediate' | 'daily' | 'weekly';
quietStart: string; // 'HH:MM:SS'
quietEnd: string;
localTime: string; // the user's wall clock, from PostgreSQL
quietEndsAt: Date;
digestAt: Date;
}
const DIGEST_TIME = '09:00'; // example: when daily and weekly digests go out
class PreferenceManager {
constructor(private db: Pool) {}
async resolveChannels(
userId: string,
notificationType: string,
priority: NotificationEvent['priority']
): Promise<ChannelPlan[]> {
// Every channel the type supports, with the user's own row on top.
// A user who changed only email keeps the defaults for the others.
const { rows } = await this.db.query<PreferenceRow>(`
SELECT d.channel,
COALESCE(p.enabled, d.enabled_by_default) AS enabled,
COALESCE(p.frequency, d.default_frequency) AS frequency,
COALESCE(p.quiet_hours_start, '22:00')::text AS "quietStart",
COALESCE(p.quiet_hours_end, '08:00')::text AS "quietEnd",
date_trunc('second', now() AT TIME ZONE u.timezone)::time::text
AS "localTime",
next_local_time(u.timezone,
COALESCE(p.quiet_hours_end, '08:00')) AS "quietEndsAt",
next_local_time(u.timezone, $3,
COALESCE(p.frequency, d.default_frequency)) AS "digestAt"
FROM users u
JOIN notification_type_channels d ON d.notification_type = $2
LEFT JOIN notification_preferences p
ON p.user_id = u.id
AND p.notification_type = d.notification_type
AND p.channel = d.channel
WHERE u.id = $1
`, [userId, notificationType, DIGEST_TIME]);
const plans: ChannelPlan[] = [];
for (const pref of rows) {
if (!pref.enabled) continue; // suppressed: the user opted out
if (priority === 'critical') {
// Critical events skip quiet hours and digests
plans.push({ channel: pref.channel, mode: 'now' });
} else if (pref.frequency !== 'immediate') {
plans.push({
channel: pref.channel,
mode: 'digest',
sendAt: pref.digestAt,
frequency: pref.frequency
});
} else if (isInQuietHours(pref.localTime, pref.quietStart, pref.quietEnd)) {
// Held until quiet hours end
plans.push({ channel: pref.channel, mode: 'defer', sendAt: pref.quietEndsAt });
} else {
plans.push({ channel: pref.channel, mode: 'now' });
}
}
return plans;
}
}
// All three values are 'HH:MM:SS' strings, so string order is time order
function isInQuietHours(localTime: string, quietStart: string, quietEnd: string): boolean {
// Handle quiet hours that cross midnight
if (quietStart > quietEnd) {
return localTime >= quietStart || localTime < quietEnd;
}
return localTime >= quietStart && localTime < quietEnd;
}
The LEFT JOIN is what keeps defaults alive. notification_type_channels lists every channel a type may use, and the user’s rows are laid over it one channel at a time. Falling back to defaults only when a user has no rows at all would silence every channel the user never touched, the moment they changed one.
The midnight-crossing branch is the part most implementations miss. When quiet_hours_start is later than quiet_hours_end, the comparison has to use OR rather than AND. The user’s local clock comes out of the same query, so the check needs no date library in Node.js.
Deferred Sends and Digests#
Suppression happens in one place only: a channel the user disabled. A deferred or digest channel still becomes a delivery row, with next_retry_at set to its send time, and two jobs drain those rows:
class DeliverySweeper {
constructor(
private db: Pool,
private engine: NotificationEngine,
private loadContext: (eventId: string) => Promise<{ event: NotificationEvent; user: User }>,
private sendDigest: (items: DigestRow[]) => Promise<void>
) {}
// One loop per channel, so a slow SMS provider only backs up SMS rows
async sweep(channel: NotificationChannel): Promise<void> {
const { rows } = await this.db.query<Delivery>(
`UPDATE notification_deliveries
SET next_retry_at = now() + interval '5 minutes' -- lease
WHERE id IN (
SELECT id FROM notification_deliveries
WHERE status = 'pending'
AND channel = $1
AND digest_frequency IS NULL
AND next_retry_at <= now()
ORDER BY next_retry_at
LIMIT 50
FOR UPDATE SKIP LOCKED
)
RETURNING id, event_id AS "eventId", channel`,
[channel]
);
await Promise.allSettled(rows.map(async delivery => {
const { event, user } = await this.loadContext(delivery.eventId);
return this.engine.send(delivery, event, user);
}));
}
// Collects every due digest item and sends one message per user and channel
async runDigests(): Promise<void> {
const { rows } = await this.db.query<DigestRow>(
`UPDATE notification_deliveries d
SET next_retry_at = now() + interval '5 minutes' -- lease
FROM notification_events e
WHERE e.id = d.event_id
AND d.id IN (
SELECT id FROM notification_deliveries
WHERE status = 'pending'
AND digest_frequency IS NOT NULL
AND next_retry_at <= now()
FOR UPDATE SKIP LOCKED
)
RETURNING d.id, d.channel, e.user_id AS "userId",
e.notification_type AS type, e.data`
);
const groups = new Map<string, DigestRow[]>();
for (const row of rows) {
const key = `${row.userId}:${row.channel}`;
groups.set(key, [...(groups.get(key) ?? []), row]);
}
for (const items of groups.values()) {
// Renders one digest template, sends it, and marks every row 'sent'
// with the same provider message ID
await this.sendDigest(items);
}
}
}
A project update that arrives at 22:30 now waits in a row due at 08:00 local time, and the sweeper sends it then. Retries take the same path, because markFailed writes its backoff into the same column. The sweeper sends through engine.send, so held rows still pass the rate limiter: one user’s notifications held overnight respect that user’s per-minute limit when quiet hours end. Weekly digests use the same job; next_local_time points them at the next Monday.
Template System: Localization and Personalization#
Templates decide what the user actually reads, so lookup has to degrade predictably and rendering has to see only what the template declares. The service below resolves the requested locale first and falls back to English rather than throwing:
interface Template {
id: string;
name: string;
type: string;
channel: NotificationChannel;
locale: string;
subject?: string;
body: string;
variables: Record<string, TemplateVariable>;
abTest?: ABTestConfig;
}
class TemplateService {
async getTemplate(
notificationType: string,
channel: NotificationChannel,
locale: string = 'en'
): Promise<Template> {
// Try to get localized template first
let template = await this.db.findTemplate({
type: notificationType,
channel,
locale,
isActive: true
});
// Fallback to English if no localized version
if (!template && locale !== 'en') {
template = await this.db.findTemplate({
type: notificationType,
channel,
locale: 'en',
isActive: true
});
}
if (!template) {
throw new Error(`No template found for ${notificationType}/${channel}/${locale}`);
}
return template;
}
async render(
template: Template,
event: NotificationEvent,
user: User
): Promise<RenderedContent> {
// Only the variables the template declares. Email address and phone
// number go to the channel router, never into a template.
const available: Record<string, unknown> = {
...event.data,
displayName: user.displayName
};
const context = Object.fromEntries(
Object.keys(template.variables)
.filter(name => name in available)
.map(name => [name, available[name]])
);
try {
// HTML-escape only where the output is HTML: the email body.
// Subjects, SMS and push are plain text, where & shows up literally.
const subject = template.subject
? this.renderString(template.subject, context, false)
: undefined;
const body = this.renderString(template.body, context, template.channel === 'email');
return {
subject,
body,
templateId: template.id,
locale: template.locale
};
} catch (error) {
// Log variable names only: the values may hold personal data
await this.logger.error('Template rendering failed', {
templateId: template.id,
error: error instanceof Error ? error.message : String(error),
variables: Object.keys(context)
});
throw new TemplateRenderError(`Failed to render template ${template.id}`, error);
}
}
private renderString(
source: string,
context: Record<string, unknown>,
html: boolean
): string {
// strict: a variable that is missing or undeclared throws instead of rendering empty
return Handlebars.compile(source, { strict: true, noEscape: !html })(context);
}
}
The render context comes from template.variables, the column the schema already reserves for declared variables. A marketing template that references email fails in strict mode, so it cannot print the address by accident. Escaping follows the output format. Handlebars HTML-escapes {{value}} by default, which is right for an email body and wrong for an SMS, where & would reach the phone as five characters.
Rate Limiting: Protecting Users and Providers#
Rate limiting balances user experience with system stability. The limiter below keeps one counter per user, type, channel, and window, and runs the whole check as a single Lua script:
// Checks every window first and increments only when all of them have room,
// so a rejected attempt never counts against the user
const CONSUME_SCRIPT = `
for i = 1, #KEYS do
local count = tonumber(redis.call('GET', KEYS[i]) or '0')
if count >= tonumber(ARGV[i]) then
return {0, redis.call('PTTL', KEYS[i])}
end
end
for i = 1, #KEYS do
if redis.call('INCR', KEYS[i]) == 1 then
redis.call('PEXPIRE', KEYS[i], ARGV[#KEYS + i])
end
end
return {1, 0}
`;
interface RateLimitConfig {
notificationType: string;
channel: NotificationChannel;
limits: {
perMinute: number;
perHour: number;
perDay: number;
};
}
type RateLimitResult =
| { allowed: true }
| { allowed: false; retryAfterMs: number };
const WINDOWS = [
{ name: 'minute', ms: 60_000, limit: (c: RateLimitConfig) => c.limits.perMinute },
{ name: 'hour', ms: 3_600_000, limit: (c: RateLimitConfig) => c.limits.perHour },
{ name: 'day', ms: 86_400_000, limit: (c: RateLimitConfig) => c.limits.perDay }
];
class RateLimiter {
constructor(private redis: Redis, private configs: RateLimitConfig[]) {}
async tryConsume(
userId: string,
notificationType: string,
channel: NotificationChannel
): Promise<RateLimitResult> {
const config = this.configs.find(c =>
c.notificationType === notificationType && c.channel === channel
);
if (!config) {
return { allowed: true };
}
const now = Date.now();
// The {userId} hash tag puts all three keys in one Redis Cluster slot
const keys = WINDOWS.map(w =>
`rate_limit:{${userId}}:${notificationType}:${channel}:${w.name}:${Math.floor(now / w.ms)}`
);
const limits = WINDOWS.map(w => w.limit(config));
// Each key expires when its fixed bucket ends, so PTTL is the time until the window resets
const ttls = WINDOWS.map(w => (Math.floor(now / w.ms) + 1) * w.ms - now);
// EVAL runs the whole script atomically
const [allowed, retryAfterMs] = await this.redis.eval(
CONSUME_SCRIPT, keys.length, ...keys, ...limits, ...ttls
) as [number, number];
return allowed === 1 ? { allowed: true } : { allowed: false, retryAfterMs };
}
}
A pipeline of INCR calls cannot do this job. Its commands run in order, but other clients’ commands can interleave between them, and a pipeline cannot make a write depend on a read. Redis runs a script atomically, so the check and the increment see the same counts. The script increments only after every window has room, so neither a rejected attempt nor a sweeper retry uses up quota. Each key expires when its bucket ends. When a window is full, the script returns that key’s remaining TTL, the time until a fresh bucket opens, and the engine moves the delivery row to that time.
The engine skips the limiter for critical events, the same exception the preference resolver makes for quiet hours. A burst of security alerts, such as repeated sign-in attempts, should all reach the user, even after the type’s own per-minute limit is spent.
Erasure and the Audit Trail#
Cascading a user deletion into the event and delivery tables erases the audit trail together with the person. The GDPR grants erasure “without undue delay” (Article 17), and the same article exempts processing needed for a legal obligation or for legal claims. Which notifications fall under those exemptions, and for how long, is a decision for whoever owns compliance. The schema has to support both outcomes, which is why notification_events.user_id uses ON DELETE SET NULL. Erasure scrubs the identifying fields first and deletes the user last:
-- Run by the application with the user's ID as $1
BEGIN;
UPDATE notification_deliveries d
SET provider_response = NULL, error_message = NULL
FROM notification_events e
WHERE e.id = d.event_id AND e.user_id = $1;
UPDATE notification_events
SET data = '{}'::jsonb
WHERE user_id = $1;
-- Pending deferred, digest and retry rows would otherwise reach the sweeper with no user
UPDATE notification_deliveries d
SET status = 'failed', next_retry_at = NULL, failed_at = now(), error_code = 'user_erased'
FROM notification_events e
WHERE e.id = d.event_id AND e.user_id = $1 AND d.status = 'pending';
-- Preferences cascade; events stay, with user_id set to NULL
DELETE FROM users WHERE id = $1;
COMMIT;
What remains is the event ID, type, channel, status, timestamps, and correlation ID. The provider message ID can still be matched against the provider’s own logs, which hold the address. Recital 26 counts pseudonymised data, which additional information can tie back to a person, as personal data. These rows therefore need a retention limit of their own, and the provider’s logs fall under the provider’s retention settings. The retention job deletes events past that limit, and deliveries follow through ON DELETE CASCADE:
-- $1: the retention period your legal basis allows, as an interval
DELETE FROM notification_events
WHERE created_at < now() - $1::interval;
Running It Locally#
The SQL above runs as shown; the TypeScript classes leave out the wiring (connection pool setup and provider clients). The versions used here are PostgreSQL 17, Redis 7.4, Node.js 20 or later (the floor for ioredis 6), pg 8.23, ioredis 6.0, and handlebars 4.7.10.
# compose.yaml
services:
postgres:
image: postgres:17
environment:
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
healthcheck:
test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres"]
interval: 2s
retries: 15
redis:
image: redis:7.4
ports:
- "6379:6379"
On first start the image initializes the database with a temporary server that listens only on the Unix socket. The healthcheck runs pg_isready over TCP, so it passes only once the final server accepts connections, and docker compose up --wait returns when the services are running or healthy. Save the CREATE TABLE, CREATE INDEX, and CREATE FUNCTION statements above, in order, as schema.sql, then load it:
docker compose up -d --wait
docker compose exec -T postgres psql -U postgres < schema.sql
docker compose exec postgres psql -U postgres
Inside psql, the claim can be checked directly. Insert a user and an event, then run the engine’s claim twice:
INSERT INTO users (id, email, timezone)
VALUES ('6f1c0a52-8c1e-4d0a-9a51-2f4c1b7d9e01', 'test@example.com', 'Europe/Berlin');
INSERT INTO notification_events (id, user_id, notification_type)
VALUES ('0b7e4c1a-3d2f-4e59-8a6b-9c0d1e2f3a4b',
'6f1c0a52-8c1e-4d0a-9a51-2f4c1b7d9e01', 'project_update');
INSERT INTO notification_deliveries (event_id, channel, next_retry_at)
VALUES ('0b7e4c1a-3d2f-4e59-8a6b-9c0d1e2f3a4b', 'email', now() + interval '5 minutes')
ON CONFLICT (event_id, channel) DO NOTHING
RETURNING id;
The first run returns one generated ID and the tag INSERT 0 1. The second run stands in for a redelivered event and returns nothing:
id
----
(0 rows)
INSERT 0 0
SELECT next_local_time('Europe/Berlin', '08:00'); checks the time zone side. It returns the next 08:00 in Berlin, printed in the session time zone: with the session in UTC that is 07:00 in winter and 06:00 in summer.
Constraints to Design For#
Four constraints shaped the code above. Each is cheaper to design for now than to retrofit:
-
Idempotency: Every send is keyed on the event ID plus the channel. The unique constraint enforces that in the database, and the provider idempotency key covers the crash window after the provider call, where the provider offers one.
-
Observability: Correlation IDs and per-delivery error records are what make a failed send explainable after the fact. Adding them later means backfilling rows that no longer exist.
-
Channel isolation: A notification engine that grows into a monolith becomes hard to scale. The sweeper already runs one loop per channel, so a slow SMS provider backs up only SMS rows. The first attempt still runs inside the engine, so every provider call needs a timeout; moving that attempt into per-channel consumers is the step that makes each channel independently deployable.
-
Data retention: The events and deliveries tables grow in proportion to traffic, so the retention job and the erasure path have to ship with the first migration. Retrofitting them later means deleting rows that an audit query may still need.
This shape earns its cost when notifications cross more than two channels, or when preferences and compliance rules vary per user. A product that sends transactional email and nothing else needs neither a router nor a deliveries table; a provider SDK plus a retry queue is enough. Add a second channel, or a support request asking why one specific user never received one specific message, and the router plus per-delivery records become the cheaper option.
The next part covers real-time delivery: WebSocket connections, push notifications, the channel-specific implementations, and the provider failover that keeps one failing provider from stalling the whole pipeline.
References#
- Common Amazon SNS scenarios - AWS Documentation (opens in new tab) - Fanout from one SNS topic to several SQS queues, the step up when more than one service consumes the same event
- Amazon SQS at-least-once delivery - AWS Documentation (opens in new tab) - Why a standard queue can deliver a message more than once and why consumers have to be idempotent
- SELECT: The Locking Clause - PostgreSQL Documentation (opens in new tab) -
FOR UPDATE SKIP LOCKEDfor several consumers reading a queue-like table - INSERT - PostgreSQL Documentation (opens in new tab) -
ON CONFLICT DO NOTHING, andRETURNINGoutput limited to rows that were inserted - Constraints - PostgreSQL Documentation (opens in new tab) - Unique constraints and the B-tree index PostgreSQL creates for each one
- Date/Time Functions and Operators - PostgreSQL Documentation (opens in new tab) -
AT TIME ZONEconversions,date + timearithmetic, andnow()as the transaction start time - CREATE INDEX - PostgreSQL Documentation (opens in new tab) - Index creation syntax, including the immutability requirement for partial index predicates
- BRIN Indexes - PostgreSQL Documentation (opens in new tab) - Block range indexes for naturally ordered columns such as append-only timestamp history
- Idempotency Keys - Resend Documentation (opens in new tab) - The
Idempotency-Keyheader, its 24-hour lifetime, the response to a repeated request, and the 409 for a reused key with a different payload - Scripting with Lua - Redis Documentation (opens in new tab) - Atomic script execution, passing every key through
KEYS, and command interleaving inside pipelines - Redis cluster specification - Redis Documentation (opens in new tab) - Hash tags that place several keys in the same cluster slot
- ioredis - GitHub (opens in new tab) - Node.js Redis client: Lua scripting support and the Node.js version required by each major release
- Compilation and Precompilation - Handlebars (opens in new tab) - The
strictandnoEscapecompile options - Art. 17 GDPR: Right to erasure - gdpr-info.eu (opens in new tab) - The right to erasure and its exemptions for legal obligations and legal claims
- Recital 26 GDPR - gdpr-info.eu (opens in new tab) - Pseudonymised data counts as personal data; anonymous information does not
- docker compose up - Docker Documentation (opens in new tab) - The
--waitoption, which waits for services to be running or healthy - pg_isready - PostgreSQL Documentation (opens in new tab) - Connection check whose exit status reports whether the server accepts connections
- docker-entrypoint.sh - docker-library/postgres (opens in new tab) - The official image’s first-start initialization through a temporary, socket-only server
Building a Scalable User Notification System
Part 1 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
Choose the right database across SQL, NoSQL, NewSQL, and edge options: the trade-offs of each category, selection criteria, and a decision framework.
data-storage-orm · postgresql · redis +6
A decision framework for the TypeScript data layer on Postgres: how much SQL the library should own, what it costs on Lambda, and when the default is wrong.
typescript · postgresql · data-storage-orm +1
What Aurora Serverless v2 is under the hood: shared storage, ACU-driven compute, platform versions, the Caspian substrate, scale-to-zero, and mixed-mode clusters.
aws · data-storage-orm · architecture +1
A guide to Aurora architecture, I/O cost analysis, and when to choose it over RDS, with migration strategies and real-world decision frameworks.
aws · data-storage-orm · postgresql +3
Why RBAC passes and users still read each other's records: OWASP API1 BOLA, four ways to close the gap, a recommended default, and a two-user test for CI.
authorization · security · api-design +3