The Problem#
Design an email service like Gmail, Outlook.com or Fastmail. Users get an address such as bob@mail.example, receive mail from anyone on the internet, send mail to anyone, read it on the web, phones and desktop apps, organise it into threads, labels or folders, search years of history in a fraction of a second, and trust that spam, phishing and viruses are kept out. The provider must never lose a message it has accepted.
Email is different from most systems you design in interviews because you do not control both ends. A chat app talks only to its own servers. Email is a fifty-year-old federated protocol: your servers exchange mail with millions of other servers run by companies, universities, spammers and hobbyists, over SMTP (Simple Mail Transfer Protocol), and everything has to interoperate. Half the design is about speaking those protocols correctly and defensively; the other half is about running a gigantic per-user storage and search system.
The hard parts are:
- Accepting mail reliably from the internet. Once your server says "250 OK" to a sending server, the message is your responsibility. Losing it silently is the worst failure an email provider can have.
- Knowing who really sent a message. SMTP was designed without authentication, so anyone can claim to be
ceo@bank.example. SPF, DKIM and DMARC are the add-on systems that make spoofing detectable. - Filtering spam and malware in an adversarial setting. Industry estimates commonly put spam at roughly half of all email traffic, and attackers adapt to every filter.
- Sending mail that actually arrives. Other providers judge your reputation; one compromised account blasting spam can get your sending IPs blocklisted.
- Storing petabytes of mail per day with very high durability, while keeping a user's inbox list fast.
- Searching a single user's mailbox of hundreds of thousands of messages in under a second.
- Keeping many devices in sync (web, phone, laptop, IMAP clients) with push notifications and cheap incremental updates.
Analogy. An email service is a city's postal system combined with a private filing service. The sorting office at the city's edge (the inbound SMTP servers) receives sacks of letters from other cities. Clerks check postmarks and seals (SPF and DKIM) and throw obvious junk mail and parcel bombs into the bin (spam and virus filtering). Accepted letters are photocopied into a fireproof vault (durable storage) before the delivery driver signs the receipt. Each resident has a personal filing cabinet (the mailbox) with a card index (metadata and labels) and a librarian who can find any letter by a word in it (search). When a new letter arrives, the resident's doorbell rings (push notification). For outgoing letters, there is a dispatch desk that stamps each letter with the city's official seal (DKIM signing), finds the destination's sorting office (MX lookup), and keeps trying if that office is closed (retries) before finally sending the letter back with a note saying it could not be delivered (a bounce).
Background: a few terms used in this design#
- MUA (mail user agent): the program the user reads mail with: Gmail's web app, Apple Mail, Outlook, Thunderbird.
- MSA (mail submission agent): the server that accepts outgoing mail from a logged-in user, usually on port 587 with authentication.
- MTA (mail transfer agent): a server that relays mail between domains over SMTP on port 25. Postfix, Exim and Microsoft Exchange are common MTAs.
- MDA (mail delivery agent): the component that writes a received message into the right mailbox.
- SMTP: the protocol for moving mail between servers and for submitting it from clients. Defined in RFC 5321.
- MX record: a DNS record that says which servers accept mail for a domain, with a priority number (lower is preferred).
- IMAP / POP3: protocols clients use to read mail from a server. IMAP keeps mail on the server and syncs state (read flags, folders) across devices; POP3 typically downloads and optionally deletes.
- JMAP: a newer JSON-over-HTTP protocol for mail clients (RFC 8620 and RFC 8621), designed for efficient sync and push on mobile.
- Envelope versus headers: the envelope (
MAIL FROM,RCPT TO) is what servers use to route the message, like the address on an outer envelope. The headers (From:,To:,Subject:) are part of the letter inside and are what the user sees. They can differ, which is how both mailing lists and spoofing work. - MIME: the format (Multipurpose Internet Mail Extensions) that lets a message contain HTML, multiple parts, non-ASCII text and attachments, usually encoded in base64.
- SPF, DKIM, DMARC: DNS-based systems that let a receiver check whether a message really comes from the domain it claims. Explained in Deep Dive 2.
- Bounce (DSN, delivery status notification): a message sent back to the sender saying delivery failed.
- Message-ID: a globally unique identifier in each message's headers, used for threading and de-duplication.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Are we building a consumer mailbox provider (like Gmail) or a transactional sender (like Amazon SES)? | Mailbox providers store and search mail; senders focus on throughput and deliverability | Consumer mailbox provider that also sends |
| How many users and how active? | Drives storage, QPS and index size | 500 million mailboxes, 200 million daily active users |
| Must we interoperate with all internet mail (SMTP)? | Means supporting legacy protocols, MX, retries, bounces | Yes, full SMTP in and out |
| Which client protocols: web/mobile API only, or IMAP and POP3 too? | IMAP's stateful sessions shape the storage design | Web and mobile via our API; IMAP and POP3 for third-party clients |
| Storage quota per user? | Total storage and quota enforcement | 15 GB free per user |
| Maximum message and attachment size? | MIME overhead, upload paths, storage | 25 MB to send, 50 MB to receive; larger files shared as links |
| Threads, labels or folders? | Data model for organisation | Gmail-style conversation threads and labels (exposed to IMAP as folders) |
| How fresh must search be? | Indexing pipeline design | New mail searchable within about 10 seconds |
| How quickly must new mail appear on devices? | Push and sync design | Within a few seconds of acceptance |
| Is end-to-end encryption required? | It rules out server-side search and spam scanning of content | No by default; discuss as an extension |
| Retention, legal hold and deletion rules? | Affects storage lifecycle and compliance | Users delete freely; trash purged after 30 days; legal hold for business accounts |
| Global users? | Multi-region placement and latency | Yes; each user has a home region |
Requirements#
Functional requirements#
- Receive mail from any internet sender for any address on our domains, and deliver it to the right mailbox (or the spam folder).
- Send mail to any internet address, with retries, bounces and correct authentication so it is not marked as spam.
- Read mail: list threads by label with unread counts, open a thread, download attachments.
- Organise: threads (conversations), labels, stars, archive, trash, filter rules ("label mail from my bank as Finance").
- Search the full mailbox, including attachments' text, with operators like
from:,has:attachmentandbefore:. - Sync and push to multiple devices, including standard IMAP clients.
- Drafts and attachments saved while composing, with quota enforcement.
- Protect users from spam, phishing and malware, and let them report spam.
Out of scope: calendar and contacts beyond address autocomplete, chat, advertising, and the details of the identity system (we assume a login service exists).
Non-functional requirements#
- Durability: an accepted message must never be lost. Target effectively zero loss (multiple synchronous replicas before acknowledging).
- Availability: 99.99 % for receiving mail at the SMTP edge (senders retry, which helps, but long outages bounce mail and hurt trust); 99.9 % or better for reading and sending.
- Latency: inbox list in under 200 ms at p99 from the API; open a message in under 300 ms; search in under 1 second at p99; end-to-end delivery from acceptance to the user's device in under 10 seconds normally.
- Scale: tens of billions of messages per day, exabytes of stored mail.
- Security and privacy: TLS in transit, encryption at rest, strict isolation between users' mailboxes, strong account security.
- Correctness of state: read/unread, labels and deletions must converge across devices; IMAP clients must never see a UID reused for a different message.
- Deliverability: our outgoing mail must keep a good reputation with other providers.
Capacity Estimation#
These are design-target numbers, not any provider's real figures. Gmail is publicly reported to have well over a billion users, so 500 million mailboxes is a reasonable "very large provider" target. See Back-of-the-Envelope Estimation for the method.
Inbound traffic.
- Each mailbox receives about 40 legitimate messages a day (newsletters, notifications, personal mail).
- 500 million × 40 = 20 billion delivered messages per day ≈ 230,000 per second on average.
- Peak-to-average ratio of about 2.5 (business hours and marketing send times overlap) gives about 600,000 deliveries per second at peak.
- Many more connection attempts arrive than messages are delivered: spam and abusive connections can be as much as the legitimate volume or more. Most are rejected cheaply at connection time, but the SMTP edge must be sized for roughly 2× the delivery rate in SMTP transactions.
- One message to several of our users (a company announcement to 200 employees) is one SMTP transaction with many
RCPT TOlines, fanned out internally.
Outbound traffic. Each daily active user sends about 5 messages a day: 200 million × 5 = 1 billion per day ≈ 12,000 per second average, 30,000 per second peak. About 70 % of recipients are typically on other providers, so most outbound messages need an external SMTP connection.
Message size. Text-only messages are a few KB to tens of KB (HTML newsletters are often 50–100 KB). Attachments make the mean much larger. Assume a mean of 75 KB per message stored (bodies plus attachments, before compression); the median is much smaller.
Storage.
- 20 billion × 75 KB = 1.5 PB of new mail per day, about 550 PB per year before compression and de-duplication.
- Text compresses about 3–4×; attachments (PDFs, images) barely compress. Blended, assume 1.5–2×.
- Bulk mail de-duplicates very well: one newsletter body sent to 5 million of our users can be stored once (Deep Dive 5). If a third of bytes are such bulk duplicates, storage drops considerably.
- Net: on the order of 200–400 PB of new physical storage per year at replication factor 1. With three replicas or erasure coding at about 1.5× overhead, raw disk needed is larger still. This is why the bodies live in a blob store with erasure coding and cold tiers, not in a database.
- The average user stores perhaps 2–5 GB, so 500 million users hold on the order of 1–2.5 EB in total. Quotas (15 GB free) cap the tail.
Metadata. Each message needs a metadata record: IDs, thread ID, labels, flags, sender, subject, snippet, size, timestamps. About 1 KB per message with indexes. A user with 100,000 messages has about 100 MB of metadata. Twenty billion new messages a day means about 20 TB of new metadata per day, about 7 PB per year. That is large, but it is well partitioned by user.
Read traffic.
- Each daily active user opens the app or syncs about 30 times a day and opens 20 messages.
- Inbox list and sync calls: 200 million × 30 = 6 billion per day ≈ 70,000 per second, peaks of about 200,000 per second.
- Message opens: 4 billion per day ≈ 46,000 per second average.
- IMAP clients hold long-lived connections: if 50 million clients are connected at once, the IMAP tier must hold 50 million TCP connections. At around 50,000–100,000 idle connections per server, that is 500–1,000 servers just for IMAP sessions.
Search. Two searches per daily active user per day = 400 million per day ≈ 5,000 per second, peak about 15,000 per second. The inverted index is typically 20–40 % of the indexed text size. If we index 30 KB of extractable text per message, 20 billion messages add about 600 TB of text a day, so about 150–250 TB of new index per day.
Push. Every delivery to an active user triggers a push to each of their devices. With 1.5 devices per user on average and many deliveries batched, expect 100,000–300,000 push notifications per second at peak, sent through Apple Push Notification service and Firebase Cloud Messaging.
Summary of the shape. Writes (deliveries) are huge and continuous; bodies are write-once and rarely read after the first week; metadata is small per item but very hot; reads are dominated by "what changed in my mailbox", not by bodies. Everything is naturally partitioned by user, which is the single most important fact in this design.
| Quantity | Estimate |
|---|---|
| Deliveries | 230k/s average, 600k/s peak |
| Outbound sends | 12k/s average, 30k/s peak |
| New mail stored | ~1.5 PB/day logical, before compression and dedup |
| Metadata | ~1 KB per message, ~20 TB/day |
| Inbox and sync reads | 70k/s average, 200k/s peak |
| Search queries | 5k/s average, 15k/s peak |
| Concurrent IMAP sessions | tens of millions |
Core Entities#
- Account / User: the person, with login identity, addresses (primary and aliases), quota and home region.
- Message: an immutable RFC 5322 message: headers plus MIME body. Stored once as a blob; identified internally by a message ID and externally by its
Message-IDheader. - Message metadata (mailbox entry): the user-specific view of a message: which labels it has, read/unread, starred, thread ID, received time, size, snippet. If a message is delivered to two of our users, each gets their own metadata entry pointing to the same (or a copied) body.
- Thread (conversation): a group of related messages, determined by headers (
References,In-Reply-To) and subject (Deep Dive 6). - Label: a user-defined or system tag (INBOX, SENT, SPAM, TRASH, STARRED, custom). Many-to-many with messages.
- Attachment: a MIME part stored as a blob, often content-addressed by hash.
- Draft: a mutable message being composed; becomes an outbound message on send.
- Filter rule: a user's condition and action ("from:bank.example → label Finance, skip inbox").
- Outbound queue entry: a message waiting to be delivered to a remote domain, with retry state.
- Change log entry: an ordered record of every change to a mailbox, used for sync (Deep Dive 10).
- Domain: for business customers, a custom domain with its MX, SPF, DKIM keys and DMARC policy.
API Design#
Email has two kinds of interfaces: standard protocols we must speak with the outside world, and our own client API for web and mobile apps. See API Design Best Practices for general conventions.
Standard protocols.
| Protocol | Port | Purpose |
|---|---|---|
| SMTP (server to server) | 25 | Receive mail from, and send mail to, other providers; STARTTLS for encryption |
| SMTP submission | 587 (STARTTLS) or 465 (implicit TLS) | Authenticated clients send mail |
| IMAP | 993 (TLS) | Third-party clients read and sync mail |
| POP3 | 995 (TLS) | Simple download clients |
| JMAP (optional) | 443 | Modern JSON sync protocol |
Client API (REST over HTTPS, JSON). It resembles the public Gmail API in shape, which is a useful mental model.
GET /v1/threads?label=INBOX&pageToken=...&limit=50
→ { threads: [{ id, snippet, subject, participants, unread, labels, lastDate }], nextPageToken }
GET /v1/threads/{threadId} → messages with headers and bodies (or body parts)
GET /v1/messages/{messageId}/attachments/{partId} → 302 to a short-lived signed URL
POST /v1/messages/send
Idempotency-Key: 7d1c... # retries never send twice
{ raw: base64url(RFC 5322 message) } or { draftId }
→ 202 { messageId, threadId }
POST /v1/drafts PUT /v1/drafts/{id} DELETE /v1/drafts/{id}
POST /v1/uploads → { uploadUrl } # large attachments go direct to blob store
POST /v1/messages/batchModify
{ ids: [...], addLabels: ["Finance"], removeLabels: ["INBOX"] }
GET /v1/search?q=from:alice has:attachment before:2026/01/01&pageToken=...
GET /v1/history?startHistoryId=918273 # changes since the client's last sync point
→ { history: [{ id, messagesAdded, labelsAdded, labelsRemoved, messagesDeleted }], historyId }
POST /v1/watch { deviceToken, platform: "apns" } # register for pushDesign notes:
- Send returns 202 Accepted, not 200: the message is queued, and delivery to remote servers happens asynchronously and may take minutes or fail days later (a bounce arrives as a new message).
- Idempotency keys on send make a retry after a mobile network drop safe; the server stores the key with the resulting message ID for 24 hours. See Idempotency and Safe Retries.
- History IDs are monotonically increasing per mailbox. A client that remembers the last ID it saw can ask for only the changes since then, which is far cheaper than re-listing the inbox. If the ID is too old (the change log was trimmed), the server returns 410-style "full sync required" and the client re-lists.
- Attachments are not streamed through the API servers; the API returns a signed URL to the blob store or a download service, the same pattern as presigned URLs in Object Storage and Blob Storage.
- Pagination uses opaque page tokens (encoding the last thread's sort key), not offsets, so new mail arriving does not shift pages.
- Rate limits per user on send (for example a few thousand recipients per day for consumer accounts) are a core anti-abuse control, returned as 429 with
Retry-After.
High-Level Design#
We build the design one requirement at a time, then combine the pieces.
1) Receiving mail from the internet#
A sender's MTA looks up the MX record for mail.example in DNS, gets the names of our inbound servers, and opens an SMTP connection on port 25. Our MX hostnames resolve to anycast IPs or to regional network load balancers that spread connections across a fleet of SMTP edge servers.
The edge server runs the SMTP conversation. It checks the connecting IP against reputation lists and rate limits before accepting anything, verifies that each recipient exists, receives the message body, runs fast checks (size, SPF, DKIM, DMARC, virus signatures, a first spam score), and only then decides. If it accepts, it must first write the message durably: to a replicated inbound queue or log with at least two replicas in different zones. Only after that write succeeds does it reply 250 OK. If anything fails before that point, it replies with a 4xx temporary error and the sender retries later, so no mail is lost.
2) Processing and delivering to mailboxes#
Delivery workers consume the inbound queue. For each recipient they run deeper spam and phishing classification, apply the user's filter rules, decide labels (INBOX or SPAM, plus any custom labels), assign a thread, store the body in the blob store, write the metadata entry and change-log entry in the mailbox metadata store, and emit an event for indexing and push. The work is idempotent per (message, recipient), so a worker crash and redelivery from the queue cannot create a duplicate.
3) Reading mail on web, mobile and IMAP#
Web and mobile apps call the Mail API through an API gateway. Inbox lists come from the metadata store, which holds everything needed to render a thread list (subject, snippet, participants, unread, labels) without touching bodies. Opening a message fetches the body from the blob store, via a cache for recently delivered mail, which is most of what users open. IMAP clients connect to an IMAP gateway that translates IMAP commands into the same metadata and blob calls.
4) Sending mail#
The user's client posts the message to the Mail API (or to SMTP submission on port 587 for IMAP clients). The submission service authenticates the user, checks rate limits and quotas, scans outbound content for spam and malware (a compromised account is a big risk), stores a copy in the user's SENT label, and places one outbound queue entry per destination domain. Recipients on our own domains are delivered internally through the inbound pipeline's delivery workers. Outbound MTAs sign with DKIM, look up the remote MX, connect over TLS, and deliver, retrying on temporary failures for days and generating a bounce if delivery finally fails.
5) Search and push#
The indexer consumes mailbox change events and updates a per-user inverted index: new messages are tokenised (including text extracted from attachments), and label changes and deletions update the index. Queries go from the Mail API to a search service that routes to the shard holding that user's index. The push service consumes the same events and sends a small notification ("mailbox changed, history ID 918300") through APNs or FCM to mobile devices, over a held-open connection to web clients, and as IMAP IDLE responses to IMAP clients. Devices then call the history API to fetch the actual changes.
The full high-level design#
Components:
- SMTP edge: stateless servers that speak SMTP, terminate TLS, enforce connection-level defences and authentication checks, and acknowledge only after a durable write.
- Durable inbound queue: a replicated log or queue (Kafka-style, or a custom replicated spool) that decouples accepting from processing; it absorbs bursts and lets delivery workers fail and retry safely.
- Delivery workers: run spam classification, user filters, threading and storage writes; idempotent per message and recipient.
- Blob store: immutable, content-addressed storage for bodies and attachments; erasure-coded, tiered by age. Similar in role to the system in Design an Object Store (Amazon S3).
- Metadata store: a horizontally partitioned store keyed by user, holding mailbox entries, labels, threads, counters and the change log. A wide-column store (Bigtable, HBase, Cassandra) or sharded relational database fits.
- Mail API and submission service: the client-facing logic for listing, reading, modifying and sending.
- IMAP and POP3 gateways: protocol translators that hold long-lived connections and map IMAP's UID and folder model onto our labels and change log.
- Search service and indexer: per-user inverted indexes, updated from change events.
- Push service: turns mailbox changes into device notifications and IMAP IDLE updates.
- Outbound queue and MTAs: per-domain queues, DKIM signing, retry scheduling, bounce generation, IP pool and reputation management.
- Caches: recent bodies, thread lists and unread counts for active users.
Key Flows#
Flow 1: a message from another provider arrives#
Alice at other.example writes to Bob at mail.example. Her provider's MTA does the MX lookup and connects to our edge. Note where the 250 happens: after the durable write, never before.
If the edge's queue write times out, it answers 451 4.3.0 temporary failure, and Alice's MTA retries later. Alice's MTA may also retry if the connection drops after we wrote the message but before it saw our 250. Then we receive the same message twice. The delivery worker de-duplicates on (recipient, Message-ID, body hash) within a window of a few days, so Bob sees one copy.
Flow 2: Bob sends a reply to a remote recipient#
The retry schedule follows the spirit of RFC 5321: retry intervals of at least tens of minutes after the first few attempts, and keep trying for about four to five days before giving up. Most real MTAs start faster (a retry after a minute or a few minutes) because many temporary failures are greylisting (Deep Dive 3) or brief overloads.
Flow 3: a new message reaches Bob's phone and laptop#
The push carries no message content by default, so a stolen push token or a compromised push provider reveals nothing, and the device always fetches through an authenticated channel. Some apps include sender and subject in the push for display, encrypted for the device, as a deliberate trade-off for faster notifications.
Data Model#
The data splits into three stores with very different access patterns: immutable blobs (bodies, attachments), mutable per-user metadata (labels, flags, threads, counters, change log) and derived indexes (search). Everything in the metadata store is keyed by user ID first.
The second half of the model covers content and sync state: each mailbox entry points to an immutable body blob (shared by many entries when de-duplicated), bodies reference separately stored attachments, and every change to the account appends to its change log.
As a relational sketch (each table sharded by user_id; in a wide-column store, each becomes a row-key prefix):
CREATE TABLE mailbox_entry (
user_id BIGINT NOT NULL,
message_id BIGINT NOT NULL, -- per-user, time-ordered (Snowflake-style)
thread_id BIGINT NOT NULL,
rfc_message_id TEXT, -- Message-ID header, for threading and dedup
internal_date TIMESTAMPTZ NOT NULL,
flags INT NOT NULL DEFAULT 0, -- seen, flagged, answered, draft bits
size_bytes INT NOT NULL,
snippet TEXT,
body_ref TEXT NOT NULL, -- pointer into the blob store
modseq BIGINT NOT NULL, -- last change number, for IMAP CONDSTORE and sync
PRIMARY KEY (user_id, message_id)
);
-- "List INBOX newest first": one range scan per label.
CREATE TABLE entry_label (
user_id BIGINT NOT NULL,
label_id INT NOT NULL,
sort_key BIGINT NOT NULL, -- e.g. reversed internal_date + message_id
message_id BIGINT NOT NULL,
PRIMARY KEY (user_id, label_id, sort_key)
);
CREATE TABLE change_log (
user_id BIGINT NOT NULL,
history_id BIGINT NOT NULL, -- strictly increasing per user
change_type SMALLINT NOT NULL, -- added, deleted, label_add, label_remove, flags
message_id BIGINT NOT NULL,
payload BYTEA,
PRIMARY KEY (user_id, history_id)
);| Data | Store | Why |
|---|---|---|
| Message bodies and attachments | Blob store (erasure-coded, tiered) | Write-once, large, read mostly in the first days; cheap per byte matters most |
| Mailbox entries, labels, threads | Wide-column store or sharded SQL, partitioned by user | Small rows, range scans per user and label, high write rate |
| Label counters | Same partition as labels, updated in the same transaction | Unread counts must match the list |
| Change log | Same partition, append-only, trimmed after weeks | Cheap incremental sync |
| Search index | Per-user inverted index shards | Queries are always scoped to one user |
| Inbound and outbound queues | Replicated log or durable queue | Absorb bursts, retries, crash safety |
| Recent bodies, hot thread lists | In-memory cache (Redis or Memcached) | Most opens are of mail from the last few days |
| Contacts for autocomplete | Small per-user store plus a prefix index | Instant suggestions while typing |
Why a per-user partition key. Every query a client makes is scoped to one mailbox: list my inbox, open my thread, search my mail. Putting all of a user's metadata on one partition makes these single-partition operations, and lets us update a message's labels, the label counters and the change log atomically in one local transaction. The cost is that very large mailboxes (a shared support inbox with 50 million messages) become hot or oversized partitions; those need sub-partitioning by time. See Partitioning and Sharding.
Why not one big relational database. 20 billion new rows a day and petabytes of metadata exceed any single database. Sharded MySQL or PostgreSQL works (many providers started that way), as does a wide-column store. Wide-column stores like Bigtable, HBase or Cassandra fit the "row key = user + label + time" access pattern naturally and scale writes horizontally, but give up rich queries and, in Cassandra's case, need careful design for counters and multi-row atomicity. Choosing a Database: A Decision Guide walks through this decision.
Deep Dives#
1. How email delivery works: SMTP, MX records, IMAP and POP#
Store and forward. Email is a store-and-forward system. Each hop takes full responsibility for a message before passing it on, so a message can survive a destination being offline for hours: the sender's server keeps it and retries. This is why email still works between millions of independently run servers with no central coordinator.
The full path of a message:
- Alice's MUA submits the message to her provider's MSA (port 587 with STARTTLS, or 465 with implicit TLS, RFC 8314), authenticating with her credentials or an OAuth token.
- Her provider's MTA looks up the recipient domain's MX records in DNS.
- It connects to the highest-priority (lowest number) MX host on port 25 and runs an SMTP transaction.
- The receiving MTA accepts responsibility (reply
250) and hands the message to its MDA, which files it into Bob's mailbox. - Bob's MUA retrieves it via IMAP, POP3, JMAP or a proprietary API.
MX lookup. A domain publishes records like:
mail.example. 3600 IN MX 10 mx1.mail.example.
mail.example. 3600 IN MX 10 mx2.mail.example.
mail.example. 3600 IN MX 20 mx-backup.mail.example.Senders try the lowest preference value first; among equal preferences they pick randomly, which spreads load. If all MX hosts fail, they queue and retry. If a domain has no MX record, RFC 5321 says to fall back to its A/AAAA record (the "implicit MX"). A domain can publish a "null MX" (MX 0 ., RFC 7505) to say it accepts no mail at all, which stops pointless retries. For a large provider, each MX hostname points at anycast or load-balanced IPs that front hundreds of edge servers per region. Keep MX TTLs moderate (minutes to an hour) so you can shift traffic during incidents without breaking caches. DNS: The Domain Name System covers resolution and caching.
An SMTP transaction. SMTP is a line-based text protocol over TCP. Each command gets a three-digit reply: 2xx success, 3xx "go on", 4xx temporary failure (retry later), 5xx permanent failure (do not retry). Enhanced status codes such as 5.1.1 (bad mailbox) add detail (RFC 3463).
S: 220 mx1.mail.example ESMTP ready
C: EHLO out.other.example
S: 250-mx1.mail.example
S: 250-SIZE 52428800
S: 250-8BITMIME
S: 250-STARTTLS
S: 250 PIPELINING
C: STARTTLS
S: 220 2.0.0 go ahead (TLS handshake, then EHLO again)
C: MAIL FROM:<alice@other.example>
S: 250 2.1.0 ok
C: RCPT TO:<bob@mail.example>
S: 250 2.1.5 ok
C: RCPT TO:<nobody@mail.example>
S: 550 5.1.1 no such user (rejected during the session, no bounce needed)
C: DATA
S: 354 end data with <CRLF>.<CRLF>
C: From: Alice <alice@other.example>
C: To: Bob <bob@mail.example>
C: Subject: Lunch?
C: Message-ID: <20261203.1234@other.example>
C:
C: Are you free on Friday?
C: .
S: 250 2.0.0 ok queued as 8f2a (sent only after the durable write)
C: QUIT
S: 221 2.0.0 byeThings worth noticing:
- Envelope and headers are separate.
MAIL FROM(the envelope sender, also called the return path or bounce address) is where bounces go. TheFrom:header is what users see. A mailing list keeps the author'sFrom:but uses its own envelope sender to receive bounces. A spoofer setsFrom: ceo@bank.examplewith any envelope. Authentication systems (Deep Dive 2) tie these together. - The extension list in the EHLO reply advertises capabilities: maximum size, 8-bit content, pipelining (send several commands without waiting), STARTTLS, and SMTPUTF8 for internationalised addresses.
- Rejecting during the session is better than bouncing later. If we accept a message for a non-existent user and then send a bounce, the bounce goes to the envelope sender, which spammers forge. Sending bounces to innocent forged addresses is called backscatter, and it gets your servers blocklisted. So the edge validates recipients in real time against the user directory.
- The end-of-data dot means lines in the body starting with "." must be escaped (dot-stuffing), a detail every SMTP implementation must handle.
Encryption in transit. STARTTLS upgrades a plain connection to TLS, but it is opportunistic: an active attacker can strip the STARTTLS capability from the EHLO reply and force plaintext. Two standards fix this:
- MTA-STS (RFC 8461): a domain publishes, over HTTPS, a policy saying "my MX hosts are these, and they always support TLS with valid certificates". Senders that support MTA-STS cache the policy and refuse to deliver in plaintext. Gmail and other large providers support it.
- DANE for SMTP (RFC 7672): the TLS certificate fingerprint is published in DNS (TLSA records), protected by DNSSEC.
- TLS-RPT (RFC 8460): receivers get daily reports of TLS failures from senders, so misconfigurations are visible.
For our service: support STARTTLS everywhere, publish MTA-STS for our domains, honour other domains' MTA-STS and DANE when sending, and collect TLS-RPT reports.
Reading mail: POP3, IMAP and JMAP.
| POP3 (RFC 1939) | IMAP (RFC 3501, IMAP4rev2 RFC 9051) | JMAP (RFC 8620, 8621) | |
|---|---|---|---|
| Model | Download messages, optionally delete from server | Mail stays on server; folders, flags, partial fetch | JSON over HTTP; mailboxes, threads, changes |
| Multi-device | Poor (each device downloads separately) | Good (shared server state) | Good, designed for it |
| Sync | Re-list everything | UIDs, UIDVALIDITY, CONDSTORE/QRESYNC for deltas | Built-in state strings and /changes |
| Push | None | IDLE (RFC 2177) per connection, one folder at a time | Push via EventSource or webhooks |
| Connections | Short-lived | Long-lived, stateful, often several per client | Stateless HTTP requests |
| Server cost | Low | High: many idle connections, complex state | Moderate |
IMAP's model shapes storage. IMAP gives each message in a folder a UID, a number that strictly increases within that folder and is never reused. A folder also has a UIDVALIDITY value; if the server ever has to renumber UIDs, it must change UIDVALIDITY, and clients then throw away their cache and re-download everything, which for a big mailbox is very expensive. So our metadata store must allocate per-label UIDs monotonically and durably. The CONDSTORE and QRESYNC extensions (RFC 7162) add a MODSEQ (modification sequence) per message, so a client can ask "what changed since MODSEQ 918250?" instead of re-fetching all flags. Our per-user change log provides exactly this.
Labels as folders. Gmail exposes labels to IMAP clients as folders: a message with labels INBOX and Finance appears in both folders. Removing it from the Finance folder removes the label; deleting it from "All Mail" deletes it. This mapping is lossy and confuses some clients (the same message downloaded twice), which is a known trade-off of labels over folders (Deep Dive 6).
Why JMAP exists. IMAP was designed for desktop clients on always-on connections. On mobile, holding a TCP connection per folder for IDLE drains batteries and breaks on network changes, and IMAP's command syntax is hard to implement correctly. JMAP, developed with significant involvement from Fastmail and standardised by the IETF in 2019, batches many operations into one HTTP request, returns only changes since a state token, and uses standard push channels. Our own client API follows the same principles: stateless HTTP, history IDs and push-then-fetch.
Practical numbers. An SMTP transaction for a small message within a continent completes in around 100–500 ms, most of it TCP and TLS handshakes and round trips; connection reuse and pipelining cut that significantly. Typical maximum accepted sizes are 25–50 MB on large providers (base64 encoding inflates attachments by about 33 %, so a 25 MB limit means roughly 18 MB of original file data). End-to-end delivery between major providers usually takes a few seconds; delays of minutes usually mean greylisting, deferrals or queue backlogs.
2. Who really sent this? SPF, DKIM and DMARC#
SMTP lets any server claim any sender. Three DNS-published mechanisms, layered on top over the 2000s and 2010s, let a receiver check claims. None is sufficient alone; together they make domain spoofing detectable and let domain owners tell receivers what to do with failures.
SPF (Sender Policy Framework, RFC 7208): "which IPs may send for my domain?" The domain in the envelope MAIL FROM publishes a TXT record listing authorised senders:
other.example. IN TXT "v=spf1 ip4:203.0.113.0/24 include:_spf.mailvendor.example -all"The receiver checks whether the connecting IP matches. Results are pass, fail (-all, hard fail), softfail (~all), neutral, none, or temperror/permerror. Details that matter:
- The 10-lookup limit. Evaluating
include,a,mx,existsandredirectmechanisms may cause at most 10 DNS lookups in total; exceeding that is apermerror. Companies that use many sending vendors hit this limit and have to "flatten" their records into IP lists, which then go stale. - SPF checks the envelope domain, not the visible
From:. A spammer can pass SPF for their own domain while showingFrom: ceo@bank.example. DMARC alignment fixes this. - Forwarding breaks SPF. If Bob forwards mail from his university address to us, the university's server is now the connecting IP, which is not in the original sender's SPF record. SRS (Sender Rewriting Scheme) rewrites the envelope sender to work around this, and ARC (below) preserves the original results.
DKIM (DomainKeys Identified Mail, RFC 6376): "this message was signed by my domain and not altered." The sending server computes a hash of the body and selected headers and signs it with a private key. The signature goes in a header:
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=other.example; s=sel2026;
h=from:to:subject:date:message-id; bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
b=AuMCt3...signature...The receiver fetches the public key from DNS at sel2026._domainkey.other.example, recomputes the hashes and verifies the signature. Key points:
- Selectors (
s=) allow several keys per domain, so keys can be rotated (publish new selector, switch signing, remove old after a few days) and different vendors can sign with their own keys. - Canonicalisation (
c=relaxed/relaxed) normalises whitespace and header case so minor changes by relays do not break the signature.simpleis stricter. - The
From:header must be signed, and senders often sign it twice ("oversigning") to prevent an attacker adding a secondFrom:header. - Key sizes: 2048-bit RSA keys are the common recommendation today (1024-bit keys are considered weak); Ed25519 signatures are standardised for DKIM (RFC 8463) but not yet universally verified, so senders that use them usually also sign with RSA.
- DKIM survives forwarding (the message is unchanged) but breaks when a mailing list adds a footer or a "[list]" subject tag.
DMARC (RFC 7489): "here is my policy if both fail, and send me reports." DMARC ties SPF and DKIM to the visible From: domain through alignment: a message passes DMARC if SPF passes and the envelope domain aligns with the From: domain, or DKIM passes and the signing domain d= aligns with the From: domain. "Relaxed" alignment allows subdomains (news.bank.example aligns with bank.example); "strict" requires an exact match.
_dmarc.bank.example. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc-reports@bank.example; adkim=s; aspf=r; pct=100"p=noneonly collects reports,p=quarantineasks receivers to put failures in spam,p=rejectasks them to refuse at SMTP time.ruareceives daily aggregate reports (XML listing source IPs and pass/fail counts) from receivers, so a domain owner can discover every system sending as their domain before moving toreject.- Domain owners typically roll out
none→quarantinewithpctsampling →rejectover weeks or months.
ARC (Authenticated Received Chain, RFC 8617). Mailing lists and forwarders break SPF and DKIM legitimately. ARC lets each intermediary record the authentication results it saw and sign them. A receiver that trusts the intermediary can honour the original pass even though the final check fails.
What we do as a receiver. For every inbound message: evaluate SPF on the envelope, verify all DKIM signatures, evaluate DMARC alignment and policy, check ARC chains from trusted forwarders, and record the results in an Authentication-Results header (RFC 8601) for downstream filters and for display ("this message may not be from bank.example"). A DMARC reject policy usually leads to a 5xx at SMTP time; quarantine routes to spam. Authentication results are strong features for the spam classifier, not the whole answer: spammers authenticate their own domains perfectly well.
What we do as a sender. Publish SPF for our outbound IPs, sign all outgoing mail with DKIM (rotating keys regularly), publish DMARC p=reject for our own domains, and for business customers with custom domains, generate DKIM keys and tell them which DNS records to add, then verify those records before enabling sending. Since February 2024, Gmail and Yahoo have required bulk senders (Google's threshold is about 5,000 messages a day to Gmail) to authenticate with SPF and DKIM, publish DMARC, support one-click unsubscribe (RFC 8058) for marketing mail, and keep reported spam rates low (Google cites staying below 0.3 %). These rules show how mailbox providers use their market position to raise authentication standards.
BIMI (Brand Indicators for Message Identification) is a newer specification that lets a domain with a strict DMARC policy show its logo next to messages in supporting clients, often requiring a verified mark certificate. It rewards strong authentication with visibility.
Lookalike domains are not stopped by any of this. bank-example-secure.com can have perfect SPF, DKIM and DMARC. Detecting those is the job of the content and reputation filters in Deep Dive 8, plus UI warnings for first-time senders and display names that impersonate known contacts.
3. The inbound pipeline: accept safely, filter in layers#
The inbound path is a funnel. Cheap checks run first on every connection; expensive checks run only on messages that survive. Industry experience is that most abusive traffic can be rejected before the DATA phase, which saves bandwidth and CPU.
Layer 1: connection time (before any message content).
- IP reputation. Look up the connecting IP in internal reputation data and public DNS blocklists (DNSBLs) such as Spamhaus. Known-bad IPs get a 5xx immediately. Large providers maintain their own reputation systems based on what each IP sent before and how users reacted.
- Reverse DNS checks. Legitimate mail servers usually have matching forward and reverse DNS; residential IPs without it are suspicious.
- Rate limiting and tarpitting. Limit connections and messages per IP and per /24 network. For suspicious clients, slow down replies (tarpitting) to make spamming expensive. See Rate Limiting and Throttling.
- Protocol hygiene. Spam bots often talk before the server's greeting or ignore pipelining rules. Detecting these "early talkers" is cheap and effective.
Layer 2: envelope (MAIL FROM, RCPT TO).
- Recipient validation against the user directory, served from an in-memory replica or cache because it is queried for every recipient (hundreds of thousands per second). A Bloom filter in front can quickly reject addresses that definitely do not exist; see Probabilistic Data Structures for Big Data.
- Directory harvest protection. Spammers try thousands of guessed addresses; limit invalid recipients per connection and per IP.
- Greylisting. For an unknown (IP, sender, recipient) triplet, reply
451 try again later. Real MTAs retry after a few minutes; many spam tools never retry. It is effective but delays legitimate first-time mail, so large providers use it selectively for low-reputation sources. - Quota check. If the recipient's mailbox is full, reply
452 4.2.2(temporary) or552and let the sender handle it.
Layer 3: content (after DATA).
- Size limits advertised in EHLO and enforced.
- Authentication (Deep Dive 2).
- Antivirus scanning with signature engines (for example ClamAV or commercial engines) and blocked file types: Gmail, for example, blocks executable attachments such as
.exefiles, even inside archives. - A first spam score from a fast model. If it is confidently spam, reject at SMTP time (5xx) so no bounce is needed. Otherwise accept and let delivery workers decide inbox versus spam.
The acceptance contract. The edge replies 250 only after the message is in a replicated, durable queue: for example, written to a log with acknowledgements from replicas in at least two availability zones. This mirrors the discipline of financial systems that must stay correct across asynchronous networks: never confirm what you have not durably recorded, and design every downstream step to be safely retried. If the edge crashes after the durable write but before replying, the sender retries and we get a duplicate, which de-duplication absorbs. If it crashes before the write, the sender retries and nothing is lost. There is no window where a message is acknowledged but not stored.
Layer 4: delivery workers. After acceptance, per recipient:
- Expand recipients: aliases, distribution groups and forwarding rules. A message to
team@corp.examplewith 500 members becomes 500 mailbox deliveries; a forwarding rule becomes an outbound send with SRS. - Full spam and phishing classification with user-specific signals (Deep Dive 8).
- User filter rules: evaluate the user's filters (from, to, subject, has-words) in order; actions are label, archive, mark read, forward, delete.
- Threading (Deep Dive 6).
- Store the body in the blob store (or reference an existing blob if de-duplicated).
- Write metadata atomically: mailbox entry, label memberships, counter increments and change-log entry in one transaction on the user's partition.
- Emit a change event for indexing and push.
Idempotency: the delivery worker computes a delivery key such as hash(recipient, queue message ID). The metadata write is conditional on that key not existing, so a redelivered queue message becomes a no-op. The queue message is acknowledged only after the metadata write.
Fan-out and large recipient lists. A newsletter sent to 2 million of our users arrives as thousands of SMTP transactions with up to a few hundred recipients each (many senders cap RCPT TO per transaction). The body is stored once; each recipient gets a small metadata entry pointing to it. This is one of the most valuable de-duplication opportunities in the whole system.
Back pressure. If delivery workers fall behind, the inbound queue grows. The edge watches queue depth and, beyond a threshold, starts replying 451 to low-reputation senders first, then to everyone. Legitimate MTAs retry, so a short slowdown is absorbed by the internet's own retry machinery. That is a graceful degradation path few other systems have for free.
4. The outbound pipeline: queues, retries, bounces and reputation#
Sending looks simple ("connect and deliver"), but at scale it is a scheduling and reputation problem. Every large receiver throttles senders it does not trust, and every mistake (a compromised account, a misconfigured customer domain) is judged against our shared IP addresses.
Submission. Mail enters from the web or mobile API, or from authenticated SMTP on port 587. The submission service:
- Authenticates the user (OAuth tokens or app passwords; large providers have been retiring plain password authentication for SMTP and IMAP in favour of OAuth).
- Enforces sending limits: per-minute and per-day message and recipient caps. Gmail documents daily limits on the order of a few hundred to a few thousand recipients depending on account type; new accounts get lower limits.
- Scans outbound content with the same spam and malware models used inbound. A sudden burst of near-identical messages to many unknown recipients is the classic sign of a compromised account; the account is throttled or suspended.
- Writes the message to the user's SENT label and change log (so it appears on all devices immediately).
- Splits recipients by destination: local recipients go to internal delivery; remote recipients are grouped by domain into outbound queue entries.
Per-domain queues and scheduling. Grouping by destination domain lets one SMTP connection carry many messages (connection reuse, up to dozens of messages per connection) and lets us respect each receiver's limits. A scheduler picks which domain queue to service next, how many parallel connections to open per destination, and when to back off. A receiver replying with 421 or 451 "too many connections" or "rate limited" makes the scheduler lower concurrency for that domain, much like TCP congestion control: additive increase while successful, multiplicative decrease on deferrals.
Retries and backoff. RFC 5321 suggests retrying at intervals of at least 30 minutes and giving up after at least 4 to 5 days. In practice:
attempt 1: immediately
attempt 2: +1 to 5 minutes # greylisting usually clears here
attempt 3: +15 minutes
attempt 4..n: +30 min, +1 h, +2 h, +4 h ... capped at about 4 h, with jitter
give up: ~5 days after first attempt, generate a bounce (DSN) to the sender
warn: optional "delayed" DSN after ~4 hours ("still trying")Each queue entry stores attempt count, next attempt time and the last remote response. A timer-wheel or time-indexed queue (for example a sorted set keyed by next attempt time, or delay queues) finds due entries efficiently. See Asynchronous Processing and Message Queues for delay queues and dead-letter handling.
MX failover. If mx1 refuses or times out, try mx2, then lower-priority hosts, before scheduling a retry. Cache MX lookups for their TTL. If DNS itself fails (SERVFAIL), treat it as temporary.
Bounces (DSNs). A permanent failure (5xx) or giving up creates a delivery status notification (RFC 3464 format) addressed to the envelope sender, delivered internally to the user's inbox with the original headers and the remote server's error ("550 5.1.1 user unknown"). Bounces for our users are simple because the envelope sender is authenticated; we never send bounces for mail we accepted from the internet without verifying the sender, to avoid backscatter.
Message lifecycle.
IP pools and reputation. Receivers judge mail largely by the reputation of the sending IP and the authenticated domain. Large providers therefore:
- Keep separate IP pools for different traffic: consumer person-to-person mail, business customers on custom domains, and high-risk or new accounts. A spam incident in one pool does not damage the others.
- Warm up new IP addresses gradually (starting with low daily volumes and increasing over weeks), because receivers distrust IPs with no history.
- Register for feedback loops with other providers, which send a report when their users mark our mail as spam, so we can find compromised accounts quickly.
- Monitor blocklist listings and receiver dashboards (for example Google Postmaster Tools for mail sent to Gmail) for reputation drops.
- Publish correct reverse DNS (PTR records) for every sending IP matching the EHLO name.
TLS when sending. Always attempt STARTTLS. If the destination publishes MTA-STS in "enforce" mode or DANE records, require TLS with a valid certificate and defer (not send in plaintext) on failure.
Throughput sizing. At 30,000 outbound messages per second at peak and a few hundred milliseconds per SMTP transaction, with about five messages per reused connection, we need on the order of a few thousand concurrent SMTP sessions, spread over dozens of outbound MTA servers per region. The bottleneck is rarely CPU; it is receivers' throttles and our reputation. Queues of deferred mail can reach millions of entries during a large receiver's outage, which is why the queue must be durable and the scheduler must avoid hammering a recovering receiver (retry jitter and per-domain concurrency caps).
Mailbox provider versus transactional sender. Services like Amazon SES, SendGrid, Mailgun and Postmark solve only this outbound problem for applications sending receipts and notifications. Their designs emphasise API throughput, per-customer reputation isolation, bounce and complaint webhooks and suppression lists (never send again to an address that hard-bounced or complained). A notification system's email channel usually sits on such a service, as described in Design a Notification System.
5. Mailbox storage and metadata#
Separate bodies from metadata. Bodies are large, immutable and rarely read after a week; metadata is small, mutable and read constantly. Storing them separately lets each use the right store:
- Blob store for bodies and attachments: write once, read occasionally, delete rarely. Durability and cost per byte dominate.
- Metadata store for mailbox entries, labels, threads and counters: random reads and writes with low latency, range scans per user.
Storing message bodies.
- Parse on ingest. The raw RFC 5322 message is stored as received (needed for "show original", forwarding and legal reasons), but the delivery worker also parses MIME structure once and stores a part index: for each MIME part, its offset, length, content type, encoding and filename. The API can then return just the text part or stream one attachment without re-parsing the whole message.
- Separate large attachments. Attachments above a threshold (say 64 KB) are stored as their own blobs, content-addressed by SHA-256, and the message blob references them. The same PDF sent to 1,000 colleagues, or forwarded ten times, is stored once.
- Single-instance storage and its history. De-duplicating bodies across mailboxes is attractive but has costs: reference counting, harder per-user deletion (a body can only be deleted when its last reference goes), and potential side channels (could one user learn whether another holds a given file by observing upload speed?). Microsoft Exchange used single-instance storage within a database for years and dropped it in Exchange 2010, trading disk for simpler, faster I/O, a useful reminder that de-duplication is a trade-off, not a free win. For a huge consumer service, bulk newsletters and attachments make cross-user de-duplication worthwhile, but it is applied to large or bulk content where savings are highest.
- Compression. Text and HTML compress about 3–5× with modern codecs such as zstd; already compressed attachments (JPEG, ZIP, most PDFs) are stored as is.
- Durability. Bodies are replicated within the write path (at least two zones before acknowledging) and then erasure-coded for long-term storage. Erasure coding such as a 10+4 Reed-Solomon scheme survives any four lost fragments at 1.4× storage overhead, versus 3× for triple replication. See Object Storage and Blob Storage.
- Tiering. Most opens target mail from the last few days. Recent bodies sit in a cache and on fast storage; older ones move to cheaper, denser storage (high-capacity HDDs with erasure coding). Reading a five-year-old message may take 50–200 ms instead of 5–10 ms, which users accept.
Storing metadata. Each user's partition holds:
- Mailbox entries keyed by (user_id, message_id).
message_idis time-ordered (Snowflake-style 64-bit IDs) so "newest first" is a natural order. See Unique ID Generation. - Label index: (user_id, label_id, sort_key) → message_id, so listing a label is one range scan. A message with three labels has three label-index rows.
- Thread rows: per-thread summary (last date, participants, snippet of the latest message, unread count), so the inbox can list threads, not messages, in one scan of a thread-level label index.
- Counters: unread and total per label. Updated in the same transaction as label changes. If counters are maintained asynchronously they drift, and users notice a badge saying "3 unread" on an empty inbox. Periodic reconciliation recomputes them as a safety net.
- Change log: (user_id, history_id) → change, append-only, trimmed after a few weeks.
- UID allocation per label for IMAP, and the per-user modseq counter.
Atomicity within a user. Marking a thread read touches several rows: each message's flags, the thread's unread count, each label's unread counter and the change log. Because they are all on the same partition, a single-partition transaction (or a single-row mutation if the design packs a user's hot state into one wide row, as Bigtable-style systems allow) makes this atomic without distributed transactions. This is the core reason to partition by user.
Big mailboxes. Most users have tens of thousands of messages; some (shared support inboxes, automated archives) have tens of millions. Mitigations: sub-partition a giant user's label index by time bucket (year or month), cap per-user write rates with back pressure (queue deliveries for that user), and for business accounts offer archive tiers.
What real systems use. Google has not published Gmail's full storage architecture in detail, so we do not claim specifics. Open-source servers show the range of designs: Dovecot stores mail in Maildir (one file per message) or its own mdbox/sdbox formats with separate index files, and Cyrus IMAP (which Fastmail runs and helps maintain) uses per-mailbox index files plus message files. Microsoft Exchange uses its Extensible Storage Engine (ESE) database per mailbox database. Large cloud providers generally build on internal distributed storage for both metadata and blobs, as this design does.
Quotas are metadata too. Each account row tracks used_bytes. Delivery increments it; deletion from trash decrements it. Exact real-time accounting across de-duplicated blobs is not required: we charge each user for the logical size of their messages, regardless of physical de-duplication, which keeps billing simple and avoids leaking de-duplication information (Deep Dive 9).
6. Threading, labels and folders#
Why threading is hard. Email has no conversation ID. Threads must be reconstructed from headers that clients set inconsistently:
Message-ID: unique ID of this message.In-Reply-To: the Message-ID of the message being replied to.References: the chain of Message-IDs back to the start of the conversation (RFC 5322 says replies should include the parent's References plus the parent's Message-ID).Subject: usually the original with "Re:" or "Fwd:" (or localised prefixes such as "AW:" or "SV:") added.
Some clients drop References, some mailing lists rewrite headers, and some automated senders reuse subjects for unrelated messages ("Your daily report"). A good threading algorithm uses headers first and subject as a careful fallback.
The JWZ algorithm. Jamie Zawinski's threading algorithm, written for Netscape Mail and widely copied (IMAP's THREAD=REFERENCES extension, RFC 5256, is based on it), builds a tree from References and In-Reply-To, creating placeholder "containers" for messages referenced but not present, then prunes empty containers and optionally groups roots by normalised subject. A server that threads incrementally, one arriving message at a time, uses a simplified version:
function assign_thread(user, msg):
ids = msg.references + [msg.in_reply_to] # newest last
for ref in reversed(ids):
t = lookup_thread_by_message_id(user, ref) # per-user index: rfc_message_id -> thread
if t: return attach(t, msg)
# no header match: try subject fallback within a time window
s = normalise_subject(msg.subject) # strip Re:, Fwd:, AW:, [list] tags
if s is not empty and is_reply_like(msg.subject):
t = recent_thread_with_subject(user, s, within=30 days,
sharing_participant=msg.participants)
if t: return attach(t, msg)
return new_thread(user, msg)
# Late arrival: if a message's own Message-ID was referenced earlier by a
# message already threaded, merge it into that thread (placeholder resolution).Notes:
- Per-user index from
rfc_message_idto thread ID makes lookups cheap. Message-IDs are not trusted globally: a malicious sender could reuse a Message-ID to inject a message into someone's thread, so threading is per user and uses headers only within that user's own mailbox. - Subject fallback needs guards: same normalised subject, a reply-like prefix, a time window and at least one shared participant. Without these, every "Invoice" email from different vendors would merge.
- Thread size cap. Gmail is known to split very long conversations after a limit (on the order of 100 messages); a cap keeps thread rows and rendering bounded.
- Merging and splitting. Out-of-order arrival can mean a reply arrives before its parent; when the parent arrives, threads may merge. The merge updates thread IDs for affected entries and writes change-log entries, so devices update.
- Users can override: "turn off conversation view" in Gmail displays messages individually; our model stores thread ID per entry, so both views come from the same data.
Labels versus folders.
| Folders (classic IMAP, Outlook) | Labels (Gmail) | |
|---|---|---|
| Membership | A message is in exactly one folder | A message can carry many labels |
| Archive | Move to an "Archive" folder | Remove the INBOX label; message stays in "All Mail" |
| Data model | Entry has one folder_id | Many-to-many entry-label table |
| Counters | One folder counter per change | Several label counters per change |
| IMAP mapping | Native | Each label appears as a folder; same message in several folders |
Labels are more flexible ("Finance" and "Taxes 2026" both apply), and archiving becomes a label removal rather than a move. The cost is more index rows and counter updates per change, and the lossy mapping to IMAP's folder model. System labels (INBOX, SENT, DRAFT, SPAM, TRASH, STARRED, IMPORTANT, UNREAD, and category labels such as Promotions and Social) are just labels with special behaviours: messages labelled SPAM or TRASH are hidden from other views, and TRASH entries are purged after 30 days.
Thread-level versus message-level labels. The inbox lists threads, but labels attach to messages. A thread appears under a label if any of its messages has the label, and it is unread if any message is unread. We maintain a thread-level label index (user, label, last_date, thread_id), updated whenever a message's labels change or a new message joins, plus per-thread counters. That makes inbox listing a single range scan returning ready-to-render threads, at the cost of extra writes on each change, which is the right trade for a read-heavy UI.
Filters. User filter rules are evaluated during delivery (Deep Dive 3) and optionally retroactively ("apply to matching conversations"), which runs a search and a batch label update as a background job with progress reporting. Filters are capped (for example a few thousand per user) to bound delivery cost.
Categories and importance. Gmail's tabbed inbox (Primary, Social, Promotions, Updates, Forums) and "Important" markers are machine-learned classifications applied as labels during delivery, using sender, content and the user's past behaviour (opens, replies, archives). The same pipeline that runs spam models can run these models, and their output is just more labels in the same data model.
7. Search over mail#
What makes mail search special. Web search queries one huge shared index. Mail search queries one user's mailbox, which is small (thousands to a few million documents) but private, and must reflect changes within seconds. So the index is a collection of per-user indexes, not one global index.
Index contents. For each message: tokens from subject, body (HTML stripped), sender and recipient names and addresses, attachment file names, and text extracted from attachments (PDF, Office documents; optical character recognition for images is possible but expensive). Structured fields support operators:
from:alice to:me subject:invoice has:attachment filename:pdf
label:finance is:unread after:2026/01/01 before:2026/07/01 larger:5M
"exact phrase" -excluded (alice OR bob)Posting lists map each term to the list of message IDs containing it (with positions for phrase queries); structured filters (labels, dates, flags) come either from the index (as fields) or from the metadata store. See Elasticsearch and Search Systems for inverted index internals.
Partitioning by user. Each user's documents live on one index shard (routing by user ID), so a query touches one shard, not hundreds. Shards hold many users each: millions of small per-user indexes packed into large index files, with the user ID as a prefix on terms or as a filter. With Elasticsearch or OpenSearch, custom routing by user ID gives the same effect, though at hundreds of millions of users, purpose-built index servers are common, because general-purpose clusters struggle with that many tenants and with very high update rates.
Freshness. New mail should be searchable within about 10 seconds. The indexer consumes change events, builds small in-memory segments per shard and makes them searchable on a short refresh interval, merging into larger segments in the background (the classic log-structured design). Label changes and deletions are frequent: deletions mark documents as deleted (tombstones), and label fields are updated in place or stored separately from text so that "archive 500 messages" does not reindex 500 bodies. Storing labels and flags outside the text index, and joining at query time with the metadata store, is a common design for exactly this reason.
Hot and cold users. Most users search rarely; their index can live on disk (SSD or even HDD) and be loaded on demand. Active users' recent segments sit in memory or page cache. Index size is about 20–40 % of the text size, so a user with 5 GB of mail (perhaps 1 GB of extractable text) has a few hundred MB of index.
Ranking. Two modes: chronological ("newest first", the default for many operator searches) and relevance (term matches weighted by field, with a strong recency boost and signals such as "from someone I reply to"). Users usually want the specific email they remember, so recall (finding it at all) matters more than fine ranking.
Caching search results. Users often repeat the same search or page through results. A per-user cache of recent query results (query string → message IDs) avoids recomputation. The cache must not hide new mail: either keep a short TTL (well under the freshness target) or, better, invalidate the user's cached queries when their mailbox changes, which is easy because the change event is per user. Cache keys must include every query parameter (query text, sort, page token, label scope). The cache is a latency optimisation, not a correctness layer.
Autocomplete. The search box and the "To:" field suggest contacts and past queries as the user types: a small per-user prefix index over contacts weighted by how often the user emails them, kept in memory for active users. Design Search Autocomplete (Typeahead) covers prefix indexes in depth.
Query latency. A typical query: parse (under 1 ms), route to the user's shard (1–2 ms), look up posting lists and intersect (5–50 ms for most users, longer for huge mailboxes with common terms), fetch metadata for the top 50 results from the metadata store (5–20 ms), assemble snippets (5–20 ms). Total p50 around 100 ms, p99 within the 1-second target.
Privacy. Indexes contain the same sensitive content as mail and are encrypted at rest, scoped strictly per user, and deleted when mail is deleted. When a user deletes a message, its index entry must go too (a tombstone immediately, physical removal at the next merge); when an account is deleted, the user's index segments are dropped.
If mail were end-to-end encrypted, the server could not build this index. Clients would index locally (as some encrypted mail services do in the browser or app), which limits search to what the device has downloaded and costs device storage.
8. Spam, phishing and virus filtering#
Spam filtering is an adversarial machine-learning problem with asymmetric costs. Letting one phishing email through can cost a user their bank account; putting a legitimate job offer in spam can cost them a job. Google has said Gmail blocks more than 99.9 % of spam, phishing and malware, and in 2019 it described using TensorFlow models to block about 100 million additional spam messages a day. Those figures show both the scale and that marginal improvements still matter.
A short history of techniques.
- Blocklists and rules (1990s): DNSBLs of known spam sources and hand-written rules ("subject contains FREE!!!"). Tools like SpamAssassin combine hundreds of rules into a weighted score.
- Statistical filters (2002 onward): Paul Graham's essay "A Plan for Spam" (2002) popularised naive Bayesian filtering: learn per-token spam probabilities from labelled mail and combine them. Simple, personalisable, still a useful feature.
- Reputation systems (2000s): score senders by IP, domain, authenticated identity and URLs, based on history across all users.
- Large-scale machine learning (2010s onward): gradient-boosted trees and deep neural networks over thousands of features, trained on billions of user-labelled examples, with per-user personalisation.
Signals.
| Signal family | Examples |
|---|---|
| Connection and IP | IP reputation, DNSBL hits, reverse DNS, sending rate, network ownership, geography |
| Authentication | SPF, DKIM, DMARC results and alignment; ARC; age of the sending domain |
| Sender reputation | History of the authenticated domain and IP across all users: spam reports, opens, replies |
| Content | Tokens, HTML structure, hidden text, images-only messages, language, embedded URL count |
| URLs | URL and domain reputation (for example Google Safe Browsing), redirect chains, newly registered domains, lookalike domains |
| Attachments | File type, macros in Office documents, password-protected archives, antivirus verdicts, sandbox detonation results |
| Recipient behaviour | Is the sender in contacts? Has the user replied before? Did similar mail get reported? |
| Campaign-level | Many near-identical messages from new sources in a short time (fuzzy hashes, clustering) |
Architecture. Filtering runs in stages, matching the funnel in Deep Dive 3:
- Edge (milliseconds, every connection): IP and network reputation, protocol anomalies, rate limits.
- SMTP-time content check (tens of milliseconds): authentication, antivirus signatures, fast model. High-confidence spam is rejected with 5xx.
- Delivery-time full model (tens to hundreds of milliseconds): the full classifier with per-user features decides inbox, spam folder, or quarantine. Attachments flagged as suspicious may be detonated in a sandbox (opened in an instrumented virtual machine to watch behaviour), which takes seconds to minutes; the message can be held or delivered with the attachment blocked until the verdict arrives.
- Post-delivery: if a campaign is identified later (many users report it, a URL turns malicious), retroactively move matching messages out of inboxes. This needs a fast way to find all recipients of a campaign, which is another reason to keep per-message fingerprints.
- Click time: rewrite or check links when clicked, so a URL that turns malicious after delivery is still blocked (common in business mail security products).
Feedback loops. "Report spam" and "Not spam" clicks are the most valuable labels. They feed training data, sender reputation and per-user personalisation (one user's newsletters are another's spam). The feedback must be robust to manipulation: spammers create accounts to mark their own mail "not spam", so feedback is weighted by account reputation.
Phishing and impersonation. Content-based spam features do not catch a well-written spear-phishing email. Specific defences:
- Display-name impersonation: "From: CEO Name <random@freemail.example>" when the user's contact list has the real CEO at
corp.example. - Lookalike domains: Unicode homographs (Cyrillic "а" in place of Latin "a") and typosquats.
- First-contact warnings in the UI: "You don't usually get mail from this sender."
- Authentication banners: unverified senders shown with a warning, verified brands with BIMI logos.
Antivirus and attachment policy. Signature-based engines catch known malware; sandboxing and heuristics catch new variants. Some file types are blocked outright (executables, scripts) even inside archives. Password-protected archives cannot be scanned and are treated as higher risk.
Images and tracking. HTML emails load remote images, which senders use as tracking pixels (they learn when and where you opened the mail). Gmail has proxied remote images through Google's servers since 2013, which hides the user's IP and device from the sender and lets Google scan images; images may be cached, so the sender may also see fewer separate loads. Serving these through an image proxy at the edge, with caching close to users, applies the same edge-caching logic used for any read-heavy content: edge nodes absorb repeated fetches and reduce latency, at the cost of cache-consistency work, more configuration, and edge platform limits on compute time and memory if transformation logic runs there.
Measuring the filter. Track false-positive rate (legitimate mail in spam, measured by "not spam" clicks and sampled human review) and false-negative rate (spam in inbox, from reports), per sender segment. A model change ships only after an offline evaluation on held-out data and a gradual rollout. A small rise in false positives for one large sender (a bank's statements going to spam) is an incident.
Adversarial dynamics. Spammers probe filters by sending variations and measuring what gets through (using seeded accounts). Defences: do not reveal exact verdicts at SMTP time for borderline mail (accept and file in spam, rather than reject with a telling error), retrain frequently, and combine many independent signals so no single trick works.
9. Attachments and quotas#
Sending attachments. MIME encodes attachments in base64, which expands them by about 33 % (every 3 bytes become 4 characters, plus line breaks). A 25 MB send limit on the encoded message therefore allows somewhat less than 25 MB of original files. Gmail lets users send up to 25 MB of attachments and receive messages up to 50 MB; larger files are shared as Google Drive links instead. That is the standard pattern: for large files, send a link, not the bytes. It saves storage (one copy, shareable), avoids receivers' size limits, and lets the owner revoke access.
Upload path. When a user attaches a file to a draft, the client uploads it directly to the blob store with a short-lived signed upload URL (resumable for large files), not through the Mail API. The draft references the uploaded blob. On send, the submission service assembles the MIME message with references to blobs; for internal recipients it never needs to materialise the base64 form at all, and for external recipients the outbound MTA streams the encoded parts while sending. See Pattern: Handling Large Files and Blobs.
Receiving attachments. The delivery worker splits out attachments above a threshold, hashes them (SHA-256), stores new ones in the blob store and references existing ones, and records the part index (filename, type, size, blob reference). Antivirus and sandbox scans run before the attachment is downloadable. Previews (thumbnails, PDF page images, document viewers) are generated asynchronously and cached, and they are rendered in a sandboxed viewer rather than with the user's local application, which reduces risk from malicious files.
Downloading. The Mail API checks the user's access to the message and returns a short-lived signed URL or streams through a download service on a separate domain (so a malicious HTML attachment cannot run scripts on the mail domain). Content-Disposition: attachment forces download for risky types.
Quotas. A user's quota covers all their stored bytes. For Google accounts, the free 15 GB is shared across Gmail, Google Drive and Google Photos, which means quota is an account-level service used by several products, not just a mail column.
Accounting details:
- What counts: the logical size of every message the user holds, including attachments and spam/trash until purged. Users are charged for logical bytes even if blobs are de-duplicated physically.
- Where the counter lives: an account-level
used_bytescounter, incremented on delivery and decremented when trash or spam is purged. Updating it synchronously on every delivery would make it a hot row for active users; a common approach is per-partition counters aggregated periodically, or a counter updated in the same transaction as the mailbox entry (the account row lives on the user's partition), plus nightly reconciliation that recomputes exact usage. - Enforcement: at 100 % usage, inbound mail is refused with a temporary error (
452 4.2.2 mailbox full) so the sender retries for a while, then a permanent552after a grace period, and sending may be blocked until the user frees space. Warnings at 80 % and 95 % give users time to act. - Trash and spam auto-purge after 30 days reclaim space automatically.
- Business accounts may pool storage across an organisation, which needs a hierarchical quota (user within organisation).
Retention and lifecycle. Blob deletion follows the last reference: when a user purges a message, its mailbox entry is removed, the blob's reference count decrements, and a garbage collector deletes blobs with zero references after a safety delay (to cover in-flight deliveries that might reference the same hash). Legal hold for business accounts suspends purging for held mailboxes. See Data Lifecycle, Tiering and Retention.
10. Push sync to many devices#
A user may have the web app open on a laptop, the mobile app on a phone and tablet, and Thunderbird on a desktop, all expecting new mail within seconds and agreeing on what is read, archived or deleted. The design has two halves: a per-mailbox change log that makes incremental sync cheap and correct, and push channels that tell devices when to sync.
The change log. Every mutation to a user's mailbox (message added, deleted, label added or removed, flags changed) appends an entry with the next history ID, a per-user strictly increasing number, in the same transaction as the mutation. This gives:
- Cheap delta sync: "give me everything after 918250" is a range scan on (user_id, history_id).
- A single order of changes for that mailbox, so every device applies them in the same order and converges.
- IMAP support: history IDs double as IMAP MODSEQ values (CONDSTORE/QRESYNC), and per-label UIDs are assigned in the same transaction.
- A source for push and indexing: the change log (or the change events published from it, using a transactional outbox or change data capture) drives the indexer and push service.
The log is trimmed after a retention window (for example a few weeks). A device offline longer than that gets a "full sync required" response and re-lists its labels, which is expensive but rare. Gmail's public API works this way: history.list returns changes since a startHistoryId, and an expired ID returns an error telling the client to do a full sync.
Client sync protocol.
on startup or push:
resp = GET /v1/history?startHistoryId={local.lastHistoryId}
if resp.status == 404 or "historyId too old":
full_sync() # re-list recent threads per label, rebuild cache
return
for change in resp.history: # already in order
apply(change) # add or remove message, update labels and flags
local.lastHistoryId = resp.historyId
fetch headers and snippets for new messages; bodies lazily on open
on local action (archive, mark read) while online:
POST batchModify ... # server applies, appends change log entries
optimistic UI update; on error roll back
on local action while offline:
queue the operation with a client operation ID; replay on reconnect (idempotent)Conflicts. Mailbox operations are mostly commutative or idempotent: adding a label twice is the same as once, marking read is idempotent. Conflicts arise when two devices do opposite things offline (one archives, another stars and labels Inbox). The server applies operations in arrival order (last writer wins per label and flag), and every device converges by applying the server's change log. Deletion wins over later modifications of the deleted message. This is far simpler than collaborative text editing because the state is a set of flags per message, not shared text.
Push channels.
| Client | Channel | Notes |
|---|---|---|
| iOS app | APNs (Apple Push Notification service) | Required for background wake-ups on iOS; payload limits around 4 KB |
| Android app | FCM (Firebase Cloud Messaging) | Similar model; high-priority messages for new mail |
| Web app | WebSocket, Server-Sent Events, or long polling to our push gateway | Connection held while the tab is open |
| IMAP clients | IMAP IDLE (RFC 2177) | Client holds a connection per watched folder; server sends untagged EXISTS/EXPUNGE |
| Third-party apps via API | Webhooks or a pub/sub topic | Gmail's API offers users.watch, publishing notifications to a Google Cloud Pub/Sub topic |
| Exchange-style clients | Exchange ActiveSync "direct push" | Long-held HTTP request that returns when something changes |
See Polling, Long Polling, SSE, WebSockets and Webhooks for the transport trade-offs.
Push service design.
- Device registry: user → list of (device, platform, token, last seen). Stored with the user's partition or in a separate key-value store.
- Connection registry for held connections: which gateway server holds a given user's web or IMAP IDLE connection. Gateways register sessions in a fast key-value store (user → gateway ID, with a TTL refreshed by heartbeats), or the push service publishes to a per-user channel on a pub/sub system that every gateway subscribes to for its connected users. This is the same problem as routing messages to a connected user in a chat system; Design a Chat System (WhatsApp) discusses it in detail.
- Coalescing: a burst of 20 messages in one second should produce one or two pushes, not 20. The push service debounces per user (for example, at most one push per device per second, carrying the latest history ID).
- Content-free by default: the push says "something changed"; the device fetches over an authenticated API. For notification display, the push may carry an encrypted sender and subject.
- Respect user settings: only notify for INBOX or "important" mail, honour quiet hours, and never notify for spam.
- Failure handling: a dead token (app uninstalled) returns an error from APNs or FCM; remove it. If push delivery fails or is delayed, clients still poll on app open, so push is an optimisation for latency, not a correctness mechanism.
Holding tens of millions of IMAP connections. IMAP gateways are stateful: each connection has a selected folder, authentication and an IDLE state. They are built on event-driven I/O (epoll), use little memory per idle connection (tens of KB), and survive restarts by letting clients reconnect (clients reconnect automatically). Deploys drain connections gradually to avoid a reconnect storm, the same discipline any WebSocket fleet needs.
End-to-end latency budget for "new mail on my phone". SMTP acceptance (~0.5 s including the durable write) → queue to delivery worker (~0.1–1 s) → classification and storage (~0.2–0.5 s) → change event to push service (~0.1 s) → APNs/FCM delivery (typically under a second, but not guaranteed) → device fetches history and headers (~0.3 s). Total: usually 2–5 seconds, within the 10-second target.
11. Scaling, multi-region and never losing mail#
Cells. Rather than one giant cluster, group users into cells: self-contained units (perhaps a few million users each) with their own metadata partitions, blob storage front ends, delivery workers, indexers and push services. A user's home cell is recorded in a global user directory (address → user ID → cell). Benefits: blast radius (a bad deploy or overload affects one cell), predictable capacity planning (add cells, not ever-bigger clusters), and simpler testing (a cell is a full copy of the system at small scale). Shared tiers remain: the SMTP edge, the user directory, the outbound MTAs and global reputation services. See Designing for High Availability for cell-based architecture.
Routing. The SMTP edge accepts mail for any user, writes it to the inbound queue of the recipient's home cell (looked up in the directory, cached at the edge), and the cell's delivery workers take over. API requests are routed by the gateway to the user's home cell. Internal services find each other through service discovery: each instance registers itself with a registry (ZooKeeper, etcd or Consul, or the platform's discovery) with a heartbeat-backed ephemeral entry, and callers watch the registry for changes, so failed instances drop out automatically within seconds. See ZooKeeper and etcd.
Home region. Each user's cell lives in a home region close to them, with synchronous replication across availability zones in that region and asynchronous replication to a second region for disaster recovery. Writes from a user travelling abroad go to the home region (an extra 100–200 ms for actions, acceptable for email). Inbound mail can be accepted at any region's edge and forwarded to the home region's queue.
Durability chain. At each step, data is durable before the previous step forgets it:
- SMTP edge: durable, replicated queue write before
250. - Delivery worker: body blob and metadata written with replication before acknowledging the queue message.
- Blob store: replicated across zones, then erasure-coded; background scrubbing verifies checksums and repairs.
- Metadata store: replicated synchronously across zones (consensus-based or quorum writes), with point-in-time backups.
- Cross-region: asynchronous replication to a DR region; RPO of seconds to minutes for metadata, minutes for blobs.
Backups are not optional. Replication copies mistakes too. A software bug that corrupts labels or deletes messages replicates instantly. Providers keep independent backups (logical snapshots of metadata, immutable copies of blobs, possibly on different storage systems or offline media) and practise restoring individual mailboxes. A widely discussed example: in early 2011 a Gmail storage software bug caused some accounts to lose mail, and Google restored those accounts from tape backups over the following days. It is the canonical argument for backups separate from replication. See Disaster Recovery and Backups.
Moving users between cells. Rebalancing (a cell is full, or a user's home region changes) needs a live migration: copy the metadata and change log, double-write or block writes briefly, switch the directory entry, then drain. Blobs can stay where they are (referenced by ID) and migrate lazily. The SMTP edge and API gateway read the directory on every request (with caching and a short TTL), so the switch takes effect within seconds; anything delivered to the old cell during the switch is forwarded.
Scaling hot spots.
- The user directory is read for every recipient on every message: hundreds of thousands of lookups per second. Replicate it widely, cache at the edge, and use Bloom filters for negative lookups.
- Large distribution lists and newsletters create fan-out bursts: one inbound message to 100,000 recipients in an organisation. Expand asynchronously and rate-limit per cell.
- Celebrity or support mailboxes receiving thousands of messages a minute become hot partitions. Per-user rate limits on delivery and sub-partitioning their label index by time help.
- Morning sync storm: at 9 a.m. in each time zone, millions of devices sync. History-based delta sync keeps each sync small; caches keep the hot thread lists in memory.
What to monitor. Email failures are often silent: nobody gets an error when mail simply does not arrive. So monitoring is built around end-to-end probes and pipeline ages, not just server health:
- Synthetic round trips: every minute, from several external networks and other major providers, send a uniquely tagged message to test mailboxes and measure the time until it is visible through the API and through IMAP. Do the same outbound to test accounts at other providers, and check whether it lands in their inbox or spam folder.
- Queue ages, not only depths: the age of the oldest message in each inbound cell queue, in the delivery workers' retry queue and in each major destination's outbound queue. A queue that is long but young is healthy; an old message means something is stuck.
- SMTP reply mix: the share of 4xx and 5xx we return at the edge, and receive from major destinations. A sudden rise in deferrals from one large provider is the earliest sign of a reputation problem.
- Filter quality: "not spam" and "report spam" rates per hour and per sender segment, as proxies for false positives and false negatives.
- Sync health: history-sync error rates, the share of clients forced into full sync (which rises if the change log is trimmed too aggressively), push delivery latency per platform, and IMAP reconnect rates after deploys.
Service level objectives follow from these: for example, 99.9 % of accepted messages visible to the recipient within 30 seconds, and 99 % of outbound messages to major providers delivered within 5 minutes. See Observability: Logs, Metrics and Traces.
Degraded modes. If search is down, mail still flows and can be read. If the spam model service is slow, fall back to a simpler model rather than blocking delivery (with a short-term risk of more spam). If a cell's metadata store is unavailable, the edge keeps accepting mail into the durable queue (or replies 4xx once the queue is full) and the backlog drains after recovery. This layered degradation is one of email's strengths, because senders retry by design.
12. Security, privacy and compliance#
Isolation between users. The worst bug an email provider can ship is showing one user's mail to another. Defences in depth: every metadata and blob access is scoped by user ID derived from the authenticated session, never from a request parameter; blob references are unguessable and checked against the user's mailbox entry before a signed URL is issued; caches key on user ID; and tests and audits specifically probe for cross-tenant access. See Multi-Tenant SaaS Architecture.
Account security. Email is the recovery channel for nearly every other account a person has, so a compromised mailbox is a skeleton key. Measures: multi-factor authentication (with security keys or passkeys as the strongest option), risk-based login challenges (new device, unusual location), OAuth for third-party IMAP and SMTP clients instead of passwords, session and device management, and alerts on suspicious activity such as new forwarding rules (attackers often add a silent forward to keep reading mail after a password reset). See Authentication and Authorization.
Encryption.
- In transit: HTTPS for clients; STARTTLS plus MTA-STS/DANE between servers (Deep Dive 1).
- At rest: blobs, metadata and indexes encrypted with keys managed by a key management service, typically with envelope encryption (data keys per object or per user, wrapped by master keys). Per-user data keys make crypto-shredding possible: deleting a user's key renders their remaining data unreadable, even in backups.
- End-to-end: standards like S/MIME and OpenPGP let senders encrypt to the recipient's public key, so the provider cannot read content. Proton Mail, for example, encrypts mail between its users end to end using OpenPGP. The trade-offs are concrete: no server-side search (clients index locally), no content-based spam filtering (rely on metadata and sender reputation), no server-side previews, harder key management and account recovery, and interoperability only with recipients who have keys. Headers such as subject and recipients often remain visible to servers for routing. A mainstream provider can offer E2E as an option for sensitive mail rather than the default.
Privacy of metadata and content. Access to user mail by employees is restricted, logged and audited, typically requiring a ticket and approval. Automated systems (spam filtering, categorisation, search indexing) process content, which should be stated clearly in the privacy policy. Google stopped scanning Gmail content for ad personalisation in 2017, which shows how sensitive users and regulators are about secondary uses of mail.
Deletion and retention. A user deleting a message moves it to trash; after 30 days it is purged: mailbox entry removed, index tombstoned, blob reference decremented, and eventually the blob is garbage-collected and expires from backups on a documented schedule. Account deletion removes everything (and crypto-shredding helps with backups). Regulations such as the EU's GDPR give users rights to access and erase data, which requires being able to find all of a user's data, which per-user partitioning makes straightforward.
Legal hold and e-discovery for business customers. Organisations may be required to preserve mail involved in litigation. A legal hold flag on a mailbox (or a query-defined subset) prevents purge, even if the user deletes; deleted items remain hidden from the user but preserved. Journaling sends a copy of every message to an archive. E-discovery search runs across many mailboxes for authorised administrators, which is the one case where search crosses user boundaries and needs separate, audited tooling.
Outbound abuse is a security problem. Compromised accounts sending phishing from our domain damage our reputation and harm recipients. Outbound scanning, per-account sending limits, anomaly detection (sudden spikes, many new recipients, new forwarding rules) and fast suspension are essential parts of security, not just anti-spam.
Rendering untrusted HTML safely. Every email is untrusted HTML from a stranger. The web client must sanitise HTML aggressively (strip scripts, event handlers, forms, dangerous CSS), render message bodies in a sandboxed iframe on a separate origin, rewrite links through a redirector that checks URL reputation at click time, and load remote images only through the image proxy. A single XSS bug in an email renderer would let an attacker take over any account by sending one email. See Security Fundamentals for System Design.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Durable inbound queue unavailable | Cannot accept mail safely | Edge replies 4xx so senders retry; queue replicated across zones; accept into another region's queue and forward later |
| Delivery workers fall behind (spike or slow storage) | Mail delayed minutes to hours; queue grows | Autoscale workers; back pressure to the edge with 451 for low-reputation senders first; prioritise person-to-person mail over bulk |
| Spam wave or new campaign | Inbox pollution; user harm from phishing | Layered filters; campaign clustering; retroactive removal from inboxes; fast model retraining; temporary stricter thresholds for new senders |
| Our sending IPs blocklisted | Outbound mail deferred or rejected by other providers | Separate IP pools; outbound scanning; quick suspension of compromised accounts; feedback loops; delisting process; warm spare IPs |
| Large receiver outage or throttling | Millions of deferred outbound messages | Durable per-domain queues; adaptive per-domain concurrency; retry jitter; give-up after about 5 days with bounce |
| Metadata partition hot (huge or very active mailbox) | Slow inbox, delivery lag for that user | Per-user delivery rate limits; sub-partition label index by time; dedicated capacity for known large mailboxes |
| User directory lookup overload | Every inbound recipient check slows | Replicated, cached directory at the edge; Bloom filters for unknown addresses; harvest limits |
| Search index lag or shard failure | New mail not searchable; search errors | Replicated index shards; degrade to metadata-only search (from, subject) while rebuilding; monitor indexing lag |
| Push provider (APNs or FCM) delays | Users see mail late | Clients sync on open and periodically; coalesce pushes; monitor push latency per provider |
| Reconnect storm after IMAP gateway deploy | Overload of authentication and sync services | Drain connections gradually; jittered client reconnects; cache sessions; rate-limit logins per user |
| Software bug corrupting or deleting mail | Data loss across replicas | Independent backups; staged rollouts per cell; soft deletes with delayed purge; restore tooling per mailbox |
| Counter drift (unread badges wrong) | Confusing UI, support tickets | Update counters in the same transaction as labels; periodic reconciliation jobs |
What Interviewers Expect#
Mid-level. Explain how email moves between providers: MX lookup, SMTP between servers, IMAP or an API for clients. Separate the system into receiving, storing, reading and sending. Store bodies and attachments in blob storage and metadata in a database partitioned by user. Use a queue between accepting and processing mail. Mention spam filtering and attachment size limits. Do the core capacity maths (deliveries per second, storage per day) and notice the system is write-heavy for storage and read-heavy for metadata.
Senior. All of the above with correct protocol details and strong reasoning. The "250 only after durable write" contract and idempotent, de-duplicated delivery. SPF, DKIM and DMARC explained well enough to say what each protects and where each breaks (forwarding, mailing lists). Outbound queues per domain with retries, backoff, bounces and backscatter avoidance. A data model that supports labels, threads, counters and a change log in single-partition transactions. Per-user search indexes with freshness and deletion handling. Push-then-fetch sync with history IDs. Layered spam filtering from connection to content to feedback.
Staff and above. Treat email as a federated, adversarial ecosystem. Discuss reputation as a shared resource (IP pools, warm-up, compromised accounts as the main threat to deliverability) and the industry's use of authentication requirements. Design cells and home regions, a durability chain with independent backups, and a migration story for moving users. Reason about the cost structure (storage dominates; de-duplication and tiering trade-offs; why Exchange dropped single-instance storage). Address security beyond encryption: tenant isolation, HTML sanitisation, account takeover, forwarding-rule abuse, legal hold and e-discovery. Explain what end-to-end encryption would break (search, spam filtering) and how to offer it anyway. Prioritise: what to build first, what to defer, and which signals would prompt each change.
Deep Dive: How real mail systems differShow
Public information about large providers' internals is limited, so this comparison sticks to well-documented, user-visible design choices and open-source architectures.
Gmail. Launched in 2004 with 1 GB of storage when competitors offered a few megabytes, it made "never delete, just search" the default and popularised conversation threading and labels instead of folders. Its public API exposes the model in this design: messages, threads, labels, and history IDs for incremental sync, with push notifications through Cloud Pub/Sub. It exposes labels to IMAP clients as folders. It is known for strict enforcement of sender authentication and for machine-learned spam and category classification.
Outlook.com and Exchange Online (Microsoft 365). Folder-based, with Exchange's rich server-side features: rules, shared mailboxes, calendars integrated with mail, and the Exchange ActiveSync protocol for mobile push and the Microsoft Graph API for applications. Business features such as retention policies, legal hold, journaling and e-discovery are central, because enterprise customers buy compliance as much as email.
Fastmail. A smaller paid provider that runs on Cyrus IMAP, which it helps maintain, and that was a driving force behind JMAP. It shows that a standards-first design (IMAP and JMAP as primary protocols, not add-ons) is viable at scale.
Proton Mail. Built around end-to-end encryption using OpenPGP between Proton users, with encrypted storage so the provider cannot read message bodies. Search over encrypted bodies is done on the client. It demonstrates the trade-offs in Deep Dive 12: stronger privacy, weaker server-side features.
Self-hosted open-source stack. A typical deployment combines Postfix (MTA, SMTP in and out), Dovecot (IMAP and POP3, mailbox storage), Rspamd or SpamAssassin (spam filtering), ClamAV (antivirus), OpenDKIM or Rspamd for signing, and Roundcube or similar for webmail. Each component maps to a box in our design. Small operators often find that the hardest part is not software but deliverability: a new server on a fresh IP with no reputation struggles to reach large providers' inboxes, which is why many organisations relay outbound mail through a reputable provider even when they host mailboxes themselves.
| Aspect | Consumer giant (this design) | Enterprise suite | Privacy-first | Self-hosted |
|---|---|---|---|---|
| Organisation | Labels and threads | Folders, shared mailboxes | Folders or labels | Folders (IMAP) |
| Search | Server-side per-user index | Server-side, plus e-discovery | Client-side for bodies | Dovecot full-text plugins |
| Spam filtering | Global ML with huge data | ML plus admin policies | Metadata and reputation | Rules plus Bayesian |
| Main risk | Abuse at scale | Compliance failures | Key loss, limited features | Deliverability, operations |
Deep Dive: Capacity sanity check for one cellShow
Turning the global numbers into one cell's hardware makes the design concrete. Assume a cell of 5 million users (100 cells for 500 million).
- Deliveries: 5 million × 40 a day = 200 million a day ≈ 2,300 per second average, about 6,000 per second peak.
- Delivery workers: if one delivery takes about 20 ms of CPU (parsing, classification, metadata write, excluding sandboxing), one core handles about 50 per second; 6,000 per second needs about 120 cores, so perhaps 10–15 machines with headroom.
- Metadata writes: each delivery writes about 5–10 rows (entry, label index rows, thread row, counters, change log): 30,000–60,000 row writes per second at peak, plus user actions (mark read, archive), perhaps 100,000 row writes per second in total. A wide-column cluster of a few dozen nodes, or 20–40 MySQL/PostgreSQL shards, handles that.
- Metadata size: 5 million users × 50,000 messages × 1 KB ≈ 250 TB per cell, with replication about 750 TB. That is dozens of storage nodes, which is why metadata must stay lean (snippets truncated, no bodies).
- Blob storage: 5 million users × 3 GB average ≈ 15 PB logical per cell before compression and de-duplication; with erasure coding at 1.4× and maybe 1.5× net savings from compression and dedup, about 14 PB raw. At around 20 TB per HDD, roughly 700 drives, or a few dozen dense storage servers. Blob storage is likely shared across cells for efficiency, with cells as logical partitions.
- Search index: perhaps 20 % of logical size for text-heavy mail, so about 1–3 PB per cell, mostly cold on disk.
- Inbox reads: 2 million daily active users in the cell × 30 syncs = 60 million a day ≈ 700 per second average, 2,000 per second peak; cheap because history sync returns only changes.
- IMAP connections: if 10 % of users run IMAP clients with 2 connections each, 1 million connections; at 50,000 per gateway server, 20 servers.
The exercise shows where money goes: storage dominates, metadata write throughput is the main database challenge, and compute for delivery and spam filtering is significant but not the bottleneck. See Capacity Planning and Load Testing.
Deep Dive: Inside a MIME message, encodings and international addressesShow
Every component that touches bodies (delivery workers, search extraction, the web renderer, the outbound MTA) must understand MIME. Getting it wrong shows up as garbled text, missing attachments or security holes.
Structure. A MIME message is a tree. The top-level Content-Type says what the body is; multipart types contain parts separated by a boundary string, and parts can be multipart themselves:
Content-Type: multipart/mixed; boundary="outer"
--outer
Content-Type: multipart/alternative; boundary="inner"
--inner
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Hi Bob, see the attached report.
--inner
Content-Type: text/html; charset=utf-8
<p>Hi Bob, see the attached <b>report</b>.</p>
--inner--
--outer
Content-Type: application/pdf; name="q3.pdf"
Content-Disposition: attachment; filename="q3.pdf"
Content-Transfer-Encoding: base64
JVBERi0xLjcKJcfsj6IK...
--outer--multipart/alternativeholds the same content in several formats (plain text and HTML); clients show the richest one they support.multipart/mixedholds the body plus attachments.multipart/relatedbundles HTML with inline images referenced bycid:URLs.message/rfc822parts are whole forwarded messages, which can themselves contain attachments, so parsers must recurse with depth limits (attackers send deeply nested messages to exhaust parsers).
Transfer encodings. SMTP was originally 7-bit ASCII. base64 encodes binary data (about 33 % overhead); quoted-printable encodes mostly-ASCII text with occasional special bytes as =XX (efficient for Western languages); 8bit and binary need the receiving server to advertise 8BITMIME or BINARYMIME. Delivery workers decode once on ingest and store the part index with decoded offsets for fast access, while keeping the original bytes for "show original" and for re-sending faithfully.
Character sets. Older mail arrives in many charsets (ISO-8859-1, Windows-1252, Shift_JIS, GB2312, KOI8-R), sometimes mislabelled. The search extractor and renderer convert everything to UTF-8, using the declared charset first and charset detection as a fallback. Headers with non-ASCII text use "encoded words" (RFC 2047), such as Subject: =?utf-8?B?5pel5pys6Kqe?=, which must be decoded before indexing and display and handled carefully to prevent header injection.
International addresses. Domain names can contain non-ASCII characters (internationalised domain names, encoded in DNS as Punycode xn-- labels), and since the SMTPUTF8 extension (RFC 6531) the local part before @ can be Unicode too, such as an address entirely in Devanagari or Chinese script. Supporting this means: advertising SMTPUTF8, storing addresses in UTF-8 with normalisation, matching recipients case-insensitively where appropriate, and falling back gracefully when a remote server does not support it (the message cannot be delivered to a Unicode local part through a server that lacks SMTPUTF8, so it bounces with a clear error). Lookalike detection (Deep Dive 8) must handle mixed-script addresses, because Unicode makes homograph attacks easier. See Internationalization and Localization.
Address normalisation and aliases. Gmail ignores dots in the local part of consumer addresses (b.o.b@ and bob@ are the same mailbox) and supports plus addressing (bob+shopping@ delivers to bob@), which users rely on for filtering. Other providers treat the local part literally. The user directory must canonicalise addresses consistently on lookup and at sign-up, so that two people cannot register addresses that deliver to the same mailbox.
Why this matters for the design. Parsing is CPU work done once on ingest, and its results (part index, decoded text, normalised addresses) are stored so no later component re-parses. Parsers handle hostile input: they must have size and depth limits, timeouts, and run with memory limits in isolated processes, because a crafted message that crashes or hangs the parser could otherwise stall the whole delivery pipeline (a "poison message", which should go to a dead-letter queue after a few attempts, with the message still delivered in raw form if possible).
Deep Dive: A 45-minute interview planShow
Minutes 0–5: clarify. Consumer mailbox provider or transactional sender? Scale, quota, attachment limits, threads and labels or folders, IMAP support, search freshness, encryption expectations.
Minutes 5–10: estimate. Deliveries per second, sends per second, storage per day, metadata per message, search and sync QPS. Conclude: storage-heavy, write-heavy for deliveries, read-heavy for metadata, everything partitioned by user.
Minutes 10–15: protocols and API. MX and SMTP in and out, IMAP for third-party clients, a REST API with threads, labels, send with idempotency, history-based sync and push registration.
Minutes 15–25: high-level design. SMTP edge → durable queue → delivery workers → blob store and metadata store; Mail API; submission and outbound MTAs; indexer and search; push. Walk through receiving and sending flows, stressing the 250-after-durable-write rule.
Minutes 25–40: deep dives (pick two or three). SPF/DKIM/DMARC; spam filtering layers; outbound retries and reputation; data model for labels, threads and counters; per-user search; push and delta sync; cells and durability.
Minutes 40–45: wrap up. Failure modes (queue backlog, blocklisting, hot mailbox, data-loss bug), backups versus replication, and what you would build first.
Common mistakes: storing bodies in the metadata database; acknowledging SMTP before the message is durable; sending bounces for unverified senders (backscatter); one global search index; full re-sync on every device wake-up; forgetting outbound abuse and reputation; ignoring that SMTP has no built-in sender authentication.
Deep Dive: Follow-up questions and strong answersShow
"How do you support custom domains for business customers?" The customer adds our MX records, an SPF include, DKIM CNAME or TXT records we generate, and a DMARC record. A verification job checks DNS (and re-checks periodically, because customers change DNS). The user directory maps the domain to the organisation. Outbound mail for that domain is signed with its DKIM key and sent from the business IP pool.
"How would you implement 'undo send'?" Hold the outbound message in the submission queue for a configurable delay (Gmail lets users choose up to 30 seconds) before releasing it to the outbound MTAs. Undo deletes the queue entry. Internal recipients are also delayed, so the message really never arrives.
"How do you implement scheduled send?" Store the message with a send-at time in a durable delay queue or a time-indexed table, and a scheduler releases due messages to the outbound pipeline. Show it in a "Scheduled" label so all devices see it, and allow edits until release. Design a Distributed Job Scheduler covers timer storage at scale.
"How do mailing lists interact with DMARC?" A list that modifies messages (footer, subject tag) breaks DKIM and re-sends from its own IP, breaking SPF alignment. For senders with p=reject, receivers would reject list mail. Lists respond by rewriting the From: header to the list's own address ("Alice via List"), not modifying messages, or using ARC so receivers can trust the list's record of the original authentication.
"How do you find all copies of a phishing campaign after delivery?" Store per-message fingerprints (normalised body hash, URL hashes, sender) in an index keyed by fingerprint → (user, message) for recent mail. When a campaign is confirmed, query the index and issue batched label changes (move to spam or remove), which flow through the change log to every device.
"What changes for 10× the scale?" More cells; more aggressive tiering of old mail to cold storage; stronger de-duplication of bulk mail; more edge capacity and regional MX endpoints. The architecture shape stays the same, because everything is partitioned by user.
"Why not use Kafka for everything?" A log is a good fit for the inbound queue and change events. Outbound retries need per-message scheduled delays and per-domain fairness, which a plain log does not provide directly; a delay-queue or time-indexed store fits better, with a log feeding it.
Key Takeaways#
- Email is a federated store-and-forward system. You speak SMTP with millions of servers you do not control, so protocol correctness and defensive design are half the problem.
- Never reply
250 OKuntil the message is durably replicated; make every downstream step idempotent and de-duplicate retried deliveries. - SPF authorises sending IPs, DKIM signs content, DMARC ties both to the visible
From:domain and states a policy; all three are features for filtering, not a guarantee of good intent. - Filter in layers, cheapest first: connection reputation, envelope checks, authentication and antivirus, full ML with user feedback, then retroactive removal.
- Outbound mail is a scheduling and reputation problem: per-domain queues, adaptive concurrency, multi-day retries, bounces only to verified senders, and separate IP pools.
- Partition everything by user. Bodies go in an erasure-coded, tiered blob store; metadata, labels, counters and a change log live on the user's partition and update atomically.
- Search uses per-user inverted indexes with near-real-time segments, tombstones for deletes and labels kept out of the text index.
- Sync is push-then-fetch: content-free notifications through APNs, FCM, WebSockets or IMAP IDLE, followed by a delta query on a per-mailbox history ID.
- Cells, home regions, a durability chain and independent backups protect against both infrastructure failures and the bugs that replication would copy.