Design a notification service
medium 85 minDesign the classes that tell people things by push, text message and email: routes from personal wishes, quiet hours, retries, fallback to another channel, and protection against repeats.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
A notification service, as a class design, takes an event for a person and gets one message to them in the way they chose. It decides the route, waits when it must, tries a slow outside channel, and remembers how it ended.
Underneath it is a work queue with due times. Each item carries an ordered list of things to try. Failures are of two kinds, and the kind decides what is tried next.
This page is about one process: objects, locks and keys. Brokers, partitions and millions of messages are the subject of the system design version.
Why it exists
Without it, every module of a product talks to vendors itself. Wishes are honoured by some and ignored by others, night is forgotten, and each retry loop has its own bug.
It is a favourite exercise because the first design is nearly always a class tree that mixes channel and content. Seeing why that tree is wrong is the lesson.
It is also a compact course in failure: temporary and permanent, accepted and delivered, once and at least once. Each of these words has a place in the code.
A short history
1792
The Chappe brothers show an optical telegraph in France: arms on towers, read by telescope. A channel with a protocol, and useless in fog.
1971
Ray Tomlinson sends the first mail between users on different hosts of the ARPANET.
1992
The first text message, "Merry Christmas", is sent over the Vodafone network in the United Kingdom on 3 December.
2009
Apple's push notification service starts with iPhone OS 3 on 17 June.
2016
RFC 8030 describes push over HTTP for the web, with a time to live, an urgency and a topic that lets a newer message replace an older one.
2017
RFC 8058 defines one-click unsubscribe for email: two headers, and no login page in between.
Words to know
- Channel
- A way to reach a person: push, text message, email.
- Route
- The ordered channels for one person and one kind of notice.
- Stop
- One entry of a route, with address and text.
- Fallback
- Trying the next stop after one is given up.
- Quiet hours
- A daily window in which only urgent kinds are sent.
- Backoff
- Waiting longer after each failed try.
- Jitter
- Randomness in the wait, so that retries do not come together.
- Idempotency key
- A name for an event. The same name twice is the same event.
- Receipt
- A later message from the vendor about what became of ours.
- Lease
- A claim that ends by itself if its owner disappears.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Accept. Key, route, texts and the earliest moment; then the caller is free
Understand it
Start here
Max and three neighbours
List, stops, quiet note, ticks: these are Profile, Stop, the due time and the key.
What an interviewer looks for here
Separating questions
What happened, who wants it, over which channel, when, and how often to try. Five questions, five places.
A clean seam
One interface for channels. The interviewer will add one, and only a new class may appear.
Failure as a design input
Not now and never are different. Most candidates have one
catchfor both.Never twice by accident
Keys, and an honest word about the crash that no key can repair.
Fast accept, slow work
The purchase must not wait for a vendor. Accept, store, return.
Scope
One process and its classes. Queues between machines, sharding and delivery at scale belong to the system design version.
Questions
Six questions, and what each answer changes
| Ask | If the answer is | Then the design has |
|---|---|---|
| Which channels, and will more come? | Push, text message, email, and yes | A Sender interface with one method |
| All channels, or the first that works? | The first that works | An ordered list of stops and a cursor |
| Who decides the channel? | The person, for each kind of notice | A profile, not parameters of the call |
| May a message be late? Lost? Doubled? | Late is fine, lost is not, doubled is bad | A store, retries and a key |
| Are there hours without noise? | 22 to 7, except for login codes | An earliest moment, and an urgent flag |
| Does the caller wait? | No | Accept and work are two methods |
Routing
Who gets what, and how
The route is wishes, filtered by addresses
| Person and kind | Wishes | Addresses | Route |
|---|---|---|---|
| Asha, code | push, sms | push, sms | push, then sms |
| Noor, order | push, email | push, email | push, then email |
| Noor, offer | none | push, email | nothing: skipped |
| Lee, code | push, sms | sms only | sms |
From an event to a try
Design, first try
The design most people draw first
A manager with a method for each vendor, and a tree of message classes. It is worth drawing for a minute, because it shows which questions were mixed.
The design to avoid: one manager, and a class for every combination
1/3A manager that knows everybody
Three vendor clients, the night rule, the retry loop and the log in one class. A new channel, a new rule and a new vendor all edit the same file.
usesextends (is a)
def notify(self, user, type, text): if type == "email": self.smtp.send(user.email, text) elif type == "sms" and not self.is_night(): for _ in range(3): try: self.sms.send(user.phone, text) break except Exception: time.sleep(5) # the buyer waits hereDesign, better
The design to reach
The service coordinates. The profile answers who and when. Templates answer what. Backoff answers how often. A sender answers how, for one channel. One small class changes over time: the delivery.
The design to reach: one event, a list of stops, one small sender for each channel
1/6Two public verbs
notify accepts quickly and stores. workOne does one slow thing later. The caller who buys a book does not wait for a text message.
usesowns (dies together)has (lives on)implements
Roles
What each class owns
| Class | Knows | Does not know |
|---|---|---|
Notice | What happened, to whom, in data | Text, channel, address |
Profile | Addresses, wishes, quiet hours | Messages, retries |
Templates | One text for each kind and channel | People |
Sender | One vendor | Profiles, retries, other channels |
Backoff | How long to wait after which try | What is being tried |
Delivery | Where one notice is on its way | How to send it |
NotificationService | Which deliveries exist and which are due | Any vendor, any sentence |
States
The life of a delivery
One delivery
That last sentence is the invariant of the whole class: in the heap once if waiting, held by one worker if sending, and nowhere else otherwise. Check every line of workOne against it.
The hard part
Not now is not never
The sender translates, the service decides
| What the vendor says | Kind | What we do |
|---|---|---|
| Timed out, 503, connection reset | Temporary | Same stop, later |
| 429, too many requests | Temporary | Same stop, after the time it names |
| Device not registered any more | Permanent | Next stop now, and delete the address |
| Number has opted out | Permanent | Next stop now, and store the wish |
| Our key is wrong, 401 | Permanent for this message, and an alarm | Not the person's fault: page somebody |
| An error nobody has seen | Unknown | Treat as permanent, log loudly |
A login code over a dead push address
How do you keep the same news from arriving twice?
BreaksLook whether it was sent
- How
if not was_sent(key): send(); mark_sent(key).- Limit
- Two callers pass the question before either marks. And a crash after the send forgets the mark.
- Choose when
- Never, although it passes every test with one thread.
WorksClaim the key first
- How
- Store the key and the delivery in one step under the lock. Whoever stores it owns it.
- Limit
- Covers callers that repeat. A crash between the vendor's yes and our note is still open.
- Choose when
- The right first answer. It removes nearly all doubles.
StrongClaim, and pass the key on
- How
- As before, and the same key goes to the vendor with each try, so it can drop the copy. Where the vendor cannot, say which side you choose: perhaps twice for a login code, perhaps never for an offer.
- Limit
- The promise ends where the vendor's memory ends.
- Choose when
- Whenever they ask about a crash. Name the gap before they do.
Time
Quiet hours are a moment, not a question
Count how far the clock is into the window. Let the window begin at q, end at e and last w seconds.
Seconds into the window, across midnight
Do
- Let the caller say what happened
- Let the profile choose the channel
- Render before you store
- Split errors into not now and never
- Send without a lock
- Put the quiet rule where entries join the heap
- Store skipped and failed, with a log
Do not
- Subclass messages by channel and by urgency
- Sleep between tries in a thread
- Retry a wrong number
- Return true from notify
- Drop a message because it is night
- Make the key inside the service
- Hold the lock while a vendor thinks
Which part changes?
Summary
The whole topic in one minute.
The caller says what happened. The profile turns that into an ordered route and an earliest moment. Templates make the words. A delivery remembers where the notice is on its way, and senders do one try each.
Accept renders, claims the key and queues. Work pops under the lock, sends without it and settles under it: sent, again later, next stop, or failed. The quiet rule sits where entries join the heap, so nothing passes it by.
- A notice says what happened, in data. It has no text and no channel.
- The profile turns a kind into an ordered route, and a time into the earliest allowed time.
- Accept is fast and complete: render, claim the key, queue. Work is slow and separate.
- Temporary failures stay on the stop. Permanent ones move to the next. No stop left is failed.
- Pop under the lock, send without it, settle under it. Whoever popped owns the delivery.
- Skipped, sent and failed are final, and each is stored with a log.
- One key for a caller's event, one for each try's channel. Say honestly what a crash can still double.
Sources
- Laravel: notifications
- Symfony: Notifier
- Prometheus: Alertmanager
- Firebase: collapsible messages
- Firebase: sending at scale
- Apple: sending notification requests to APNs
- RFC 8030: Generic Event Delivery Using HTTP Push
- RFC 8058: One-Click Unsubscribe
- Amazon SNS: message delivery retries
- Android: create and manage notification channels
- Apprise
- Python: zoneinfo
- Wikipedia: Optical telegraph
- Wikipedia: SMS
- Wikipedia: Ray Tomlinson
- Wikipedia: Apple Push Notification service