Design a Mail Client – Frontend System Design

We’ll walk through the frontend system design for a desktop-style email client like Outlook or Apple Mail. Our goal is a three-pane shell — folders, message list, reading pane — plus a composer, search, and a sync engine that feels instant on a mailbox with tens of thousands of messages. This is a product interview. Treat it like a ChatGPT-scale walkthrough: panes, a local cache, sync, and a composer that cannot become an XSS hole.
You’ll see how we keep metas and bodies apart, how a cursor-based sync prepends new mail, and how archive and send stay idempotent when the network flakes. We are not implementing IMAP in the browser. The backend speaks a custom REST API plus a sync cursor. The frontend’s job is to feel local.
Problem Statement
Build the frontend for a desktop-style email client like Outlook or Apple Mail.
Requirements:
- A three-pane layout: folders, message list, reading pane
- Inbox with unread badges, archive, delete, and a composer
- Search across messages
- It should feel instant on a mailbox with tens of thousands of messages
Describe the panes, the local cache, sync, and the composer.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Web app that looks like desktop, or Electron? | Web. Same design either way. |
| 2 | IMAP/SMTP or a custom API? | Custom REST + a sync cursor. Don’t implement IMAP in the browser. |
| 3 | Calendar and contacts? | Out of scope. |
| 4 | Offline? | Yes. Cached folders and bodies, queued sends. |
Two more that change the design: is the reading pane a single message or a thread (we’ll design single message and say how threads would group metas by threadId), and do we need multiple accounts (one account; mention an account switcher as a later folder root). Offline is already yes — that forces IndexedDB and an outbox, not just an in-memory store.
Requirements
Functional Requirements
- Three-pane layout: folder list, virtualized message list, reading pane
- Inbox and standard folders with unread badges
- Open a message, mark read, archive, delete, star
- Composer with To / Subject / rich body, drafts, and send
- Search across metas, then fetch matching bodies as needed
- Offline: cached folder metas and recently opened bodies; queued sends
Non-Functional Requirements
- First Inbox paint from a local cache, then a sync cursor
- 50,000 metas in memory is fine; 50,000 DOM rows is not
- Archive and send are optimistic and idempotent
- Message HTML is hostile. Sanitize, sandbox, proxy images
- Keyboard: arrows in a pane, Tab between panes, j/k to move the list
Scalability Estimates
This is a full client. Use product-scale numbers, but keep the arithmetic on what the browser holds.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Daily active users | 5M | Web client only | Interview scale. Same UI if this were Electron. |
| Messages per mailbox | 20,000 | Power-user inbox + archive | Metas in the list. Bodies on demand. |
| Meta size | 200 bytes | 20,000 × 200 B ≈ 4 MB | Fine in memory and in IndexedDB. |
| Visible list rows | 25 | Viewport / row height | Virtualize. Do not mount 20,000 rows. |
| Body size | ~40 KB HTML | Load on open | Cache the last ~50 bodies in IndexedDB. |
| First Inbox page | 50 metas | GET with cursor | Then idle sync with a since token. |
| Search debounce | 250ms | Keystrokes | Abort the in-flight query. Local cache hits first. |
| Unread counts | Per folder | Stored on the folder object | Do not scan 20,000 metas to badge Inbox. |
Architecture
<MailShell>
<FolderList />
<MessageList /> // virtualized
<ReadingPane />
<Composer /> // modal or docked
</MailShell>
Normalized store:
export type Folder = { id: string; name: string; unread: number };
export type MessageMeta = {
id: string;
folderId: string;
from: string;
subject: string;
snippet: string;
date: number;
unread: boolean;
hasAttach: boolean;
};
export type MessageBody = { id: string; html: string; text: string };
// metas in the list, bodies loaded on open and cached
Never put the HTML body on every list row.
That last rule is the architecture. The list is a virtualized window over MessageMeta. The reading pane is a cache lookup of MessageBody. Folders hold unread counts so a badge never walks the meta array. The Network Manager and a Sync Engine sit under a Mail View Model. Views do not fetch.
Component Structure and Responsibilities
- MailShell: Three-pane grid plus a composer overlay. Owns which pane has keyboard focus. Remembers splitter widths.
- FolderList: Inbox, Drafts, Sent, Archive, Trash, user folders. Renders
unreadfrom the folder object. Clicking a folder switches the list query and resets the list scroll. - MessageList: Virtualized metas for the current folder (or search hits). Row height is fixed. Click or Enter opens a meta; j/k move the selection.
- ReadingPane: Empty state, loading, or a sandboxed body. Also hosts the action bar (archive, delete, reply). Reply opens the composer with a quote.
- Composer: Docked at the bottom or a modal on small widths. To, Cc, Subject, a small rich-text surface, attachments. Autosaves a draft.
- SearchBox: Debounced input in the shell header. Swaps the list data source from a folder query to a search query without unmounting the list.
- MailViewModel: Selected folder, selected message id, list window, composer draft, online/offline, outbox depth.
- Network Manager: REST for folders, paged metas, bodies, batch ops, send, drafts, search.
- Sync Engine: Holds the since cursor. On idle, pulls new metas and folder unread deltas. Applies them into IndexedDB and the in-memory store.
- Outbox: Queued sends and drafts when offline. Same
clientIdon retry so we do not create two messages.
Network Layer and Data Management
The Network Manager is the only module that knows URLs. Everything else reads a normalized store.
- Folders and unread:
GET /api/folderson boot, then unread comes in on the sync cursor - Metas: paged
GET /api/messages?folder=&cursor=&limit=50 - Bodies:
GET /api/messages/:id, then write IndexedDB - Mutations:
POST /api/messages/batchfor archive / read / delete so starring 40 rows is one request - Send:
POST /api/sendwithclientId - Search:
GET /api/search?q=&cursor=with anAbortController
IndexedDB holds folder rows, metas (keyed by id, indexed by folderId + date), bodies (keyed by id, LRU of ~50), the sync cursor, and the outbox. The in-memory store is a subset: the current folder’s metas (or a window of them), the open body, and folder unread. Cold start paints from IDB, then the Sync Engine confirms.
Open-Inbox Workflow
- Shell mounts. View Model reads folders and the last-open Inbox page from IndexedDB and paints immediately if present.
- Network Manager refreshes folders and the first 50 Inbox metas. Sync Engine stores the new since cursor.
- The user highlights a row. ReadingPane shows the cached body if we have it; otherwise a skeleton and a GET.
- On 2xx, the body is sanitized, written to IDB, and rendered in the sandboxed frame. The meta flips to read; folder.unread decrements locally; a batch read is queued.
- Prefetch the next meta’s body (j/k navigation) so the next open is cache-hot.
- Idle: Sync Engine polls or holds a push channel with the since cursor. New metas prepend. Unread badges update from the folder delta, not from a full scan.
- If the tab goes offline, reads keep using IDB. Sends go to the outbox and flush when
onlinefires.
Sync
- First load: first page of Inbox metas (cursor).
- Idle: a sync cursor / “since” token. New mail prepends.
- Open a thread: GET body, cache it in IndexedDB.
- Actions (archive, read): optimistic, then a batch endpoint so starring 40 messages is one request.
// GET /api/folders
// GET /api/messages?folder=inbox&cursor=&limit=50
// GET /api/messages/:id
// POST /api/messages/batch { ids, op: "archive" | "read" | "delete" }
// GET /api/sync?cursor=
// POST /api/send { to, subject, html, clientId } // idempotent
A sync response is a delta, not a snapshot. It contains new or changed metas, folder unread patches, and a new cursor. The Sync Engine applies the delta in one transaction: write IDB, then notify the store. If the cursor is expired (the user was offline for a week), the server returns a 410 and the client falls back to a paged refetch of the current folder. Do not invent a three-way merge in the interview unless they push — last-writer on unread/archive is enough if the batch op is idempotent.
Optimistic archive removes the row from the Inbox window and decrements unread. The meta still exists in the store with folderId: "archive" so an undo (or a failed batch) can put it back. The same pattern works for read/unread. Delete is archive-plus-trash unless they want a hard delete; say you would soft-delete.
Building the List and the Reader

Two surfaces, two different engines. The list is a virtualized camera over metas. The reader is a sandboxed iframe you must not let touch your app origin.
Message list
Same window function as the data table. Rows are fixed height (say 64px). start = floor(scrollTop / 64), overscan 8, spacer = n * 64. The list store holds ids in folder order; each row reads metas[id]. Do not put the body HTML on the row.
Keyboard is first-class: j/k (or arrows) move activeId, Enter opens, e archives, # trash, u unread, / focuses search. The active row is aria-selected and scrolled into view the same way Sheets scrolls the active cell.
Prefetch: when activeId sits still for ~150ms, GET /api/messages/:id warms the body cache. Hover can do the same. Opening a message the user already hovered should paint from memory.
Infinite folders: a sentinel at the bottom fetches the next cursor of metas. Do not fetch bodies for the page. Unread badges on folders come from the sync delta, not from recounting the window.
Reading pane = sandboxed iframe
Mail you did not write is hostile. Never dangerouslySetInnerHTML a message body into your app origin.
function Reader({ html, srcDoc }: { html: string }) {
// srcDoc is the sanitized body plus a <base target="_blank"> and a tiny CSP
return (
<iframe
sandbox="allow-popups allow-popups-to-escape-sandbox"
csp="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; font-src https:;"
srcDoc={srcDoc}
title="Message body"
/>
);
}
No allow-scripts, no allow-same-origin. That pair together is how a message runs JS as your user. Images: either rewrite to a proxy you control (so trackers do not see the reader’s IP) or block remote images until the user clicks “load images.” Links: intercept via base target="_blank" plus rel="noopener noreferrer", or rewrite hrefs through an interstitial. Inline styles stay; <style> from the sender is why you allow style-src 'unsafe-inline' inside the iframe only.
Height: listen to a postMessage from a trusted wrapper, or measure via a second pass. A growing iframe must not fight the list’s scroll container — the reader has its own overflow.
Composer
A small rich-text surface (reuse ideas from the Docs article — a timeboxed contenteditable is fine here; you are not painting 50-page documents). Drafts autosave every few seconds to /api/drafts with the same clientId so retries don’t create two drafts. Send is optimistic: the message appears in Sent, and a failure banner lets you retry.
Sanitize HTML on read. Email is the XSS capital of the web. Render bodies in the sandboxed iframe above and rewrite links to go through an interstitial.
The composer is a second document the user is writing, not a view of someone else’s HTML. Keep those paths separate. Draft HTML you created can be shown in a contenteditable. Mail you received cannot. On send, serialize the draft to HTML, attach the clientId, and POST. If offline, the Outbox holds the same payload. A successful send moves the optimistic Sent meta to the real id from the response, or keeps the client id if the server echoes it.
Autosave is a debounce, not a keystroke POST. Five seconds or on blur, whichever comes first. The draft endpoint is idempotent on clientId. Closing the composer with unsaved keystrokes flushes once.
State and Data Flow
The store is normalized. Views subscribe to slices. A command never writes the DOM and the network in the same component.
- User action: select folder, open message, archive, type a search, or hit Send.
- View Model updates selection or enqueues a command (optimistic meta patch, outbox push).
- Network Manager runs the matching request. Batch ops flush on a short timer so five rapid archives become one POST.
- Responses and sync deltas land in the store and IndexedDB together.
- MessageList, FolderList, and ReadingPane re-render from those slices. A failed command restores the optimistic patch and shows a banner.
Search is a parallel data source, not a folder. While q is non-empty the list reads search hits. Clearing search returns to the previous folder and scroll offset. Cancel the in-flight search when q changes.
Data Model
Extend the metas you already have with sync, drafts, and an outbox. Do not add the body HTML onto MessageMeta.
type Folder = {
id: string;
name: string;
unread: number;
system: "inbox" | "drafts" | "sent" | "archive" | "trash" | "user";
};
type MessageMeta = {
id: string;
folderId: string;
threadId?: string;
from: string;
to: string[];
subject: string;
snippet: string;
date: number;
unread: boolean;
flagged: boolean;
hasAttach: boolean;
};
type MessageBody = {
id: string;
html: string; // raw from the server — not safe to mount
text: string;
sanitizedHtml: string; // after the client sanitizer
};
type Draft = {
clientId: string;
to: string[];
cc: string[];
subject: string;
html: string;
updatedAt: number;
};
type OutboxItem =
| { type: "send"; clientId: string; draft: Draft }
| { type: "batch"; op: "archive" | "read" | "unread" | "delete"; ids: string[] };
type SyncCursor = {
token: string;
updatedAt: number;
};
type MailState = {
folders: Folder[];
metasById: Record<string, MessageMeta>;
listIds: string[]; // current folder or search window
bodiesById: Record<string, MessageBody>;
selectedFolderId: string;
selectedMessageId: string | null;
cursor: SyncCursor | null;
draft: Draft | null;
outbox: OutboxItem[];
online: boolean;
};
listIds is what the virtualizer walks. metasById is the source of truth so a sync patch of one message does not rebuild the whole list array. threadId is optional — if they ask for threads, group listIds by it and keep the reading pane on the latest body.
API Design
CRUD for folders and messages, a cursor for idle sync, a batch mutation, and an idempotent send. Auth is a cookie plus a CSRF header on POSTs.
| Action | Method / Endpoint | Description |
|---|---|---|
| List folders | GET /api/folders | Returns Folder[] with unread already computed. |
| Page metas | GET /api/messages?folder=&cursor=&limit=50 | Returns { metas, nextCursor }. Newest first. |
| Read body | GET /api/messages/:id | Returns MessageBody. Mark-read is a separate batch, or a side effect you should name. |
| Idle sync | GET /api/sync?cursor= | Delta of metas + folder unread + new cursor. 410 means refetch. |
| Batch mutate | POST /api/messages/batch | Body { ids, op }. Idempotent per id. Used for archive, read, delete. |
| Search | GET /api/search?q=&cursor= | Returns metas. Debounce + abort on the client. |
| Save draft | POST /api/drafts | Body includes clientId. Upsert, do not insert twice. |
| Send | POST /api/send | Body { to, subject, html, clientId }. Returns the Sent meta. |
Example: Opening a Message and Prefetching the Next
async function openMessage(id: string, nextId: string | null) {
const cached = await idb.bodies.get(id);
if (cached) {
store.setBody(cached);
} else {
const body = await api.getMessage(id);
const sanitized = sanitizeEmailHtml(body.html);
const safe = { ...body, sanitizedHtml: sanitized };
store.setBody(safe);
await idb.bodies.put(safe);
}
store.patchMeta(id, { unread: false });
queueBatch({ op: "read", ids: [id] });
if (nextId && !store.bodiesById[nextId]) {
api.getMessage(nextId).then(async (body) => {
const safe = { ...body, sanitizedHtml: sanitizeEmailHtml(body.html) };
await idb.bodies.put(safe);
store.primeBody(safe); // cache only; do not change the reading pane
}).catch(() => undefined);
}
}
sanitizeEmailHtml runs on the client even if the server already tried. You still render sanitizedHtml inside a sandboxed frame, not into the React tree as raw HTML.
Optimizations
- Virtualize the list (react-window). 50,000 metas is fine in memory; 50,000 DOM nodes is not.
- Keep folder unread counts in the folder objects, not by scanning metas.
- Prefetch the next message body when you open one (j/k navigation).
- Search: debounce, cancel with AbortController, show local cache hits first.
Those four are the default senior list. The code that makes search feel instant is the abort plus a local first pass.
Search with local hits, then the network
function searchMailbox(q: string, metasById: Record<string, MessageMeta>, signal: AbortSignal) {
const needle = q.trim().toLowerCase();
const local = Object.values(metasById).filter((meta) => {
return meta.subject.toLowerCase().includes(needle) || meta.from.toLowerCase().includes(needle) || meta.snippet.toLowerCase().includes(needle);
}).slice(0, 25);
store.setList(local.map((m) => m.id), { source: "search-local" });
return fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal })
.then((res) => {
if (!res.ok) throw new Error("search_failed");
return res.json() as Promise<{ metas: MessageMeta[] }>;
})
.then(({ metas }) => {
store.upsertMetas(metas);
store.setList(metas.map((m) => m.id), { source: "search-remote" });
});
}
// in the SearchBox view model
let controller: AbortController | null = null;
function onQueryChange(q: string) {
controller?.abort();
if (!q) {
restoreFolderList();
return;
}
controller = new AbortController();
window.setTimeout(() => {
searchMailbox(q, store.metasById, controller!.signal).catch((err) => {
if (err.name !== "AbortError") store.setSearchError();
});
}, 250);
}
Local hits keep the list from going empty while the GET is in flight. Remote results replace them. A new keystroke aborts the previous GET so a slow “invoi” response cannot overwrite a later “invoice” result.
Accessibility and Security
- Three panes as complementary regions; arrow keys move within a list, Tab moves between panes
- Unread announced on the folder (“Inbox, 12 unread”)
- Sandboxed bodies; no remote scripts; proxy remote images (tracking pixels)
- httpOnly session; CSRF on send/archive
Give each pane a label: “Folders”, “Messages”, “Reading pane”. The focused list uses roving focus on the selected row. Tab from Folders lands on Messages, Tab from Messages lands on the reading pane action bar, not on every virtualized row. j/k (and arrows) move the selection and, if the user has the preview pane open, open the new message. Announce the new subject on a polite live region so a screen reader is not stuck on the old body.
Unread on the folder button is part of the accessible name, not a colored blob the tree cannot see. The list row name is sender, subject, date, and unread state.
Security is the reading pane. Message HTML is an attack. The pipeline is: fetch → sanitize (drop script, event handlers, inline js URLs) → render in a sandboxed frame with a strict CSP and no allow-scripts → rewrite href through an interstitial → load images through a proxy that strips cookies so tracking pixels do not fire with the user’s mail session. Do not use a React dangerouslySetInnerHTML into the shell document.
Session cookies are httpOnly. Every POST (send, batch, draft) carries a CSRF token. The composer’s attachments go through the same auth. Do not put access tokens in IndexedDB next to cached bodies.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| ❌ Send with an empty To | Validate before the outbox. Do not create a Sent meta. |
| ❌ Double Send / retry | Same clientId. Server upserts. UI keeps one optimistic Sent row. |
| 🔄 Reload mid-compose | Drafts live in IDB and on /api/drafts. Rehydrate the docked composer from clientId. |
| 🔁 Archive of 40 messages | Optimistic remove, one batch POST. Failure restores those ids to listIds. |
| 📶 Offline send | Outbox holds the payload. On online, flush in order. Banner shows “Waiting to send.” |
| ⏳ Expired sync cursor | 410 from /api/sync. Refetch the current folder page. Do not apply a partial delta. |
| 🚫 Hostile HTML / tracking pixel | Sanitize, sandboxed frame, proxy images, interstitial on links. Never mount raw html into the shell. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| List window | Fixed row height + react-window (or an equivalent). Overscan 8. Do not measure every row. |
| Batch flush | Coalesce archive/read for ~50ms so a j/j/j + archive burst is one POST. |
| Body LRU | Keep ~50 sanitized bodies in IDB. Evict the oldest unread-or-closed. Metas stay. |
| Unread math | Patch folder.unread on the object. A full recount is a recovery path, not the hot path. |
| Composer | Autosave on a 5s debounce with a stable clientId. Do not POST per keystroke. |
| Mobile / narrow | Stack panes: list or read, not both. Keyboard j/k still works. Composer becomes a full-screen modal. |
Interview details people skip
Clarify the product first. GFE’s writeup is a desktop Mail User Agent talking SMTP / IMAP. Ours is webmail with a custom REST + sync cursor. Both paint the same three panes. The protocol story is what interviewers use to see if you know why the client looks the way it does.
IMAP is the retrieval model. SMTP is send. POP is legacy. POP downloads the message and, by default, deletes it on the server — one device, one mailbox, no flags, no server search. IMAP keeps the server as source of truth, supports multiple clients, folders, SEEN / flagged, and partial fetch. Users expect phone, desktop, and webmail to agree, so POP cannot drive the architecture. Mention MX lookup when Alice@gmail sends to Bob@outlook: the sending SMTP server resolves the recipient domain, then relays. You will not implement that in the browser. In this interview you wrap it behind HTTP (our API) or you name IMAP FETCH / IDLE if they insist on a desktop client.
Three mailbox shapes:
| Model | Source of truth | Use when |
|---|---|---|
| Store-and-forward (POP) | The device that downloaded it | Legacy. Inconsistent across devices. Search is local-only. |
| Server-only (classic webmail) | The mailbox on the server | No offline. Cheap client. Bad airplane mode. |
| Server + client cache | Server; client caches metas/bodies | Outlook / Apple Mail / our design. Offline browse + consistent flags. |
The hybrid is the default. The server still wins on conflict. The cache is what makes 20,000 metas feel local.
Named commands, one queue. Archive can fire from the toolbar, a context menu, a File menu, or e. All of them dispatch mail.archive. The store applies the optimistic patch; a durable task queue (IndexedDB, survives refresh) talks to the server with backoff. Reject → roll back and show the error. That same command list is how undo send (a 10s hold in the outbox) and redo stay consistent. If they ask for Electron / Tauri, the isomorphic core is commands + store + sync; the shell and the database adapter change (IndexedDB vs SQLite). Desktop also gets a menubar, a dock badge, and shortcuts that do not fight the browser.
Normalize further if they push: Account, Folder (with role and unreadCount), Thread, Message, Attachment, Contact, Draft. Threads are a grouping of metas by threadId, not a second list component. Incoming HTML is still hostile — sandboxed iframe, tight CSP, no allow-scripts + allow-same-origin, proxy or block remote images so tracking pixels do not fire on open.
Conclusion: How to Design a Mail Client
An email client is a sync engine with three panes. Keep metas and bodies apart, virtualize the list, treat HTML as hostile, and make archive/send idempotent.
We’ll have designed it as a product, not a layout exercise. The shell is folders, a virtualized meta list, a reading pane, and a composer. A Mail View Model plus a Network Manager and a Sync Engine own the rest: a since cursor, IndexedDB, an outbox, and batch mutations. 20,000 metas at 200 bytes is about 4 MB. That is not the problem. Mounting 20,000 rows and fetching 20,000 bodies is.
The details that separate a senior answer are the hostile-HTML pipeline, the idempotent clientId on send and drafts, unread counts stored on the folder, and search that shows local hits before the remote page lands. If the list is a window, the cache is split, and the composer cannot XSS the shell, the client will feel like mail — even on a mailbox that has been around for years.
