Design an Email Service
How to design an email service: SMTP receiving, per-user mailbox storage, search, sending with retries, device sync, and what interviewers ask.
On this page
An email service receives messages from other mail servers over SMTP, stores them in each user's mailbox, lets users read, label and search them from several devices, and sends outgoing mail to other providers. Interviewers ask about it because it combines a strict durability requirement, large storage, per-user partitioning, search, and communication with servers that you do not control.
The steps below follow A Framework for Any Design.
Clarify the problem
Design an email service like a big web mail provider.
I'll assume the core features are sending and receiving mail, labels, search and attachments. Do we also need to support desktop clients over IMAP?
Our own apps only. IMAP is a stretch goal.
How many users are there, and how much mail does each one get?
There are 100 million users. Each receives about 40 emails a day after spam is rejected, and sends about 5.
Then my priorities are these. Once we tell the sender's server that a message is accepted, we never lose it. New mail reaches every device within a few seconds. A user's own actions show up immediately. Search results can lag by a few seconds.
- Functional requirements: receive mail over SMTP, filter spam and viruses, list mail by label, open messages and attachments, send mail with retries and bounces, change labels, search a user's own mail, and sync devices.
- Non-functional requirements: no accepted message is lost, new mail is visible within 5 seconds, the inbox opens in under 200 ms, search answers in under 500 ms, and receiving keeps working when reading is degraded.
- Out of scope: calendar, contacts, chat, ads, end-to-end encryption, and IMAP (which comes up as a follow-up question).
Estimate the scale
Assume that an average email takes 30 KB of storage. Headers and body take about 10 KB, and one email in 20 has a 400 KB attachment, which adds 400 KB ÷ 20 = 20 KB on average. Peak traffic is about twice the average.
- Received mail: 100 million users × 40 emails = 4 billion emails a day. That is about 46,000 a second on average and about 92,000 a second at peak.
- Reads: at 20 opened messages per user a day, 2 billion reads a day, about 23,000 a second.
- Inbound bandwidth: 4 billion × 30 KB = 120 TB a day, which is 120 TB ÷ 86,400 s ≈ 1.4 GB/s on average. Bodies and attachments go to object storage, and only about 500 B of metadata per email (2 TB a day) goes in a database.
How many emails per second does the receive path handle on average?
- 100 million users
- 40 emails received per user per day
- A day is 86,400 seconds
Show the working
- 100,000,000 × 40 = 4 billion emails a day
- 4 × 109 ÷ 86,400 ≈ 46,000 a second
- At twice the average, the peak is about 92,000 a second
Estimate 46 thousand/s (anything from 15 thousand/s to 150 thousand/s is a good answer)
Writes outnumber reads here (46,000 a second against 23,000), which is unusual for a consumer product.
Write the endpoints the mail apps need: list a label, open a message, send, change labels, search, and sync. What should "send" return when delivery can take days?
Compare with a model answer
Listing is a GET by label with a cursor. Send returns 202, meaning queued and not yet delivered. Sync asks for "changes since sequence number N".
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
Other mail servers talk to you over SMTP on port 25. Your own apps use an HTTP API:
GET /messages?label=INBOX&limit=50&cursor=...
200 { "messages": [ { "id": "m_9f2", "from": "...", "subject": "...",
"snippet": "...", "labels": ["INBOX", "UNREAD"] }, ... ], "next_cursor": "..." }
GET /messages/{id} headers, body, attachment list
GET /attachments/{id} 302 to a short-lived signed URL in object storage
POST /attachments upload first, get an id back
POST /messages/send Idempotency-Key: draft_771
body: { "to": [...], "subject": "...", "body": "...", "attachment_ids": [...] }
202 Accepted { "id": "m_a01", "status": "queued" }
400 Bad Request an address is malformed
413 Payload Too Large over the size limit
429 Too Many Requests over the daily sending limit
POST /messages/{id}/labels { "add": ["Receipts"], "remove": ["INBOX"] }
GET /search?q=from:bob invoice has:attachment&cursor=...
GET /changes?since=81237
200 { "changes": [ ... ], "latest": 81240 }
410 Gone too far behind; do a full resyncThe decision worth arguing is how devices sync. Re-downloading the first 50 inbox messages on every wake-up wastes bandwidth and misses label changes on older mail. Instead, each user has a change log, and a device asks for everything after the last sequence number it has seen, for example "everything after 81,237". Label changes are sent as operations such as "add Receipts, remove INBOX", so two devices editing different labels on one message both succeed.
Sketch the records. Where do bodies and attachments live? What is the partition key, and how do you list "Inbox, newest first" quickly when a message can have many labels?
Compare with a model answer
Metadata is partitioned by user_id, and bodies and attachments live in object storage. A per-label index ordered by time makes a listing one range scan.
Model the data
messages
user_id BIGINT
message_id BIGINT
thread_id BIGINT
dedupe_key BINARY(32) -- hash of Message-ID header + content
from_addr VARCHAR(320)
subject VARCHAR(1000)
snippet VARCHAR(200)
received_at TIMESTAMP
labels BIGINT[] -- INBOX, UNREAD, SPAM, user labels
body_key VARCHAR(64) -- object storage key
attachments JSON -- [{ name, size, blob_key }]
PRIMARY KEY (user_id, message_id), UNIQUE (user_id, dedupe_key)
label_index -- one row per (message, label)
user_id, label_id, received_at, message_id
PRIMARY KEY (user_id, label_id, received_at DESC, message_id)
labels (user_id, label_id, name, total, unread)
changes (user_id, seq, message_id, kind) PRIMARY KEY (user_id, seq)A message can carry many labels. Inbox, Sent, Spam and Trash are system labels, and archiving a message removes its INBOX label without moving anything.
Almost every query is about one user's mail, so everything is partitioned by user_id. The label_index table has one row for each message and label, so "the newest 50 messages in the Inbox" is a single range scan. Bodies and attachments never change after they are written, which suits object storage.
Sketch how a message is received, filed, and shown on a phone. At what exact point do you tell the sending server that the message is accepted?
Compare with a model answer
Write the raw message to object storage and a reference to a durable queue, and only then reply "accepted". Workers filter and file it afterwards.
High-level design
request and replyasynchronous message
- recipient
- ana@
- size
- 45 KB
1A sender's server finds our MX record and names the recipient, ana@. SMTP in checks that the address exists and that the sender passes the reputation and SPF checks.
- recipient
- ana@
- copies
- 3
2The 45 KB message arrives. SMTP in writes it to the blob store as 3 copies and a reference to the replicated queue, then replies 250 OK. The message is now our responsibility.
- spam score
- 0.02
- virus
- none
3A worker reads the message from the blob store, finds a low spam score and no virus, and decides it belongs in the inbox.
- inbox unread
- 4 → 5
- latest seq
- 81,240
4The worker runs one transaction on Ana's shard. It inserts the message, adds the INBOX and UNREAD rows, raises the unread count, and appends change 81,240 to her change log.
- phone seq
- 81,237 → 81,240
5A push tells Ana's phone that her mailbox changed. The phone asks for changes since 81,237 and receives three: a read flag from her laptop, an archive, and the new message.
6In the first crash, a worker commits the delivery and then dies before it acknowledges the queue message. The queue gives the same reference to another worker.
- copies in inbox
- 1
7The second worker's insert violates the unique (user_id, dedupe_key) constraint, so nothing changes and the worker acknowledges the message. Ana sees one copy.
- copies in inbox
- 1
8In the second crash, SMTP in dies after queuing a message but before replying. The sender retries later, and the dedupe key makes the second copy a no-op.
Deep dives
Receiving mail and deciding when to reply 250
SMTP gives every reply a meaning. A 4xx reply means "try again later", and the sending server will retry. A 5xx reply means "permanently refused", and the sending server tells its own user that the message was not delivered. A 250 reply after the message body means that you now own the message and the sender may delete its copy.
There are three places to deal with unwanted mail. The first is to reject it during the SMTP conversation. The sender learns immediately and you store nothing, but the check runs while the sender waits, so only fast and certain checks belong here, such as an unknown recipient or a sending IP address with a bad reputation.
The second is to accept the message and file it in the Spam label. This leaves time for content classifiers and virus scans, which are too slow to run while the connection is open, and the user can rescue a false positive. The cost is that you store the spam.
The third is to accept the message and then send a bounce to the sender. This is the option to avoid. Spam usually forges its sender address, so the bounce goes to an innocent person who never sent anything. That is called backscatter, and it can get your servers blocklisted. Bounces are only for undeliverable mail, from the send path described later.
SMTP in also checks who is really sending the message, because the From address is easy to forge. SPF checks that the connecting IP address is allowed to send for the sender's domain. DKIM checks a cryptographic signature that the sending domain put on the message. DMARC is the policy the domain publishes for what to do when those checks fail, such as reject the message or file it as spam. The results feed into the spam score.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Reject during SMTP | The sender learns about the failure at once, and you store nothing. | The check runs while the connection is open, so it has to be fast. | Use it for cheap and certain checks such as an unknown recipient. |
| Accept, then file as spam Usual default | There is time for content classifiers and virus scans, and false positives can be rescued. | You store the spam, and the sender is never told. | Use it for decisions that depend on message content, which covers most mail. |
If the inbound queue is nearly full, SMTP in replies 451, so senders retry later and mail is delayed but not dropped.
The pipeline delivers each message at least once, and this is deliberate. A sender may retry after a 250 reply gets lost, and the queue may give one message to two workers. Exactly-once delivery is not practical, so the mailbox write is made idempotent with a per-recipient dedupe key, which is a hash of the Message-ID header and the content (see idempotency and retries).
Storing mailboxes, partitioned by user
Each user's mail is independent of everyone else's, so the partition key is user_id. The choice that matters is the kind of store, because one delivery changes several things at once: it adds a message row and label rows, raises the unread count, and appends a change-log entry.
A sharded relational database keeps one user on one shard, so a delivery is one transaction. The message, its labels, the counts and the change log cannot disagree, and the sync sequence number is simple to assign. The cost is operating the sharding yourself. This is the choice for mailboxes.
A wide-column store such as Cassandra also partitions by user and adds capacity by adding nodes, so it absorbs 46,000 writes a second without much effort. Its transactions only cover a single partition, so the label rows, counters and change log can drift apart and need repair jobs.
Users are mapped to shards through a directory and not with user_id modulo the number of shards, so you can move a single user without redistributing everyone (see sharding and partitioning).
Attachments are stored under the SHA-256 hash of their bytes. A 5 MB file that is sent to 200 of your users then takes 5 MB of storage and not 1,000 MB. Users reach an attachment only through a message that they own, never by its hash.
Searching one user's mail
Every search is limited to the mail of the person who asks, so the index is sharded by user. All of one user's documents sit on one shard, a query goes to a single machine, and it cannot return another user's mail.
A global index would send every query to all shards and filter down to one user, and a bug in that filter would show people each other's mail. Mail search never crosses users, so a global index has no benefit.
The index covers headers, body text and attachment names. Operators such as from:, has:attachment and label: are filters on stored fields. The indexer reads the change log, which is why search lags by a couple of seconds, and results are checked against the mailbox so that a message deleted a second ago does not appear. Search systems explains the inverted index itself.
Sending mail with retries and bounces
request and replyasynchronous message
Before the API returns 202, one transaction writes the message to the Sent label and an outbox row, and a relay process moves outbox rows to the outbound queue. Without the outbox row, a crash could leave a message in Sent that was never queued. The draft id is the idempotency key, so a double tap on Send results in one message.
For other recipients, an SMTP out worker takes the message from the queue and does the following:
- Delivery: it groups the recipients by domain, looks up each domain's MX record, connects over TLS, and signs the message with DKIM so that the receiving server can verify that it came from you.
- Temporary failures: a
4xxreply or a timeout means the message goes to the retry schedule. The gaps grow, for example 5 minutes, then 15, then hourly, for at least four to five days as the SMTP standard suggests. - Permanent failures: a
5xxreply such as "no such user", or running out of retries, produces a bounce message in the sender's inbox with the address and the reason.
Syncing devices
Each user has a counter, which is an ordinary column on the user's shard. Every change to the mailbox takes the next number and writes a row to the changes table in the same transaction. Taking the number locks the counter row until commit, so changes commit in order and a reader cannot skip one. A device only has to remember the last number it has seen.
Three situations need explicit handling:
- Telling devices that something changed: web clients keep an open connection and phones receive a push notification (see realtime communication). The notification only says that something changed, so a lost push causes a delay and nothing worse.
- Offline edits: the device queues operations such as "mark m_9f2 read" and replays them when it reconnects. If two devices set conflicting flags, the last write wins.
- A device that is far behind: the change log is kept for 30 days. A request for older changes gets
410, and the device resyncs the newest 500 messages in each label.
Bottlenecks and failures
At 10 times the load, the system would receive about 460,000 messages a second on average and about 1.2 PB of new data a day. Storage cost is the first limit that is hit. You reduce it by compressing bodies, storing attachments once, moving old mail to cheaper tiers, and enforcing quotas. SMTP in and the filter workers are stateless, so you add more of them behind several MX records, and the mailbox and search tiers add shards.
| When this fails | What happens | What you do |
|---|---|---|
| Filter workers fall behind | The inbound queue grows and new mail arrives late, but nothing is lost. | Add workers, and use 451 replies to hold mail at the senders if the queue nears its limit. |
| A mailbox shard primary | Its users cannot read their mail, and deliveries for them wait in the queue. | Fail over to a synchronous replica, and the queue drains. |
| The search cluster | Search fails, while receiving, reading and sending keep working. | Restore the cluster, and the indexer resumes from the change log. |
| The blob store in one zone | Reads are served from the copies in other zones. | Keep each object in at least 3 zones before acknowledging a write. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Draws a mail server that writes into a database, and adds object storage when prompted. |
| Mid | Puts queues between the SMTP edge and processing, partitions by user, and retries outbound mail. |
| Senior | Ties durability to the 250 reply, makes delivery idempotent, avoids backscatter, keeps labels, counts and the sync log in one per-user transaction, and starts the 10x discussion with storage cost. |
A sender's server hands you a message. When do you say "accepted"?
After the raw message is in object storage with three copies and a reference to it is on a replicated queue. Until then I can fail with a 4xx and the sender keeps its copy. After that point, losing the message is our fault.
What if you crash after writing but before replying?
The sender never saw the 250, so it retries. The mailbox insert is unique on a dedupe key built from the Message-ID and a content hash, so the second copy changes nothing.
Follow-up questions
How does undo send work?
The outbound message is queued with a delay of about 10 seconds, and pressing undo deletes it from the queue before it is released. After the message has been handed to another provider it cannot be recalled.
A mailing list sends one message to 1 million of your users. What happens?
You store the body once and queue 1 million deliveries, about 22 seconds of work at 46,000 a second. A lower-priority queue keeps this bulk work from delaying personal mail.
How would you support IMAP clients?
You add an IMAP front end that maps labels to folders and maps the change log to IMAP's modification sequence numbers. A message with two labels appears in two folders, and deleting it from one folder must remove only that label.
How do you group messages into conversations?
Each message carries a Message-ID, and a reply names its parent in the In-Reply-To and References headers. At delivery the worker looks up those ids among the user's recent messages and reuses the existing thread_id, or creates a new one if none matches.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".