Backend / Infrastructure8 min readUpdated: 2025-01-10

Notification Service: Reliable Multi-Channel Delivery

Building a fault-tolerant message distribution engine with Apache Kafka topic partitioning, dead-letter queues, and provider failover.

Role / Scope: Backend Infrastructure Engineer

Executive Summary

Delivering transaction-critical notifications (email verification, transactional receipts, push alerts) across disparate applications requires decoupling notification triggers from user-facing API request cycles. This case study details the architecture of an enterprise Notification Service leveraging Apache Kafka for message distribution, channel-specific worker pools, and automated dead-letter queues.

The Engineering Challenge & Context

When applications invoke third-party messaging providers (SendGrid, Twilio, Firebase) synchronously within HTTP request handlers, provider latency spikes or transient outages directly degrade user response times. Furthermore, network partitions frequently cause duplicate notifications or lost alerts without distributed queueing, idempotency checks, and persistent retry management.

System Architecture & Data Flow

The service decouples event ingestion from physical delivery through an asynchronous event-driven pipeline. Client microservices publish notification intent events to an ingestion Kafka topic. The Notification Service ingests events, validates payloads, enforces deduplication using an Idempotency-Key in PostgreSQL, and routes messages to channel-specific Kafka topics (`notifications.email`, `notifications.push`, `notifications.sms`). Dedicated consumer worker pools process each channel independently. If an external delivery provider fails, messages back off exponentially before moving to a Dead-Letter Queue (DLQ) for alerting and manual replay.

+-----------------------+     POST /api/v1/notify
|  Upstream Services    | ------------------------------------+
| (Auth, Orders, Feeds) |                                     |
+-----------------------+                                     v
                                             +------------------------------------+
                                             |     INGESTION GATEWAY (NestJS)     |
                                             | - Validate JWT / API Key           |
                                             | - Check PostgreSQL Idempotency Key |
                                             +------------------------------------+
                                                              |
                                                              v Kafka Topic: notifications.raw
                                             +------------------------------------+
                                             |        EVENT ROUTER SERVICE        |
                                             | Dispatches by Channel Priority     |
                                             +------------------------------------+
                                              /                |                \
               +-----------------------------+                 |                 +-----------------------------+
               v Kafka: notifications.email                    v Kafka: notifications.push                     v Kafka: notifications.sms
+-----------------------------+                +-----------------------------+                +-----------------------------+
|    Email Consumer Pool      |                |     Push Consumer Pool      |                |      SMS Consumer Pool      |
| - Primary: Resend           |                | - Firebase Cloud Messaging  |                | - Twilio / Karix Gateway    |
| - Fallback: SMTP Relay      |                +-----------------------------+                +-----------------------------+
+-----------------------------+                                |                                               |
               |                                               | (On 3 Failures)                               |
               +-----------------------------------------------+-----------------------------------------------+
                                                               |
                                                               v
                                             +------------------------------------+
                                             |      DEAD LETTER QUEUE (DLQ)       |
                                             | Stored in PostgreSQL with Audit Log|
                                             +------------------------------------+

Key Engineering Decisions & Trade-offs

Kafka Topic Partitioning by User ID vs. Channel-Only Queues

Rationale: Partitioning Kafka topics using the recipient's `userId` ensures strict sequential ordering for all notifications sent to a single recipient (e.g., 'Account Created' is guaranteed to arrive before 'Password Reset'), while allowing unlimited parallel processing across different users.

Trade-offs & Constraints: If a single user receives an anomalous burst of messages, their assigned partition experiences a minor queue lag, but the rest of the system remains unaffected.

Dual-Provider Fallback for Transactional Email

Rationale: Email deliverability cannot depend on a single third-party vendor. The system integrates Resend as the primary modern transactional API, with automatic runtime fallback to a managed SMTP relay upon receiving HTTP 5xx responses or connection timeouts.

Trade-offs & Constraints: Requires maintaining active credentials and health checks across two provider accounts.

Idempotency Storage in PostgreSQL with Unique Constraint

Rationale: Network retries from upstream callers can submit identical requests. By requiring an `Idempotency-Key` header and persisting a hash of the key + payload with a `UNIQUE` index in PostgreSQL, duplicate requests return HTTP 200 with the original dispatch ID without sending duplicate messages.

Trade-offs & Constraints: Adds one database query during ingestion, which is negligible compared to the cost and brand damage of duplicate user communications.

Idempotent Event Ingestion Handler

Ingestion uses database transactions to guarantee at-least-once message delivery without duplicates.

Idempotent Ingestion Service
async function ingestNotification(
  dto: IngestNotificationDto,
  idempotencyKey: string
): Promise<{ status: string; id: string }> {
  const existing = await notificationRepo.findOne({ where: { idempotencyKey } });
  if (existing) {
    return { status: 'already_processed', id: existing.id };
  }

  const notification = notificationRepo.create({
    idempotencyKey,
    recipient: dto.recipient,
    channel: dto.channel,
    payload: dto.payload,
    status: 'QUEUED',
  });
  await notificationRepo.save(notification);

  await kafkaProducer.send({
    topic: 'notifications.' + dto.channel.toLowerCase(),
    messages: [{
      key: dto.recipient.userId,
      value: JSON.stringify({ id: notification.id, ...dto }),
    }],
  });

  return { status: 'queued', id: notification.id };
}

Reliability, Security & Operational Considerations

Lessons Learned

  • ✓Third-party messaging APIs fail in subtle ways (silent HTTP 200 with delivery drops, socket hangs). Robust timeout configurations (under 5 seconds) are essential to prevent worker pool starvation.
  • ✓Separating channel topics prevented slow SMS carrier handshakes from blocking time-sensitive email verification delivery.

Known Limitations & Future Architecture Roadmap

Back to all case studies