Design a Notification System by ByteByteGo
Design a Notification System by ByteByteGo
A notification system has already become a very popular feature for many applications in recent
years. A notification alerts a user with important information like breaking news, product updates,
events, offerings, etc. It has become an indispensable part of our daily life. In this chapter, you are
asked to design a notification system.
A notification is more than just mobile push notification. Three types of notification formats are:
mobile push notification, SMS message, and Email. Figure 1 shows an example of each of these
notifications.
Push
SMS Email
notification
Figure 1 illustrates the three main types of notifications supported by the system: Push notification,
SMS, and Email. It shows example visuals for each:
These represent the primary channels through which the notification system can reach users with
important information.
Building a scalable system that sends out millions of notifications a day is not an easy task. It
requires a deep understanding of the notification ecosystem. The interview question is purposely
designed to be open-ended and ambiguous, and it is your responsibility to ask questions to clarify
the requirements.
This section shows the high-level design that supports various notification types: iOS push
notification, Android push notification, SMS message, and Email. It is structured as follows:
1. The process begins with a Provider, which is the server-side component that initiates the
notification.
2. The Provider sends a notification request to Apple Push Notification Service (APNS), a remote
service managed by Apple.
3. APNS then forwards the notification to the target iOS Device.
4. The iOS Device receives and displays the push notification to the user.
The diagram also shows that the Provider supplies two key pieces of information:
Provider. A provider builds and sends notification requests to Apple Push Notification Service
(APNS). To construct a push notification, the provider provides the following data:
Device token: This is a unique identifier used for sending push notifications.
Payload: This is a JSON dictionary that contains a notification’s payload. Here is an example:
{
"aps":{
"alert":{
"title":"Game Request",
"body":"Bob wants to play chess",
"action-loc-key":"PLAY"
},
"badge":5
}
}
APNS: This is a remote service provided by Apple to propagate push notifications to iOS
devices.
Android adopts a similar notification flow. Instead of using APNs, Firebase Cloud Messaging (FCM)
is commonly used to send push notifications to android devices.
This process mirrors the iOS flow but uses Google's FCM instead of Apple's APNS.
SMS message
For SMS messages, third party SMS services like Twilio [1], Nexmo [2], and many others are
commonly used. Most of them are commercial services.
1. It begins with our Notification System, representing the core of our design.
2. The Notification System connects to a Third-party SMS Service, such as Twilio or Nexmo.
3. The Third-party SMS Service then sends the SMS message to the user's Phone.
This approach leverages established SMS providers rather than managing the complex
infrastructure required for direct SMS sending.
Although companies can set up their own email servers, many of them opt for commercial email
services. Sendgrid [3] and Mailchimp [4] are among the most popular email services, which offer a
better delivery rate and data analytics.
1. Starting with our Notification System, which generates the email content.
2. The system connects to a Third-party Email Service like Sendgrid or Mailchimp.
3. The Email Service then delivers the email to the recipient's Email Client.
Using third-party email services often provides better delivery rates and analytics compared to self-
hosted email servers.
Figure 6 shows the design after including all the third-party services.
Figure 6 presents a comprehensive view of the notification system, incorporating all previously
discussed notification types:
This unified view shows how a single notification system can manage multiple notification channels
efficiently.
This process ensures the notification system has the necessary contact details to reach users
through various channels.
Figure 8 shows simplified database tables to store contact info. Email addresses and phone
numbers are stored in the user table, whereas device tokens are stored in the device table. A user
can have multiple devices, indicating that a push notification can be sent to all the user devices.
Figure 8 shows a simplified database schema for storing user contact information:
1. User Table:
user_id (primary key)
email
phone
2. Device Table:
device_id (primary key)
user_id (foreign key referencing User table)
device_token
device_type
This structure allows for multiple devices per user, enabling notifications to be sent to all of a user's
devices.
High-level design
Figure 9 shows the design, and each system component is explained below.
Figure 9 This diagram presents the initial high-level design of the notification sending/receiving
flow:
This design, while functional, has limitations in scalability and reliability that are addressed in
subsequent iterations.
Service 1 to N: A service can be a micro-service, a cron job, or a distributed system that triggers
notification sending events. For example, a billing service sends emails to remind customers of
their due payment or a shopping website tells customers that their packages will be delivered
tomorrow via SMS messages.
Third-party services: Third party services are responsible for delivering notifications to users.
While integrating with third-party services, we need to pay extra attention to extensibility. Good
extensibility means a flexible system that can easily plugging or unplugging of a third-party service.
Another important consideration is that a third-party service might be unavailable in new markets or
in the future. For instance, FCM is unavailable in China. Thus, alternative third-party services such
as Jpush, PushY, etc are used there.
Hard to scale: The notification system handles everything related to push notifications in one
server. It is challenging to scale databases, caches, and different notification processing
components independently.
Performance bottleneck: Processing and sending notifications can be resource intensive. For
example, constructing HTML pages and waiting for responses from third party services could
take time. Handling everything in one system can result in the system overload, especially
during peak hours.
After enumerating challenges in the initial design, we improve the design as listed below:
The best way to go through the above diagram is from left to right:
Service 1 to N: They represent different services that send notifications via APIs provided by
notification servers.
Provide APIs for services to send notifications. Those APIs are only accessible internally or by
verified clients to prevent spams.
POST https://api.example.com/v/sms/send
Request body
{
"to":[
{
"user_id":123456
}
],
"from":{
"email":"[email protected]"
},
"subject":"Hello World!",
"content":[
{
"type":"text/plain",
"value":"Hello, World!"
}
]
}
Message queues: They remove dependencies between components. Message queues serve as
buffers when high volumes of notifications are to be sent out. Each notification type is assigned
with a distinct message queue so an outage in one third-party service will not affect other
notification types.
Workers: Workers are a list of servers that pull notification events from message queues and send
them to the corresponding third-party services.
Next, let us examine how every component works together to send a notification:
2. Notification servers fetch metadata such as user info, device token, and notification setting
from the cache or database.
3. A notification event is sent to the corresponding queue for processing. For instance, an iOS
push notification event is sent to the iOS PN queue.
In the high-level design, we discussed different types of notifications, contact info gathering flow,
and notification sending/receiving flow. We will explore the following in deep dive:
Reliability.
Updated design.
Reliability
We must answer a few important reliability questions when designing a notification system in
distributed environments.
One of the most important requirements in a notification system is that it cannot lose data.
Notifications can usually be delayed or re-ordered, but never lost. To satisfy this requirement, the
notification system persists notification data in a database and implements a retry mechanism. The
notification log database is included for data persistence, as shown in Figure 11.
APNs
iOS PN Workers
Notification log
This setup prevents data loss by logging notifications and allows for retry mechanisms in case of
delivery failures.
The short answer is no. Although notification is delivered exactly once most of the time, the
distributed nature could result in duplicate notifications. To reduce the duplication occurrence, we
introduce a dedupe mechanism and handle each failure case carefully. Here is a simple dedupe
logic:
When a notification event first arrives, we check if it is seen before by checking the event ID. If it is
seen before, it is discarded. Otherwise, we will send out the notification. For interested readers to
explore why we cannot have exactly once delivery, refer to the reference material [5].
Notification template
A large notification system sends out millions of notifications per day, and many of these
notifications follow a similar format. Notification templates are introduced to avoid building every
notification from scratch. A notification template is a preformatted notification to create your unique
notification by customizing parameters, styling, tracking links, etc. Here is an example template of
push notifications.
BODY:
You dreamed of it. We dared it. [ITEM NAME] is back — only until [DATE].
CTA:
Order Now. Or, Save My [ITEM NAME]
The benefits of using notification templates include maintaining a consistent format, reducing the
margin error, and saving time.
Notification setting
Users generally receive way too many notifications daily and they can easily feel overwhelmed.
Thus, many websites and apps give users fine-grained control over notification settings. This
information is stored in the notification setting table, with the following fields:
user_id bigInt
Rate limiting
To avoid overwhelming users with too many notifications, we can limit the number of notifications a
user can receive. This is important because receivers could turn off notifications completely if we
send too often.
Retry mechanism
When a third-party service fails to send a notification, the notification will be added to the message
queue for retrying. If the problem persists, an alert will be sent out to developers.
For iOS or Android apps, appKey and appSecret are used to secure push notification APIs [6]. Only
authenticated or verified clients are allowed to send push notifications using our APIs. Interested
users should refer to the reference material [6].
A key metric to monitor is the total number of queued notifications. If the number is large, the
notification events are not processed fast enough by workers. To avoid delay in the notification
delivery, more workers are needed. Figure 12 (credit to [7]) shows an example of queued
messages to be processed.
This visualization helps monitor system performance and identify periods when more workers might
be needed to process notifications efficiently.
Events tracking
Notification metrics, such as open rate, click rate, and engagement are important in understanding
customer behaviors. Analytics service implements events tracking. Integration between the
notification system and the analytics service is usually required. Figure 13 shows an example of
events that might be tracked for analytics purposes.
click
unsubscribe
error
Tracking these events allows for analytics on notification effectiveness and system performance.
Updated design
Putting everything together, Figure 14 shows the updated notification system design.
This design addresses scalability, reliability, security, and analytics needs of a robust notification
system.
In this design, many new components are added in comparison with the previous design.
The notification servers are equipped with two more critical features: authentication and rate-
limiting.
We also add a retry mechanism to handle notification failures. If the system fails to send
notifications, they are put back in the messaging queue and the workers will retry for a
predefined number of times.
Finally, monitoring and tracking systems are added for system health checks and future
improvements.
Step 4 - Wrap up
Notifications are indispensable because they keep us posted with important information. It could be
a push notification about your favorite movie on Netflix, an email about discounts on new products,
or a message about your online shopping payment confirmation.
In this chapter, we described the design of a scalable notification system that supports multiple
notification formats: push notification, SMS message, and email. We adopted message queues to
decouple system components.
Besides the high-level design, we dug deep into more components and optimizations.
Security: AppKey/appSecret pair is used to ensure only verified clients can send notifications.
Tracking and monitoring: These are implemented in any stage of a notification flow to capture
important stats.
Respect user settings: Users may opt-out of receiving notifications. Our system checks user
settings first before sending notifications.
Rate limiting: Users will appreciate a frequency capping on the number of notifications they
receive.
Congratulations on getting this far! Now give yourself a pat on the back. Good job!
Reference materials
[1] Twilio SMS: SMS API | Twilio
[2] Nexmo SMS: Business Phone, VoIP, Communication APIs, Contact Center | Vonage