Sub topic 3
A high-level architecture
This chapter assumes you know how HTTP APIs work, what a message queue is, and how to read short Python snippets. It shows how the parts of a notification system fit together. Later chapters cover each part in detail.
What the architecture must achieve
The requirements chapter fixed the goals. The architecture has to meet three of them:
- Producers, such as the order service, must not wait for a provider like an email gateway. A slow provider must not slow checkout.
- A failure in one channel must not stop the others. If SMS is down, push and email should still go out.
- The system must absorb bursts, such as a flash sale that triggers a million messages in a few minutes.
The usual answer is to split the pipeline into stages joined by queues. Each stage does one job, scales on its own, and can fail without taking down the stages around it.
The components
The diagram shows the path of one event from a producer to a user's device.
Each component has a narrow responsibility.
| Component | Responsibility | State it owns |
|---|---|---|
| Ingestion API | Authenticate producers, validate events, assign or check the event id, acknowledge quickly | None, or a short-lived record of event ids |
| Event queue | Buffer accepted events so producers are decoupled from routing | Messages in flight |
| Routing service | Look up preferences, apply quiet hours and opt-outs, and fan one event out to per-channel messages | None. It reads the preference store |
| Channel queues | Hold work for one channel so each channel has its own backlog | Messages in flight |
| Channel workers | Render the template, call the provider, retry transient failures, record the result | Per-send status |
| Providers | Deliver to the device or mailbox (APNs, FCM, an SMS gateway, an email service) | Outside your system |
| Delivery tracking store | Record states such as queued, sent, delivered, failed | Status history per message |
Why the event queue sits before routing
You could let the ingestion API do the routing and write straight to the channel queues. That is simpler, but the API's latency would then depend on the preference lookup. A preference store outage would also turn into producer errors. With an event queue in between, the API only has to validate and enqueue. Routing can fall behind during a spike without any producer noticing.
The cost is extra latency and one more thing to operate. For most systems that cost is acceptable. A small system with one channel and low volume may reasonably skip this queue.
Why each channel has its own queue
Channels differ in speed, cost and failure behavior. Email providers accept large batches. SMS is slow and expensive and often rate limited. Push is fast but can fail for individual tokens. If all channels shared one queue, a stalled SMS provider would block every push message behind it. This is called head-of-line blocking. Separate queues give you:
- Failure isolation. A backlog in one queue does not delay the others.
- Independent scaling. You add email workers without adding SMS workers.
- Channel-specific limits. Each worker pool can respect its own provider's rate limits.
Fan-out: one event, many messages
An event describes something that happened. A message is one send on one channel to one user. The routing service turns one event into zero or more messages. Zero is a valid result: the user may have opted out of this type, or quiet hours may have removed every intrusive channel.
This example reuses the event shape and the choose_channels function from the spine, and adds a fan_out function that builds the per-channel messages. Each message carries a deduplication key built from the event, user and channel, which later chapters rely on to avoid double sends.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class NotificationEvent:
event_id: str
user_id: str
type: str
priority: str = "normal"
payload: dict = field(default_factory=dict)
def choose_channels(event, prefs, quiet_hours_active):
allowed = list(prefs.get(event.type, []))
if quiet_hours_active and event.priority != "critical":
allowed = [c for c in allowed if c == "in_app"]
return allowed
def fan_out(event, prefs, quiet_hours_active):
"""Turn one event into one message per chosen channel."""
messages = []
for channel in choose_channels(event, prefs, quiet_hours_active):
messages.append(
{
"queue": f"notifications.{channel}",
"dedup_key": f"{event.event_id}:{event.user_id}:{channel}",
"type": event.type,
"priority": event.priority,
"payload": event.payload,
}
)
return messages
event = NotificationEvent(
event_id="evt-1001",
user_id="user-42",
type="order_shipped",
payload={"order_id": "A-77"},
)
prefs = {"order_shipped": ["push", "email", "in_app"]}
for quiet in (False, True):
print("quiet hours:", quiet)
for message in fan_out(event, prefs, quiet):
print(" ", message["queue"], message["dedup_key"])With quiet hours off, the event produces three messages. With quiet hours on, only the in-app message remains.
Delivery semantics: at least once
Queues and providers can both fail after doing the work but before reporting success. A worker may call the provider, crash, and never acknowledge the queue message. The queue then redelivers the message, and the user gets two notifications.
You cannot remove this uncertainty, so the architecture picks a delivery guarantee on purpose:
- At most once: acknowledge the queue message before sending. A crash loses the notification.
- At least once: acknowledge after sending. A crash can cause a duplicate.
Most notification systems choose at least once and then reduce duplicates with idempotency keys. Losing a password reset or a payment alert is usually worse than showing a duplicate shipping notice. The deduplication key in the fan_out output is the hook for this. Later chapters cover how to enforce it.
Synchronous versus asynchronous boundaries
Only one boundary is synchronous: the call from the producer to the ingestion API. Everything after the API's acknowledgment is asynchronous. The API's response therefore means "accepted", not "delivered". Producers that need the outcome should read it from delivery tracking or receive a callback, not expect it in the HTTP response.
Return a clear status code. A 202 Accepted with the event id tells the producer the event is queued. If the API cannot write to the event queue, it must return an error so the producer can retry. Silently dropping the event breaks the whole contract.
Common mistakes
- Rendering templates in the routing service. Rendering depends on the channel and locale, so do it in the channel worker. Routing then stays small and fast.
- One shared queue for all channels. One slow provider then delays everything.
- Letting producers pick channels. Producers know what happened, not what the user wants. Channel choice belongs to the routing service, which can read preferences.
- Treating "accepted" as "delivered". Track delivery states separately, as the tracking chapter explains.
- No dead-letter path. Messages that fail repeatedly need somewhere to go for inspection, or they will be retried forever or silently lost.
Exercise
During a sale, the SMS provider slows to a crawl and the SMS queue grows to hundreds of thousands of messages. Which design choices keep push and email notifications flowing, and which keep producers from seeing errors?
Show answer
Each channel has its own queue and worker pool, so the SMS backlog cannot block push or email workers (failure isolation). Producers only talk to the ingestion API, which enqueues to the event queue and returns 202 Accepted without waiting for any provider, so the SMS slowdown never reaches them. The routing service keeps writing SMS messages to the SMS queue while its workers drain it slowly.
Exercise
A push worker sends a message to the provider and then crashes before acknowledging the queue message. What happens next, and which field in the fan-out output helps prevent a duplicate notification?
Show answer
The queue redelivers the message to another worker, because the delivery guarantee is at least once. The dedup_key (event id, user id and channel) lets the next worker check whether the send was already claimed and skip it if so.