# Notification System

# 1\. Introduction: Why I Started Exploring Notification System Design

While working on an application with multiple features, I started noticing something interesting.

Different parts of the application needed to send notifications for different events. Whenever an important action happened, the application had to inform the relevant user.

Initially, this seemed like a straightforward requirement. We could simply call an API, send an email or push notification, and move on.

But as the number of features increased, so did the number of notification events.

Different features needed different notification types, different delivery channels, and different rules about when and to whom a notification should be sent.

This raised a few questions:

- Should every feature implement its own notification logic?
- What happens if an external notification provider is unavailable?
- Should the user request wait until a notification is delivered?
- How do we handle thousands of notifications arriving simultaneously?
- What happens when millions of users need to receive the same notification?
- How do we ensure that important notifications are not delayed by bulk notifications?
- Should we send a notification every time an event occurs?
- What happens if a user is already active in the application?

What initially looked like a simple API integration turned out to be an interesting distributed systems problem.

In this article, I'll build the notification system step by step, starting from a simple implementation and gradually evolving it into a scalable architecture.

We'll also study how Slack decides whether a notification should be sent, because it demonstrates an important lesson:

**A notification system is not just responsible for delivering messages. It is also responsible for deciding which messages deserve the user's attention.**

---

# 2\. Understanding the Problem: What Is a Notification System?

A notification system is responsible for communicating important events to users or external systems.

Almost every modern application depends on notifications.

| Application | Event | Notification |
| --- | --- | --- |
| Banking | Money credited | SMS / Push |
| E-commerce | Order placed | Email |
| Social media | Someone liked a post | In-app notification |
| Video platform | Creator uploaded a video | Push notification |
| Food delivery | Order dispatched | Push notification |
| Payment gateway | Payment completed | Merchant webhook |

Notifications can be delivered through multiple channels:

- Email
- SMS
- Push notifications
- In-app notifications
- WhatsApp
- Webhooks

Our system should support these channels without forcing every application feature to understand how each channel works.

## 2.1 Functional requirements

Before designing the architecture, let's define what the system should do.

1. Accept notification events from different application services.
2. Identify the users who should receive notifications.
3. Support multiple delivery channels.
4. Allow users to manage notification preferences.
5. Store in-app notifications and their read/unread status.
6. Support retries when delivery fails.
7. Support notification aggregation to prevent spam.
8. Support scheduled or delayed notifications.
9. Track notification delivery status.
10. Handle bulk notification requests.

## 2.2 Non-functional requirements

The system should also satisfy certain quality requirements.

| Requirement | Explanation |
| --- | --- |
| Scalability | Handle increasing notification volume |
| Reliability | Avoid losing important notification events |
| Low latency | Deliver important notifications quickly |
| Availability | Continue processing when individual components fail |
| Fault isolation | Notification failures should not break core application features |
| Observability | Track delays, failures, and system health |
| Cost efficiency | Avoid unnecessary provider calls and notification generation |

## 2.3 Not every notification is equally important

Consider two events:

- A payment failure notification.
- A promotional message about a festival discount.

Both are notifications, but their urgency is completely different.

If a system processes both with equal priority, a large promotional campaign could delay important payment notifications.

We will address this later using priority queues and workload isolation.

But priority alone isn't enough.

Even if a notification is technically important, the user might have muted that channel, already read the message, or configured their application to receive only mentions.

This is where notification decision logic becomes important.

---

# 3\. Start Simple: Synchronous Notification Delivery

Let's start with a basic example.

A user signs up for an application, and we want to send a welcome email.

```js
app.post("/signup", async (req, res) => {
  const user = await User.create(req.body);

  await emailProvider.send({
    to: user.email,
    subject: "Welcome!",
    body: "Welcome to our application."
  });

  res.status(201).json({
    message: "Signup successful"
  });
});
```

The execution flow is:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/3cdc43f2-e196-4103-bf6e-2df06ba88e31.jpg align="center")

At first glance, there is nothing wrong with this implementation.

But let's understand what happens when the application grows.

## <mark>Problem 1:</mark> High API latency

Suppose:

- Saving a user takes 100 ms.
- Calling the external email provider takes 3 seconds.

The signup API must wait for both operations.

The user waits for the email provider even though sending the welcome email is not necessary to complete the signup request.

This increases API response time.

## <mark>Problem 2:</mark> External provider dependency

What happens if the email provider is unavailable?

The user might already have been saved successfully in the database, but the signup API could still return an error because email delivery failed.

A temporary problem with an external notification provider should not necessarily affect the main business operation.

## <mark>Problem 3:</mark> Provider rate limits

External notification providers impose rate limits.

For example, suppose our email provider supports 30 emails per second.

Now imagine 100 users sign up simultaneously.

We try to send 100 emails, but the provider accepts only 30 requests within that second.

The remaining requests may be rejected or throttled.

Should we restrict signup to 30 requests per second?

Obviously not. Signup capacity should not depend on the email provider's capacity.

## <mark>Problem 4:</mark> Tight coupling

As the application grows, different APIs start implementing notification logic independently.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/25afeec1-2506-4384-bff3-e129cdb40e1d.jpg align="center")

Now imagine changing the notification provider or adding a new channel.

We may need to modify multiple services.

This is a maintenance problem.

The first important design decision is to separate notification delivery from the main business request.

---

# 4\. Introduce Message Queues and Background Workers

Instead of calling the external provider directly, the API can publish a notification job to a message queue.

A background worker will consume that job and send the notification.

We can use:

- Amazon SQS
- RabbitMQ
- Apache Kafka

For our initial implementation, let's use Amazon SQS as an example.

## 4.1 Updated architecture

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/bba547ed-a41c-4e41-95ef-a5bb7c8a1a5f.jpg align="center")

The API becomes:

```js
app.post("/signup", async (req, res) => {
  const user = await User.create(req.body);

  await notificationQueue.send({
    type: "WELCOME_EMAIL",
    userId: user.id,
    email: user.email
  });

  res.status(201).json({
    message: "Signup successful"
  });
});
```

The worker processes the job independently:

```js
async function processNotification(message) {
  await emailProvider.send({
    to: message.email,
    subject: "Welcome!",
    body: "Welcome to our application."
  });
}
```

The API now waits for the queue operation, not for the external email provider to complete delivery.

The queue acts as an intermediary between the application and notification workers.

## 4.2 What is a message queue?

A message queue is a system that temporarily stores messages or jobs until consumers process them.

Think of it like a waiting line.

Instead of asking an email provider to send 100 emails immediately, the application can place 100 jobs in the queue.

Workers process them at a controlled rate.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/dbadb827-e16f-4fab-9ab7-aebced395734.jpg align="center")

## 4.3 What is a worker?

A worker is an independent application process that performs background work.

Unlike an API server, which primarily handles incoming requests, a worker continuously processes jobs.

For example:

- API servers handle user requests.
- Notification workers send emails.
- Image workers resize images.
- Payment workers process asynchronous payment-related tasks.

We can increase the number of workers without necessarily increasing the number of API servers.

## 4.4 Why does a message queue help?

### 1\. Decoupling

The application does not need to know how a notification is delivered.

It simply publishes a job.

### 2\. Buffering

Suppose 100,000 users sign up during a campaign.

The API can enqueue notification jobs while workers process them at a controlled rate.

### 3\. Independent scaling

We can scale API servers and notification workers independently.

### 4\. Failure isolation

If the email provider is temporarily unavailable, jobs can remain queued instead of causing signup requests to fail.

### 5\. Load smoothing

A queue absorbs sudden traffic spikes.

Instead of processing every job immediately, the system processes jobs at a sustainable rate.

However, queues do not eliminate overload.

If jobs arrive faster than workers can process them for a long period, the queue will continue growing.

We will discuss this problem later.

---

# 5\. Understanding Queue-Based Processing: What Can Go Wrong?

Moving delivery to a background worker does not mean notifications will always succeed.

A notification can fail because:

- The provider is unavailable.
- The network request times out.
- The provider returns a rate-limit response.
- The recipient's email address is invalid.
- The worker crashes during processing.
- The queue temporarily becomes unavailable.

We need a failure-handling strategy.

## 5.1 Retry mechanism

If a temporary failure occurs, the worker should retry the notification.

But immediately retrying is not a good idea.

Imagine the email provider is down. If thousands of workers retry immediately, they may overload the provider further.

Instead, we can use exponential backoff.

### Exponential backoff

The delay between retries increases after every failure.

| Attempt | Retry delay |
| --- | --: |
| 1 | 1 second |
| 2 | 2 seconds |
| 3 | 4 seconds |
| 4 | 8 seconds |
| 5 | 16 seconds |
| 6 | 32 seconds |

Formula:

```text
delay = min(maxDelay, initialDelay × 2^attempt)
```

We should also introduce jitter, which adds randomness to the retry delay.

This prevents thousands of messages from retrying at exactly the same time.

For example:

```text
Without Jitter:

Worker 1 -> Retry at 10:00:10
Worker 2 -> Retry at 10:00:10
Worker 3 -> Retry at 10:00:10
Worker 4 -> Retry at 10:00:10


With Jitter:

Worker 1 -> Retry at 10:00:08
Worker 2 -> Retry at 10:00:12
Worker 3 -> Retry at 10:00:09
Worker 4 -> Retry at 10:00:15
```

This spreads the retry traffic.

Not every failure should be retried.

| Failure | Retry? |
| --- | --- |
| Provider timeout | Yes |
| Temporary provider error | Yes |
| Rate limit exceeded | Yes, after waiting |
| Invalid email address | Generally no |
| Invalid request payload | No, unless corrected |

## 5.2 Dead Letter Queue

What happens if a message fails after all retry attempts?

We move it to a Dead Letter Queue (DLQ).

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/e9e20498-3974-46c1-b6e2-56cec897cb43.jpg align="center")

The DLQ stores messages that could not be processed successfully.

We can inspect them, identify the issue, fix it, and reprocess them through a controlled process.

A DLQ does not automatically fix failed notifications.

It gives us a safe place to investigate them without blocking the main queue.

## 5.3 Idempotency: Preventing Duplicate Notifications

There is an important problem with queues.

Most queue-based systems provide at-least-once delivery.

This means the same message may be delivered more than once.

Consider this scenario:

1. A worker receives a notification job.
2. The worker successfully sends an email.
3. The worker crashes before acknowledging the queue message.
4. The queue makes the message available again.
5. Another worker sends the same email.

The user receives two emails.

To reduce this risk, we need idempotency.

### What is idempotency?

An operation is idempotent when executing it multiple times produces the same final result as executing it once.

Assign every logical notification a unique identifier.

```json
{
  "notificationId": "notif_123",
  "eventId": "event_456",
  "type": "PAYMENT_SUCCESSFUL",
  "userId": "user_789"
}
```

Before processing, the worker checks whether the notification has already been processed.

We can enforce uniqueness using a database constraint on an appropriate idempotency key.

Where supported, we should also pass an idempotency key to the external provider.

A database check alone cannot completely eliminate duplicates if a worker crashes between sending the request and recording success.

This is an important distributed systems limitation:

**Exactly-once delivery to arbitrary external providers is generally not guaranteed.**

Our goal is to make processing reliable and duplicates controlled.

---

# 6\. Moving Towards an Event-Driven Architecture

So far, we have used a queue to send welcome emails.

But real applications generate many different events.

```text
USER_REGISTERED
PAYMENT_SUCCESSFUL
PAYMENT_FAILED
ORDER_PLACED
FRIEND_REQUEST_RECEIVED
POST_LIKED
NEW_VIDEO_PUBLISHED
```

We should not implement notification delivery separately inside every application API.

Instead, application services should publish business events.

A separate notification service should decide what to do with them.

## 6.1 Event-driven architecture

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/67e59b8e-ee9f-4598-bab4-9b2c11a703eb.jpg align="center")

Now application services do not need to know whether an event results in an email, SMS, push notification, or no notification at all.

They simply publish what happened.

## 6.2 Event vs notification

An event and a notification are not the same thing.

**An event describes something that happened in the application.**

**A notification is a communication generated because of that event.**

For example:

```json
{
  "eventId": "event_123",
  "eventType": "POST_LIKED",
  "actorId": "user_101",
  "entityId": "post_456",
  "timestamp": "2026-11-27T10:00:00Z"
}
```

This event tells us that someone liked a post.

The notification service decides:

- Who should receive it?
- Should a notification be created?
- Which channel should be used?
- Should it be combined with other likes?
- What priority should it receive?
- Is the user currently active?
- Does the user want this type of notification?

This separation makes the notification system reusable.

## 6.3 Event broker vs message queue

These concepts overlap, but their responsibilities can differ.

A traditional task queue is often designed around a job being processed by one worker, then acknowledged or removed.

An event broker is often designed to distribute events to multiple independent consumers.

For example, after a payment succeeds:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/1ea22cac-078e-4365-9946-900db937bc13.jpg align="center")

Different services can react independently to the same event.

A notification service doesn't need to know whether analytics or audit services exist.

### Why this matters

If we directly call multiple services from the Payment API:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/6c0134ee-f64a-41b3-8cf2-2afc9a054c3d.jpg align="center")

The Payment API becomes tightly coupled to all of them.

If one service is unavailable, we must decide how the payment flow behaves.

With an event-driven approach, the Payment Service publishes a business event, and downstream consumers process it independently.

This improves decoupling but introduces asynchronous processing, eventual consistency, duplicate handling, and more complex debugging.

---

# 7\. Transactional Outbox Pattern

There is one important reliability problem with event publishing.

Suppose the Payment Service:

1. Saves a successful payment in its database.
2. Publishes PAYMENT_SUCCESSFUL to Kafka.

What happens if the database write succeeds but publishing to Kafka fails?

The payment exists, but the notification system never receives the event.

This is called the dual-write problem.

## 7.1 Why dual writes are dangerous

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/91939a80-69e2-4fb5-a926-710dada71a6c.jpg align="center")

Now our database and event broker have inconsistent information.

The payment succeeded, but no event was published.

We cannot simply assume that wrapping both operations in application code makes them atomic.

## 7.2 Transactional Outbox

The Transactional Outbox Pattern solves this problem.

The service writes both the business record and an outbox event in the same database transaction.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/176346f3-0e8b-4c5f-a01b-a2af4c7a2c8c.jpg align="center")

Example:

```sql
BEGIN;

INSERT INTO payments (...);

INSERT INTO outbox_events (
    event_type,
    payload,
    status
)
VALUES (
    'PAYMENT_SUCCESSFUL',
    '{"paymentId":"pay_123"}',
    'PENDING'
);

COMMIT;
```

Because the payment and outbox record are stored in the same transaction, both succeed or both fail.

A separate publisher reads pending outbox records and sends them to the event broker.

After publishing, it marks them as processed.

The publisher may publish an event more than once, so consumers must be idempotent.

This pattern is especially useful when losing a business event is unacceptable.

---

# 8\. Designing the Notification Decision Engine

Now that we receive events, we need to decide how they should be delivered.

Consider the following examples:

| Event | Email | SMS | Push | In-app |
| --- | --- | --- | --- | --- |
| Payment successful | Yes | Optional | Yes | Yes |
| Payment failed | Yes | Yes | Yes | Yes |
| Friend request | No | No | Yes | Yes |
| Post liked | No | No | Optional | Yes |
| New video published | Optional | No | Yes | Yes |
| Welcome | Yes | No | Optional | No |

The notification service should own these decisions.

We can introduce a Notification Decision Engine.

Its responsibilities include:

- Identifying recipients.
- Checking user preferences.
- Checking notification eligibility.
- Selecting channels.
- Assigning priority.
- Applying rate limits.
- Deciding whether to aggregate notifications.
- Deciding whether to delay or suppress notifications.
- Checking whether the user is currently active.
- Preventing duplicate or unnecessary notifications.

## 8.1 User notification preferences

Users should be able to control which types of notifications they receive.

For example:

| Notification Type | Email | SMS | Push | In-app |
| --- | --- | --- | --- | --- |
| Security alerts | Yes | Yes | Yes | Yes |
| Payment updates | Yes | Yes | Yes | Yes |
| Social activity | No | No | Yes | Yes |
| Marketing | Yes | No | Optional | No |

A simplified database table could be:

```sql
CREATE TABLE user_notification_preferences (
    id BIGINT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    notification_type VARCHAR(100) NOT NULL,
    channel VARCHAR(30) NOT NULL,
    is_enabled BOOLEAN DEFAULT TRUE,
    updated_at TIMESTAMP
);
```

We may also support:

- Global opt-out.
- Category-level preferences.
- Marketing consent.
- Quiet hours.
- User time zone.
- Language preference.
- Frequency limits.

Security and transactional notifications may have different legal and product requirements from promotional notifications. Preferences must respect the applicable consent and delivery rules.

## 8.2 Recipient resolution

For some events, the recipient is already known.

For example, a payment confirmation might contain the customer and merchant IDs.

But for other events, we need to resolve recipients.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/bb91eb30-00a7-4074-873f-8bfb60299597.jpg align="center")

This is called recipient resolution.

For a high-volume event, recipient resolution can become a major part of the system's workload.

---

# 9\. Slack Notification System: Why Notification Decisions Are More Complex Than Delivery

This is one of the most interesting parts of notification system design.

A naive implementation might say:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/00d36951-7402-4e96-8e93-7cc11ec388cc.jpg align="center")

But Slack cannot work like this.

Imagine you're part of 100 channels.

Some channels are muted.

Some channels are important.

You only want to receive notifications when someone mentions you in certain channels.

You are currently active on your desktop.

You don't want your mobile phone to send notifications for every message that you're already reading.

A system that sends notifications for every event would quickly become unusable.

This is why Slack needs a notification decision engine.

## 9.1 Understanding Slack's notification decision

A notification decision is not a single check.

It is a series of rules.

A simplified decision flow can look like this:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/250ecdee-74f5-46a5-88fb-ad7f455436b8.jpg align="center")

This is a simplified representation of the decision-making process, not a complete reproduction of Slack's implementation.

The important point is that the system evaluates context before generating a notification.

## 9.2 Step 1: Check the channel's notification state

A user might have:

- Muted the channel.
- Enabled notifications for all messages.
- Enabled notifications only for mentions.
- Disabled notifications completely.

The system needs to check the channel-level preferences first.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/f627ca84-4ac6-4755-8f32-a6ec4cba8ef3.jpg align="center")

Muting a channel does not necessarily mean that every possible notification is suppressed.

Important exceptions may still exist, such as direct mentions or explicitly followed threads, depending on the product's rules.

This is why notification settings need a clear precedence model.

## 9.3 Step 2: Check Do Not Disturb

Do Not Disturb allows the user to temporarily stop notifications.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/eb2d88f2-4ba0-48ef-87c3-6a2a58fd1a48.jpg align="center")

A normal message might be suppressed.

An important event, such as a specially configured urgent notification, may be allowed to bypass the restriction.

The exact override behavior depends on the product's rules.

The lesson is that a notification engine must distinguish normal notifications from exceptional notifications.

## 9.4 Step 3: Understand the message type

Not all messages are equally important.

Consider:

| Message | Potential notification behavior |
| --- | --- |
| Normal channel message | Depends on channel preferences |
| Direct message | Usually important |
| @mention | Usually important |
| @here | May notify relevant active members |
| @channel | May notify a broader group |
| Thread reply | Depends on subscription |
| Keyword match | Depends on user configuration |

The system must understand the event's context.

For example, receiving a normal channel message does not necessarily mean the user should be notified.

But a message containing a direct mention may qualify even if the channel is configured for reduced notifications.

## 9.5 Step 4: Check channel-level preferences

A channel may have different notification settings.

For example:

```text
Channel Notification Preference

1. Everything
2. Mentions
3. Nothing
4. Default
```

The decision engine evaluates the message against the user's selected preference.

| Preference | Example behavior |
| --- | --- |
| Everything | Notify for qualifying messages in that channel |
| Mentions | Notify for direct mentions or configured important activity |
| Nothing | Suppress normal notifications |
| Default | Use the user's global preference |

This means the system cannot decide based only on the event type.

It also needs to know the user's preferences for the specific conversation.

## 9.6 Step 5: Check global notification preferences

If the channel uses default settings, the system needs to evaluate global preferences.

For example:

```text
Global Notification Preference

All
Mentions and DMs
DMs only
Highlight words
Never
```

The notification decision becomes:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/bfd6894b-f1fc-4566-9f04-42dc5ec35358.jpg align="center")

This is important because the same message may produce different outcomes for different users.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/cdda35b8-0b92-4afa-b012-12d9cab71767.jpg align="center")

One event can produce many different notification decisions.

## 9.7 Step 6: Check thread subscriptions

Threads introduce another level of notification complexity.

Suppose someone replies to a thread.

Should every member of the channel be notified?

Usually not.

The system needs to know who is subscribed to the thread.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/28afe2ca-4164-4b9f-be52-0f6c3245d4d5.jpg align="center")

This prevents users from receiving notifications for conversations they are not interested in.

Thread subscription is a separate preference from channel membership.

## 9.8 Step 7: Check user presence and device state

The user may already be active in Slack.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/26199579-7136-487e-a8e7-d080cfa026d2.jpg align="center")

Presence can help determine whether a mobile push notification is necessary.

But presence is not perfect.

A user might be marked active while away from the computer.

Therefore, presence should be treated as a useful signal, not proof that the user has seen the message.

For important notifications, the system should not rely solely on presence.

## 9.9 Step 8: Device-specific notification decisions

The user may have Slack open on multiple devices.

For example:

- Desktop application.
- Browser.
- Android phone.
- iPhone.
- Tablet.

The notification engine may need to decide whether to send a push notification to a mobile device.

Consider this scenario:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/b39d9d79-8911-4bb3-a038-4a26e4644006.jpg align="center")

If the user has already read the message on desktop, sending the same notification to mobile may be unnecessary.

Slack's notification decision flow also considers mobile-specific timing and notification state.

This helps reduce duplicate interruptions.

## 9.10 The complete simplified decision engine

Combining the above checks:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/185f38e5-85e3-4c88-bafd-bd0918b29490.jpg align="center")

The order shown above is illustrative. A real implementation may evaluate these conditions differently, combine checks, or use different internal services.

## 9.11 What can we learn from Slack?

The most important takeaway is that notification delivery and notification eligibility are two different problems.

A notification system has to answer:

1. Did an event happen?
2. Who is affected?
3. Is the event relevant to that user?
4. Does the user's preference allow the notification?
5. Is the user already active?
6. Which device should receive it?
7. Should it be delivered now?
8. Should it be suppressed, delayed, or aggregated?
9. If delivered, did it reach the device?
10. Did the user actually open it?

This is a much more complex problem than sending an email after an API request.

---

# 10\. Notification Decision Engine: How Should We Design It?

Slack's notification decision flow gives us a useful design direction.

Instead of implementing notification logic inside every application feature, we can create a centralized decision engine.

However, centralized logic does not necessarily mean one giant service or one synchronous function.

At smaller scale, it may be a module inside the notification service.

At larger scale, different responsibilities may be distributed across services.

## 10.1 Notification eligibility

We can define a notification eligibility function.

```js
async function shouldNotify(event, user, context) {
  if (!user.notificationPreferences.enabled) {
    return false;
  }

  if (context.isMuted && !context.hasOverride) {
    return false;
  }

  if (context.isInDND && !context.hasOverride) {
    return false;
  }

  if (!matchesNotificationPreference(event, user, context)) {
    return false;
  }

  if (context.isDuplicate) {
    return false;
  }

  return true;
}
```

This is only a simplified example.

In a real system, notification rules may be complex, and we should avoid making the decision using a single boolean when we need to understand why a notification was suppressed.

## 10.2 Return a decision, not only a boolean

Instead of:

```js
return true;
```

or:

```js
return false;
```

We can return a structured decision.

```json
{
  "eligible": false,
  "reason": "CHANNEL_MUTED",
  "channels": [],
  "priority": "LOW"
}
```

Or:

```json
{
  "eligible": true,
  "reason": "DIRECT_MENTION",
  "channels": ["IN_APP", "PUSH"],
  "priority": "HIGH"
}
```

This makes the system easier to debug.

For example, if a user reports:

"I didn't receive a notification."

We can investigate:

- Was the event generated?
- Was the user selected as a recipient?
- Was the notification suppressed because of preferences?
- Was the channel muted?
- Was the user in DND?
- Was the push request sent?
- Did the provider accept it?
- Did the device receive it?

This is much more useful than logging only `notification sent`.

## 10.3 Rule precedence

Notification preferences may conflict.

For example:

- Global preference: All messages.
- Channel preference: Mentions only.
- User is in DND.
- Message contains a direct mention.

We need to define which rule takes precedence.

A simplified precedence model might be:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/1dd9b911-da31-4cee-a602-e3e2679898de.jpg align="center")

The exact precedence is product-specific.

The important part is that rules should be explicit, testable, and consistent.

We should not scatter preference checks across API routes, workers, and provider integrations.

---

# 11\. Designing a Generic Notification Data Model

Different notification types contain different information.

For example:

- Someone liked your photo.
- Someone commented on your post.
- Someone followed you.
- Someone mentioned you.

All of them share some common fields, but their additional details differ.

We can store them using a generic notification schema.

## 11.1 Notification table

```sql
CREATE TABLE notifications (
    id BIGINT PRIMARY KEY,
    recipient_id BIGINT NOT NULL,
    actor_id BIGINT,
    type VARCHAR(100) NOT NULL,
    title VARCHAR(255),
    body TEXT,
    entity_type VARCHAR(100),
    entity_id VARCHAR(100),
    metadata JSON,
    created_at TIMESTAMP NOT NULL,
    read_at TIMESTAMP,
    status VARCHAR(30)
);
```

Example record:

```json
{
  "id": "notif_123",
  "recipient_id": "user_101",
  "actor_id": "user_202",
  "type": "POST_LIKED",
  "title": "New like",
  "body": "Someone liked your photo",
  "entity_type": "POST",
  "entity_id": "post_456",
  "metadata": {
    "postImageUrl": "https://example.com/image.jpg"
  },
  "created_at": "2026-11-27T10:00:00Z",
  "read_at": null,
  "status": "CREATED"
}
```

## 11.2 Why use a generic schema?

Imagine we introduce a new notification type next month.

We should not need to create a new database table for every notification type.

A generic schema allows us to store shared fields and use optional metadata for type-specific information.

However, metadata should not become an unstructured dumping ground.

Frequently queried fields should be explicit columns.

We should also validate metadata according to notification type.

## 11.3 Entity-based navigation

A notification should contain enough information for the frontend to know what to open when the user clicks it.

For example:

```text
POST_LIKED
    -> Open the post

FRIEND_REQUEST_RECEIVED
    -> Open the profile or request screen

PAYMENT_SUCCESSFUL
    -> Open transaction details
```

We can use:

- `entity_type`
- `entity_id`
- A validated action identifier

The frontend should maintain a mapping between notification types and supported actions.

Avoid blindly trusting arbitrary URLs or routes coming from notification payloads.

## 11.4 Type-aware frontend rendering

The frontend can use a common notification component with type-specific rendering.

```jsx
function NotificationItem({ notification }) {
  switch (notification.type) {
    case "POST_LIKED":
      return <PostLikedNotification data={notification} />;

    case "POST_COMMENTED":
      return <PostCommentedNotification data={notification} />;

    case "FRIEND_REQUEST_RECEIVED":
      return <FriendRequestNotification data={notification} />;

    default:
      return <GenericNotification data={notification} />;
  }
}
```

The backend provides structured data, while the frontend decides how to render it.

---

# 12\. Notification APIs: How Does the Frontend Use the System?

So far, we have focused on generating and delivering notifications.

But an application also needs APIs to display notifications to users.

For an in-app notification system, we can expose endpoints like these:

| Method | Endpoint | Purpose |
| --- | --- | --- |
| GET | `/notifications` | Fetch notifications |
| GET | `/notifications/unread-count` | Get unread count |
| PATCH | `/notifications/:id/read` | Mark one notification as read |
| PATCH | `/notifications/read-all` | Mark all as read |
| DELETE | `/notifications/:id` | Delete or hide a notification |

## 12.1 Fetching notifications

A user may have thousands of notifications.

We should not return all of them in one API response.

Use cursor-based pagination.

Example:

```http
GET /notifications?limit=20&cursor=abc123
```

Response:

```json
{
  "data": [
    {
      "id": "notif_123",
      "type": "POST_LIKED",
      "body": "Someone liked your photo",
      "createdAt": "2026-11-27T10:00:00Z",
      "readAt": null
    }
  ],
  "nextCursor": "xyz789",
  "hasMore": true
}
```

Cursor pagination is useful for notification feeds because new notifications may arrive while the user is scrolling.

## 12.2 Real-time notification delivery

How does the frontend know that a new notification has arrived?

There are several approaches.

### Polling

The frontend periodically calls the notification API.

```text
Frontend
   |
   | Every few seconds
   v
Notification API
   |
   v
Database
```

Simple, but it creates repeated requests even when there are no new notifications.

### WebSockets

The server pushes updates to an active connection.

Useful for real-time in-app updates.

### Server-Sent Events (SSE)

The server sends one-way updates to the browser.

Useful when the client mainly needs to receive updates.

### Mobile push

For mobile applications, push notification services such as Firebase Cloud Messaging or Apple Push Notification service are commonly used.

These approaches solve different problems.

A WebSocket connection is not a replacement for storing notifications: users may be offline when an event occurs.

---

# 13\. Notification Aggregation: Preventing Notification Spam

Imagine you publish a photo on a social media platform.

Within a few minutes, 50 people like it.

A naive system may generate 50 separate notifications.

This creates notification fatigue.

Instead, we can aggregate similar events.

For example:

"User A, User B and 48 others liked your photo."

## 13.1 How aggregation works

We maintain an aggregation window.

For example, we aggregate likes received within 30 seconds.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/575ba9df-8d0d-42b8-a7e2-160037d4626c.jpg align="center")

A simplified aggregation table could be:

```sql
CREATE TABLE notification_aggregations (
    id BIGINT PRIMARY KEY,
    recipient_id BIGINT NOT NULL,
    notification_type VARCHAR(100),
    entity_type VARCHAR(100),
    entity_id VARCHAR(100),
    event_count INT DEFAULT 0,
    window_start TIMESTAMP,
    window_end TIMESTAMP,
    status VARCHAR(30)
);
```

A useful aggregation key is:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/7efe2f08-7374-41e5-b7db-39140810f8f0.jpg align="center")

When the aggregation window closes, we generate the final notification.

## 13.2 When should we aggregate?

Aggregation works well for:

- Likes.
- Comments.
- Reactions.
- Follower activity.
- Repeated low-priority updates.

It should not delay urgent events such as payment failures or security alerts.

Aggregation reduces notification volume and provider costs, but introduces a small delivery delay.

---

# 14\. Online Presence: Choosing the Right Delivery Channel

Suppose someone sends a message to a user who is already active in the application.

Sending an additional email for the same event may be unnecessary.

We can use presence information to make smarter channel decisions.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/934ebaa1-459f-4227-8cf5-9baeba88f7c2.jpg align="center")

Presence can be maintained using a Redis-backed presence service or a real-time connection service.

However, presence is only a best-effort signal.

A user being online does not guarantee that they have seen the notification.

For important notifications, we should not rely only on presence-based delivery.

---

# 15\. Scaling Notifications to Millions of Users: Understanding Fan-out

Now let's consider a different problem.

Imagine a creator with 10 million followers uploads a new video.

We want to notify all eligible subscribers.

How do we distribute one event to millions of users?

This is called fan-out.

## 15.1 Understanding fan-out

Fan-out means distributing one event to multiple recipients.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/3a2eee8f-6051-4634-9b1f-80ae53aa1dd1.jpg align="center")

The challenge is not publishing one event.

The challenge is finding the recipients, checking eligibility, generating notification records or delivery jobs, and delivering them without overwhelming the infrastructure.

There are two major strategies.

## 15.2 Fan-out on Write (Push Model)

In fan-out on write, we distribute the event to recipients when it is created.

When a creator publishes a video:

1. The content service publishes `NEW_VIDEO_PUBLISHED`.
2. The notification system retrieves eligible subscribers.
3. Fan-out workers generate notification records or delivery jobs.
4. Workers send notifications through the selected channels.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/de531b97-dec4-45bb-a7d2-613cb8781277.jpg align="center")

### Advantages

- Notifications are precomputed.
- Reading the notification feed is fast.
- Users can retrieve their notifications directly from storage.

### Disadvantages

- One event can generate millions of writes.
- Storage and queue traffic increase.
- Large creators can create significant write amplification.
- Fan-out processing may take time.

## 15.3 Fan-out on Read (Pull Model)

Instead of generating notification records for every follower, we store the event once.

When a user opens their notification feed, the system retrieves relevant events from accounts they follow.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/bc75fb62-592a-4b26-8807-a5ca0f721dd8.jpg align="center")

### Advantages

- Avoids creating millions of records immediately.
- Reduces write amplification.
- Useful for highly popular accounts.

### Disadvantages

- Reading becomes more expensive.
- The system must merge events from multiple sources.
- Feed generation can become slower.
- Computation may be repeated for different users.

## 15.4 The Celebrity Problem

Consider two users:

- User A has 100 followers.
- User B has 10 million followers.

Using the same strategy for both users is inefficient.

Fan-out on write works well for User A.

But for User B, one event can create 10 million notification jobs.

This is known as the celebrity problem.

## 15.5 Hybrid Fan-out

Large social platforms often combine both approaches.

- Normal users use fan-out on write.
- High-follower accounts use fan-out on read.
- The system chooses based on audience size and workload.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/367a90f4-d71d-4022-a475-7f67a6f74826.jpg align="center")

The threshold is not universal.

It depends on the number of followers, event frequency, read traffic, write capacity, freshness requirements, and infrastructure cost.

### Important distinction: Event-broker fan-out vs recipient fan-out

These are not the same thing.

- Event-broker fan-out distributes an event to multiple independent services.
- Recipient fan-out distributes an event to individual users.

A large notification architecture may need both.

---

# 16\. Kafka Partitioning and Consumer Groups

As notification traffic grows, one consumer may not be able to process all incoming events.

We need parallel processing.

This is where Kafka partitioning and consumer groups become useful.

## 16.1 What is a partition?

A partition is a subdivision of a Kafka topic.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/3da4e245-a8e4-49ea-9e13-37801b6be668.jpg align="center")

Partitions allow multiple consumers to process messages in parallel.

A partition key determines which partition receives a message.

For example, we may use `recipient_id` to keep events for a recipient in the same partition.

However, a poorly chosen key can create a hot partition.

A highly active account might generate far more events than other accounts, making one partition overloaded.

## 16.2 What is a consumer group?

A consumer group allows multiple consumers to share the processing of a topic's partitions.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/6d271770-65dc-4518-bcdb-d0b631a87ecb.jpg align="center")

Both services can independently consume the same event stream.

Within a consumer group, partitions are assigned among consumers.

Important points:

- A partition is assigned to only one consumer within a consumer group at a time.
- Adding more consumers than available partitions does not increase parallelism for that group.
- Ordering is guaranteed only within a partition, not across the entire Kafka topic.

This helps us understand why simply adding more workers does not always increase throughput.

We must also ensure that the broker has enough partitions and that the workload is distributed evenly.

---

# 17\. Priority Queues: Protecting Important Notifications

Consider a fintech application sending:

- Payment confirmation.
- Payment failure alerts.
- Security notifications.
- Promotional campaigns.

Now imagine it sends a New Year promotional notification to 20 million customers.

At the same time, an important payment notification needs to be delivered.

If both messages share the same queue, the critical notification might wait behind millions of marketing messages.

We need priority queues.

## 17.1 Priority-based queues

We can divide notifications into three queues.

| Queue | Priority | Example |
| --- | --- | --- |
| P0 | Critical | Payment failure, security alert |
| P1 | Normal | Order updates, account activity |
| P2 | Low | Marketing, promotional messages |

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/fa5b4bb4-8ce8-4425-aa3e-532c32a963a9.jpg align="center")

The router determines which queue should receive the message.

This ensures that critical messages do not wait behind bulk traffic.

However, always processing P0 first could starve P1 and P2.

We should use weighted or fair scheduling.

For example:

- 70% P0
- 20% P1
- 10% P2

These are illustrative values.

The actual weights depend on the system's SLA and traffic.

Also, event category and priority are separate dimensions. Not every transactional event is equally urgent.

---

# 18\. Rate Limiting: Protecting the System and External Providers

Priority queues solve one problem, but we still need to control the number of notifications being processed.

Imagine one customer sends a promotional message to 10 million users.

Even if these messages go into P2, they can consume significant worker capacity and provider bandwidth.

We need rate limiting.

## 18.1 Provider-level rate limiting

Suppose our email provider supports 30 requests per second.

We might configure the system to send 25 requests per second to maintain some headroom.

But consider this:

We have five workers, and each independently sends 25 requests per second.

Total throughput becomes:

```text
5 × 25 = 125 requests/second
```

This exceeds the provider's limit.

Therefore, the rate limiter must be shared across workers.

We can use Redis to implement distributed rate limiting with algorithms such as:

- Token bucket.
- Leaky bucket.
- Sliding window.

## 18.2 Customer-level rate limiting

Provider-level rate limiting is not enough.

One customer should not be able to consume the entire available capacity.

We can apply limits based on:

- Customer.
- Queue.
- Event type.
- Recipient.
- Channel.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/c3eb82fc-9f14-4f65-8609-b5fb7f71fd67.jpg align="center")

If a customer exceeds their limit, we can move the event to a deferred queue and process it later.

For expired or low-value events, we may instead drop or coalesce them according to product rules.

---

# 19\. Backpressure: What Happens When the System Cannot Keep Up?

A queue can absorb temporary traffic spikes.

But what if traffic remains higher than processing capacity for a long period?

Consider:

```text
Incoming rate = 10,000 jobs/sec

Processing rate = 6,000 jobs/sec
```

The queue grows by approximately 4,000 jobs every second.

Eventually, the system can run out of storage, processing capacity, or acceptable delivery time.

This is called a backlog problem.

## 19.1 Understanding backpressure

Backpressure is a mechanism that prevents an overloaded system from accepting or generating work faster than it can safely process.

Possible strategies:

- Slow down producers.
- Limit bulk campaign creation.
- Reduce worker concurrency.
- Defer low-priority jobs.
- Reject work when capacity is exhausted.
- Drop expired notifications.
- Aggregate repetitive events.
- Allocate separate capacity for critical workloads.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/65e06f82-85c3-4ac3-8cdf-c4a60e86be39.jpg align="center")

The goal isn't to make the queue infinitely large.

The goal is to keep the system stable and protect critical work.

---

# 20\. Database Bottlenecks: Learning from a Fintech Notification Architecture

Let's now look at how a notification system can evolve in a fintech environment.

A payment gateway may need to send:

- A confirmation email to the customer.
- A notification to the merchant.
- A webhook to an external system.
- A delivery status record for tracking and retries.

Delivery tracking is critical because a missing payment notification can create confusion and support issues.

## 20.1 Initial architecture

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/782422de-7a8b-40b1-ab51-4b82f4e4f649.jpg align="center")

The executor sends the outbound communication and records its status in MySQL.

The scheduler periodically checks for failed notifications and republishes eligible retry jobs.

Why store notification information in a database?

Because we need to know:

- Was the email sent?
- Did the webhook succeed?
- Did the provider reject the request?
- Does this notification need another attempt?

The database provides a persistent record of notification processing and delivery status.

## 20.2 Understanding the scaling problem

In the engineering example discussed in the source material, P99 latency increased from approximately 2 seconds to 4 seconds when throughput exceeded 1,000 transactions per second.

The main challenges were:

### Challenge 1: Database read load

The executor needs information about users, transactions, email addresses, phone numbers, and webhook configurations.

At peak traffic, these reads increase.

Other application services may also depend on the same database.

### Challenge 2: Scaling workers increases database pressure

Suppose we increase the number of workers from 100 to 500.

More workers can process more messages, but they also create more concurrent database operations.

If the database can comfortably handle only 300 concurrent connections, increasing the worker count may overload it.

The worker layer is horizontally scalable, but the database may not scale at the same rate.

### Challenge 3: Traffic surges

Traffic may increase during:

- Large sales.
- Festivals.
- IPL matches.
- End-of-year activity.
- Promotional events.

Provisioning the database permanently for the highest possible traffic is expensive.

We need a way to decouple worker processing from database writes.

## 20.3 Asynchronous database writes

The original architecture looks like:

```text
Worker
  |
  v
Executor
  |
  v
MySQL Database
```

Every executor directly updates MySQL.

The improved architecture introduces a durable streaming system such as Amazon Kinesis.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/88c9c6f8-c721-4156-afbb-2f423bd89a29.jpg align="center")

Now the executor publishes a status event to Kinesis instead of directly writing to MySQL.

A separate consumer reads the events and updates the database.

Why does this help?

- The executor no longer waits for every database write.
- Kinesis buffers status events durably.
- Database consumers process updates at a controlled rate.
- The executor and database can scale more independently.
- The database no longer needs to handle every executor's write synchronously.

### Reliability considerations

Asynchronous writes introduce new failure scenarios.

We need:

- Durable stream retention.
- Acknowledgements and checkpointing.
- Consumer retries.
- Idempotent database updates.
- Dead Letter Queue handling.
- Monitoring of consumer lag.

We must also distinguish between the provider accepting a request and the database recording that status.

A notification may have been accepted by the provider while its status update is still waiting in the stream.

For critical notifications, this temporary inconsistency must not lead to incorrect retries or duplicate external delivery.

---

# 21\. Complete Notification System Architecture

We can now combine all the components.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/5700f2b4-1ffb-493a-9623-8fe898bdda32.jpg align="center")

This is a reference architecture, not a requirement to deploy every component from day one.

Some components can initially live inside the same service.

The important thing is to maintain clear responsibilities so that they can be separated when necessary.

---

# 22\. Understanding Notification Delivery States

Sending a request successfully does not necessarily mean the user received or read the notification.

We should track different stages.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/d6d1e645-21c3-4c3e-82cb-70a08ac76231.jpg align="center")

| State | Meaning |
| --- | --- |
| CREATED | Notification record generated |
| QUEUED | Job accepted by the queue |
| PROCESSING | Worker is processing the job |
| PROVIDER_ACCEPTED | Provider accepted the request |
| DELIVERED | Delivery confirmation received, where supported |
| READ | User opened or read the notification, where measurable |
| FAILED | Delivery failed |
| EXPIRED | Notification is no longer useful |

Not every channel supports every state.

For example, provider acceptance does not mean a push notification appeared on the user's device.

Similarly, email delivery does not prove that the user read the email.

We should track only states that the channel can actually report.

---

# 23\. Notification Tracing: How Do We Debug a Notification?

This is another important lesson from studying Slack.

A notification can pass through many different services:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/d528691f-616a-4a3f-bb49-a1966a735dab.jpg align="center")

If the user says they did not receive a notification, which component failed?

Without tracing, we may only know:

```text
Notification API -> Success
```

But that doesn't tell us whether the notification:

- Was generated.
- Was eligible.
- Was queued.
- Was processed.
- Was accepted by the provider.
- Was received by the device.
- Was opened by the user.

Slack Engineering's article, *Tracing Notifications*, describes the effort to model notification delivery as a consistent trace across services and clients. The goal was to understand whether a notification was sent, where it was sent, whether it was received, and whether the user opened or read it.

## 23.1 A notification trace

We can model a notification as a series of stages.

| Stage | Meaning |
| --- | --- |
| `notification:trigger` | Determine whether notification should be sent |
| `notification:notify` | Notify the user across their clients |
| `notification:sent` | Notification sent to client/device |
| `notification:received` | Notification received by client |
| `notification:opened` | User opened notification |
| `notification:read` | Notification content was opened/rendered in application |

These stages help us identify where the flow stopped.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/62c0db3a-6d6d-422b-9b30-b59790ca0777.jpg align="center")

We can investigate the device, provider, or client delivery path instead of blindly retrying the entire workflow.

## 23.2 Trace IDs and correlation IDs

Every notification should have a unique identifier.

For example:

```json
{
  "notificationId": "notif_123",
  "eventId": "event_456",
  "traceId": "trace_789",
  "userId": "user_101"
}
```

These identifiers allow us to connect logs from different services.

When a worker processes the notification, it should preserve the trace context.

This helps us answer:

- Which event generated the notification?
- Which service processed it?
- How long did it spend in the queue?
- How many times was it retried?
- Which provider was used?
- Was it delivered?
- Did the client receive it?

This is distributed tracing.

It is especially useful when a notification passes through many asynchronous systems.

---

# 24\. Database Design and Indexing

The database should be designed around the queries the application performs.

For example, fetching a user's latest notifications:

```sql
SELECT *
FROM notifications
WHERE recipient_id = ?
ORDER BY created_at DESC
LIMIT 20;
```

A suitable index could be:

```sql
CREATE INDEX idx_notifications_recipient_created
ON notifications (recipient_id, created_at DESC);
```

For unread notifications, we may need an additional index depending on the database and query patterns.

At larger scale, we should also consider:

- Partitioning old notification records.
- Archiving historical records.
- Retention policies.
- Database connection pooling.
- Read replicas for suitable read-heavy workloads.
- Cursor-based pagination.

We should not introduce database sharding or partitioning without understanding the actual query and workload requirements.

---

# 25\. Observability: How Do We Know the System Is Working?

A notification system can contain hundreds of workers, multiple queues, and several external providers.

Without monitoring, it becomes difficult to identify where delays are happening.

We need end-to-end observability.

## 25.1 Queue metrics

Monitor:

- Queue depth.
- Oldest message age.
- Message arrival rate.
- Processing rate.
- Delayed messages.
- DLQ message count.

Queue depth alone is not enough.

The oldest message age is often a better indicator of whether the system is meeting its delivery SLA.

## 25.2 Worker metrics

Monitor:

- Active workers.
- Worker utilization.
- Processing latency.
- Worker failures.
- Retry count.
- Throughput per worker.

## 25.3 Provider metrics

Monitor:

- Provider response time.
- Provider error rate.
- Rate-limit responses.
- Accepted requests.
- Delivery confirmation rate.
- Provider availability.

## 25.4 Database metrics

Monitor:

- Query latency.
- Connection utilization.
- Read/write throughput.
- Replication lag.
- Consumer lag.

## 25.5 Business metrics

Monitor:

- Percentage of notifications delivered within the SLA.
- Percentage of failed notifications.
- Notification volume per customer.
- Cost per notification.
- User engagement.
- Unsubscribe rates.

We can use Prometheus and Grafana to build dashboards and alerts.

Distributed tracing and correlation IDs also help follow a single event through the entire system.

---

# 26\. Additional Production-Level Considerations

There are a few more things we should consider before calling our design production-ready.

## 26.1 Message ordering

Some notifications need to be processed in order.

For example:

- Order placed.
- Payment successful.
- Order shipped.
- Order delivered.

We can use a partition key such as `order_id` to preserve ordering within a partition.

However, ordering is generally guaranteed only within a partition, not across an entire Kafka topic.

Retries and multiple workers can also introduce application-level ordering challenges.

## 26.2 Notification expiration

Not every notification remains useful forever.

For example:

- An OTP expires within minutes.
- A promotional message may become irrelevant after a sale.
- A delivery update may be outdated after the order is delivered.

We should support message expiration and time-to-live (TTL).

Workers should avoid sending notifications that are no longer useful.

## 26.3 Provider failover

What happens if the primary SMS provider becomes unavailable?

We can configure a secondary provider.

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/306dccc7-c97a-4b45-927b-da5969e8d284.jpg align="center")

But we must be careful.

The primary provider might have accepted the message even if our request timed out.

Sending it again through a secondary provider could create duplicate SMS messages.

Failover should consider delivery status, idempotency support, and timeout handling.

## 26.4 Circuit breakers

If an external provider repeatedly fails, we should avoid sending thousands of requests to it.

A circuit breaker temporarily blocks requests to an unhealthy dependency.

It has three states:

- **Closed:** Requests are allowed.
- **Open:** Requests are temporarily blocked.
- **Half-open:** A limited number of test requests are allowed.

This prevents a failing provider from consuming worker resources continuously.

## 26.5 Security and privacy

Notifications may contain sensitive information.

We should:

- Avoid putting sensitive details directly in push payloads.
- Encrypt data in transit and at rest.
- Protect provider credentials.
- Validate webhook signatures.
- Enforce authorization on notification APIs.
- Prevent users from accessing another user's notifications.
- Avoid logging OTPs or sensitive content.
- Validate recipient addresses and phone numbers.

## 26.6 Cost optimization

Sending every event through every channel is expensive and unnecessary.

We can reduce costs through:

- Aggregation.
- Duplicate suppression.
- User preference checks.
- Channel selection.
- Bulk provider APIs.
- Expiring outdated messages.
- Provider-level rate optimization.
- Avoiding unnecessary SMS delivery.

The goal is not to send the maximum number of notifications.

It is to send the right notification to the right user through the right channel at the right time.

---

# 27\. How to Actually Build This System: A Beginner-Friendly Implementation Roadmap

Understanding the architecture is one thing. Implementing it is another.

If you're building your first notification system, don't start with Kafka, multiple providers, Redis, and ten different microservices.

Start small and introduce complexity only when there is a real requirement.

Here is the order I would follow.

## Phase 1: Build a basic notification service

Start with:

- Node.js and Express.
- PostgreSQL or MongoDB.
- One notification provider.
- One background worker.
- One queue.

Implement:

- A basic notification API.
- A database table for notifications.
- A queue for pending notification jobs.
- A worker that consumes jobs.
- A provider integration.

At the end of this phase, you should be able to create a notification and deliver it asynchronously.

## Phase 2: Add reliability

Implement:

- Retry handling.
- Exponential backoff.
- Maximum retry attempts.
- Dead Letter Queue.
- Idempotency keys.
- Delivery status tracking.

Test what happens when the provider fails and when a worker crashes.

At the end of this phase, your system should handle common failures without losing track of notification jobs.

## Phase 3: Add multiple channels

Introduce:

- Email.
- SMS.
- Push notifications.
- In-app notifications.

Add a channel router so that the notification service can decide which channel to use.

Keep provider-specific code behind separate adapters.

For example:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/b7e570d9-e3c5-482c-a559-25832647b760.jpg align="center")

## Phase 4: Add user preferences and aggregation

Implement:

- Per-channel preferences.
- Notification categories.
- Unread status.
- Read APIs.
- Aggregation rules.
- Quiet hours.
- User timezone.

Now your system starts behaving like a real product notification service rather than a simple email queue.

## Phase 5: Introduce the notification decision engine

Implement:

- Recipient resolution.
- Channel-level preferences.
- Global notification preferences.
- Mute rules.
- DND.
- Mentions.
- Thread subscriptions.
- User presence.
- Device-specific decisions.
- Suppression reasons.

At this point, notifications should no longer be generated simply because an event exists.

The system should decide whether the event deserves to interrupt the user.

## Phase 6: Introduce event-driven architecture

Move business event generation away from notification-specific logic.

Introduce:

- Event schemas.
- An event broker.
- Notification consumers.
- Transactional Outbox.
- Idempotent event processing.

At this point, multiple application services can publish events without knowing how notifications are delivered.

## Phase 7: Scale the architecture

Only when traffic requires it, introduce:

- Kafka partitions.
- Consumer groups.
- Redis-based distributed rate limiting.
- Priority queues.
- Fan-out workers.
- Hybrid fan-out.
- Asynchronous status streams.
- Database partitioning and retention.

Add monitoring and load testing throughout the process.

## What should you build first?

For a beginner, I would recommend this minimum working architecture:

![](https://cdn.hashnode.com/uploads/covers/663daf04046caab7489ff930/a06bc938-e574-4871-bb52-aa1b83e6254a.jpg align="center")

This gives you the foundation.

Once this works, every other concept in the article becomes an extension of something you already understand.

---

# 28\. Key Design Trade-offs

There is no single architecture that is best for every notification system.

| Design Decision | Benefit | Trade-off |
| --- | --- | --- |
| Synchronous delivery | Simple implementation | High latency and tight coupling |
| Asynchronous delivery | Better scalability and failure isolation | More infrastructure |
| Fan-out on write | Fast notification reads | High write amplification |
| Fan-out on read | Lower write overhead | More expensive reads |
| Hybrid fan-out | Balances read and write costs | More complex routing |
| Priority queues | Protect critical notifications | Requires fair scheduling |
| Aggregation | Reduces notification spam | Introduces delivery delay |
| Multiple providers | Better resilience | More operational complexity |
| Async DB writes | Separates workers from DB | Eventual consistency |
| Centralized decision engine | Consistent notification behavior | Requires careful scaling and rule management |
| Presence-based routing | Reduces unnecessary interruptions | Presence can be inaccurate |
| Distributed rate limiting | Protects providers and infrastructure | Adds coordination and state management |

The right architecture depends on the product's requirements, traffic patterns, delivery guarantees, and infrastructure budget.

A small application may only need one queue and a few workers.

A large social platform may need hybrid fan-out, partitioned event streams, aggregation, and complex notification decision rules.

A fintech platform may prioritize auditability, low latency, delivery tracking, and reliability.

---

# 29\. Final Takeaways

A notification system is much more than an API connected to an email provider.

It is a distributed system that converts business events into relevant, reliable, and timely communications.

We started with a simple synchronous API and gradually introduced the components needed to support larger workloads.

The key ideas are:

- **Asynchronous processing:** Move notification delivery out of the main request-response flow.
- **Message queues:** Buffer traffic and decouple producers from consumers.
- **Background workers:** Process notification jobs independently.
- **Retries and DLQs:** Handle temporary and permanent failures.
- **Idempotency:** Reduce duplicate processing.
- **Event-driven architecture:** Separate business events from notification delivery.
- **Transactional Outbox:** Prevent business data and event publishing from becoming inconsistent.
- **Notification decision engine:** Decide whether a notification should be generated and delivered.
- **Notification preferences:** Respect user choices and consent.
- **Aggregation:** Avoid overwhelming users with repetitive notifications.
- **Fan-out strategies:** Handle events involving millions of recipients.
- **Priority queues:** Protect critical notifications from bulk traffic.
- **Rate limiting and backpressure:** Protect external providers and infrastructure from overload.
- **Asynchronous database writes:** Prevent the database from becoming a bottleneck.
- **Distributed tracing:** Understand what happened to a notification across the system.
- **Observability:** Understand whether the system is meeting its SLAs.

The most important lesson I took away from exploring notification system design is that the difficult part is not sending a notification.

The difficult part is deciding:

- Who should receive it?
- Is it important enough to interrupt them?
- When should it be sent?
- Through which channel?
- Should it be suppressed, delayed, or aggregated?
- What happens when something goes wrong?
- How can we prove that it was delivered?

That is what makes notification systems an interesting system design problem.

A simple feature that appears to be just a push notification can involve event-driven architecture, distributed queues, preference evaluation, presence detection, fan-out, reliability, observability, and multiple failure scenarios.

And the best architecture is not the one with the most components.

It is the one that solves the actual problem while keeping complexity under control.
