Notification system
What we are building
Section titled “What we are building”A notification system is the one place in a company that tells users things. An order shipped, a code to type, a friend replied, a bill is due. The services that have something to say do not talk to phones, mail servers and carriers themselves; they hand the notification to this system, and it decides how to reach the user and does it. It looks like plumbing, and it has a particular shape: the system’s speed is set less by its own servers than by the outside providers it sends through.
Functional requirements. Accept a notification for a user from another service. Choose the channels from the user’s preferences (push, email, SMS), send through each, and record what happened. Let a user turn a channel off. Urgent notifications, such as a one-time code, must not wait behind bulk ones. Templates, translation, scheduling and in-app inboxes are real features and are left out.
Non-functional requirements. These are targets chosen for this lesson. An urgent notification is handed to a provider within a few seconds. A notification is never lost once it has been accepted, and is never sent twice on the same channel. A user who has opted out of a channel gets nothing on it. The service stays up when a provider is slow or down.
Scale. 250 million notifications a day, with a peak about three times the average. Email and SMS go through outside providers that limit how fast the service may send.
Mental model. A notification system is a funnel into a few narrow pipes. In front of the pipes you can have as many servers as you like, but each pipe, a provider’s sending limit, lets through a fixed number a second. The design is about queueing in front of the pipes, using each pipe fully without overflowing it, and making sure that what goes in once comes out once.
This case study does not repeat how a queue or a cache works: the messaging and caching modules cover them. The new questions are how to send one request over several channels, how to retry when a provider refuses, and how to make a message that is delivered at least once arrive only once.
Estimate before you design
Section titled “Estimate before you design”The same method as in the file storage lesson, with one difference: the numbers that matter are compared with limits that belong to someone else. In the lab, one request is one notification, and the mix is the same for each 100: 75 push messages, 30 emails and 5 SMS messages, which is 1.1 messages per notification because some users receive two channels.
| Quantity | Working | Result |
|---|---|---|
| Notifications per second, on average | 250 million ÷ 86,400 | about 2,900 |
| Notifications per second at the peak, assuming 3 times the average | 2,894 × 3 | about 9,000 |
| Push at the peak | 9,000 × 0.75 | 6,750 per second |
| Email at the peak | 9,000 × 0.30 | 2,700 per second |
| SMS at the peak | 9,000 × 0.05 | 450 per second |
| Messages a day | 250 million × 1.1 | 275 million, of which 75 million emails and 12.5 million SMS |
| Preference reads at the peak | one for each notification | 9,000 per second |
| Delivery log, if each record is 200 bytes and kept for 30 days | 275 million × 200 bytes × 30 | about 1.65 TB |
| A campaign of 10 million emails, at 4,000 emails per second | 10 million ÷ 4,000 | 2,500 s, about 42 minutes |
The 3 times for the peak, the mix, the 200 bytes and the limits are assumptions. Three things follow for any reasonable values. The rates are modest next to what a database or a cache serves: 9,000 per second is not the hard part. The hard part is the sending limits: an email provider typically limits both how many messages you may send in a day and how many per second (Amazon SES documents a daily sending quota and a maximum sending rate for each account), and SMS has its own, lower, throughput. And a campaign is a burst that the average hides: 10 million emails is more than three hours of work for a provider that accepts 800 per second, and 42 minutes for two that accept 4,000.
The API and the data
Section titled “The API and the data”One call carries the traffic. The producer sends a key that identifies the notification, so that a retry of the request does not create a second one.
POST /notificationsIdempotency-Key: order-81234-shipped{"userId": "u17", "template": "order_shipped", "priority": "normal", "params": {"orderId": 81234}}→ 202 Accepted {"id": "n_9d2f"}202 Accepted means the notification is in the queue, not that it has been delivered. That is the point of the second stage below.
| Table | Meaning |
|---|---|
preferences |
User, channel, whether it is on, quiet hours. Read for every notification, changed a few times a year. |
device_tokens |
User, platform, the token a push provider gave the device. Tokens expire and must be removed when a provider says so. |
notifications |
Id, user, template, priority, the producer’s idempotency key. |
deliveries |
Notification id and channel (together the key), state (claimed, sent, delivered, failed), attempts, the provider’s message id. This is the delivery log. |
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab starts with the simplest design that works and adds one thing at a time. Each stage is designed for a load, and the slider raises the load to 3 times and 10 times that. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out, among them that the API servers and workers are drawn large enough not to be the story after the first stage.
A service that tells users about events by push, email and SMS. Producers send one request per notification. The service chooses the channels from the user’s preferences, sends through outside providers that limit how fast it may go, and must not send the same message twice. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.
Start simple: send from the request
Design load of this stage: 100 req/s
- What we add
- Producers call one API with a notification for a user. The API reads the user’s preferences from a database, then calls the push, email and SMS providers itself, and answers when they have all answered.
- Why: the number that forced it
- The API server is held for as long as the providers take: about 3 ms of its own work, plus 60 ms for a push message, 200 ms for an email and 400 ms for an SMS. Weighted by the mix, that is about 128 ms for each notification, so two servers working on 16 requests at a time can do about 250 per second. At 100 notifications per second they are at 40%.
- What it costs
- Nothing to run but the API and a database. The cost is the coupling: a slow SMS provider makes the API slow for every producer, a failed provider call fails the request or loses the message, and nothing remembers what was sent.
- What breaks next
- At 3 times the load, 300 notifications per second, the API is asked for 300 per second and can do 250: it is at 120% and 17% of the requests fail. The database and the providers are far from their limits.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- Notification APIHealthy40% of its capacity
- p95, whole request
- 315.8 s
- p99, whole request
- 677 s
- Requests served
- 100%100 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Producer services | Healthy | <1% | 100 | 100 | 0 | 0 ms | 0 ms | 0 ms |
| Notification API | Healthy | 40% | 100 | 100 | 0 | 89 ms | 383 ms | 589 ms |
| Preferences database | Healthy | 13% | 100 | 100 | 0 | 3.5 ms | 15 ms | 23 ms |
| Push provider | Healthy | 1% | 75 | 75 | 0 | 6.3 s | 27.2 s | 41.9 s |
| Email provider | Healthy | 4% | 30 | 30 | 0 | 86.6 s | 374.5 s | 575.6 s |
| SMS provider | Healthy | 2% | 5 | 5 | 0 | 231 s | 998.6 s | 1,535.1 s |
- Traffic
- 100 req/s
- Successful
- 100 req/s
- Error rate
- 0%
- Mean latency
- 61.1 s
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: send from the request | 100 req/s | 100 req/sNotification API: 40%none fail | 300 req/sNotification API: 120%17% fail | 1K req/sNotification API: 400%75% fail |
| 2. Put a queue between the request and the sending | 300 req/s | 300 req/sPreferences database: 38%none fail | 900 req/sPreferences database: 113%none fail | 3K req/sPreferences database: 375%none fail |
| 3. Cache the preferences | 1K req/s | 1K req/sEmail provider: 38%none fail | 3K req/sEmail provider: 113%none fail | 10K req/sEmail provider: 375%none fail |
| 4. Add a second email provider | 3K req/s | 3K req/sSMS provider: 50%none fail | 9K req/sSMS provider: 150%none fail | 30K req/sSMS provider: 356%29% fail |
| 5. Keep a delivery log, and send SMS only when push is not enough | 9K req/s | 9K req/sEmail provider: 68%none fail | 27K req/sEmail provider: 160%21% fail | 90K req/sNotification API: 422%76% fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- For every 100 notifications, the service sends 75 push messages, 30 emails and 5 SMS messages (1.1 messages per notification, because some users receive two channels), and reads the user’s preferences once for each. In the last stage SMS drops to 2 in 100. These ratios are teaching figures.
- The outside providers limit how many messages per second the service may send: 11,000 for push, 800 for email (3,200 for a second provider) and 300 for SMS. Every number (service times, limits, the cache hit ratio of 98%) is illustrative model output, not the limit or the speed of a real provider.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A campaign that sends to millions of users at once is a burst and is not modelled, nor is a queue that grows for minutes.
- The queue is drawn as a hand-over: a producer gets its answer when the notification is accepted, so the failure rate in the lab does not show notifications that wait in the queue or are delayed behind a slow provider.
- The API servers and the workers are drawn large enough not to be the limit after the first stage, because they mostly wait for providers. The limits that matter are the database, the providers and the delivery log.
- Retries, backoff and dead letters are not drawn: they are in the lesson. Templates, translation, quiet hours, priorities, expired device tokens and several regions are not modelled.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, send from the request. The API reads the preferences, calls the providers and answers when they have answered. It is held for about 3 ms of its own work, plus 60 ms for a push message, 200 ms for an email and 400 ms for an SMS: weighted by the mix, about 128 ms for each notification. Two servers working on 16 requests at a time can do about 250 per second, and at 100 per second they are at 40%. At 3 times the load the API is asked for 300 per second and is at 120%: 17% of the requests fail. The number that ends the stage is the time spent waiting for the providers.
Stage 2, a queue. The API puts the notification in a queue and answers at once, and 16 workers that each keep 256 sends in flight do the waiting. The API now needs about 3 ms for each notification, and at 300 notifications per second nothing is above 38%. The next limit is the preferences database: at 3 times the load it is asked for 900 reads per second and can do 800, which is 113%. The lab shows 0% of requests failing, because producers wait only for the queue. That is the new cost: the answer means “accepted”, and a limit further along shows up as delay and not as an error.
Stage 3, a preferences cache. Preferences change a few times a year and are read for every notification, so 98% of the reads are answered by a cache: 18 reads per second reach the database at 900 notifications, and 60 at 3,000, which is 8%. The stage’s price is staleness, covered below. Now the first outside limit is reached. At 3 times the load, 3,000 notifications per second, the email provider is asked for 900 emails per second and accepts 800, which is 113%.
Stage 4, a second email provider. Email goes to two providers with limits of 800 and 3,200 per second, in that proportion. Together they accept 4,000, and at 9,000 notifications per second the 2,700 emails are 68% of each limit. The price is a second contract and a second sender reputation, and a failover that needs headroom you pay for: if the larger provider fails, the other takes only 800 of the 2,700. The next limit is SMS: at 3 times the load, 9,000 per second, it is asked for 450 messages per second against 300, which is 150%, while push is at 61%.
Stage 5, a delivery log, and SMS only when needed. A log records the state of every delivery, so a worker can claim a delivery before sending it, and so the system knows whether a push message was acknowledged. With that, SMS is sent only for critical notifications or when push was not acknowledged in time. In the model, that is 2 SMS messages in 100 notifications instead of 5, so 180 per second at 9,000, which is 60% of the limit. The log takes 2.2 operations for each notification, 19,800 per second at 9,000, which is 31% of its 64,000. At 3 times the load, 27,000 per second, the API is at 127% and the providers are over: email 160%, push 145% and SMS 142%, and 21% of the requests fail. More providers and accounts, a rate limiter in front of each provider and priority lanes come next.
Fan-out over channels
Section titled “Fan-out over channels”One request becomes up to three messages, each on a different pipe with its own speed, limit and failure behaviour. The worker, not the producer, decides which. It reads the user’s preferences, drops the channels that are off, and then makes one delivery for each remaining channel: the key of the delivery is the notification id and the channel. Push is fast and cheap, so it goes first; email is slower and rate-limited; SMS is slowest and costs money for every message. Each delivery is retried and tracked on its own, because the push message can succeed while the email fails, and the notification as a whole is only as done as its deliveries.
Two other fan-outs exist and are different. A campaign expands one request into millions of notifications, which a fan-out job produces from a list of users at a rate you control, and which must go into its own low-priority lane. And a notification for a group expands into one per member. Both happen before the flow described here, which starts from one notification for one user.
Retries
Section titled “Retries”A provider refuses messages for ordinary reasons: it is throttling you, it is briefly down, a device token has expired. The worker has to tell them apart. A rate-limit answer, which in HTTP is a 429 with a retry delay (Firebase’s documentation describes exactly this for FCM), means wait for the stated time and slow down. A temporary error means retry later. A permanent error, such as an invalid token, means do not retry and remove the token.
Retry with exponential backoff and jitter, not at once. Without them the retries arrive together and add to the load on a provider that is already refusing: if half of the calls fail and each is retried up to 3 times immediately, a call makes (1 − 0.5^4) ÷ 0.5 = 1.875 attempts, so the 2,700 emails per second of the peak become about 5,060 attempts per second against a limit of 4,000. The Amazon Builders’ Library explains why retries must be limited and spread out, and Firebase’s scaling guide calls the first effect retry amplification. Limit the retries with a budget (a token bucket on retries, as the library describes), and after a few attempts move the message to a dead-letter queue where a person or a job can look at it. Never retry forever.
Never twice
Section titled “Never twice”The queue delivers a message at least once. A worker can send an email, crash before it tells the queue, and the queue will deliver the message again. A timeout is worse: the provider may have sent the email even though the worker never heard back. The Amazon Builders’ Library makes the same point, that a timeout or failure does not mean the side effects did not happen. Two layers prevent a duplicate.
At the front, the producer’s Idempotency-Key makes a retried POST return the same notification, as in the idempotency keys lesson. Behind the queue, the worker claims the delivery in the delivery log before it sends: a conditional write that succeeds only if no record exists for this notification and channel. If it fails, someone else has the delivery, and the worker drops the message. After the send, the worker marks the delivery as sent with the provider’s message id. This is the idempotent consumer pattern with the log as the memory.
The claim leaves a choice, and it is a real one. A worker that claims and then crashes before sending leaves a delivery that is claimed and never sent. To avoid the loss, a claim expires after some time, and another worker may take it; then the case where the first worker did send before crashing produces a duplicate. You cannot have no loss and no duplicate when the send itself cannot be made idempotent, and many providers give you no way to do it. So you choose per message. A one-time code that is sent twice is harmless and one that is lost is not; a payment confirmation might be the other way round.
What happens if a preference is stale
Section titled “What happens if a preference is stale”A user opens the settings and turns email off. The change goes to the database, but the preferences cache still holds the old entry, and for the next few minutes the user receives emails they have opted out of. In the US, the CAN-SPAM Act makes it unlawful to send commercial email more than 10 business days after a request to stop, so a few minutes is within that rule and is still a poor experience for the user. Invalidate the cache entry in the same operation that writes the change, keep the expiry short as the backstop, and for the channels where an opt-out is strict, check the database for the final decision on bulk sends instead of trusting the cache.
What happens if a provider refuses everything
Section titled “What happens if a provider refuses everything”The email provider answers every call with an error for ten minutes. Without a plan, workers retry and fill the queue with retries. With one, a circuit breaker per provider stops calling it after a run of failures, the messages for that channel stay in the queue (with a limit on how long they may wait, since an email about a delivery that happened an hour ago is useless), and the other channels continue. If there is a second provider, the breaker sends that provider’s share to the other one, which can take only what its limit allows; in the lab’s design, the larger provider’s 3,200 per second cannot be replaced by the smaller one’s 800. When the provider returns, workers drain the backlog at the provider’s limit and no faster, and a rate limiter in front of each provider enforces that.
What happens if a campaign starts
Section titled “What happens if a campaign starts”A marketing campaign for 10 million users is released at the top of the hour. If it shares a queue with the one-time codes, a code requested at 10:00:01 waits behind millions of messages and arrives after its user has given up. Give urgent traffic its own lane, a separate queue and workers, and a reserved share of each provider’s limit. Release the campaign at a rate below the limit, over a delivery window the business can accept. Firebase’s scaling guide calls sending as fast as the systems allow an anti-pattern, and suggests asking whether a 5-minute window would do and whether customers can be segmented by priority. Bulk traffic then takes what is left, and urgent traffic never waits.
Trade-offs
Section titled “Trade-offs”| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| A queue between the request and the sending | Producers are not held by slow providers, and bursts wait instead of failing | “Accepted” is not “delivered”, a backlog to watch, and duplicates from at-least-once delivery | When the producer must know the outcome at once (a login code that blocks the user), send directly and accept the coupling |
| A cache of preferences | Almost no load on the database, and sends do not wait for a read | A stale preference sends a message that was turned off | When an opt-out must apply at once, read the database for those channels |
| Two providers for a channel | More capacity, and a provider can fail without stopping the channel | Two contracts, two reputations, and a failover that needs paid headroom | Low volume, where one provider’s limit is far above your peak |
| A delivery log | No second send, a record of what happened, and the memory that escalation needs | A write for every delivery on the path of every send, and a choice between loss and duplicate when the claim fails | Messages where a duplicate does no harm and a log is not worth its cost: send and forget |
| SMS only when push is not enough | Far fewer messages on the costly, slowest channel | A delay before the SMS, and users without push get it later | Notifications that must reach a person within seconds regardless of the app, such as a security code |
Defend your design
Section titled “Defend your design”An interviewer asks for this system in 45 minutes. A good answer starts with the numbers and notices that the providers’ limits, not the servers, are what bound the design; puts a queue in front of the pipes; covers preferences, retries and duplicates in turn; and says what happens to an urgent message while a campaign runs. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design a notification system that sends push messages, emails and SMS to users on behalf of other services in the company. Walk through your design.
Assume 250 million notifications a day, with a peak about three times the average. Email and SMS go through outside providers that limit how fast you may send. Users can turn off any channel, and a few notifications, such as one-time codes, are urgent.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 80 characters written to unlock the strong answer
- 250 million notifications a day are about 2,900 per second on average and 9,000 at the peak, which is 6,750 push messages, 2,700 emails and 450 SMS messages per second. The providers’ sending limits, not the servers, bound the design.
- Sending from the request holds the API for about 128 ms per notification: two servers do about 250 per second and are at 120% at 300. A queue and workers that each keep 256 sends in flight remove that wait.
- Preferences are read for every notification: a cache with a 98% hit ratio takes 900 reads per second to 18. A stale entry sends a message the user turned off, so invalidate on change.
- The single email provider (800 per second) is overloaded at 900 emails, and two providers (800 and 3,200) bring the peak’s 2,700 to 68%. SMS at 450 per second against 300 is the next limit, and a delivery log with escalation cuts it to 180.
- Retry with backoff and jitter and a budget: immediate retries at a 50% failure rate make 1.875 attempts per call and turn 2,700 emails per second into about 5,060 attempts. Move what keeps failing to a dead-letter queue.
- The queue delivers at least once, so claim each delivery by notification id and channel in a log before sending. A failed claim forces a choice between a loss and a duplicate, made per message.
Next: Chat, which delivers messages between people in order, in real time and to devices that are offline.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.