Skip to content

Design an Email Service like Gmail

A system design interview walkthrough for an email service like Gmail, covering mailbox storage, inbound delivery, per-user search, sync and spam.

Advanced24 minUpdated 2 December 2026

Before this: Search Systems (Elasticsearch), Data Partitioning (Sharding), Message Queues

"Design an email service like Gmail" is a question about private data at huge volume. Every user owns a mailbox that only they may read, the mailbox grows for years and never shrinks, and each user expects to find a message from 2019 in under a second.

Interviewers use it to see whether you reach for the right partition key. Almost nothing in a mailbox is shared between users, so partitioning by user is the natural cut, and the interesting questions are what stays shared (one copy of a big newsletter, one copy of an attachment), how search stays private and fast, and what you promise the sender when a message arrives.

Email also has a twist most designs lack: your system is one node in an open protocol. Mail arrives from servers you do not control, so abuse and spam are part of the core design, not an afterthought.

Clarify the requirements

Functional requirements:

  1. Receive email from the outside world (SMTP) and deliver it to the right mailbox.
  2. Send email to other domains.
  3. Read a mailbox: list messages by label or folder, newest first, open a message, view a conversation thread.
  4. Search a user's own mail by sender, subject, date and body text.
  5. Attachments up to 25 MB, labels, mark read or unread, delete.
  6. Keep several clients in sync (web, phone, a desktop IMAP client).

Out of scope, said aloud: calendar and contacts, rich-text composition, end-to-end encryption, and the spam model itself (we place it in the pipeline).

Non-functional requirements:

  • Never lose accepted mail. When we answer "250 OK" to a sending server, the message must be durable. The sender will not retry after that.
  • Strict privacy. One user's search and listing can never touch another user's data.
  • Fast reads: list the inbox in under 200 ms, search in under a second.
  • Availability over perfect freshness. A message arriving a few seconds late in search is fine. A mailbox that will not open is not.
  • Durable for years, with cheap storage for old mail.

Estimate the scale

Assume 50 million daily active users, each receiving 40 messages a day (most of it newsletters and notifications) and opening or searching their mail about 100 times a day. Average stored message: 50 KB, headers, body and small attachments together.

Inbound writes: 50M × 40 = 2 billion messages a day ÷ 86,400 s ≈ 23,100 per second, and about 69,400 per second at 3× peak.

Reads: 50M × 100 = 5 billion operations a day ÷ 86,400 s ≈ 57,900 per second on average.

Storage: 2B × 50 KB = 100 TB a day, or about 36.5 PB a year (100 TB × 365). We cannot afford to store a duplicate per recipient, and most of it is cold.

Search index: if the index adds roughly 20% on top of the text it covers, assume 20 TB a day of index, which is why the index is also partitioned by user.

Hot data: users mostly open mail from the last 30 days. 30 days is 3 PB of recent mail, a small slice of the whole, and the part to keep on fast storage.

"23,000 writes a second spread across 50 million separate mailboxes is not a hot-spot problem: user id is a fine partition key and every mailbox is a tiny slice. The cost is petabytes, so store each body once, push old mail to cheap storage and index it per user."

Try different shapes in the capacity estimator.

API and data model

GET    /v1/messages?label=INBOX&limit=50&cursor=      -> { messages[], nextCursor }
GET    /v1/messages/{id}                               -> full message
GET    /v1/threads/{threadId}                          -> messages in conversation
GET    /v1/search?q=from:alice invoice&limit=20       -> { hits[], nextCursor }
POST   /v1/messages/send        { to, subject, body, attachmentIds }
POST   /v1/messages/{id}/modify { addLabels, removeLabels }
GET    /v1/sync?since=<historyId>                      -> changes since a point
message_blob  (message_id) -> headers, body, attachment refs   // object store, written once
mailbox       (user_id, label, received_at DESC, message_id)
              -> subject, from, snippet, flags, thread_id       // wide-column row
thread        (user_id, thread_id) -> message ids
history       (user_id, history_id) -> change record            // powers sync

The non-obvious choice is the split between message_blob and mailbox. The body is stored once and the mailbox holds only a small row per recipient, so a newsletter to a million subscribers is one body and a million 200-byte index rows, not a million copies.

High-level design

We simulate the core of the read and write path: a gateway, a mail API, the mailbox store and the search cluster.

Mail passes a gateway to a mail API that stores messages in a wide-column mailbox store and indexes them in a search cluster.mail clientsgatewaymail apimailbox storemessage search
Mail passes a gateway to a mail API that stores messages in a wide-column mailbox store and indexes them in a search cluster.
  • The mail API lists and opens messages from the wide-column mailbox store, keyed by user.
  • Search requests go to the search cluster, where each user's mail is indexed separately.
Describe this diagram

Components

  • mail clients (Client)
  • gateway (API gateway)
  • mail api (Service)
  • mailbox store (Cassandra)
  • message search (Search cluster (Elasticsearch))

Connections

  • mail clients sends to gateway
  • gateway sends to mail api
  • mail api sends to mailbox store
  • mail api sends to message search

Run it, then raise the load or take down a search node, and watch search latency climb while mailbox listing stays steady. They are separate stores with separate failure modes on purpose.

The inbound path: an SMTP front end accepts the connection, checks the sender (SPF, DKIM), runs a quick spam filter, writes the body to the object store, appends a row to each recipient's mailbox and only then answers "250 OK". Indexing happens afterward, from a queue.

The read path: listing is a range scan on one mailbox partition. Opening a message loads the blob. Search goes to the user's index.

The interesting problem: search over private mailboxes

The search systems lesson explains inverted indexes. Email adds one hard constraint: every query is scoped to one user, and there are 50 million users. Three ways to build it:

Approach A: one global index with a user filter

Index every message in one big cluster, and add user_id = X as a filter to each query.

Good: the simplest mental model, standard tooling.

Bad: the filter is applied after the engine looks at all matching documents, so a query for a common word touches millions of postings that belong to other people. A bug in the filter is a privacy breach. And at 20 TB of index a day, the cluster is enormous.

Approach B: a separate index per user

Give each user their own tiny index.

Good: perfect isolation, and each query scans only that user's data, which is small.

Bad: 50 million indexes means 50 million files, open handles and merge schedules. Most users search rarely, so most of that overhead is wasted.

Approach C: shard by user, one index per shard

Route a user to a shard by hashing the user id (see consistent hashing). Inside the shard, all of its users' postings are stored grouped by user, so a query reads one contiguous region of one shard. Use the routing key so a query goes to exactly one shard, never a fan-out.

Conceptual diagramhash user idNew mailbox rowIndex queueIndex workersShard 1: users A-HShard 2: users I-PShard 3: users Q-ZSearch query user 42
Diagram, as text
  • New mailbox row leads to Index queue
  • Index queue leads to Index workers
  • Index workers leads to Shard 1: users A-H
  • Index workers leads to Shard 2: users I-P
  • Index workers leads to Shard 3: users Q-Z
  • Search query user 42 leads to Shard 2: users I-P (hash user id)

This is the answer to aim for. Privacy is enforced twice: the route picks the shard from the authenticated user id, and the query always carries the user's id as a mandatory term. Because each query hits one shard, search cost does not grow with the total number of users.

The second decision: accept mail only after it is durable

When a sending server connects, the conversation ends in 250 OK or an error code. This is your durability contract. Before you say OK, three things must have happened: the blob is written, every recipient's mailbox row is written and both are replicated.

If you answer too early and then lose the message, the sender believes it was delivered and will not retry. If your storage is slow or down, answer with a temporary failure (451). That is not an error to hide: SMTP servers queue and retry for days, so the sender's queue is your backpressure buffer.

Two details matter:

  • Multiple recipients. One message to 200 local users writes one blob and 200 mailbox rows. If some rows succeed and some fail, return success only for recipients that are durable, and a temporary failure for the others so the sender retries just those.
  • Idempotency. A sender may retry after a timeout, so the same message can arrive twice. Deduplicate on the Message-ID header plus recipient, so a retry never produces a duplicate in the inbox. The idempotency lesson covers the pattern.

For multi-device sync, give every mailbox a monotonically increasing history_id. A client remembers the last one it saw and asks for "everything since", which is cheaper and safer than re-listing the mailbox. If the client is too far behind, it does a full re-sync.

Bottlenecks and failures

A giant mailing list. A message to a list of one million users writes one blob and one million mailbox rows. The blob is free, but the rows are not: 1M rows at 200 bytes is 200 MB of writes. Do that fan-out asynchronously from a queue, spread across partitions, and rate-limit per sender so one list cannot starve normal mail.

Hot user. A shared support address that receives 10,000 messages a minute makes one mailbox partition hot. Split large mailboxes into time buckets inside the partition key, for example (user, month), so no single partition grows without bound.

Search cluster down. Mail still arrives and opens. Search shows a "search is unavailable" message and the index catches up from the change stream when the shard returns. This is why indexing is asynchronous.

Spam and abuse. Most inbound mail is unwanted. Check SPF, DKIM and DMARC alignment, reject by sender reputation before writing a body, and score content after. A classifier that is too eager silently loses real mail, so move spam to a folder instead of dropping it. Outbound: rate-limit each account, because a compromised account will try to send spam from your reputation.

What if a region is down? Replicate each mailbox to a second region. Reads can fail over with slightly stale data, and new inbound mail queues at the senders until the home region accepts it again. Pick one home region per user to avoid two regions writing the same mailbox.

Large attachments. Do not send a 25 MB attachment through the API tier. Upload it directly to object storage with a signed URL and attach the reference, as in design Dropbox.

Trade-offs to name aloud

  • One blob, many references: storage saved, at the cost of reference counting when a message is deleted.
  • Asynchronous indexing: a short search delay in return for fast, reliable delivery.
  • Shard-by-user search: simple routing and strong privacy, but a very large mailbox can unbalance a shard.
  • Durable before OK: slower acceptance in return for never losing mail.
  • Spam to a folder, not the void: a bigger inbox of junk in return for no silent loss of real mail.

What interviewers listen for

  • A working answer: partition mailboxes by user id, store bodies in object storage, keep a search index and use a queue for inbound mail.
  • A strong answer: store each body once with per-recipient references, make search per-user and asynchronous, answer SMTP only after durability and estimate the petabytes.
  • A standout answer: handles the million-recipient list, treats the sender's retry queue as backpressure, uses a history id for sync and brings up SPF, DKIM, DMARC and outbound reputation on its own.

Check your understanding

Common mistakes

One global search index with a user filter. It is the first idea and the riskiest: a filter bug leaks private mail, and every query pays for everyone else's data. Route by user.

Acknowledging before durable. Saying "250 OK" and then writing to a queue in memory loses mail on a crash. The sender will not retry what you accepted.

Copying the body per recipient. At petabyte scale this is wasteful, and mass mailings make it absurd. Store it once.

Indexing in the delivery path. It couples mail arrival to the slowest, most failure-prone component. Index from a change stream.

Forgetting abuse. An open protocol means constant spam, and your own users can be compromised. A design with no sender checks, no spam folder and no outbound rate limits is incomplete.

Re-listing the whole mailbox to sync. Clients need an incremental "changes since" feed, not a repeat of everything they already have.

Practice

A user imports 20 years of mail from another provider, 400,000 messages in one afternoon. What does your system do so that this user does not hurt everyone else?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Think about the write rate to one partition, the index queue and fairness between users.

Show a strong answer

Treat it as a bulk job, not as inbound mail. Route imports through a separate queue with its own worker pool and rate limit, so they cannot compete with live delivery.

Spread the mailbox writes. 400,000 rows into one user's partition at full speed makes a hot partition. Because the key includes a time bucket (user, month), 20 years of mail lands in about 240 buckets, which spreads the load naturally. Write in batches at a capped rate.

Index later and slowly. Feed the change stream through a lower-priority lane so live mail is indexed first. The imported mail becomes searchable over the next hour, and the user sees an "indexing" progress note.

Protect fairness. A per-user rate limit on bulk writes means one import takes longer but never starves the shard.

The pattern worth keeping: give heavy, one-off work its own lane with a rate limit, so a single user's burst never shares a queue with everyone else's live traffic.

A user deletes a message that was part of a one-million-recipient mailing. How do you delete it without breaking the other recipients' copies?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Remember that the body is shared and the mailbox rows are not.

Show a strong answer

Delete only the mailbox row. The user's delete removes their row (or moves it to trash with a 30-day timer). It never touches the shared body.

Track references on the body. Keep a reference count, or better, let a periodic garbage-collection job find bodies with no remaining rows. A count that is updated on every delete is a hot counter when a million rows share one body. A background job avoids that.

Delete the index entries too. The change stream carries the delete to the user's index shard, so the message stops appearing in search. Do this before the body can disappear.

Handle legal holds. If the account is under retention rules, mark the row as held and skip the delete until it clears.

The pattern worth keeping: when many records share one object, delete the per-user reference now and reclaim the shared object later, in the background.

Key takeaways

  • Partition by user. Mailboxes are private and independent, so user id is the natural key.
  • Store each body once, with a small per-recipient reference, and tier old mail to cheap storage.
  • Search is per user and asynchronous, fed by a change stream, routed to one shard.
  • Answer "250 OK" only after the data is durable, and use temporary failures to push work back to the sender's queue.
  • Sync with a history id, never by re-listing the mailbox.
  • Design for abuse: SPF, DKIM, DMARC, spam folders and outbound rate limits are part of the system.

Further reading

  • J. Klensin, RFC 5321 "Simple Mail Transfer Protocol" (2008): the delivery contract and retry behavior behind "250 OK".
  • P. Resnick, RFC 5322 "Internet Message Format" (2008): headers, Message-ID, References and In-Reply-To, which threading builds on.
  • M. Crispin, RFC 3501 "Internet Message Access Protocol, Version 4rev1" (2003): the classic mailbox-sync model.
  • D. Crocker, T. Hansen and M. Kucherawy, RFC 6376 "DomainKeys Identified Mail (DKIM) Signatures" (2011), and S. Kitterman, RFC 7208 "Sender Policy Framework" (2014): how receivers check who sent a message.
  • Fay Chang and colleagues, "Bigtable: A Distributed Storage System for Structured Data" (OSDI, 2006): the wide-column model used for mailbox rows.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track