Skip to content

Debugging Notification Delivery Failures at Scale

How a notification cascade spreads across email, push and WebSocket, how to trace it to one root cause, and the breakers and limits that contain it

Ayhan Sipahi Ayhan Sipahi

Notification systems fail in ways that hurt most: silently, at peak load, when a launch or a campaign depends on them. Welcome emails don’t arrive, push notifications time out, and in-app alerts lag, but the dashboards stay green because each subsystem looks fine in isolation.

Rank monitoring signals by their distance from the user, and put a circuit breaker in front of every dependency you do not control, since CPU and memory alerts describe the wreckage without identifying which subsystem started it.

Cascade Failures Under Peak Traffic#

A pipeline that moves millions of messages a day across email, push, and in-app channels can run for months without incident, then fail on every channel within minutes of a traffic peak. The failure is rarely one bug: it is a chain in which each subsystem’s defensive behavior becomes the next subsystem’s load.

The Initial Symptoms#

The example below is a composite cascade with illustrative times and values. Its alerts arrive in an order that points the wrong way. Email fires first and suggests provider throttling, while the cause sits in a mobile release two layers away. Each alert fires on its own evaluation window, so the firing order follows window lengths more than causality.

FiredAlertValue / thresholdWhat it pointed atWhat was underneath
06:15Email delivery rate60% / 95%Provider throttlingRenders waiting for a saturated database pool; the provider was healthy
06:16Push timeout rate25% / 5%APNs or payload troubleToken lookups waiting for the same pool
06:18WebSocket connections85,000 / 50,000A traffic spikeA reconnect storm from one app release
06:20Database connection pool95% / 80%Slow queriesSession lookups from every handshake attempt
06:22Redis memory92% / 85%A memory leakConnection rows written faster than closed sockets remove them

The Debugging Process#

Step 1: Stop the Bleeding

Restarting services is the first instinct and usually the wrong one: a restart drops in-flight work and feeds the retry storm that is already saturating the system. In this cascade, two controls contain the damage. Circuit breakers stop the push and email workers from holding pool connections on calls that keep failing, and the WebSocket tier refuses handshakes before it authenticates them (shown in the WebSocket section below).

type Channel = 'email' | 'push' | 'websocket';

class CircuitOpenError extends Error {}

class ChannelCircuitBreaker {
  private state: 'closed' | 'open' | 'half-open' = 'closed';
  private openedAt = 0;
  private probeInFlight = false;
  private outcomes: { at: number; ok: boolean }[] = [];

  constructor(
    private readonly windowMs = 30_000,  // sliding window for the failure rate
    private readonly minCalls = 20,      // too few calls say nothing about health
    private readonly maxFailureRate = 0.5,
    private readonly openMs = 30_000
  ) {}

  get isClosed(): boolean {
    return this.state === 'closed';
  }

  async execute<T>(operation: () => Promise<T>): Promise<T> {
    if (this.state === 'open') {
      if (Date.now() - this.openedAt < this.openMs) throw new CircuitOpenError('circuit open');
      this.state = 'half-open';
    }

    if (this.state === 'half-open') {
      // One probe at a time; every other call is still refused
      if (this.probeInFlight) throw new CircuitOpenError('probe in flight');
      this.probeInFlight = true;
      try {
        const result = await operation();
        this.state = 'closed';
        this.outcomes = [];
        return result;
      } catch (error) {
        this.open();
        throw error;
      } finally {
        this.probeInFlight = false;
      }
    }

    try {
      const result = await operation();
      this.record(true);
      return result;
    } catch (error) {
      this.record(false);
      throw error;
    }
  }

  private record(ok: boolean): void {
    if (this.state !== 'closed') return; // a late result from a call started before the breaker opened
    const now = Date.now();
    this.outcomes.push({ at: now, ok });
    this.outcomes = this.outcomes.filter((o) => now - o.at <= this.windowMs);
    const failures = this.outcomes.filter((o) => !o.ok).length;
    if (this.outcomes.length >= this.minCalls && failures / this.outcomes.length >= this.maxFailureRate) {
      this.open();
    }
  }

  private open(): void {
    this.state = 'open';
    this.openedAt = Date.now();
    this.outcomes = [];
    console.warn('Circuit breaker opened');
  }
}

abstract class NotificationDispatcher {
  private readonly breakers: Record<Channel, ChannelCircuitBreaker> = {
    email: new ChannelCircuitBreaker(),
    push: new ChannelCircuitBreaker(),
    websocket: new ChannelCircuitBreaker()
  };

  async processNotification(event: NotificationEvent): Promise<void> {
    // Channels come from the user's preferences, so each one is sent at most once
    const channels = await this.resolveChannels(event);
    await Promise.allSettled(channels.map((channel) => this.sendOrDefer(event, channel)));
  }

  // Runs on a timer: releases deferred deliveries at a capped rate per tick.
  // While the breaker is not closed, one delivery per tick becomes the half-open
  // probe once the open period ends, so recovery does not wait for new traffic.
  async drainDeferred(channel: Channel, maxPerTick: number): Promise<void> {
    const limit = this.breakers[channel].isClosed ? maxPerTick : 1;
    const due = await this.claimDueDeliveries(channel, limit);
    for (const event of due) {
      await this.sendOrDefer(event, channel);
    }
  }

  private async sendOrDefer(event: NotificationEvent, channel: Channel): Promise<void> {
    try {
      await this.breakers[channel].execute(() => this.send(channel, event));
    } catch {
      // No cross-channel fallback: the other channels already carry this event.
      // The delivery row goes back to 'pending' with a next_retry_at.
      await this.deferDelivery(event.id, channel);
    }
  }

  protected abstract resolveChannels(event: NotificationEvent): Promise<Channel[]>;
  protected abstract send(channel: Channel, event: NotificationEvent): Promise<void>;
  protected abstract deferDelivery(eventId: string, channel: Channel): Promise<void>;
  protected abstract claimDueDeliveries(channel: Channel, limit: number): Promise<NotificationEvent[]>;
}

The breaker opens on a failure rate over a sliding window, and the minimum call count keeps a few early errors from tripping it. After the open period it moves to half-open: one probe call goes through while every other call is still refused, and the probe’s result either closes the breaker or restarts the open period. A failed send is deferred on its own channel. Routing it to another channel would deliver it twice, because the event already goes out on every channel the user’s preferences select, and the in-app inbox from Part 2 still holds it for a client that reconnects. Deferred deliveries drain at a capped rate once the breaker closes, so the backlog does not become the next spike. While the breaker is open, the drain takes one delivery per tick, and that delivery becomes the probe once the open period ends; a channel with no new traffic still recovers. A call that was already in flight when the breaker opened does not count toward the next window.

Step 2: Trace the Root Cause

With the damage contained, the question is why every channel failed at once. Traces and logs joined on correlation IDs put the steps in causal order. The root cause is a single client change: a mobile release rewrote the WebSocket reconnect handler days earlier, and it stayed harmless while every handshake succeeded. The campaign fan-out was only the trigger. Every later step is a defensive behavior (a reconnect, an authentication, a retry) turning into the next subsystem’s load.

TimeStepEvidence
06:10Campaign fan-out starts; handshake latency rises and some handshakes failHandshake failure rate at the load balancer
06:11Each failed handshake fires error and then close on the client; the new release reconnects from both handlers, so attempts double every roundHandshake attempts per client ID; the app version in the upgrade request’s User-Agent is the new release
06:13Every attempt is authenticated before any limit applies, and each authentication reads a session from PostgreSQLPool wait time; the session lookup is the top statement by call count
06:14Push and email workers wait for the same pool: push sends time out, email renders stallPool-wait spans inside push-send and render traces
06:15Push workers retry the timed-out sends, adding queue depth and more pool demandPush queue depth; attempt count per delivery row
06:17Each accepted connection writes a row to the Redis connection hash, and connections churn faster than clean closes remove themHash size against the live socket count

The query that surfaces the failing deliveries uses the statuses from the Part 1 schema (pending, sent, delivered, failed, bounced). A send stuck behind the pool has no status of its own: it stays pending. Digest rows and quiet-hours deferrals also wait as pending, so the query leaves digest rows out and skips rows whose next_retry_at still lies more than a lease (five minutes) ahead.

const debugQuery = `
  SELECT
    ne.correlation_id,
    ne.notification_type,
    nd.channel,
    nd.status,
    nd.error_code,
    nd.error_message,
    nd.created_at
  FROM notification_events ne
  JOIN notification_deliveries nd ON ne.id = nd.event_id
  WHERE ne.created_at > NOW() - INTERVAL '1 hour'
    AND nd.digest_frequency IS NULL
    AND (nd.status = 'failed'
         OR (nd.status = 'pending'
             AND nd.created_at < NOW() - INTERVAL '5 minutes'
             AND nd.next_retry_at <= NOW() + INTERVAL '5 minutes'))
  ORDER BY nd.created_at DESC
  LIMIT 1000;
`;

Step 3: Confirm the Fix with Before and After Numbers

The fix is two changes, both shown in the WebSocket section below: the client reconnects from close only, with jittered backoff, and the server limits handshakes before it authenticates them. Whether the fix worked is a comparison of the same metrics over the incident window and over a comparable window after the release, taken from the user-impact level of the hierarchy below:

-- Run once for the incident window and once for a comparable window after the fix
SELECT
  nd.channel,
  COUNT(*) AS deliveries,
  -- Push has no delivery receipt, so sent_at stands in when delivered_at is empty
  AVG(CASE WHEN COALESCE(nd.delivered_at, nd.sent_at) <= ne.created_at + INTERVAL '5 minutes'
           THEN 1 ELSE 0 END) AS on_time_rate,
  PERCENTILE_CONT(0.95) WITHIN GROUP (
    ORDER BY EXTRACT(EPOCH FROM COALESCE(nd.delivered_at, nd.sent_at) - ne.created_at)
  ) AS p95_seconds,
  COUNT(DISTINCT ne.user_id) FILTER (
    WHERE nd.status = 'failed'
       OR COALESCE(nd.delivered_at, nd.sent_at) IS NULL
       OR COALESCE(nd.delivered_at, nd.sent_at) > ne.created_at + INTERVAL '5 minutes'
  ) AS affected_users
FROM notification_events ne
JOIN notification_deliveries nd ON nd.event_id = ne.id
WHERE ne.created_at >= $1 AND ne.created_at < $2
  AND nd.digest_frequency IS NULL -- digests wait for their schedule on purpose
GROUP BY nd.channel;

The clock starts at ne.created_at, because Part 1 uses ne.scheduled_at as the worker’s lease and moves it forward on every claim. Quiet-hours deferrals leave no marker once sent (markSent clears next_retry_at), so they count as late here; comparing windows that cover the same hours of the day keeps their share comparable on both sides.

Time to recovery comes from the alert history: from the first user-impact alert to the point where the on-time rate stays above its SLO. The cause is confirmed only when a load test that fails a share of handshakes on purpose shows flat handshake attempts per client, where the old release doubled them.

Observability Hierarchies#

The hierarchy below turns that ranking into a concrete shape:

interface ObservabilityHierarchy {
  // Level 1: User Impact (What customers see)
  userImpact: {
    notificationsReceived: number;
    averageDeliveryTime: number;
    userComplaints: number;
  };
  
  // Level 2: Service Health (How our systems are performing)  
  serviceHealth: {
    deliveryRates: Record<NotificationChannel, number>;
    errorRates: Record<string, number>;
    responseTimes: Record<string, number>;
  };
  
  // Level 3: Infrastructure (What's happening under the hood)
  infrastructure: {
    databaseConnections: number;
    redisMemory: number;
    queueDepths: Record<string, number>;
  };
  
  // Level 4: External Dependencies (Things we don't control)
  externalDeps: {
    emailProviderStatus: string;
    pushProviderLatency: number;
    cloudServiceHealth: string;
  };
}

class HierarchicalMonitoring {
  async assessSystemHealth(): Promise<SystemHealthSnapshot> {
    // Start with user impact - this is what actually matters
    const userImpact = await this.getUserImpactMetrics();
    
    if (userImpact.isHealthy) {
      return { status: 'healthy', details: userImpact };
    }
    
    // If user impact is poor, drill down through the hierarchy
    const serviceHealth = await this.getServiceHealthMetrics();
    const infrastructure = await this.getInfrastructureMetrics(); 
    const externalDeps = await this.getExternalDepMetrics();
    
    // Correlate issues across hierarchy levels
    const rootCause = this.correlateIssues({
      userImpact,
      serviceHealth, 
      infrastructure,
      externalDeps
    });
    
    return {
      status: 'degraded',
      rootCause,
      remediationSteps: this.generateRemediationPlan(rootCause)
    };
  }
}

Template Rendering Under Load#

Multi-language templates with dynamic content and per-user personalization are the second common source of pipeline-wide stalls, because a template engine looks like presentation code and rarely gets the query budget that application code gets.

The N+1 Hiding in the Template#

A template author adds what reads as a small feature: recent activity in the welcome email. The pipeline renders with Eta in async mode (renderStringAsync), which allows await inside a template, so the template can call a data function directly. It looks harmless:

<% for (const activity of it.user.recentActivities) { %>
  <div class="activity-item">
    <span><%= it.formatDate(activity.createdAt) %></span>
    <span><%= activity.description %></span>
    <% if (activity.projectId) { %>
      <span>in <%= (await it.getProjectDetails(activity.projectId)).name %></span>
    <% } %>
  </div>
<% } %>

Each await runs one query and waits for it before the loop moves on. Every activity of every recipient costs a database round trip, in sequence, inside the render.

Profiling the Render Path#

The symptoms are subtle at first: email deliveries slow down, then time out. Render workers spend most of their time waiting, and the slow-query log stays empty. Each lookup is a fast primary-key read; the cost lies in how many there are and in the round trips the render waits on one after another. A profiler that counts queries per render makes the cause visible. The counter lives in an AsyncLocalStorage store, so concurrent renders each count only their own queries:

import { AsyncLocalStorage } from 'node:async_hooks';
import { performance } from 'node:perf_hooks';

interface RenderScope {
  templateId: string;
  queries: number;
}

const renderScope = new AsyncLocalStorage<RenderScope>();

// Installed once at startup. A query counts against the render that issued it,
// however many renders run at the same time.
export function countQueriesPerRender(db: Db): void {
  const query = db.query.bind(db);
  db.query = (sql, params) => {
    const scope = renderScope.getStore();
    if (scope) scope.queries++;
    return query(sql, params);
  };
}

export class TemplatePerformanceProfiler {
  private samples = new Map<string, { ms: number; queries: number }[]>();

  async profileRender(templateId: string, render: () => Promise<string>): Promise<string> {
    const scope: RenderScope = { templateId, queries: 0 };
    const start = performance.now();
    try {
      return await renderScope.run(scope, render);
    } finally {
      const ms = performance.now() - start;
      this.record(templateId, ms, scope.queries);
      if (scope.queries > 10) {
        console.warn(`Template ${templateId} made ${scope.queries} DB queries in one render`);
      }
      if (ms > 1000) {
        console.warn(`Template ${templateId} took ${Math.round(ms)}ms to render`);
      }
    }
  }

  summary(templateId: string) {
    const recent = this.samples.get(templateId) ?? [];
    const times = recent.map((s) => s.ms).sort((a, b) => a - b);
    const avg = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / Math.max(xs.length, 1);
    return {
      renders: recent.length,
      avgRenderMs: avg(times),
      p95RenderMs: times[Math.min(times.length - 1, Math.floor(times.length * 0.95))] ?? 0,
      avgQueries: avg(recent.map((s) => s.queries))
    };
  }

  private record(templateId: string, ms: number, queries: number): void {
    const list = this.samples.get(templateId) ?? [];
    list.push({ ms, queries });
    this.samples.set(templateId, list.slice(-100)); // last 100 renders
  }
}

Patching db.query around each render would break under concurrency. A second render saves the first render’s wrapper as its “original”, and when the first render finishes before the second, a wrapper stays installed for good and counts every other render’s queries. The wrapper above is installed once, and the store decides which render a query belongs to. A pipeline that already runs OpenTelemetry’s pg instrumentation gets the same number by counting database spans under a render span.

The Solution: Template Performance Guardrails#

Once the N+1 pattern is identified, the fix moves data loading out of the template. Two batched queries load the activities and their projects before the render. The render itself runs synchronously, so the template has no way to reach the database:

import { Eta } from 'eta';

class DeadlineExceeded extends Error {}

function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const deadline = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new DeadlineExceeded()), ms);
  });
  return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
}

class SafeTemplateRenderer {
  private readonly MAX_PRELOAD_MS = 2000;

  constructor(
    private readonly eta: Eta,
    private readonly store: ActivityStore
  ) {}

  async renderWelcome(template: string, user: User): Promise<string> {
    let activities: ActivityView[];
    try {
      activities = await withDeadline(this.loadActivityViews(user.id), this.MAX_PRELOAD_MS);
    } catch (error) {
      if (!(error instanceof DeadlineExceeded)) throw error;
      // Losing the race does not cancel the queries: they finish in the background
      // and hold their connections, so the fallback adds no queries of its own
      activities = [];
    }
    // Synchronous render: the template has no way to reach the database
    return this.eta.renderString(template, { user, activities });
  }

  private async loadActivityViews(userId: string): Promise<ActivityView[]> {
    const activities = await this.store.recentActivities(userId, 10);
    const projectIds = [...new Set(activities.flatMap((a) => (a.projectId ? [a.projectId] : [])))];
    // One query for all projects: WHERE id = ANY($1)
    const projects = projectIds.length > 0 ? await this.store.projectsByIds(projectIds) : [];
    const names = new Map(projects.map((p) => [p.id, p.name]));
    return activities.map((a) => ({
      ...a,
      projectName: a.projectId ? names.get(a.projectId) : undefined
    }));
  }
}

Promise.race ends the wait; the queries keep running and hold their pool connections until they finish. That is why the fallback renders the same template with an empty activity list and adds no queries of its own. The template reads activity.projectName from the preloaded data, so the profiler’s count for this template stays at two queries at most, however many activities a user has, and a regression shows up at once.

WebSocket Connection Storms#

A WebSocket fanout usually carries live notifications, document updates, and presence on the same connection, so one client-side retry bug lands on all three at once.

Why the Client Kept Reconnecting#

Client retry logic like this reads as robust:

// The mobile app's "improved" retry logic - don't do this
class NotificationConnectionManager {
  connect() {
    this.ws = new WebSocket(this.endpoint);
    
    this.ws.onclose = () => {
      // Exponential backoff... or so they thought
      this.retryDelay = Math.min(this.retryDelay * 2, 30000);
      setTimeout(() => this.connect(), this.retryDelay);
    };
    
    this.ws.onerror = () => {
      // Immediately retry on error - this was the problem
      this.connect();
    };
  }
}

A refused handshake triggers both handlers. When a connection fails, the WebSockets standard fires error and then close, so each failure starts two connect() calls: one at once from onerror, one later from onclose. Either of them can fail the same way, so attempts double every round. retryDelay has no starting value, is never reset and carries no jitter, so clients that failed together also retry together.

The fixed client reconnects from onclose only. Its delay uses full jitter, a random value between zero and the exponential ceiling, one of the two best performers in the AWS Architecture Blog comparison of backoff strategies. The attempt counter resets only after a connection has held for a while, so a server that accepts and then closes at once still sees the backoff grow:

// Reconnects from onclose only: a failed connection fires error, then close
class NotificationConnectionManager {
  constructor(endpoint) {
    this.endpoint = endpoint;
    this.attempt = 0;
    this.stopped = false;
  }

  connect() {
    this.ws = new WebSocket(this.endpoint);

    this.ws.onopen = () => {
      this.openedAt = Date.now();
    };

    this.ws.onerror = () => {
      // Log only; close always follows and schedules the retry
    };

    this.ws.onclose = (event) => {
      if (this.stopped) return;
      // Reset only after a connection held, so accept-then-close still backs off
      if (this.openedAt && Date.now() - this.openedAt > 30000) this.attempt = 0;
      this.openedAt = undefined;

      // 1013 (Try Again Later): the server is shedding load, start from a higher base
      const base = event.code === 1013 ? 5000 : 1000;
      const ceiling = Math.min(60000, base * 2 ** this.attempt);
      this.attempt++;
      // Full jitter: a random delay between zero and the exponential ceiling
      setTimeout(() => this.connect(), Math.random() * ceiling);
    };
  }

  disconnect() {
    this.stopped = true;
    this.ws?.close(1000);
  }
}

Close code 1013 (Try Again Later in the IANA registry) only reaches a client whose connection was accepted first. A handshake the server refuses reaches a browser client as close code 1006, so the HTTP status and any Retry-After header of the refusal stay invisible to it. For that case the jittered backoff carries the load.

The Server-Side Solution#

The server cannot rely on clients backing off, so admission control belongs on its side, and the order of the checks matters. They run from cheapest to most expensive, all before the upgrade: load shedding, a per-client handshake rate, authentication, then a per-user connection count. A refusal is a plain HTTP 429 or 503 with Retry-After, written to the socket before any WebSocket exists. The counters live in Redis. An in-memory map behind a load balancer gives each of N instances its own limit, which multiplies the real limit by N.

import type { IncomingMessage, Server } from 'node:http';
import type { Duplex } from 'node:stream';
import { WebSocketServer } from 'ws';

// The subset of an ioredis client this class uses
interface Counters {
  incr(key: string): Promise<number>;
  decr(key: string): Promise<number>;
  expire(key: string, seconds: number): Promise<number>;
}

const RATE_LIMIT_WINDOW_S = 60;
const RATE_LIMIT_MAX = 10; // handshakes per client per window
const MAX_CONNECTIONS_PER_USER = 5;

class AdmissionControlledServer {
  private readonly wss = new WebSocketServer({ noServer: true });

  constructor(
    private readonly redis: Counters,
    private readonly loadScore: () => number, // 0..1, from CPU, memory, connections, queue depth
    private readonly authenticate: (request: IncomingMessage) => Promise<string | null>,
    private readonly clientIdentifier: (request: IncomingMessage) => string
  ) {}

  attach(server: Server): void {
    server.on('upgrade', (request: IncomingMessage, socket: Duplex, head: Buffer) => {
      // A client can reset the connection while the checks await Redis;
      // an 'error' event with no listener would crash the process
      const onSocketError = () => socket.destroy();
      socket.on('error', onSocketError);
      this.admit(request, socket, head, onSocketError).catch(() => refuse(socket, 503, 30));
    });
  }

  private async admit(
    request: IncomingMessage,
    socket: Duplex,
    head: Buffer,
    onSocketError: () => void
  ): Promise<void> {
    // Cheapest checks first: nothing below runs for a refused handshake
    if (this.loadScore() > 0.9) return refuse(socket, 503, 30);

    const windowId = Math.floor(Date.now() / 1000 / RATE_LIMIT_WINDOW_S);
    const rateKey = `ws:rate:${this.clientIdentifier(request)}:${windowId}`;
    const attempts = await this.redis.incr(rateKey);
    if (attempts === 1) await this.redis.expire(rateKey, RATE_LIMIT_WINDOW_S);
    if (attempts > RATE_LIMIT_MAX) return refuse(socket, 429, RATE_LIMIT_WINDOW_S);

    // Token verification and the session lookup only run for admitted handshakes
    const userId = await this.authenticate(request);
    if (!userId) return refuse(socket, 401);

    // One count per user, shared by every instance behind the load balancer
    const userKey = `ws:conns:${userId}`;
    if ((await this.redis.incr(userKey)) > MAX_CONNECTIONS_PER_USER) {
      await this.redis.decr(userKey);
      return refuse(socket, 429, RATE_LIMIT_WINDOW_S);
    }

    // The client may have gone away during the checks; give the slot back
    if (socket.destroyed) return void this.redis.decr(userKey);

    socket.removeListener('error', onSocketError);
    this.wss.handleUpgrade(request, socket, head, (ws) => {
      ws.on('close', () => void this.redis.decr(userKey));
      this.wss.emit('connection', ws, request, userId);
    });
  }
}

// Plain HTTP refusal, written before any WebSocket exists
function refuse(socket: Duplex, status: 401 | 429 | 503, retryAfterS?: number): void {
  const reason = { 401: 'Unauthorized', 429: 'Too Many Requests', 503: 'Service Unavailable' }[status];
  const retryAfter = retryAfterS ? `Retry-After: ${retryAfterS}\r\n` : '';
  socket.write(`HTTP/1.1 ${status} ${reason}\r\n${retryAfter}Connection: close\r\n\r\n`);
  socket.destroy();
}

The upgrade handler with noServer: true, the temporary socket error listener that is removed right before handleUpgrade, and the raw HTTP refusal follow the client-authentication example in the ws README. The per-user count has one weak spot: if an instance dies, the decrements for its connections never run, and the count drifts upward. Part 2 solves the same gap for connection rows with a liveness key per server; per-instance counters under that key bound the drift the same way.

Debugging Toolkit#

During a notification incident, a dashboard answers “what is broken right now,” and a trace answers “what happened to this one message.”

Real-Time Dashboard for Incidents#

class IncidentDashboard {
  async getCurrentSystemState(): Promise<SystemSnapshot> {
    const timestamp = new Date();
    
    // Gather metrics in parallel for speed
    const [
      deliveryMetrics,
      errorMetrics, 
      performanceMetrics,
      externalServiceStatus
    ] = await Promise.all([
      this.getDeliveryMetrics(),
      this.getErrorMetrics(),
      this.getPerformanceMetrics(),
      this.checkExternalServices()
    ]);
    
    return {
      timestamp,
      overall: this.calculateOverallHealth(deliveryMetrics, errorMetrics),
      deliveryMetrics: {
        email: deliveryMetrics.email,
        push: deliveryMetrics.push,
        websocket: deliveryMetrics.websocket,
        sms: deliveryMetrics.sms
      },
      errors: {
        byChannel: errorMetrics.byChannel,
        byType: errorMetrics.byType,
        trending: errorMetrics.trending
      },
      performance: {
        avgDeliveryTime: performanceMetrics.avgDeliveryTime,
        p95DeliveryTime: performanceMetrics.p95DeliveryTime,
        queueDepths: performanceMetrics.queueDepths
      },
      externalServices: externalServiceStatus,
      recommendations: this.generateRecommendations(deliveryMetrics, errorMetrics)
    };
  }

  private generateRecommendations(
    delivery: any, 
    errors: any
  ): string[] {
    const recommendations: string[] = [];
    
    // Email delivery issues
    if (delivery.email.successRate < 0.95) {
      recommendations.push('Check email provider status and reputation score');
    }
    
    // Push notification problems  
    if (delivery.push.successRate < 0.9) {
      recommendations.push('Verify push certificates and payload format');
    }
    
    // High error rates
    if (errors.overall.rate > 0.05) {
      recommendations.push('Investigate most common error patterns');
    }
    
    return recommendations;
  }
}

Correlation ID Tracing#

The single most valuable debugging tool for notification systems is comprehensive correlation ID tracing. The correlation ID lives on the event row, and the providers know the event by the notificationId that Part 2 sends in the message metadata, so the event id is the join key to their logs:

class NotificationTracer {
  async traceNotificationJourney(correlationId: string): Promise<NotificationTrace> {
    // Get the full journey of a notification through the system
    const events = await this.db.query(`
      SELECT 
        ne.id as event_id,
        ne.notification_type,
        ne.created_at,
        ne.data,
        nd.channel,
        nd.status,
        nd.attempt_count,
        nd.error_message,
        nd.sent_at,
        nd.delivered_at
      FROM notification_events ne
      LEFT JOIN notification_deliveries nd ON ne.id = nd.event_id  
      WHERE ne.correlation_id = $1
      ORDER BY ne.created_at, nd.created_at
    `, [correlationId]);
    
    // Provider logs are keyed by event id (Part 2's notificationId)
    const eventIds = [...new Set(events.map((e: { event_id: string }) => e.event_id))];
    const externalLogs = await Promise.all([
      this.getEmailProviderLogs(eventIds),
      this.getPushProviderLogs(eventIds),
      this.getWebSocketLogs(correlationId)
    ]);
    
    return {
      correlationId,
      timeline: this.buildTimeline(events, externalLogs),
      status: this.determineOverallStatus(events),
      failurePoints: this.identifyFailures(events, externalLogs),
      recommendations: this.generateTraceRecommendations(events)
    };
  }

  private buildTimeline(events: any[], externalLogs: any[]): TimelineEvent[] {
    const allEvents = [
      ...events.map(e => ({ 
        timestamp: e.created_at, 
        type: 'internal', 
        details: e 
      })),
      ...externalLogs.flat().map(e => ({ 
        timestamp: e.timestamp, 
        type: 'external', 
        details: e 
      }))
    ];
    
    return allEvents.sort((a, b) => 
      new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
    );
  }
}

Monitoring Strategy#

Threshold alerts fire once the damage is done. The alerts worth adding fire while there is still room to act.

Predictive Alerting#

Alert on the direction a metric is moving, and compute the predicted impact from the current value, the slope and a limit. Without a limit there is no time to impact: the delivery rate aims at its SLO, and the queue depth at the queue’s capacity (a configured maximum length, or a backlog budget derived from how fast the workers drain it).

interface Trend { current: number; slopePerMin: number } // least-squares fit over the window

// Minutes until a linear trend crosses the limit in the given direction;
// null when it is already past the limit or moving away from it
function minutesUntil(
  trend: Trend,
  limit: number,
  direction: 'falling' | 'rising'
): number | null {
  const approaching =
    direction === 'falling'
      ? trend.current > limit && trend.slopePerMin < 0
      : trend.current < limit && trend.slopePerMin > 0;
  return approaching ? (limit - trend.current) / trend.slopePerMin : null;
}

abstract class PredictiveAlerting {
  constructor(
    private readonly deliverySlo: number,   // e.g. 0.95
    private readonly queueCapacity: number, // max length, or a backlog budget
    private readonly horizonMin = 60        // only alert on crossings this close
  ) {}

  async checkPredictiveMetrics(): Promise<Alert[]> {
    const alerts: Alert[] = [];

    const delivery = await this.deliveryRateTrend('1h'); // ratio 0..1
    const toSlo = minutesUntil(delivery, this.deliverySlo, 'falling');
    if (toSlo !== null && toSlo < this.horizonMin) {
      alerts.push({
        level: 'warning',
        message: 'Delivery rate heading below SLO',
        details: `${(delivery.current * 100).toFixed(1)}% now, ${(delivery.slopePerMin * 6000).toFixed(1)} points per hour`,
        predictedImpact: `Crosses ${this.deliverySlo * 100}% in ~${Math.round(toSlo)} min at the current slope`
      });
    }

    const queue = await this.queueDepthTrend('30m'); // items
    const toFull = minutesUntil(queue, this.queueCapacity, 'rising');
    if (toFull !== null && toFull < this.horizonMin) {
      alerts.push({
        level: 'critical',
        message: 'Notification queue growing toward capacity',
        details: `${queue.current} of ${this.queueCapacity} items, +${Math.round(queue.slopePerMin)} per minute`,
        predictedImpact: `Full in ~${Math.round(toFull)} min at the current growth`
      });
    }

    return alerts;
  }

  protected abstract deliveryRateTrend(window: string): Promise<Trend>;
  protected abstract queueDepthTrend(window: string): Promise<Trend>;
}

A linear fit says nothing about a curve that bends, so the predicted time is an estimate at the current slope, and the alert text says so. The horizon keeps a slow drift that would cross the limit in a day from paging anyone now. A value already past its limit belongs to the threshold alert, so a delivery rate climbing back toward its SLO does not page as if it were falling.

Instrumentation to Add Before the Next Incident#

These additions are cheap now and expensive once an incident is already running:

  1. Correlation IDs on every hop. Each notification event, delivery attempt, and external service call carries the same ID; logs without it are hard to piece back together.

  2. User-impact alerts above infrastructure alerts. “Users are not receiving notifications” sits at the top of the alert hierarchy; the CPU, memory, and queue-depth signals exist to explain it, not to page on their own.

  3. A limit on every unbounded path. Render time, queries per template, handshakes per client, connections per user, and queue depth all need one, so a cascade stays local to the component that started it.

This ordering holds when you own the delivery path end to end. If delivery is outsourced to a provider, levels 3 and 4 of the hierarchy move behind that provider’s event webhooks: the trace has to be assembled from their delivery events instead of your own logs, and the circuit breaker guards your own queue depth.

The final part of this series covers analytics and performance tuning: A/B testing notification strategies, optimization patterns that move delivery metrics, and the performance monitoring that catches regressions before users report them.

References#

Building a Scalable User Notification System

Part 3 of 4

A 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.

Related posts