跳到正文
DEV Community· Mayank chopra·· 37 分鐘前AI 評分55

cloudmail 以每個電郵信箱一個 SQLite 數據庫在 Durable Objects 上運行電郵服務

One SQLite database per mailbox: running email on Durable Objects

AI 導讀

cloudmail 為每個電郵信箱配置一個 Cloudflare Durable Object,並以各自的 SQLite 數據庫儲存郵件及相關資料,避免以大型共用數據庫按帳戶欄位區分郵件。

正文

Most mail systems keep every user's messages in one large database and filter by an account column. cloudmail, the webmail app I build, does the opposite. Each mailbox is a Cloudflare Durable Object with its own SQLite database.

This post covers how that works, what it made easy, and where it hurts.

The pieces

cloudmail architecture inside a Cloudflare account

Everything runs in the Cloudflare account of the person who deploys it.

  • One Worker serves the web app (React Router), the REST API (Hono), the MCP server for agents, and the email() handler for incoming mail.
  • MailboxDO is one Durable Object per mailbox. It holds messages, threads, labels, rules and the search index in SQLite.
  • AuthDO holds accounts, sessions, API tokens, domains and aliases.
  • R2 holds attachments, raw messages and exports.
  • Vectorize holds embeddings for semantic search, one namespace per mailbox.
  • Workers AI runs summaries, triage and embeddings.
  • A cron runs every five minutes for scheduled sends, retention and expiry.

A mailbox is addressed by its email address

The Worker gets a mailbox's object by name:

const stub = env.MAILBOX.get(env.MAILBOX.idFromName(address));

There is no table mapping accounts to shards. The address is the key, and Cloudflare routes the call to the one object with that name. That object runs single-threaded, so two requests for the same mailbox never write at the same time. I do not hold locks or retry on write conflicts.

Migrations run when the object wakes

There is no fleet-wide migration step. Each object migrates itself in its constructor:

export class MailboxDO extends DurableObject<Env> {
  db: ReturnType<typeof drizzle>;

  constructor(state: DurableObjectState, env: Env) {
    super(state, env);
    this.db = drizzle(this.ctx.storage, { schema });
    applyMigrations(this.ctx.storage.sql, mailboxMigrations, this.ctx.storage);
  }
}

applyMigrations keeps a table of applied migration names and runs whatever is missing, in order. A mailbox nobody has opened for a year catches up the next time mail arrives for it. The newest migration today is 47_label_move_to_folder.

One constraint to know: the Durable Object runtime does not allow SQL-level BEGIN and COMMIT. A migration has to run inside the storage API's transactionSync() instead, so the runner strips any transaction wrapper from the SQL first.

The cost of this design is that every migration must be safe to run on a database of any age, at any time, with no operator watching. I cannot run a one-off script against all mailboxes, because nothing lists them all in one place to connect to.

Search is FTS5 inside each mailbox

SQLite ships with FTS5, so full-text search needs no extra service. This is the migration that adds it:

CREATE VIRTUAL TABLE IF NOT EXISTS emails_fts USING fts5(
    subject,
    body,
    sender,
    recipient,
    content='emails',
    content_rowid='rowid',
    tokenize='porter unicode61'
);

It is an external-content table: the index points at rows in emails and does not store the text a second time. Triggers on insert, update and delete keep it in step.

A search query has two kinds of terms, and they run differently.

  • Free text and phrases become one FTS5 MATCH expression, including OR and -word. One MATCH costs one index traversal. A subquery per word would cost one per word.
  • Operators such as from:, label:, has:attachment, in: and before: become ordinary SQL predicates on columns and joins, because FTS5 cannot express them.

The text part is hoisted into a CTE when the query allows it. That is also what makes highlighted snippets possible, since FTS5 only offers snippet() in a query that matches against the index itself.

Because the index lives in the mailbox's own database, a search can only ever see that mailbox's mail. There is no WHERE account_id = ? to forget.

Incoming mail routes on the envelope

How an inbound message is routed to a mailbox

Cloudflare Email Routing delivers every message for the domain to the Worker's email() handler. The handler parses it with postal-mime, then picks a mailbox:

if (await deps.mailboxExists(target)) {
  return { mailboxId: target, deliveredTo: target, via: "direct" };
}

const { aliases, catchAll } = await deps.lookup(target);

const aliasOf = aliases[target];
if (aliasOf && (await deps.mailboxExists(aliasOf))) {
  return { mailboxId: aliasOf, deliveredTo: target, via: "alias" };
}

const fallback = catchAll[domainOfAddress(target)];
if (fallback && (await deps.mailboxExists(fallback))) {
  return { mailboxId: fallback, deliveredTo: target, via: "catch_all" };
}
return null;

Two decisions here are worth explaining.

It routes on the envelope recipient. The envelope says where Cloudflare delivered the message. The To: header says whom the sender addressed, and it can name any mailbox. If routing fell through to header addresses, mail for an unknown address could land in a different real mailbox only because that mailbox was also listed in To:. The header is a fallback only when the envelope recipient is missing or on a domain the deployment does not serve.

A failed lookup throws. The alias and catch-all lookup reads the AuthDO, with a 5 second timeout. If that read fails, the handler throws, and Cloudflare retries or bounces the message. The alternative is to guess a mailbox or drop the message, and both lose mail silently.

Attachments go to R2 and the message row goes into the mailbox's database. A blocked sender's mail is stored in Spam, not dropped.

What this made easy

  • Isolation. One mailbox's data is physically separate from another's. A bug in a query cannot leak across mailboxes.
  • Deleting a mailbox is deleting one object's storage, its R2 keys and its vectors.
  • No database to run. No connection pool, no replicas, no capacity plan. An idle mailbox uses no compute.
  • Exact counters. Send caps and quotas are counted in the object that owns them, with no race between requests.

What it made hard

  • Anything across mailboxes. There are no cross-mailbox joins. "All inboxes" and search across mailboxes fan out to each object and merge the results. One request fans out to at most 20 mailboxes, and a filter reaches the rest.
  • Size limits. A SQLite Durable Object holds up to 10 GB on the Workers Paid plan, and a single row or blob is capped at 8 MB (limits). Attachments live in R2 for that reason. A very large mailbox is a ceiling I have to plan for.
  • No ad-hoc SQL. I cannot open a console and query all mail. Admin tools go through the same object methods the app uses.
  • Lock-in. Durable Objects exist only on Cloudflare. The app cannot move to another host. Mail can leave: every mailbox exports as .mbox.
  • Mail clients. There is no IMAP or SMTP server, so Apple Mail, Outlook and Thunderbird cannot connect. A Worker answers HTTP and the email() event, and IMAP needs a long-lived TCP server.

Would I do it again?

Yes, for this product. cloudmail is deployed by one person or one small team into their own account, with tens of mailboxes. At that size, a database per mailbox removes a class of bugs and all of the database operations. For a service with millions of mailboxes and analytics across them, I would look harder at the fan-out cost first.

The code is open source under Apache-2.0: github.com/cloudmail-hq/cloudmail

Disclosure: I build cloudmail. This post was written with AI. The code and limits were checked against the repository and Cloudflare's docs.

來源:DEV Community · dev.to