AlgoViz

Design a notification service

medium 85 min

Design 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

0:00 / 4:50

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

  1. 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.

  2. 1971

    Ray Tomlinson sends the first mail between users on different hosts of the ARPANET.

  3. 1992

    The first text message, "Merry Christmas", is sent over the Vodafone network in the United Kingdom on 3 December.

  4. 2009

    Apple's push notification service starts with iPhone OS 3 on 17 June.

  5. 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.

  6. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Accept. Key, route, texts and the earliest moment; then the caller is free

Understand it

Start here

Max and three neighbours

One shopkeeper, three ways to tell the hill
AshaLeeNoorBREADWho likes whatAshaflag, then bellNoorbellLeelanternThe bread isready!

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 catch for 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

AskIf the answer isThen the design has
Which channels, and will more come?Push, text message, email, and yesA Sender interface with one method
All channels, or the first that works?The first that worksAn ordered list of stops and a cursor
Who decides the channel?The person, for each kind of noticeA profile, not parameters of the call
May a message be late? Lost? Doubled?Late is fine, lost is not, doubled is badA store, retries and a key
Are there hours without noise?22 to 7, except for login codesAn earliest moment, and an urgent flag
Does the caller wait?NoAccept and work are two methods

Routing

Who gets what, and how

The route is wishes, filtered by addresses

Person and kindWishesAddressesRoute
Asha, codepush, smspush, smspush, then sms
Noor, orderpush, emailpush, emailpush, then email
Noor, offernonepush, emailnothing: skipped
Lee, codepush, smssms onlysms
The last row is a common edge. Lee wants push first and has no device yet. The route is shorter, not broken.

From an event to a try

Every question is asked once, in this order. The key comes first, because a repeat must not even cost a look at the profile's rules.

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

NotificationManager- smtp, smsClient, pushClient+ notify(user, type, text)- sendEmail(), sendSms()- isNight(), retry(), log()

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)

What is told, how it travels and when it may travel are three questions. Each deserves its own answer.
Python
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 here
Five mistakes: the caller picks the channel, night drops the message, all errors look alike, sleeping in the caller's thread, and a break after which nobody knows whether it was sent.

Design, 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

NotificationService- due: Heap<time, Delivery>- byKey: Map<key, Delivery>- lock+ notify(notice)+ workOne(): bool+ report(key): Report

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

A new channel is one class and some texts. A new wish is a row in a profile. Neither edits the service.

Roles

What each class owns

ClassKnowsDoes not know
NoticeWhat happened, to whom, in dataText, channel, address
ProfileAddresses, wishes, quiet hoursMessages, retries
TemplatesOne text for each kind and channelPeople
SenderOne vendorProfiles, retries, other channels
BackoffHow long to wait after which tryWhat is being tried
DeliveryWhere one notice is on its wayHow to send it
NotificationServiceWhich deliveries exist and which are dueAny vendor, any sentence

States

The life of a delivery

One delivery

Waiting and Sending repeat. The other three are final. A delivery is in the heap exactly while it is waiting.

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 saysKindWhat we do
Timed out, 503, connection resetTemporarySame stop, later
429, too many requestsTemporarySame stop, after the time it names
Device not registered any morePermanentNext stop now, and delete the address
Number has opted outPermanentNext stop now, and store the wish
Our key is wrong, 401Permanent for this message, and an alarmNot the person's fault: page somebody
An error nobody has seenUnknownTreat as permanent, log loudly

A login code over a dead push address

The login page is free after the second arrow. The rest happens without it.

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

i=(t−q) mod 86400,w=(e−q) mod 86400,due={t+(w−i)i<wtotherwisei = (t - q) \bmod 86400, \qquad w = (e - q) \bmod 86400, \qquad \text{due} = \begin{cases} t + (w - i) & i < w \\ t & \text{otherwise} \end{cases}
22:00 to 07:00: w = 32400. At 23:00, i = 3600, so due is 28800 seconds later: 07:00. At 07:00, i = 32400, not less than w: due now.

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?

If the arrow ever points at NotificationService, look again.

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