Design a Scalable Distributed Mass Email Delivery Engine
System DesignModel answerLast updated
Architect an enterprise marketing dispatch platform supporting timezone-aware scheduling, template rendering, deduplication, fault-tolerant ESP dispatch, and tracking.
Problem Overview
Design a high-throughput, fault-tolerant marketing email platform for a large global e-commerce and ticketing network. The system must dispatch scheduled targeted messaging, respect recipients' local operating hours across global timezones, dynamically inject user-specific profile data into templates, perform A/B experiment routing, and process engagement metrics (opens and clicks) without degradation.
Functional Requirements
- Timezone-Aware Dispatching: Schedule campaigns to trigger based on the user's local standard time across global regions.
- Template Customization & Experimentation: Support dynamic variable substitution and user-level A/B variant assignment.
- Engagement Analytics: Track individual open and click events with low-latency redirection.
- Suppression & Preference Handling: Enforce globally suppressive lists (unsubscribes, hard bounces, spam complaints) before dispatching.
Non-Functional Requirements & Key Scale Constraints
- Volume: 10 million messages daily, subject to significant burst traffic (e.g., ticket drops) reaching up to 5,000 dispatches/sec peak.
- Reliability & Idempotency: Zero silent message loss. At-most-once or effectively-once delivery guarantees (minimize accidental duplicate sends).
- Extensibility: Multi-provider failover across external Email Service Providers (ESPs) like AWS SES or SendGrid.
Hints
Hint 1
Break down local time handling into localized dispatch buckets (e.g., 15-minute UTC intervals) mapped to standard IANA timezone identifiers rather than raw static offsets.
Hint 2
Ensure deterministic A/B routing using consistent hashing on campaign ID and user ID to avoid stateful lookup bottlenecks during bulk rendering.
Hint 3
Use a conditional ledger update (atomic state machine check) immediately before issuing an external ESP API request to guarantee idempotency across worker retries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture Solution Walkthrough
1. Requirements Clarification & Capacity Estimation
Scale & Throughput Calculations
- Daily Volume: $10,000,000$ emails/day.
- Average Load: $\frac{10,000,000}{86,400} \approx 116 \text{ messages/sec}$.
- Peak Burst Load: Due to synchronized timezone releases (e.g., 9:00 AM local time across major population hubs) and promotional launches, assume a peak factor of $\approx 45\times$ average load $\rightarrow \mathbf{5,000 \text{ dispatches/sec}}$.
- Engagement Events: Assuming a $20%$ open rate and a $3%$ click-through rate, the system will process approximately $2.3\text{M}$ events/day, peaking at roughly $1,500\text{ tracking requests/sec}$.
- Storage Footprint:
- Send ledger: $200 \text{ bytes/record} \times 10\text{M records/day} = 2 \text{ GB/day} \rightarrow \approx 730 \text{ GB/year}$.
- Tracking events: $150 \text{ bytes/event} \times 2.3\text{M events/day} = 345 \text{ MB/day}$.
2. High-Level System Architecture
+-----------------------+
| Campaign Management |
| & Admin Portal |
+-----------+-----------+
|
v
+-----------------------+
| Campaign Postgres |
+-----------+-----------+
|
v
+-----------------------+
| Scheduler / Planner | (Leader-elected)
+-----------+-----------+
|
v
+-----------------------+
| Audience Expander |
+-----------+-----------+
|
v
[ Kafka: send-batches ]
|
v
+-----------------------+
| Delivery Workers | <---> [ User Profile Store ]
+--+-----------------+--+ <---> [ Suppression Cache (Redis) ]
| | <---> [ Send Ledger DB ]
v v
+----------+ +----------+
| ESP A | | ESP B |
|(Primary) | |(Failover)|
+----+-----+ +----+-----+
| |
+-------+--------+
|
v
[ External Recipient ]
|
v
+------------------+ +--------------------+ +------------------------+
| Tracking Edge | ----------> | Kafka: raw-events | ---------> | Real-Time Analytics |
| (Redirect / Pixel)| +--------------------+ | (ClickHouse / Flink) |
+------------------+ +------------------------+
3. Key Component Design
A. Scheduler & Timezone Execution Strategy
- Timezone Modeling: Recipient timezones are stored using IANA identifiers (e.g.,
America/New_York,Europe/London) to natively support Daylight Saving Time adjustments. - Time Bucketing:
- Time is evaluated in discrete 15-minute UTC buckets.
- The Scheduler / Planner queries campaigns set for local time delivery (e.g.,
target_time = 09:00). - Every 15 minutes, it translates the current UTC window to matching IANA zones and enqueues execution tasks:
(campaign_id, utc_bucket_id, target_timezones).
- Audience Expansion:
- The Audience Expander queries segment data for users in the selected timezones.
- Users are streamed and batched into chunks (e.g., 500 users per batch) and published to the
send-batchesKafka topic.
B. Delivery Engine & Worker Execution Loop
When a worker node pulls a batch from send-batches:
- Suppression Filtering: Check user IDs against a high-throughput Redis Bloom Filter (backed by Postgres) to exclude unsubscribed users, complaints, and hard bounces.
- Deterministic A/B Routing:
Compute variant assignment without stateful database writes using stateless consistent hashing:
$$\text{hash_val} = \text{MurmurHash3}(\text{campaign_id} + \text{user_id}) \pmod{100}$$
If
hash_valfalls within specified range weights, assign the designated variant. - Idempotent Lock (Send Ledger):
Perform an atomic state registration in the distributed ledger (e.g., DynamoDB / Cassandra):
If the record exists, drop execution to eliminate duplicate delivery.INSERT INTO send_ledger (campaign_id, user_id, status, created_at) VALUES ('cmp_123', 'usr_456', 'PENDING', NOW()) IF NOT EXISTS; - Dynamic Personalization: Fetch profile traits from a cache/store, render the HTML template, rewrite URLs with signed tracking tokens, and append a $1\times 1$ tracking pixel.
- Provider Dispatch: Send payload to external ESP (AWS SES / SendGrid) API with an idempotency key corresponding to
campaign_id + user_id.
4. High-Performance Engagement Tracking
To handle event spikes cleanly without slowing down user interactions, tracking relies on a low-overhead Edge service:
User Click --> CDN / Tracking Edge --> Return HTTP 302 Redirect
\-> Asynchronously push event to Kafka "raw-events"
Token Security & Data Flow
- Link Token: Embedded links use HMAC SHA-256 signed payloads containing:
{ campaign_id, user_id, variant_id, destination_url, timestamp }. - Validation: Tracking Edge validates HMAC signatures to protect against open-redirect vulnerabilities before generating an HTTP 302 redirect.
- Analytics Ingestion: Open pixel and click requests asynchronously emit structured logs to the
raw-eventsKafka topic, consumed by Apache Flink and written to ClickHouse for campaign reporting.
5. Data Schemas
PostgreSQL (Metadata Store)
CREATE TABLE campaigns (
campaign_id UUID PRIMARY KEY,
name VARCHAR(255) NOT NULL,
audience_segment_id UUID NOT NULL,
target_local_time TIME NOT NULL,
status VARCHAR(50) NOT NULL, -- DRAFT, SCHEDULED, PROCESSING, COMPLETED
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE campaign_variants (
variant_id UUID PRIMARY KEY,
campaign_id UUID REFERENCES campaigns(campaign_id),
template_id UUID NOT NULL,
weight_percentage INT NOT NULL -- e.g., 50 for 50%
);
DynamoDB / Cassandra (Send Ledger)
- Partition Key:
campaign_id - Sort Key:
user_id - Attributes:
status(PENDING,DISPATCHED,FAILED),esp_message_id,updated_at,ttl
6. Resilience, Recovery & Edge Cases
| Scenario | Recovery Mechanism |
|---|---|
| Worker Failure Mid-Batch | Workers process Kafka messages with client-managed offset commits. If a node crashes, the uncommitted message is re-assigned to a new worker. The atomic send_ledger entry prevents duplicate dispatches. |
| Primary ESP Outage | Implemented Circuit Breakers evaluate consecutive 5xx failures or rate limits. Traffic instantly reroutes to pre-warmed secondary ESP credentials. |
| Complete Third-Party Outage | Messages remain buffered in persistent Kafka topics. Exponential backoff with jitter prevents overloading recovering provider endpoints. Expiration headers (expires_at) prevent sending outdated marketing content. |
| Clock Drift Across Nodes | Timezone execution rely on server NTP sync and discrete UTC 15-minute window boundaries rather than local worker hardware clocks. |
7. Trade-offs & Common Pitfalls
- Lazy Audience Expansion vs. Pre-Materialization: Trade-off: Materializing all 10 million user records right at campaign creation ensures an immutable snapshot, but risks using stale user preferences and high storage overhead. Decision: Expanding lazily per 15-minute bucket preserves dynamic audience changes and minimizes unnecessary DB footprint, accepting minor performance trade-offs during expansion runs.
- At-Least-Once vs. At-Most-Once Delivery:
Trade-off: External networks can drop responses after accepting payloads. Ensuring absolute zero duplicates requires complex two-phase commits across third-party boundaries.
Decision: Aim for effectively-once execution by passing deterministic vendor idempotency headers (
campaign_id + user_id) to external ESPs.