Sub topic 7
Decoupling with queues and channel workers
This chapter assumes you know the earlier chapters' architecture sketch, how HTTP APIs hand off work, and what a message queue is (producers add messages, consumers take them). You should also be able to read short Python snippets.
Why put a queue between ingestion and delivery
The ingestion API should answer quickly: "I accepted your event." Delivering a notification is slow and unreliable by comparison. An SMS provider may take two seconds to respond, or return a 503. If the API called providers directly, a slow provider would make every producer slow, and a provider outage would become an outage of the whole system.
A queue breaks that chain. The API writes a message and returns. Workers pull messages at their own pace. This gives you four properties:
- Latency isolation. Producers never wait for providers.
- Burst absorption. A flash sale that creates 2 million events in a minute fills the queue. It does not overload the providers.
- Failure isolation. If the email provider is down, email messages pile up while push and SMS keep flowing.
- Independent scaling. You add workers only for the channel that is behind.
The cost is that delivery becomes asynchronous and eventually consistent. The caller cannot learn from the API response whether the user received anything. Delivery tracking, covered in a later chapter, answers that question.
Two stages: fan-out, then per-channel queues
A single event may produce several sends: a push and an email, for example. A common layout uses two stages.
- A router consumes accepted events, loads the user's preferences, picks the channels, and enqueues one message per channel.
- Each channel worker pool consumes from its own queue (
push,sms,email,in_app), renders the template, and calls the provider.
Separate queues per channel matter because channels differ in speed, cost and failure behavior. A stuck email provider should not block push messages sitting behind it in a shared queue. This is head-of-line blocking, and separate queues prevent it.
Delivery guarantees: at-least-once
Most queues (SQS, RabbitMQ, Kafka consumers with manual commits) give at-least-once delivery. A worker receives a message, and the queue hides it for a while (the visibility timeout). If the worker acknowledges (acks) the message before the timeout, it is removed. If the worker crashes or is too slow, the message reappears and another worker gets it.
This means the same message can arrive twice. The consequences for worker design are:
- Ack only after the work is done. If you ack on receipt and then crash, the notification is lost. At-most-once is rarely acceptable for notifications such as password resets.
- Make sends idempotent. A message that is redelivered after the provider call succeeded but before the ack would send a duplicate. The deduplication key from the idempotency chapter (event, user, channel) is checked before the provider call.
- Set the visibility timeout above the worst-case send time. If the provider call can take 30 seconds, a 10-second timeout makes healthy messages reappear and be sent twice.
What a worker does with a message
A channel worker loop has a small number of outcomes for each message:
| Outcome | Cause | Action |
|---|---|---|
| Success | Provider accepted the message | Ack, record status |
| Duplicate | Dedup key already claimed | Ack, skip the send |
| Transient failure | Timeout, 5xx, provider throttling | Retry later, with a delivery count |
| Permanent failure | Invalid token, malformed payload | Send to dead-letter queue, no retry |
| Too many attempts | Delivery count above the limit | Send to dead-letter queue |
The retry timing policy (backoff and jitter) belongs to the retries chapter. Here the point is the structure: the worker classifies the error and chooses where the message goes next.
A runnable sketch
The following program simulates the pattern with Python's standard library. It has one in-memory queue per channel, one worker thread per queue, a retry limit, and a dead-letter queue. Real systems replace queue.Queue with a broker, but the control flow is the same.
import queue
import threading
MAX_ATTEMPTS = 3
class TransientError(Exception):
"""A failure worth retrying."""
class PermanentError(Exception):
"""A failure that retrying cannot fix."""
def fan_out(event, channels, queues):
"""Router step: one message per channel."""
for channel in channels:
queues[channel].put(
{"event_id": event["event_id"], "user_id": event["user_id"],
"channel": channel, "attempts": 0}
)
def run_worker(inbox, dead_letters, send):
while True:
msg = inbox.get()
if msg is None: # shutdown signal
inbox.task_done()
return
try:
send(msg)
print("sent", msg["channel"], msg["event_id"])
except TransientError:
msg["attempts"] += 1
if msg["attempts"] >= MAX_ATTEMPTS:
dead_letters.put(msg)
else:
inbox.put(msg) # a real broker would delay this
except PermanentError:
dead_letters.put(msg)
finally:
inbox.task_done() # "ack" after the outcome is decided
flaky_calls = {"count": 0}
def send_push(msg):
pass
def send_email(msg):
flaky_calls["count"] += 1
if flaky_calls["count"] < 3:
raise TransientError("provider timeout")
def send_sms(msg):
raise PermanentError("invalid phone number")
queues = {name: queue.Queue() for name in ("push", "email", "sms")}
senders = {"push": send_push, "email": send_email, "sms": send_sms}
dead_letters = queue.Queue()
threads = [
threading.Thread(target=run_worker, args=(queues[c], dead_letters, senders[c]))
for c in queues
]
for t in threads:
t.start()
fan_out({"event_id": "evt-1001", "user_id": "user-42"}, ["push", "email", "sms"], queues)
for q in queues.values():
q.join() # wait until every message has an outcome
q.put(None) # then stop the worker
for t in threads:
t.join()
print("dead-lettered:", [(m["channel"], m["event_id"]) for m in list(dead_letters.queue)])The email send fails twice and succeeds on the third attempt. The SMS send fails permanently and lands in the dead-letter queue on the first try. Push succeeds immediately. Output order between channels can vary because the threads run concurrently.
Dead-letter queues are an operational tool
A dead-letter queue (DLQ) holds messages the system gave up on. Treat it as an inbox that someone reads:
- Alert when the DLQ depth rises above a small threshold.
- Keep the original payload and the last error, so an engineer can see why the message failed.
- Provide a way to redrive messages back to the main queue after fixing a bug or a provider outage.
An unmonitored DLQ is a place where notifications silently disappear.
Sizing, backpressure and poison messages
- Concurrency per worker pool. Throughput is roughly
workers × concurrency ÷ average send time. Size each pool to your provider's limits, not just to the queue depth, or you will trigger provider throttling. - Backpressure. Watch queue depth and the age of the oldest message. Age is more useful than depth, because it tells you how late a notification will be.
- Poison messages. A message that crashes the worker every time (for example, a payload that breaks template rendering) will keep reappearing. The delivery count limit and the DLQ stop it from blocking the queue.
- Ordering. Standard queues do not guarantee order. Notifications such as "order shipped" and "order delivered" can arrive reversed. If order matters, include a sequence number or timestamp in the message, or use per-user partitioning.
Where later chapters plug in
This structure leaves clear places for other concerns. Rate limiting sits in the worker before the provider call. Priority is usually modeled as separate queues, or separate pools, per priority level. Scheduling delays messages before they enter the channel queue. Scaling reliability builds on running many workers against the same queue. Each of those is covered in its own chapter.
Exercise
A worker receives an email message, calls the provider successfully, and then crashes before acking. What happens next, and which mechanism prevents the user from getting two emails?
Show answer
After the visibility timeout expires, the queue makes the message visible again and another worker receives it (at-least-once delivery). The deduplication key (event id, user id, channel) was claimed by the first worker, so the second worker finds it already claimed, acks the message and skips the send. Without the dedup check, the user would receive the email twice.
Exercise
Why is one shared queue for all channels a worse design than one queue per channel?
Show answer
Channels have different speeds and failure modes. In a shared queue, slow or failing messages for one provider (for example, email timeouts) sit in front of messages for healthy channels, which delays them (head-of-line blocking). Separate queues let each channel have its own worker pool, scaling, retry behavior and alerts, so one provider outage stays contained.