Sub topic 13
Prioritizing urgent notifications
This chapter assumes you know the queue-and-worker design from the previous chapters, including how a notification event carries a priority field. You should also be able to read short Python snippets. Here you will see how that field changes the way work flows through the system.
Why one queue is not enough
Suppose every event goes into one first-in, first-out queue. A marketing team schedules a campaign for 2 million users. Behind those 2 million messages sits a one-time password (OTP) for a user who is trying to log in. The OTP waits until the campaign drains, and by then it has expired.
This is head-of-line blocking. Adding workers only shortens the delay. It does not fix the ordering problem. Prioritization means urgent work does not wait behind bulk work, even when the system is saturated.
Defining priority levels
Keep the set of levels small. Each level should differ in behavior, not only in name.
| Level | Typical examples | Latency goal | Bypasses quiet hours | Can be dropped under overload |
|---|---|---|---|---|
| critical | OTP, fraud alert, security notice | seconds | yes | no |
| high | order shipped, message from a person | under a minute | no | no |
| normal | social activity, reminders | minutes | no | rarely |
| bulk | newsletters, campaigns, digests | hours | no | yes, after delay |
Three or four levels are usually enough. With more, nobody can say what separates level 6 from level 7, and producers will choose the highest one anyway.
Separate queues, not a priority field
A single queue with a sort key looks simple, but it has problems. Many brokers do not support per-message priority well. Where they do, ordering is often only approximate, and a large backlog of low-priority items still costs memory and storage in the shared queue.
The more common design is one queue per priority level, and often one per channel as well, such as push.critical and email.bulk. This gives you three benefits:
- Each queue has its own depth metric and alert threshold.
- Each queue can have its own worker pool and scaling rule.
- A backlog in
email.bulkcannot touchpush.critical.
Deciding which queue a worker reads next
Workers that read several queues need a policy.
- Strict priority. Always drain critical first, then high, then normal. Urgent work gets the best latency. A steady stream of critical events starves everything below it.
- Weighted polling. Poll queues in a ratio such as 6:3:1. Lower levels always make some progress, and urgent work still gets most of the capacity.
- Dedicated pools. Reserve workers for critical only, and let the rest share the other queues. This is the most predictable option, but idle reserved workers are wasted capacity.
The sketch below implements weighted polling in memory. A real worker would poll broker queues instead, but the scheduling logic is the same.
from collections import deque
class WeightedQueues:
def __init__(self, weights):
self.queues = {name: deque() for name in weights}
self._schedule = [n for n, w in weights.items() for _ in range(w)]
self._pos = 0
def push(self, level, item):
self.queues[level].append(item)
def next_item(self):
"""Return (level, item) following the weights, or None if all are empty."""
for _ in range(len(self._schedule)):
level = self._schedule[self._pos]
self._pos = (self._pos + 1) % len(self._schedule)
if self.queues[level]:
return level, self.queues[level].popleft()
return None
q = WeightedQueues({"critical": 3, "normal": 1})
for i in range(6):
q.push("critical", f"c{i}")
for i in range(2):
q.push("normal", f"n{i}")
order = []
while (result := q.next_item()) is not None:
order.append(result[1])
print(order)This prints ['c0', 'c1', 'c2', 'n0', 'c3', 'c4', 'c5', 'n1']. The normal items are not stuck behind all six critical ones. When a level's queue is empty, its slots are skipped, so no capacity is wasted.
Where priority is decided
Do not let the producer's word be final. Two rules work well:
- Derive priority from the notification type. A configuration table maps
order_shippedto high andotpto critical. Producers send the type, and ingestion looks up the level. - Restrict who may request critical. Check at ingestion that the calling service is allowed to send critical types. Otherwise one team's "urgent" flag will eventually fill the critical queue with promotions.
If the payload does carry a priority, validate it against an allowlist and reject unknown values rather than defaulting silently.
How priority interacts with other features
Priority affects more than queue order. Each earlier mechanism needs a rule about it.
- Quiet hours. In the routing function from the preferences chapter, only
criticalskips the quiet-hours filter. Keep that list short, because every bypass is a night-time interruption. - User opt-outs. Priority never overrides a legal opt-out for marketing. Security and transactional messages may be exempt by policy, but that is a compliance decision, not a priority setting.
- Rate limiting. Apply per-user limits to normal and bulk traffic. Critical messages usually get a separate, higher limit, so a burst of low-priority sends cannot block an OTP.
- Retries. Retries must go back to a queue of the same priority. A retried critical message that lands in the normal queue loses its advantage. Retry delays can also differ by level. An OTP that is 90 seconds late is useless, so critical sends may use shorter caps and fewer attempts. Bulk can wait longer.
- Provider quotas. Providers throttle per account. If bulk sends consume the whole quota, critical sends get throttled too. Reserve part of the quota for critical, or use a separate provider account or sender ID for bulk.
Failure modes
- Priority inflation. Producers mark everything urgent. Fix it with an allowlist per service and a dashboard of volume per level.
- Starvation. Strict priority with a constant stream of high events leaves normal work stuck. Use weights, or age an item up a level after it has waited too long.
- Shared dependencies. Separate queues do not help if all workers share one database connection pool or one provider client with a small concurrency limit. A bulk burst can still exhaust it. Isolate those resources as well.
- Expired content. A critical notification that arrives late can be harmful. Store an expiry time on the event, and have the worker drop or downgrade the message when it is past due instead of sending a stale OTP.
- Overload without shedding. When the system is saturated, decide in advance what to drop. Delaying or discarding bulk is acceptable, and dropping critical is not.
Measuring whether it works
Track these per priority level, not only in aggregate:
- Queue depth and age of the oldest message.
- Time from event accepted to sent, as p50 and p99.
- Count of messages dropped for expiry.
A healthy system shows flat critical latency while bulk latency grows during a campaign. If critical latency rises with bulk volume, something shared is still blocking, such as a connection pool, a provider quota, or a worker pool.
Exercise
A worker pool reads queues with weights critical:5, normal:3, bulk:1 using weighted polling. During a large campaign the bulk queue holds 1 million messages, and critical OTP latency is still rising even though the critical queue is short. Name two likely causes and a fix for each.
Show answer
First, a shared resource is saturated, such as the provider client's concurrency limit or the database connection pool, so critical workers wait for slots that bulk workers hold. Fix it by giving critical its own connection pool or client limit. Second, the provider account quota is being used up by bulk sends, so the provider throttles critical requests too. Fix it by reserving quota for critical or by sending bulk through a separate account or sender ID. A third possibility is that retries for critical messages are re-enqueued at normal priority. Fix it by re-enqueuing to the original level.