Sub topic 16
Scaling and reliability
This chapter covers how a notification system keeps working as load grows and as parts of it fail. It assumes you know message queues, key-value stores, and the retry and idempotency ideas from earlier chapters. The code is short Python.
What scaling and reliability mean here
Scaling is handling more events per second. Reliability is delivering each notification at least once, and not more than once from the user's point of view, even when machines, queues, or providers fail.
The two goals pull against each other. Retries improve delivery but create duplicates. Buffering absorbs bursts but adds delay. Most decisions in this chapter trade one against the other.
A useful way to start is to name the numbers. Suppose the system has 10 million users and sends 50 million notifications a day. That averages about 580 per second. A marketing campaign or a breaking-news alert can push the peak to 50,000 per second for a few minutes. Design for the peak, not the average.
Scaling each layer independently
The architecture from earlier chapters separates ingestion, queues, and channel workers. That separation is the main scaling tool, because each layer scales on its own signal.
| Layer | Scale by | Signal to watch |
|---|---|---|
| Ingestion API | Adding stateless instances behind a load balancer | Request latency, CPU |
| Queue | Adding partitions or shards | Queue depth, publish latency |
| Channel workers | Adding consumers per channel | Queue lag, age of oldest message |
| Preference and token stores | Read replicas, caching, sharding by user id | Read latency, cache hit rate |
| Provider calls | Parallel connections, rate-limit budgets | Provider error rate, throttling responses |
Keep the ingestion API stateless so any instance can handle any request. Keep workers stateless too. Store state in the queue, the database, or the shared deduplication store.
Partitioning
A partitioned queue splits messages across several independent logs. Choose the partition key deliberately.
- Partition by
user_idif you need per-user ordering, for example "order placed" before "order shipped". All events for one user land on one partition and are handled in order. - Partition by
event_idfor the most even spread when ordering does not matter. - Beware hot keys. One very active user or one tenant sending a huge campaign can overload a single partition while others sit idle.
Autoscale workers on queue lag, meaning how far behind the consumers are, not only on CPU. A worker waiting on a slow provider uses little CPU but is still the bottleneck.
Absorbing bursts
A queue is a buffer. When 50,000 events arrive in a second and workers handle 5,000, the queue grows and drains later. This is acceptable for low-priority traffic and unacceptable for a one-time passcode.
Three practices keep bursts from harming urgent traffic:
- Use separate queues per priority and per channel, so a bulk email campaign cannot delay a security SMS.
- Give each queue its own worker pool, so a slow provider only stalls its own pool.
- Set a maximum age on low-priority messages. A "flash sale ends in 10 minutes" notification that is 2 hours old should be dropped, not sent.
The expiry check is small:
import time
def is_expired(enqueued_at, max_age_seconds, now=None):
"""Return True if a queued message is too old to be worth sending."""
now = time.time() if now is None else now
return (now - enqueued_at) > max_age_seconds
print(is_expired(enqueued_at=time.time() - 7200, max_age_seconds=600))Failure isolation
A failure in one place should not spread. The common tools:
- Separate pools per provider and channel. If the SMS provider hangs, email workers keep running.
- Timeouts on every external call. Without a timeout, a hung provider ties up worker threads until the pool is exhausted.
- Circuit breakers. After repeated failures, stop calling the provider for a short time, then probe with a few requests.
- Provider fallback. Keep a secondary provider for critical channels such as SMS. Route to it when the primary's circuit is open.
A circuit breaker has three states.
A minimal implementation:
import time
class CircuitBreaker:
def __init__(self, failure_threshold=5, cooldown=30.0):
self.failure_threshold = failure_threshold
self.cooldown = cooldown
self.failures = 0
self.opened_at = None
def allow(self):
if self.opened_at is None:
return True
if time.time() - self.opened_at >= self.cooldown:
return True # half-open: let a probe through
return False
def record_success(self):
self.failures = 0
self.opened_at = None
def record_failure(self):
self.failures += 1
if self.failures >= self.failure_threshold:
self.opened_at = time.time()When allow() returns False, do not drop the message. Leave it in the queue or re-enqueue it with a delay. While the breaker is open, retrying only adds load to a provider that is already struggling.
Dead-letter queues
Some messages fail every time, such as a malformed payload or a template bug. After the maximum retry attempts, move the message to a dead-letter queue (DLQ). The DLQ keeps the message for inspection and replay, and it stops a poison message from blocking the main queue.
Alert on DLQ growth. A rising DLQ usually means a code or data bug, not a provider outage. After you fix the cause, replay the messages through the normal path so deduplication still applies.
Delivery guarantees and duplicates
Most queues give at-least-once delivery. A worker can send a notification, crash before acknowledging the queue message, and have the message delivered again. Exactly-once delivery to a third-party provider is not achievable in general, so you design for at-least-once with deduplication.
The sequence that causes a duplicate:
This design has its own edge case. If the worker claims the key and then crashes before the provider call, the redelivered message is skipped and the notification is lost. Choose which error you prefer:
- Claim first, then send risks a missed notification.
- Send first, then record risks a duplicate.
For most notifications, a rare duplicate is better than a lost message. For payment confirmations, many teams accept a duplicate. For marketing messages, a miss is cheaper. A common refinement is to store a state such as in_progress with a short expiry, so a crashed claim becomes retryable after the expiry passes.
Data stores and regions
Several stores sit on the hot path: preferences, device tokens, deduplication keys, and delivery status.
- Cache preferences with a short time to live. A stale cache might send one notification after an opt-out, so keep the time to live short, and check the authoritative store for critical or legally sensitive types.
- Expire deduplication keys. Keep them as long as the longest plausible redelivery or retry window, such as 24 hours.
- Write delivery status asynchronously so a slow status database never slows sending.
- Run in more than one availability zone. For stronger guarantees, run in multiple regions with a failover plan. Multi-region setups raise the duplicate risk, because a failover can replay messages. Keep deduplication keys replicated or accept a small duplicate window.
Graceful degradation
When the system is overloaded, decide in advance what to shed. A sensible order:
- Pause or delay bulk and marketing traffic.
- Delay normal traffic and extend retry delays.
- Protect critical traffic such as one-time passcodes and security alerts to the end.
Back-pressure on the ingestion API helps too. Return 429 Too Many Requests with a Retry-After header to producers that exceed their quota, so one noisy service cannot flood the pipeline.
Common mistakes
- Autoscaling workers without raising provider rate limits, which turns scaling into a flood of throttling errors.
- Using one shared queue for all priorities.
- Retrying with no cap, which keeps a failing provider overloaded.
- Treating the DLQ as a trash can that nobody reads.
- Testing only the happy path. Run failure drills: kill a worker mid-send, block the provider, and fill the queue.
Exercise
A worker claims a deduplication key, calls the SMS provider, and crashes before acknowledging the queue message. The queue redelivers the message. What happens, and what happens in the opposite case, where the worker crashes after claiming the key but before calling the provider?
Show answer
In the first case the redelivered message finds the key already claimed and is skipped, so the user gets one SMS. In the second case the redelivered message also finds the key claimed and is skipped, but the SMS was never sent, so the notification is lost. To reduce this risk, store an in_progress state with a short expiry so that an unfinished claim can be retried after the expiry.
Exercise
Why should you autoscale channel workers on queue lag instead of only on CPU?
Show answer
Workers that wait on slow provider responses spend most of their time idle, so CPU stays low even when the queue is growing. Queue lag, or the age of the oldest message, shows directly how far behind the consumers are.