Multi-Channel Messaging Platform Design
System DesignModel answerLast updated
Build a platform that routes millions of messages per day across email, SMS, and mobile push, handling both real-time triggers and scheduled campaigns.
You're building a messaging platform for a two-sided marketplace with millions of users. The platform must dispatch communications through multiple channels—email, SMS, and mobile push notifications—and accommodate different user roles including buyers, sellers, and internal staff.
Your system needs to handle two distinct sending patterns:
Real-time triggered messages: Individual messages fired by application events. For example, when a transaction completes, the buyer receives a receipt; when an appointment time arrives, the seller gets a reminder with access credentials.
Scheduled audience campaigns: Bulk sends to user segments, either one-time or recurring. A marketing team might send a promotion to all sellers in a region, or operations might notify users about a policy change.
You can assume upstream services already produce events for business activities. Your platform consumes these events and handles message delivery.
Design the complete system, addressing:
-
Scope and capacity planning: What functional capabilities and performance targets drive your design? Estimate throughput, latency requirements, and reliability goals.
-
Architecture and flow: Sketch the major components and trace the path a message takes from trigger to delivery for both sending patterns.
-
Storage schema: What entities do you persist and how do they relate?
-
Interface contracts: What APIs do other services call? How do external providers report back?
-
Content management: How are message templates created, stored, customized per user, and selected for each channel?
-
User control and regulations: How do users manage what they receive? How do you comply with anti-spam laws and handle opt-outs?
-
Traffic management: How do you prevent low-priority bulk sends from delaying time-sensitive messages?
-
Correctness guarantees: What prevents duplicate sends? When does ordering matter and how do you enforce it?
-
Resilience: How do you handle failures—both transient errors and complete provider outages?
-
Horizontal scaling: What strategies let you grow capacity? How do you partition work and handle sudden spikes?
-
Visibility: What instrumentation reveals system health and proves compliance?
-
Economic controls: How do you keep provider costs predictable as volume grows?
State your assumptions clearly. Explain the reasoning behind key decisions and the trade-offs you're accepting. Describe how you'd validate the design before launching.
Hints
Hint 1
Start with concrete numbers—daily volume, peak throughput, and latency targets for different message types. These drive every downstream choice about queuing, partitioning, and provider capacity.
Hint 2
Separate the concerns: one pipeline validates preferences and renders content; distinct priority queues per channel prevent bulk campaigns from starving urgent messages; workers handle provider interaction and retries.
Hint 3
Think through the compliance layer carefully—suppression lists, category-based consent, frequency limits, and timezone-aware quiet hours must all execute atomically before any message leaves the system.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Multi-Channel Messaging Platform: Model Answer
1. Scope and Capacity
Functional requirements:
- Consume application events and dispatch individual messages immediately
- Execute scheduled bulk sends to filtered user segments
- Route through email, SMS, and push (APNs for iOS, FCM for Android)
- Serve multiple user populations with different contact preferences
- Provide message templates with localization and personalization
- Track delivery status and maintain an audit log
Scale assumptions (be explicit):
- Total addressable users: ~150 million
- Daily active: ~30 million
- Average daily messages: 200 million (≈2,300/sec sustained)
- Design for 20,000/sec peak to handle traffic spikes
- Large campaigns may target 50M recipients and should complete within a few hours
Performance targets:
- Critical messages (one-time codes, access credentials): p99 < 5 seconds to provider
- Transactional (receipts, confirmations): p99 < 30 seconds
- Marketing: complete within send window, no hard real-time requirement
Reliability:
- At-least-once processing internally, with idempotency preventing user-visible duplicates
- 99.95% availability for the ingestion path—no lost transactional messages
- Graceful degradation: marketing pauses before transactional traffic is affected
Compliance:
- Honor opt-outs within seconds of receipt
- Respect quiet hours, frequency caps, and category preferences
- Maintain auditable trail of send decisions
2. Architecture
Event streams ─────┐
Ingestion API ─────┼──> Policy Engine ──> Rendering ──> Priority Queues ──> Channel Workers ──> Providers
Campaign Scheduler ┘ (dedupe, │ (per channel (rate limit, (SendGrid,
│ preferences, │ × priority) retry, circuit Twilio,
└──> Audience suppression, │ break) APNs/FCM)
Fanout routing) │ │
│ │ │
└─ Decision Log └─ Message Store │
│
Webhook Ingestion <───────────────────────────────────┘
│
└──> Delivery Events ──> Analytics
Real-time path:
- Event arrives (e.g.,
OrderCompletedwith order ID and buyer ID) - Service maps event to message type (
order_receipt) - Idempotency check using event ID + type + recipient
- Policy engine: load user preferences, check suppression list, apply frequency caps
- Select channel(s) based on type and user preferences
- Render template with personalization data
- Persist message record with status
PENDING - Enqueue to priority queue (e.g.,
email.transactional) - Worker sends via provider, records provider message ID, updates to
SENT - Provider webhook updates status to
DELIVERED,BOUNCED, orFAILED
Campaign path:
- Marketer defines campaign: target segment, template, schedule, rate limit
- Scheduler activates campaign at send time
- Audience query runs against data warehouse, yields ~50M user IDs
- IDs split into shards of 10,000 each (5,000 shards total)
- Fanout workers process shards through same policy and rendering pipeline
- Messages enqueue at marketing priority
- Progress checkpointed per shard for resumability
- Workers respect campaign-level rate limit to spread over send window
Both paths converge at the policy engine—single source of truth for compliance.
3. Storage Schema
Users & Preferences (Postgres with read replicas):
users: id, type, locale, timezone, email, phone, push_tokenschannel_preferences: user_id, category (transactional|marketing|reminders), channel, enabled, quiet_hours_start, quiet_hours_endsuppression_list: address_hash, channel, reason (bounce|complaint|unsubscribe), created_atfrequency_counters: user_id, category, window, count (could be Redis for TTL)
Templates (Postgres):
templates: id, name, type, channel, locale, version, content, required_fields, status, approved_at
Campaigns (Postgres):
campaigns: id, name, segment_sql, template_id, schedule, rate_limit, statuscampaign_shards: campaign_id, shard_index, user_ids, processed_at
Messages & Delivery (Cassandra/DynamoDB, partitioned by user_id):
messages: id, user_id, idempotency_key, type, channel, priority, template_version, status, provider_id, provider_message_id, created_at, sent_at, decision_reasonsdelivery_events: message_id, event_type, provider_status, raw_payload, timestamp
TTL of 90 days; older data archived to S3 for compliance.
4. Interface Design
Ingestion API:
POST /v1/messages
{
"idempotency_key": "evt_123_order_receipt",
"type": "order_receipt",
"user_id": "user_456",
"data": { "order_id": "ord_789", "amount": "$42.00" },
"priority": "transactional"
}
Response: 202 Accepted { "message_ids": ["msg_abc"] }
Campaign API:
POST /v1/campaigns
{
"name": "Spring Sale",
"segment": "active_sellers_us",
"template_id": "tmpl_123",
"send_at": "2024-03-15T09:00:00Z",
"respect_timezones": true,
"rate_limit_per_hour": 500000
}
POST /v1/campaigns/{id}/activate
GET /v1/campaigns/{id}/progress
POST /v1/campaigns/{id}/cancel
Status lookup:
GET /v1/messages/{id}
Response: {
"id": "msg_abc",
"status": "delivered",
"channel": "email",
"sent_at": "2024-03-10T14:32:11Z",
"delivered_at": "2024-03-10T14:32:45Z",
"decision_log": ["passed_suppression", "passed_frequency_cap"]
}
Provider webhooks:
POST /webhooks/sendgrid
POST /webhooks/twilio
POST /webhooks/fcm
(Verified via signature; processed async)
5. Templates and Personalization
Template management:
- Templates authored in CMS with approval workflow
- Immutable versions: draft → approved → active
- Each template keyed by (type, channel, locale)
- Schema defines required variables with types
Rendering:
- Use sandboxed template engine (Handlebars/Mustache)
- Validate all required variables are present before rendering
- Missing variable → fail to dead-letter queue (never send "Hello {{name}}")
- Locale resolution: exact match → language fallback (es-MX → es) → default (en)
- Channel-specific limits: SMS segment count, push payload size
Channel selection:
- Based on message type priority: urgent codes → SMS+push first, email fallback
- Marketing: email unless user explicitly opted into push
- Record final channel choice in message log
6. User Control and Compliance
Policy enforcement order:
- Suppression check: If address is on suppression list (hard bounce, spam complaint, STOP keyword), block immediately
- Category consent:
- Transactional and security messages send regardless of marketing preferences
- Marketing requires explicit opt-in per jurisdiction (GDPR, CAN-SPAM)
- Quiet hours:
- Marketing deferred until user's morning (timezone-aware delay queue)
- Urgent messages exempt
- Frequency caps:
- Redis counters with sliding windows
- Example: max 2 marketing/day, 5/week per user
- Check and increment atomically
Opt-out handling:
- Email: one-click unsubscribe header (List-Unsubscribe)
- SMS: STOP/HELP keywords detected via webhook
- Push: token removal when user disables in device settings
- Updates propagate to suppression list + preference store + cache within 5 seconds
- Campaign workers recheck preferences at send time, not just at audience snapshot time
Decision logging:
- Every send decision recorded: which checks passed/failed, which policy version applied
- Audit trail answers: "Why did user X receive message Y?" or "Why didn't they?"
7. Traffic Prioritization
Separate queues per channel × priority:
- P0: security codes, one-time passwords (5% of traffic, reserved capacity)
- P1: transactional (40% of traffic)
- P2: marketing (55% of traffic, throttled first under load)
Worker pool allocation:
- Dedicated workers per priority tier
- P0 workers consume only from P0 queues
- Shared provider capacity pre-allocated: 30% reserved for P0/P1, 70% for P2
Backpressure handling:
- Weighted queue polling: P0 always processed first
- When queues grow, pause P2 enqueuing before affecting P1
- Campaign scheduler respects rate limit to avoid overwhelming system
Sender reputation:
- Email: separate IP pools for transactional vs marketing
- Keeps marketing bounces from harming transactional deliverability
8. Deduplication and Idempotency
Idempotency key construction:
- Events:
{event_id}:{message_type}:{user_id}:{channel} - Campaigns:
{campaign_id}:{user_id}:{channel} - Check against message store before creating new record
- Idempotent within 7-day window (sufficient for any legitimate retry)
Ordering:
- Most messages are independent; ordering is not required
- Where it matters (sequential status updates for same entity), partition queue by user_id
- Tradeoff: per-user ordering sacrifices some parallelism but guarantees sequence
Preventing double-sends:
- Exactly-once processing inside our system
- Providers may deliver duplicate due to retries (their at-least-once guarantee)
- User-facing: idempotency key in webhook prevents recording duplicate delivery
- SMS replies: dedupe on (phone, keyword, timestamp) within 1-minute window
9. Resilience
Retry strategy by error class:
- 4xx client errors (invalid recipient, malformed request): no retry, log to DLQ
- 5xx server errors: exponential backoff up to 1 hour
- Rate limit (429): backoff with jitter, up to 6 hours
- Provider timeout: retry immediately once, then exponential
Dead-letter queue:
- Messages exceeding retry limit move to DLQ
- Monitored and manually reviewed
- Can be requeued after fixing root cause
Circuit breaker per provider:
- After 10 consecutive failures, open circuit for 60 seconds
- Prevents stampeding a failing provider
- Half-open: try one request, close if successful
Multi-provider failover:
- Email: SendGrid primary, AWS SES secondary (requires different templates for format differences)
- SMS: Twilio primary, MessageBird secondary (requires managing multiple accounts)
- Failover manual or automated based on error rate threshold
- Costs: failover provider may have higher per-message cost
Data durability:
- Messages persisted before sending
- Queue messages durable (Kafka/SQS with replication)
- Worker crash: message remains in queue for another worker
10. Scaling Strategies
Horizontal scaling:
- Stateless workers: scale worker pools independently per queue
- Partition queues by user_id hash for ordering, or round-robin for throughput
- Campaign fanout: parallelize shard processing across workers
Campaign optimization:
- Snapshot audience to shards once, not per message
- Process shards concurrently with bounded parallelism
- Checkpoint progress per shard for crash recovery
- Spread sends over time window to respect rate limits
Rate limiting:
- Per-provider: token bucket enforced in workers, refill rate = contracted limit
- Per-campaign: global rate stored in Redis, decremented atomically
- Per-user frequency: Redis counters with TTL
Backpressure:
- Queue depth metrics trigger alerts
- Auto-scale workers when depth exceeds threshold
- Pause campaign scheduling when P1 queue is backed up
Multi-region:
- Deploy in 3+ regions for availability
- Route users to nearest region by geo
- Replicate templates and preferences globally
- Partition messages by region to reduce cross-region traffic
- Campaigns fan out in originating region, workers send locally
Database scaling:
- Read replicas for preferences and templates (heavily read)
- Cassandra/DynamoDB for messages: partition by user_id, scales horizontally
- Postgres for preferences: shard by user_id hash if single instance saturates
- Redis cluster for counters and caching
11. Observability
Metrics (by channel, priority, type):
- Request rate, queue depth, processing latency
- Send success/failure rate, delivery rate
- Provider latency and error rate
- Suppression checks, preference blocks, frequency cap blocks
SLIs:
- P99 latency: ingestion API, policy engine, worker send
- Success rate: % messages reaching provider successfully
- Delivery rate: % provider-confirmed delivered (by channel)
Tracing:
- Distributed trace from event ingestion to delivery webhook
- Correlate message_id across all components
- Reveals bottlenecks in policy checks or template rendering
Logging:
- Structured logs with message_id, user_id, type, decision_reasons
- Centralized (ELK/Splunk) for searchability
- Audit trail: query "all messages to user X in date range"
Alerting:
- Queue depth above threshold
- P99 latency SLO breach
- Error rate spike for any provider
- Suppression list growth anomaly (potential attack)
Dashboards:
- Real-time: throughput, queue depth, error rate by channel
- Campaign view: progress, remaining recipients, ETA
- Cost dashboard: messages sent by channel, projected monthly spend
12. Cost Management
Unit economics:
- Email: $0.0001–$0.001 per message (cheapest)
- SMS: $0.01–$0.05 per message (10–500× email)
- Push: $0 incremental cost (fixed FCM/APNs infrastructure)
Cost controls:
- Budget caps per campaign: hard limit on spend, campaign pauses when reached
- Channel preference: prefer push > email > SMS for cost efficiency where appropriate
- Deduplication: prevents waste from double-sends
- Suppression: avoids sending to invalid addresses (bounces cost money)
- Smart routing: OTP via push if available, SMS as fallback
- Volume discounts: negotiate tiered pricing with providers
- Reserved capacity: commit to minimum volume for lower rates
Monitoring:
- Daily spend by channel, type, campaign
- Alert when approaching monthly budget
- Anomaly detection: sudden spend spike indicates misconfigured campaign or attack
Validation Plan
Before production launch:
- Load testing: Replay 30 days of production events at 2× speed to validate 40k/sec peak
- Chaos engineering: Kill workers, partition network, fail provider to verify recovery
- Compliance audit: Send test messages, verify opt-outs block within 5 seconds, check decision logs
- Cost simulation: Run campaigns against staging to project real costs
- Shadow mode: Run new system in parallel, compare output to current system
- Gradual rollout: 1% → 10% → 50% → 100% of traffic with rollback plan
Key Trade-offs
- At-least-once delivery (simpler, lower cost) vs exactly-once (complex coordination, higher latency)
- Single priority queue (simpler) vs separate queues (prevents starvation, chosen)
- Synchronous rendering (simple) vs pre-rendered campaigns (faster, but staleness risk)
- Multi-provider failover (availability) vs single provider (simpler operations, cost negotiation leverage)
- Real-time preference checks (accurate) vs cached (faster, risk of sending to opted-out user within cache TTL)
This design prioritizes correctness and compliance over absolute performance, treats user preferences as first-class concerns, and isolates critical traffic from bulk sends through architectural boundaries rather than runtime heuristics.