Present the architecture diagrammatically (using text/boxes).
Explain the flow.
Focus heavily on the Priority Queue mechanism.
Discuss scaling and failure handling.
Self-Correction/Review:
Initial thought: Just use one queue with a priority field.
Correction: Many message brokers (like RabbitMQ) support priority queues, but standard Kafka doesn't easily support prioritizing messages within a partition. A better approach for scalability is often separate topics/queues or a consumer-side logic that polls high-priority sources more frequently. I will suggest separate queues as it's the most robust pattern.
Final Polish: Ensure the tone is professional and structured like an interview answer.
Designing a notification system requires balancing reliability, latency, and throughput. Introducing priority levels adds complexity because high-priority messages (like a security alert) must bypass the queue congestion that low-priority messages (like a weekly newsletter) might cause.
Here is a comprehensive design for a Notification Delivery System with Priority Levels.
1. Requirements
Functional:
Support multiple channels: Email, SMS, Push Notifications, In-App.
Support priority levels (e.g., Critical, High, Normal, Low).
User preferences (opt-out, quiet hours).
Templates and variable injection.
Non-Functional:
Reliability: No lost messages. At-least-once delivery.
Latency: Critical messages must be sent immediately (p99 < 500ms).
Throughput: Handle massive spikes of low-priority traffic without blocking critical alerts.
Scalability: Horizontally scalable.
2. High-Level Architecture
The system follows a Producer-Consumer model using Priority Queues.
mermaid
graph TD
A[Client Services] --> B[API Gateway]
B --> C[Notification Service]
C --> D[(Database)]
C --> E{Priority Router}
E -->|Critical/High| F[High Priority Queue]
E -->|Normal| G[Default Queue]
E -->|Low/Batch| H[Low Priority Queue]
F --> I[Channel Workers]
G --> I
H --> I
I --> J[3rd Party Providers]
J --> K[User Devices]
3. Core Components Design
A. Notification Service (API Layer)
This is the entry point. It validates payloads, checks user preferences, and converts the request into an internal job.
Idempotency: Uses an idempotency_key to prevent duplicate sends if the client retries.
Rate Limiting: Prevents a single user or service from flooding the system.
Priority Mapping: Maps business logic types to system priorities (e.g., type: "OTP"→priority: HIGH).
B. The Priority Logic (The "Smart" Part)
We cannot rely on a single First-In-First-Out (FIFO) queue. If we send a million marketing emails, a password reset email behind them will wait hours.
We implement a Multi-Tiered Queue Strategy (e.g., using RabbitMQ, ActiveMQ, or SQS with Delay Seconds):
Critical Queue (Real-time):
Use cases: 2FA, Password Reset, Fraud Alerts.
Configuration: Maximum concurrency, no delay, dedicated workers.
SLA: Process instantly.
Default Queue (Standard):
Use cases: "You have a new message", "Your order shipped".
Configuration: Standard processing speed.
Low/Bulk Queue (Background):
Use cases: Newsletters, Promotions, Digests.
Configuration: Subject to throttling. If the system is under load, these are paused first.
C. The Scheduler / Consumer Logic
How do we ensure the High Priority queue is drained faster than the Low Priority queue?
Approach 1: Weighted Polling (Recommended)
The workers (consumers) do not listen to one queue. They actively poll queues in a loop based on a ratio.
Strict Priority: Only poll Low if High and Default are empty.
Approach 2: Dedicated Worker Pools
Pool A (Small, Powerful): Dedicated exclusively to High Priority. Scales instantly.
Pool B (Large, General): Handles Default and Low.
Pros: Guarantees resources for High Priority.
Cons: Resource wastage if there are no high-priority messages.
D. Channel Workers & Providers
These workers take the job, hydrate the template (e.g., "Hello {{Name}}"), and call the external provider (Twilio, SendGrid, APNS).
Circuit Breaker: If SendGrid goes down, the worker stops attempting delivery to prevent thread blocking. The message returns to the queue (DLQ - Dead Letter Queue) after max retries.
4. Database Schema
We need to track the state of every notification for auditing and retry logic.
Table: notifications
Column
Type
Description
id
UUID
Unique ID
user_id
BigInt
Target user
channel
Enum
EMAIL, SMS, PUSH
priority
Int
0=Critical, 1=High, 2=Normal, 3=Low
status
Enum
PENDING, SENT, FAILED, RETRYING
payload
JSONB
Content and variables
created_at
Timestamp
For SLA monitoring
5. Handling Failure & Retries
Priority affects how we handle failure.
High Priority Failure:
Retry immediately with exponential backoff (retry at 1s, 5s, 10s).
If max retries reached: Alert the dev team immediately and push to a "Dead Letter Queue" for manual inspection.
Low Priority Failure:
If the provider is down, mark as FAILED and move on. Do not retry immediately to avoid clogging the system.
Batch retry these 24 hours later or discard if the event is stale (e.g., a "flash sale" notification is useless after the sale ends).
6. Optimization: Circuit Breaker & Rate Limiting
A critical risk in notification systems is Provider Backpressure. If we try to send 1 million emails in a minute, SendGrid will throttle us.
Rate Limitter (Token Bucket):
Before a worker picks up a job, it checks a Redis counter for the specific provider.
Key: sendgrid_minutely_limit
If limit reached → Worker pauses (sleeps) or re-queues the message with a delay.
7. Summary of Flow
Ingest: API receives request. Mark as PENDING in DB.
Classification: Determine priority. Push to RabbitMQ priority.high exchange.
Consumption: Worker uses Weighted Polling. It picks the High Priority job first.
Processing: Worker fetches user details (email/phone) and renders template.
Delivery: Worker calls SendGrid API.
Confirmation:
Success: Update DB to SENT. Emit metrics.
Failure: Re-queue (if High Priority) with delay or move to DLQ.
8. Tech Stack Recommendations
Queues: RabbitMQ (Native priority queue support) or Kafka (Partition by priority).
Database: PostgreSQL (Reliability) or DynamoDB (Scale).
Cache/Lock: Redis (For rate limiting and user preference caching).