Notification Analytics and Performance Optimization: A/B Testing, Metrics, and Tuning at Scale
Advanced analytics strategies, A/B testing frameworks, and performance optimization techniques for notification systems serving millions of users
Notification systems turn from basic delivery mechanisms into growth infrastructure through comprehensive analytics, systematic A/B testing, and performance optimization.
Once notification systems achieve basic functionality and stability, organizations face a new challenge: moving beyond simple delivery metrics to drive business growth. Product teams need answers about engagement rates, optimal timing, and content effectiveness. Engineering teams encounter performance bottlenecks as volume scales. Traditional monitoring approaches become insufficient when systems need to support millions of users while maintaining cost efficiency.
Delivery rates and open counts show whether messages arrive. Whether they change what users do takes experiments that hold up statistically, metrics measured against the system’s own baseline, and code paths that stay fast and cheap as volume grows.
Goals for the Optimization Layer#
An optimization layer worth the engineering time has to:
- Transform basic delivery metrics into actionable business insights
- Enable safe, systematic A/B testing at scale
- Optimize system performance while controlling costs
- Generate continuous improvements through data-driven decisions
- Provide product and marketing teams with strategic intelligence
Multi-Layered Analytics Architecture#
The foundation requires moving beyond basic delivery metrics (sent, delivered, opened, clicked) to a more comprehensive analytics approach. Opens and clicks say little on their own; the metrics that drive decisions sit one or two steps later, in what the user did after the notification.
The analytics architecture supporting decision-making at scale includes four distinct layers:
interface NotificationAnalytics {
// Layer 1: Delivery Fundamentals
delivery: {
sent: number;
delivered: number;
failed: number;
bounced: number;
deliveryRate: number;
avgDeliveryTime: number;
};
// Layer 2: User Engagement
engagement: {
opened: number;
clicked: number;
dismissed: number;
actioned: number; // User took intended action
openRate: number;
clickThroughRate: number;
conversionRate: number; // Action completion rate
};
// Layer 3: Business Impact
businessImpact: {
revenueGenerated: number;
userRetention: number;
featureAdoption: number;
supportTicketReduction: number;
userLifetimeValue: number;
};
// Layer 4: System Performance
performance: {
processingLatency: number;
queueDepth: number;
resourceUtilization: number;
costPerNotification: number;
errorRates: Record<string, number>;
};
}
class NotificationAnalyticsEngine {
private eventStore: EventStore;
private metricsAggregator: MetricsAggregator;
private cohortAnalyzer: CohortAnalyzer;
async trackNotificationEvent(event: NotificationAnalyticsEvent): Promise<void> {
// Store raw event
await this.eventStore.store(event);
// Real-time aggregation for dashboards
await this.metricsAggregator.update(event);
// Cohort analysis for deeper insights
if (event.type === 'user_action') {
await this.cohortAnalyzer.processUserAction(event);
}
// Trigger anomaly detection
await this.checkForAnomalies(event);
}
async generateInsights(
dateRange: DateRange,
segmentBy?: string[]
): Promise<NotificationInsights> {
const baseMetrics = await this.getBaseMetrics(dateRange);
const segmentedAnalysis = segmentBy ?
await this.getSegmentedAnalysis(dateRange, segmentBy) : null;
const insights: NotificationInsights = {
summary: baseMetrics,
segments: segmentedAnalysis,
trends: await this.getTrendAnalysis(dateRange),
anomalies: await this.getAnomalies(dateRange),
recommendations: await this.generateRecommendations(baseMetrics)
};
return insights;
}
private async generateRecommendations(
metrics: NotificationMetrics
): Promise<OptimizationRecommendation[]> {
const recommendations: OptimizationRecommendation[] = [];
// Compare each channel with its own trailing baseline (same notification
// type, previous 28 days) instead of published industry averages
const baseline = await this.getBaseline(metrics.channel, metrics.notificationType, 28);
const alerts = this.alertConfig[metrics.channel]; // per-channel tolerances, tuned locally
if (metrics.delivery.deliveryRate < baseline.deliveryRate - alerts.maxDeliveryDrop) {
recommendations.push({
type: 'delivery',
priority: 'high',
description: `${metrics.channel} delivery rate ${pct(metrics.delivery.deliveryRate)} vs ${pct(baseline.deliveryRate)} baseline`,
suggestedActions: [
'Review channel-specific authentication settings',
'Check sender reputation and certificates',
'Audit suppression and opt-out lists'
]
});
}
// Click-through and conversion drive decisions; open rate stays diagnostic
const ctrFloor = baseline.clickThroughRate * (1 - alerts.maxRelativeEngagementDrop);
if (metrics.engagement.clickThroughRate < ctrFloor) {
const channelActions = {
email: ['A/B test subject lines', 'Review send time optimization', 'Analyze sender name impact'],
push: ['Test notification copy and timing', 'Optimize badge and icon usage', 'Review permission prompts'],
sms: ['Test message length and clarity', 'Optimize send timing', 'Review opt-in messaging']
};
recommendations.push({
type: 'engagement',
priority: 'medium',
description: `${metrics.channel} click-through ${pct(metrics.engagement.clickThroughRate)} vs ${pct(baseline.clickThroughRate)} baseline`,
suggestedActions: channelActions[metrics.channel] || channelActions.email
});
}
// Performance optimization against the team's latency SLO
if (metrics.performance.processingLatency > this.latencySloMs) {
recommendations.push({
type: 'performance',
priority: 'high',
description: `Processing latency above the ${this.latencySloMs} ms SLO`,
suggestedActions: [
'Review template rendering performance',
'Optimize database queries',
'Consider implementing caching layer'
]
});
}
return recommendations;
}
}
The recommendations compare each channel with its own history because published averages differ by industry, audience, and how each vendor counts an open. A drop against the recent baseline of the same notification type points at something the team can act on: a copy or timing change, a provider problem, or a broken template.
Open rate is the weakest of the engagement metrics, and for email it is distorted. Apple’s Mail Privacy Protection downloads remote content in the background by default, whether or not the recipient engages with the message, so a tracking pixel can record an open for a message nobody read. Clicks on tracked links and in-app conversions are unaffected, which is why the code above alerts on click-through and treats opens as diagnostic. Push and SMS have no equivalent of the pixel: a push open is a tap that the app reports itself, and for SMS the dependable signal is a click on a tracked link.
User Journey Analytics#
Tracking user journeys provides more value than analyzing individual events. Journey data surfaces patterns that single-event metrics miss: where a multi-step flow loses people, and which step is worth rewriting first.
interface UserNotificationJourney {
userId: string;
journeyType: string; // 'onboarding', 'feature_adoption', 'retention'
startedAt: Date;
currentStep: number;
totalSteps: number;
events: NotificationJourneyEvent[];
outcome?: JourneyOutcome;
dropOffReason?: string;
}
class NotificationJourneyTracker {
async trackJourneyEvent(
userId: string,
journeyType: string,
event: NotificationJourneyEvent
): Promise<void> {
const journey = await this.getOrCreateJourney(userId, journeyType);
journey.events.push({
...event,
timestamp: new Date(),
stepNumber: journey.currentStep
});
// Update journey state based on event
await this.updateJourneyState(journey, event);
// Check for journey completion or abandonment
await this.evaluateJourneyStatus(journey);
await this.saveJourney(journey);
}
async analyzeJourneyPerformance(
journeyType: string,
dateRange: DateRange
): Promise<JourneyAnalytics> {
const journeys = await this.getJourneys(journeyType, dateRange);
const stepConversionRates = this.calculateStepConversions(journeys);
const dropOffPoints = this.identifyDropOffPoints(journeys);
const timeToComplete = this.calculateCompletionTimes(journeys);
return {
totalJourneys: journeys.length,
completionRate: journeys.filter(j => j.outcome === 'completed').length / journeys.length,
stepConversionRates,
dropOffPoints,
averageTimeToComplete: timeToComplete.average,
medianTimeToComplete: timeToComplete.median,
recommendations: this.generateJourneyOptimizations(stepConversionRates, dropOffPoints)
};
}
private generateJourneyOptimizations(
conversionRates: Record<number, number>,
dropOffPoints: DropOffAnalysis[]
): JourneyOptimization[] {
const optimizations: JourneyOptimization[] = [];
// Find steps with low conversion rates
Object.entries(conversionRates).forEach(([step, rate]) => {
if (rate < 0.7) { // Less than 70% conversion
optimizations.push({
stepNumber: parseInt(step),
type: 'low_conversion',
currentRate: rate,
suggestions: [
'Simplify the required action',
'Improve notification copy clarity',
'Add progress indicators',
'Provide contextual help'
]
});
}
});
// Analyze major drop-off points
dropOffPoints.forEach(dropOff => {
if (dropOff.dropOffRate > 0.3) { // More than 30% drop-off
optimizations.push({
stepNumber: dropOff.stepNumber,
type: 'high_dropoff',
currentRate: 1 - dropOff.dropOffRate,
suggestions: [
'Review notification timing',
'Check message relevance',
'Test different call-to-action phrases',
'Consider breaking step into smaller actions'
]
});
}
});
return optimizations;
}
}
Systematic A/B Testing Framework#
Notification A/B testing presents unique challenges: users only see one version, feedback cycles are extended, and poor tests can impact retention for weeks. The solution requires a safety-first approach with built-in guardrails, and that safety covers the statistics as well: an experiment that assigns users unevenly or declares a winner too early does as much damage as one that annoys users.
The testing infrastructure includes comprehensive experiment management:
import { createHash } from 'node:crypto';
// Users outside the experiment are "not enrolled", never "control"
type ExperimentAssignment =
| { enrolled: false; reason: 'experiment_not_running' | 'not_in_target_audience' | 'traffic_allocation' }
| { enrolled: true; experimentId: string; variant: string; assignedAt: Date };
interface NotificationExperiment {
id: string;
name: string;
type: ExperimentType; // 'subject_line', 'timing', 'content', 'frequency', 'channel'
status: ExperimentStatus;
hypothesis: string;
variants: ExperimentVariant[];
targetAudience: AudienceDefinition;
trafficAllocation: number; // Percentage of eligible users
primaryMetric: string;
// Guardrails: tested together, Holm-adjusted. Direction matters: a higher
// complaint or unsubscribe rate is worse, a higher click-through is better
secondaryMetrics: { name: string; higherIsBetter: boolean }[];
minimumDetectableEffect: number;
significanceLevel: number;
powerLevel: number;
requiredSamplePerVariant: number; // fixed horizon, computed at creation
outcomeWindowMs: number; // how long after assignment the outcome is measured
startDate: Date;
endDate?: Date;
results?: ExperimentResults;
}
class NotificationExperimentManager {
private statisticalEngine: StatisticalEngine;
private userSegmenter: UserSegmenter;
private safetyMonitor: SafetyMonitor;
async createExperiment(
experimentConfig: ExperimentConfig
): Promise<NotificationExperiment> {
// Calculate required sample size per variant
const sampleSize = this.statisticalEngine.calculateSampleSize(
experimentConfig.minimumDetectableEffect,
experimentConfig.significanceLevel,
experimentConfig.powerLevel,
experimentConfig.baselineConversionRate
);
// Validate experiment safety
const safetyCheck = await this.safetyMonitor.validateExperiment(experimentConfig);
if (!safetyCheck.isSafe) {
throw new Error(`Experiment failed safety check: ${safetyCheck.reasons.join(', ')}`);
}
// Set up user segmentation
const audience = await this.userSegmenter.defineAudience(
experimentConfig.targetCriteria,
sampleSize
);
const experiment: NotificationExperiment = {
id: this.generateExperimentId(),
name: experimentConfig.name,
type: experimentConfig.type,
status: 'draft',
hypothesis: experimentConfig.hypothesis,
variants: experimentConfig.variants,
targetAudience: audience,
trafficAllocation: experimentConfig.trafficAllocation,
primaryMetric: experimentConfig.primaryMetric,
secondaryMetrics: experimentConfig.secondaryMetrics,
minimumDetectableEffect: experimentConfig.minimumDetectableEffect,
significanceLevel: experimentConfig.significanceLevel,
powerLevel: experimentConfig.powerLevel,
requiredSamplePerVariant: sampleSize,
outcomeWindowMs: experimentConfig.outcomeWindowMs,
startDate: experimentConfig.startDate
};
await this.saveExperiment(experiment);
return experiment;
}
async assignUserToExperiment(
userId: string,
experimentId: string
): Promise<ExperimentAssignment> {
const experiment = await this.getExperiment(experimentId);
if (experiment.status !== 'running') {
return { enrolled: false, reason: 'experiment_not_running' };
}
// Check if user is in target audience
const isEligible = await this.userSegmenter.isUserEligible(
userId,
experiment.targetAudience
);
if (!isEligible) {
return { enrolled: false, reason: 'not_in_target_audience' };
}
// Traffic gate and variant pick use independent hashes (different salts)
const trafficBucket = this.hashUserId(userId, `${experiment.id}:traffic`) % 100;
if (trafficBucket >= experiment.trafficAllocation) {
return { enrolled: false, reason: 'traffic_allocation' };
}
// Control is variants[0]: a real arm with its own stored assignments
const variantIndex =
this.hashUserId(userId, `${experiment.id}:variant`) % experiment.variants.length;
const assignedVariant = experiment.variants[variantIndex];
// Store assignment for consistency; analysis reads only these rows
await this.storeUserAssignment(userId, experimentId, assignedVariant.id);
return {
enrolled: true,
variant: assignedVariant.id,
experimentId,
assignedAt: new Date()
};
}
// Unsigned 32-bit integer, stable for the same (salt, userId) pair
private hashUserId(userId: string, salt: string): number {
return createHash('sha256').update(`${salt}:${userId}`).digest().readUInt32BE(0);
}
async analyzeExperimentResults(
experimentId: string
): Promise<ExperimentAnalysis> {
// The analysis runs once; later calls get the stored result
const stored = await this.getStoredAnalysis(experimentId);
if (stored) return stored;
const experiment = await this.getExperiment(experimentId);
// Fixed horizon, counted in users whose outcome window has closed
const maturedBefore = new Date(Date.now() - experiment.outcomeWindowMs);
const matured = await this.countAssignmentsPerVariant(experimentId, maturedBefore);
const smallestArm = Math.min(
...experiment.variants.map(v => matured[v.id] ?? 0)
);
if (smallestArm < experiment.requiredSamplePerVariant) {
return {
status: 'collecting',
smallestArm,
required: experiment.requiredSamplePerVariant
};
}
// Horizon reached: stop enrolling (assignUserToExperiment checks status),
// then analyze the first N assignments of each arm, by assignment time
await this.updateExperimentStatus(experimentId, 'stopped');
const rawData = await this.getExperimentData(experimentId, {
firstPerVariant: experiment.requiredSamplePerVariant
});
// Statistical significance testing
const primaryResults = await this.statisticalEngine.performTest(
rawData,
experiment.primaryMetric,
experiment.significanceLevel
);
// Secondary metrics are guardrails: one family, Holm-adjusted
const guardrailTests = await Promise.all(
experiment.secondaryMetrics.map(metric =>
this.statisticalEngine.performTest(rawData, metric.name, experiment.significanceLevel)
)
);
const significant = holmReject(
guardrailTests.map(t => t.pValue),
experiment.significanceLevel
);
const secondaryResults = guardrailTests.map((t, i) => {
const metric = experiment.secondaryMetrics[i];
return {
...t,
significantAfterCorrection: significant[i],
// effect = variant minus control; "worse" depends on the metric
regression: significant[i] && (metric.higherIsBetter ? t.effect < 0 : t.effect > 0)
};
});
// Effect size calculation
const effectSize = this.statisticalEngine.calculateEffectSize(
primaryResults,
experiment.minimumDetectableEffect
);
// Business impact estimation
const businessImpact = await this.estimateBusinessImpact(
primaryResults,
experiment
);
const analysis: ExperimentAnalysis = {
status: 'complete',
experiment,
primaryResults,
secondaryResults,
effectSize,
businessImpact,
// A guardrail regression blocks rollout even when the primary metric wins
recommendation: this.generateRecommendation(
primaryResults,
secondaryResults,
businessImpact
),
confidenceLevel: primaryResults.confidenceLevel
};
await this.storeAnalysis(experimentId, analysis);
return analysis;
}
}
// Holm-Bonferroni: which hypotheses to reject at family-wise error rate alpha
function holmReject(pValues: number[], alpha: number): boolean[] {
const order = pValues
.map((p, index) => ({ p, index }))
.sort((a, b) => a.p - b.p);
const reject = new Array<boolean>(pValues.length).fill(false);
for (let k = 0; k < order.length; k++) {
if (order[k].p > alpha / (order.length - k)) break;
reject[order[k].index] = true;
}
return reject;
}
Four decisions in that code keep the result trustworthy. The traffic gate and the variant pick use two independent hashes, so a 50% allocation with two variants splits the enrolled half evenly. Reusing the gate’s bucket is easy to get wrong: with a 50% gate and two variants, Math.floor((bucket / 100) * 2) is 0 for every enrolled user. Users who are ineligible or outside the allocation get enrolled: false and the default experience. They never reach the analysis, because control is a real variant with its own stored assignments. Returning 'control' for them would mix people who were never randomized into the control arm.
The analysis runs on a fixed horizon, and the horizon counts only users whose outcome window has closed: a user enrolled an hour ago has not had time to click or convert yet. Once the smallest arm reaches the sample size computed at creation, the experiment stops enrolling. The analysis then runs once, on the first that-many assignments of each arm, and later calls return the stored result. Checking a running test again and again and stopping at the first significant result pushes the false-positive rate well above the nominal level. Teams that need to look early should use a sequential method with always-valid p-values, which is designed for continuous monitoring, instead of peeking at a fixed-horizon test.
Secondary metrics act as guardrails. Their p-values are adjusted together with the Holm procedure, which keeps the family-wise error rate at the chosen significance level. Each guardrail declares which direction is worse: a rise in complaint or unsubscribe rate counts as a regression, and so does a drop in click-through. A significant regression on a guardrail blocks the rollout even when the primary metric improves.
Experiment Safety Monitoring#
Safety monitoring prevents experiments from negatively impacting user experience or business metrics. It runs continuously, which does not conflict with the fixed horizon: the monitor can only pause an experiment for harm and never declares a winner. A false alarm costs a paused experiment and a human review, which is cheap next to a harmful variant running for the full horizon.
class ExperimentSafetyMonitor {
private alerting: AlertingService;
private metrics: MetricsService;
async monitorExperimentSafety(experimentId: string): Promise<SafetyStatus> {
const experiment = await this.getExperiment(experimentId);
const safetyChecks = await Promise.all([
this.checkDeliveryRates(experiment),
this.checkEngagementMetrics(experiment),
this.checkUserComplaintsRate(experiment),
this.checkBusinessMetricImpact(experiment),
this.checkSystemPerformance(experiment)
]);
const criticalIssues = safetyChecks.filter(check => check.severity === 'critical');
const warnings = safetyChecks.filter(check => check.severity === 'warning');
if (criticalIssues.length > 0) {
await this.triggerExperimentPause(experimentId, criticalIssues);
await this.alerting.sendCriticalAlert({
type: 'experiment_safety_violation',
experimentId,
issues: criticalIssues
});
}
return {
status: criticalIssues.length > 0 ? 'critical' :
warnings.length > 0 ? 'warning' : 'healthy',
checks: safetyChecks,
lastChecked: new Date()
};
}
private async checkDeliveryRates(experiment: NotificationExperiment): Promise<SafetyCheck> {
const deliveryRates = await this.getVariantDeliveryRates(experiment.id);
for (const [variantId, rate] of Object.entries(deliveryRates)) {
if (rate < 0.90) { // Less than 90% delivery rate
return {
checkType: 'delivery_rate',
severity: 'critical',
message: `Variant ${variantId} has delivery rate of ${rate * 100}%`,
threshold: 0.90,
actualValue: rate,
recommendation: 'Pause experiment and investigate delivery issues'
};
}
}
return {
checkType: 'delivery_rate',
severity: 'healthy',
message: 'All variants have acceptable delivery rates'
};
}
private async checkUserComplaintsRate(experiment: NotificationExperiment): Promise<SafetyCheck> {
const complaintRates = await this.getVariantComplaintRates(experiment.id);
for (const [variantId, rate] of Object.entries(complaintRates)) {
if (rate > 0.01) { // More than 1% complaint rate
return {
checkType: 'user_complaints',
severity: 'critical',
message: `Variant ${variantId} has complaint rate of ${rate * 100}%`,
threshold: 0.01,
actualValue: rate,
recommendation: 'Immediately pause experiment - high complaint rate indicates poor user experience'
};
}
}
return {
checkType: 'user_complaints',
severity: 'healthy',
message: 'Complaint rates within acceptable range'
};
}
private async triggerExperimentPause(
experimentId: string,
reasons: SafetyCheck[]
): Promise<void> {
await this.updateExperimentStatus(experimentId, 'paused_for_safety');
// Log the pause reason
await this.logExperimentEvent(experimentId, {
type: 'safety_pause',
timestamp: new Date(),
reasons: reasons.map(r => r.message),
autoResumeEligible: reasons.every(r => r.severity === 'warning')
});
// Notify experiment owners
await this.notifyExperimentOwners(experimentId, reasons);
}
}
Performance Optimization Strategies#
As volume grows, processing time tends to concentrate in three places: template rendering, database reads, and queue handling. The techniques below target each of them:
Template Rendering Optimization#
Template rendering frequently becomes a hidden bottleneck. Compiled-template caching inside each render worker, batched data preloading, and a worker pool for the render step remove most of that cost:
interface TemplateRecord {
source: string;
version: number;
requiredData: string[];
}
class OptimizedTemplateRenderer {
// Holds template records (plain data), not compiled functions
private templateCache: LRUCache<string, TemplateRecord>;
private dataPreloader: DataPreloader;
private renderPool: WorkerPool;
constructor() {
this.templateCache = new LRUCache({ max: 1000, ttl: 1000 * 60 * 60 }); // 1 hour
this.renderPool = new WorkerPool({
size: 10,
taskTimeout: 5000
});
}
// Call from the template publish path; otherwise an edit waits out the 1-hour TTL
invalidateTemplate(templateId: string): void {
this.templateCache.delete(templateId);
}
async renderTemplate(
templateId: string,
userData: any,
notificationData: any
): Promise<RenderedContent> {
let template = this.templateCache.get(templateId);
if (!template) {
template = await this.getTemplateRecord(templateId);
this.templateCache.set(templateId, template);
}
// Pre-load commonly needed data to prevent N+1 queries
const preloadedData = await this.dataPreloader.preloadForTemplate(
template.requiredData,
userData.userId
);
const renderContext = {
...userData,
...notificationData,
...preloadedData
};
// Use worker pool for CPU-intensive rendering. The task must survive
// structured cloning, so it carries source and version, never a function
const renderTask: RenderTask = {
templateId,
version: template.version,
source: template.source,
context: renderContext
};
try {
const result = await this.renderPool.execute(renderTask);
// Track rendering performance
await this.trackRenderingMetrics(templateId, result.renderTime, true);
return result.content;
} catch (error) {
await this.trackRenderingMetrics(templateId, 0, false);
// Fallback to simple template
return await this.renderFallbackTemplate(templateId, renderContext);
}
}
}
interface RenderTask {
templateId: string;
version: number;
source: string;
context: Record<string, unknown>; // plain data only
}
// Inside each pool worker: compile once per template version, then reuse
const compiledTemplates = new Map<string, (context: Record<string, unknown>) => string>();
function handleRenderTask(task: RenderTask): { content: string; renderTime: number } {
const key = `${task.templateId}:${task.version}`;
let render = compiledTemplates.get(key);
if (!render) {
render = compileTemplate(task.source);
compiledTemplates.set(key, render);
}
const startedAt = performance.now();
const content = render(task.context);
return { content, renderTime: performance.now() - startedAt };
}
class DataPreloader {
private queryBatcher: QueryBatcher;
private dataCache: Cache;
async preloadForTemplate(
requiredData: string[],
userId: string
): Promise<Record<string, any>> {
const preloadPromises: Promise<any>[] = [];
const preloadedData: Record<string, any> = {};
if (requiredData.includes('user_projects')) {
preloadPromises.push(
this.queryBatcher.batch('user_projects', userId)
.then(data => preloadedData.projects = data)
);
}
if (requiredData.includes('user_activities')) {
preloadPromises.push(
this.queryBatcher.batch('user_activities', userId)
.then(data => preloadedData.recentActivities = data)
);
}
if (requiredData.includes('user_settings')) {
preloadPromises.push(
this.queryBatcher.batch('user_settings', userId)
.then(data => preloadedData.settings = data)
);
}
await Promise.all(preloadPromises);
return preloadedData;
}
}
class QueryBatcher {
private batches: Map<string, BatchQuery> = new Map();
private batchTimeout = 50; // 50ms batch window
async batch<T>(queryType: string, param: any): Promise<T> {
return new Promise((resolve, reject) => {
if (!this.batches.has(queryType)) {
this.batches.set(queryType, {
params: [],
promises: [],
timeoutId: setTimeout(() => this.executeBatch(queryType), this.batchTimeout)
});
}
const batch = this.batches.get(queryType)!;
batch.params.push(param);
batch.promises.push({ resolve, reject });
});
}
private async executeBatch(queryType: string): Promise<void> {
const batch = this.batches.get(queryType);
if (!batch) return;
this.batches.delete(queryType);
clearTimeout(batch.timeoutId);
try {
const results = await this.executeQuery(queryType, batch.params);
batch.promises.forEach((promise, index) => {
promise.resolve(results[index]);
});
} catch (error) {
batch.promises.forEach(promise => {
promise.reject(error);
});
}
}
}
The worker boundary shapes this design. Node’s postMessage copies values with the structured clone algorithm, and that algorithm throws DataCloneError for functions, so a compiled template cannot travel to a worker. Each worker compiles the source it receives and caches the result by template ID and version. The render context has to be plain data for the same reason.
The main-thread cache keeps template records for one hour. Without a call to invalidateTemplate from the publish path, a template edit stays invisible to users for up to that hour. Because the worker cache key includes the version, a fresh record is enough to make the workers compile the new template.
Database Query Optimization#
Database queries are the other major bottleneck: read replicas for analytics reads, a write-invalidated cache for preference lookups, and batched user fetches keep that load flat as volume grows.
class OptimizedNotificationQueries {
private readReplica: Database;
private primary: Database;
private queryCache: Redis;
async getUserNotificationPreferences(
userId: string
): Promise<NotificationPreferences> {
const cacheKey = `prefs:${userId}`;
// Try cache first
const cached = await this.queryCache.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
// Cache misses read the primary: a lagging replica could return a row
// from before an opt-out, and the cache would then keep it
const preferences = await this.primary.query(`
SELECT
np.notification_type,
np.channel,
np.enabled,
np.frequency,
np.quiet_hours_start,
np.quiet_hours_end,
u.timezone,
u.locale
FROM notification_preferences np
JOIN users u ON u.id = np.user_id
WHERE np.user_id = $1
`, [userId]);
const structured = this.structurePreferences(preferences);
// 5-minute TTL is a backstop; writes delete the key directly
await this.queryCache.setex(cacheKey, 300, JSON.stringify(structured));
return structured;
}
async updateNotificationPreference(
userId: string,
change: PreferenceChange
): Promise<void> {
// Upsert: a user has no row until the first change, because defaults
// live in notification_type_channels (Part 1)
await this.primary.query(`
INSERT INTO notification_preferences (user_id, notification_type, channel, enabled)
VALUES ($1, $2, $3, $4)
ON CONFLICT (user_id, notification_type, channel)
DO UPDATE SET enabled = EXCLUDED.enabled, updated_at = NOW()
`, [userId, change.notificationType, change.channel, change.enabled]);
// Invalidate after the write commits, so the next send sees the change
await this.queryCache.del(`prefs:${userId}`);
}
async getBatchUserData(userIds: string[]): Promise<Map<string, UserData>> {
// Batch query instead of N individual queries. It reads the primary
// because the *_enabled flags carry channel opt-outs (Part 2's
// complaint handler sets email_enabled = false)
const userData = await this.primary.query(`
SELECT
u.id,
u.email,
u.locale,
u.timezone,
u.email_enabled,
u.sms_enabled,
u.push_enabled,
array_agg(pt.token) as push_tokens,
array_agg(pt.platform) as push_platforms
FROM users u
LEFT JOIN push_tokens pt ON pt.user_id = u.id AND pt.is_active = true
WHERE u.id = ANY($1)
GROUP BY u.id, u.email, u.locale, u.timezone, u.email_enabled, u.sms_enabled, u.push_enabled
`, [userIds]);
const userMap = new Map<string, UserData>();
userData.forEach(row => {
userMap.set(row.id, {
id: row.id,
email: row.email,
locale: row.locale,
timezone: row.timezone,
emailEnabled: row.email_enabled,
smsEnabled: row.sms_enabled,
pushEnabled: row.push_enabled,
pushTokens: row.push_tokens?.filter(Boolean) || [],
pushPlatforms: row.push_platforms?.filter(Boolean) || []
});
});
return userMap;
}
async getNotificationAnalytics(
dateRange: DateRange,
filters?: AnalyticsFilters
): Promise<NotificationAnalytics> {
// Read Part 1's hourly aggregate. The query assumes a writer that upserts
// one count per event (sent, delivered, opened, clicked, failed):
// ON CONFLICT (date, hour, notification_type, channel, status)
// DO UPDATE SET count = notification_metrics.count + 1
// so an opened message still counts as delivered
let query = `
SELECT
notification_type,
channel,
date,
SUM(count) FILTER (WHERE status = 'sent') AS sent,
SUM(count) FILTER (WHERE status = 'delivered') AS delivered,
SUM(count) FILTER (WHERE status = 'opened') AS opened,
SUM(count) FILTER (WHERE status = 'clicked') AS clicked,
SUM(count) FILTER (WHERE status = 'failed') AS failed
FROM notification_metrics
WHERE date >= $1 AND date <= $2
`;
const params = [dateRange.start, dateRange.end];
if (filters?.notificationType) {
query += ` AND notification_type = $${params.length + 1}`;
params.push(filters.notificationType);
}
if (filters?.channel) {
query += ` AND channel = $${params.length + 1}`;
params.push(filters.channel);
}
query += `
GROUP BY notification_type, channel, date
ORDER BY date DESC
`;
const results = await this.readReplica.query(query, params);
return this.aggregateAnalytics(results);
}
}
Two reads skip the replica: preference lookups and the batched user fetch on the send path. Part 2 requires preference changes and opt-outs to take effect on the very next send. Opt-outs live in two places: the preference rows and the channel flags on users, such as the email_enabled column that Part 2’s complaint handler switches off. Both are read from the primary. The preference write is an upsert, because a user has no row until their first change and the defaults come from notification_type_channels; a plain UPDATE would match nothing and lose the opt-out. The write path deletes the cache key after it commits, and cache misses read the primary. A small race remains: a reader that fetched the old row just before the write can put it back into the cache after the delete. The 5-minute TTL bounds that window. A send path that must never miss an opt-out can check the enabled flag on the primary directly at send time.
The analytics query counts events. The notification_metrics table from Part 1 stores one row per hour, type, channel, and status. The query assumes a writer that upserts one count into that row for every event a message produces, as the comment in the code shows. A message that is delivered and then opened adds to both counts. Counting the current status of each delivery row would move an opened message out of delivered and make the delivery rate look lower than it is. Delivery latency is not part of the aggregate; it comes from the sent_at and delivered_at columns of notification_deliveries.
Queue Processing Optimization#
Queue processing is where batching and adaptive concurrency pay off:
class OptimizedNotificationProcessor {
private processingQueue: Queue;
private batchProcessor: BatchProcessor;
private resourceMonitor: ResourceMonitor;
constructor() {
this.batchProcessor = new BatchProcessor({
batchSize: 100,
batchTimeout: 1000, // 1 second
concurrency: 10
});
}
async startProcessing(): Promise<void> {
// Dynamic concurrency based on system resources
this.processingQueue.process('notification', async (job) => {
const notifications = Array.isArray(job.data) ? job.data : [job.data];
// Group by similar processing requirements
const groupedNotifications = this.groupNotifications(notifications);
const processingPromises = Object.entries(groupedNotifications).map(
([group, groupNotifications]) =>
this.processNotificationGroup(group, groupNotifications)
);
return await Promise.allSettled(processingPromises);
});
// Adjust processing concurrency based on system load
setInterval(async () => {
const systemLoad = await this.resourceMonitor.getCurrentLoad();
const optimalConcurrency = this.calculateOptimalConcurrency(systemLoad);
this.processingQueue.setConcurrency(optimalConcurrency);
}, 30000); // Every 30 seconds
}
private async processNotificationGroup(
groupType: string,
notifications: NotificationEvent[]
): Promise<BatchProcessingResult> {
switch (groupType) {
case 'email_batch':
return await this.processEmailBatch(notifications);
case 'push_batch':
return await this.processPushBatch(notifications);
case 'template_heavy':
return await this.processTemplateHeavyBatch(notifications);
default:
return await this.processIndividualNotifications(notifications);
}
}
private async processEmailBatch(
notifications: NotificationEvent[]
): Promise<BatchProcessingResult> {
const startedAt = performance.now();
// Batch similar email notifications
const templateGroups = this.groupByTemplate(notifications);
const batchPromises = Object.entries(templateGroups).map(
async ([templateId, templateNotifications]) => {
// Pre-render template once for the batch
const baseTemplate = await this.getTemplate(templateId);
// Batch user data lookup
const userIds = templateNotifications.map(n => n.userId);
const userData = await this.getBatchUserData(userIds);
// Process all notifications with pre-loaded data
const emailPromises = templateNotifications.map(notification =>
this.processEmailWithPreloadedData(notification, userData, baseTemplate)
);
return await Promise.allSettled(emailPromises);
}
);
const results = await Promise.all(batchPromises);
return {
processed: notifications.length,
successful: results.flat().filter(r => r.status === 'fulfilled').length,
failed: results.flat().filter(r => r.status === 'rejected').length,
processingTime: performance.now() - startedAt // ms, monotonic clock
};
}
private calculateOptimalConcurrency(systemLoad: SystemLoad): number {
const baseConcurrency = 10;
if (systemLoad.cpu > 0.8) {
return Math.max(2, baseConcurrency * 0.5);
} else if (systemLoad.cpu > 0.6) {
return Math.max(5, baseConcurrency * 0.7);
} else if (systemLoad.cpu < 0.3) {
return Math.min(20, baseConcurrency * 1.5);
}
return baseConcurrency;
}
}
The batch timer subtracts two performance.now() readings. In Node, performance.now() counts milliseconds from the start of the process, so subtracting it from Date.now() (milliseconds since the Unix epoch) yields a number that measures nothing.
Cost Optimization and Resource Management#
For notification systems, the most impactful performance optimizations often target cost efficiency rather than speed:
Selecting a Processing Tier#
// Example set: messages a user needs whatever their engagement history says
const TRANSACTIONAL_TYPES = new Set(['security_alert', 'password_reset', 'payment_receipt']);
interface CostThresholds {
highValue: number; // per-product values, derived from observed conversion data
lowCost: number;
highCost: number;
}
class CostOptimizedNotificationSystem {
private costTracker: CostTracker;
private conversionStats: ConversionStatsStore;
private resourceAllocator: ResourceAllocator;
private thresholds: CostThresholds;
async processNotificationWithCostOptimization(
notification: NotificationEvent
): Promise<void> {
// Transactional messages never pass through the ROI gate
if (TRANSACTIONAL_TYPES.has(notification.type)) {
await this.processPremium(notification);
return;
}
const costAnalysis = await this.analyzeCost(notification);
// Choose processing strategy based on cost-benefit
if (costAnalysis.highValue && costAnalysis.lowCost) {
// Premium processing for high-value, low-cost notifications
await this.processPremium(notification);
} else if (costAnalysis.highValue && costAnalysis.highCost) {
// Optimized processing for high-value, high-cost notifications
await this.processOptimized(notification);
} else if (costAnalysis.lowValue && costAnalysis.lowCost) {
// Batch processing for low-value, low-cost notifications
await this.queueForBatchProcessing(notification);
} else {
// Evaluate if notification should be sent at all
const shouldSend = await this.evaluateROI(notification, costAnalysis);
if (shouldSend) {
await this.processEconomical(notification);
}
}
}
private async analyzeCost(notification: NotificationEvent): Promise<CostAnalysis> {
const channels = await this.getTargetChannels(notification.userId, notification.type);
let totalCost = 0;
let estimatedValue = 0;
for (const channel of channels) {
const channelCost = await this.costTracker.getChannelCost(channel);
const channelValue = await this.estimateChannelValue(notification, channel);
totalCost += channelCost;
estimatedValue += channelValue;
}
const highValue = estimatedValue > this.thresholds.highValue;
return {
totalCost,
estimatedValue,
roi: estimatedValue / totalCost,
highValue,
lowValue: !highValue,
lowCost: totalCost < this.thresholds.lowCost,
highCost: totalCost > this.thresholds.highCost
};
}
// Incremental value of one send: conversion lift over a holdout group that
// did not receive this type on this channel, times the value of a conversion
private async estimateChannelValue(
notification: NotificationEvent,
channel: NotificationChannel
): Promise<number> {
const stats = await this.conversionStats.get(notification.type, channel);
return (stats.conversionRate - stats.holdoutConversionRate) * stats.valuePerConversion;
}
private async evaluateROI(
notification: NotificationEvent,
costAnalysis: CostAnalysis
): Promise<boolean> {
// Don't send notifications with negative ROI
if (costAnalysis.roi < 1.0) {
await this.trackSkippedNotification(notification, 'negative_roi');
return false;
}
// For marginal ROI, consider user engagement history
if (costAnalysis.roi < 1.5) {
const userEngagement = await this.getUserEngagementScore(notification.userId);
if (userEngagement < 0.1) { // Very low engagement
await this.trackSkippedNotification(notification, 'low_engagement_roi');
return false;
}
}
return true;
}
}
The ROI gate applies only to messages whose value is optional. Security alerts, password resets, and receipts bypass it, because skipping one breaks the product whatever the engagement score says. For everything else, estimateChannelValue comes from measurement: the conversion lift over a holdout group that did not receive that notification type, multiplied by the value of one conversion. The thresholds sit in per-product configuration and come from the same data, since a dollar cut-off has no meaning outside the product it was measured in.
Implementation Playbook#
A workable rollout order for these analytics and optimization strategies:
Instrumentation comes first: comprehensive event tracking across every channel, journey tracking for the flows that matter, real-time dashboards with business-impact metrics, and baseline performance benchmarks.
Database query tuning, read replicas, template caching, rendering optimization, batch processing for similar notifications, and basic safety monitoring make up the next stage. After that, the experimentation layer goes in: the experiment management system, the statistical testing framework with a fixed horizon and guardrail metrics, safety monitoring with automatic pausing, and first tests on high-impact areas like subject lines and timing.
The more advanced work, cost-aware processing, send-time machine learning, advanced user segmentation, predictive engagement analytics, comes once the earlier layers are running.
None of it stops once it ships: experiment reviews, performance and cost audits, and safety monitoring need a recurring cadence to stay useful.
When the Analytics Layer Earns Its Cost#
Instrumentation, guarded experimentation, and cost-aware processing pay for themselves once notification volume is high enough that a percentage point of engagement outweighs the engineering time. Below that volume, a single delivery dashboard and manual copy review get you further for less.
Two limits are worth stating plainly. A/B tests on notifications need enough traffic to reach the planned sample size before the result goes stale, so low-volume products should run fewer and larger experiments instead of many small ones. Cost-aware skipping is only as good as the value estimate behind it: when that estimate is a guess rather than an observed conversion lift, the ROI gate quietly suppresses notifications users wanted. Transactional messages stay outside the gate for that reason.
Series Conclusion#
- Part 1: Architectural foundation for scalable delivery
- Part 2: Real-time processing engine for reliability
- Part 3: Monitoring and debugging for system health
- Part 4: Analytics and optimization for business growth
References#
- How Not To Run an A/B Test - Evan Miller (opens in new tab) - Why repeated significance checks on a running test inflate false positives, and why committing to a sample size in advance fixes it
- Always Valid Inference: Bringing Sequential Analysis to A/B Testing - Johari, Pekelis, Walsh (arXiv) (opens in new tab) - Always-valid p-values and confidence intervals for experiments that are monitored continuously
- Holm-Bonferroni method - Wikipedia (opens in new tab) - Step-down procedure that controls the family-wise error rate across several metrics tested together
- Mail Privacy Protection & Privacy - Apple (opens in new tab) - Apple’s description of Protect Mail Activity, which downloads remote content in the background and breaks pixel-based open tracking
- The structured clone algorithm - MDN (opens in new tab) - Which values can cross a worker boundary; functions throw
DataCloneError - Worker threads - Node.js Documentation (opens in new tab) -
port.postMessageandworkerDatacopy values with the structured clone algorithm - Performance measurement APIs - Node.js Documentation (opens in new tab) -
performance.now()returns milliseconds since the start of the current Node process - Amazon Pinpoint end of support - AWS Documentation (opens in new tab) - Pinpoint engagement features, including analytics and the KPI APIs, ended on October 30, 2026; event delivery to Kinesis, Data Firehose, and CloudWatch continues
- What is Amazon CloudWatch? - AWS Documentation (opens in new tab) - CloudWatch as the observability layer for tracking notification throughput, latency, and cost metrics over time
- Common Amazon SNS scenarios - AWS Documentation (opens in new tab) - SNS fanout and filtering patterns that underpin per-segment and per-user notification delivery optimization
Building a Scalable User Notification System
Part 4 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
Multi-environment CDK setup, 302 redirects with a short edge cache, on-demand capacity for campaign spikes, EMF metrics, origin load tests and canary deploys.
aws-cdk · lambda · dynamodb +6
Step-by-step guide to adding Sentry to a React Native Expo app: SDK setup, Expo Router instrumentation, session replay, and source maps for EAS.
react-native · expo · monitoring +2
Strategies to prevent and handle DynamoDB throttling in Single Table Design: partition key design, write sharding, capacity modes, DAX, and retry patterns.
dynamodb · aws · reliability +4
Build reliable, maintainable E2E suites with Playwright and Cypress: framework selection, flaky-test prevention, CI/CD integration, and optimization.
testing · ci-cd · automation +2
Running LangChain 1.x in production: the anti-patterns that cause failures, the patterns that hold up, with create_agent middleware, caching and cost-control code.
langchain · llm · production +5