DEV Community

Felipe Rohde
Felipe Rohde

Posted on

Reading EmailEngine's source: how a one-person email API is built on Node and Redis

This week on X I posted about EmailEngine, a self-hosted email API run by one person. It's built by the author of Nodemailer, the email library a big chunk of Node apps already depend on. What caught my eye wasn't the revenue, it was that the source is public on GitHub, so you can actually go read how a one-person infra product is put together.

Quick note before anything: EmailEngine is not open source. The README calls it "source available", you can read and copy the code but you need a paid subscription to run it past the 14-day trial. The site lists $1,450 a year or $199 a month, unlimited mailboxes. So this post is me reading the code and the docs, not a fork guide.

What it does, in one line: you point it at Gmail, Microsoft 365 or any IMAP mailbox, and it gives you one REST API plus webhooks for everything in there. Your app never talks IMAP or parses MIME.

the stack

Opening package.json is the fastest way to understand a Node project. Here's what stood out:

  • plain JavaScript, CommonJS, 'use strict' at the top of files. no TypeScript, no build step for the server
  • hapi (@hapi/hapi) for HTTP, with joi for validation and the usual hapi plugins (bell, cookie, crumb, inert, vision)
  • Redis through ioredis, as the primary database
  • BullMQ for queues
  • imapflow, nodemailer, mailparser, smtp-server, libmime... basically the author's own email libraries
  • handlebars for a server-rendered admin UI, tailwind for the CSS
  • pino for logs, a Prometheus client for metrics
  • pkg to ship it as a single binary

There's even a comment in server.js that says the project is "Pure JavaScript only", no native addons. That fits something people self-host on all kinds of machines: npm install just works, and the prebuilt binaries don't need to compile anything.

Redis is the database, not a cache

This is the part I found most interesting. The README is very explicit: Redis is the primary store, you have to set maxmemory-policy to noeviction, and Redis Cluster isn't supported. If Redis evicts keys, sync state disappears, messages that were already synced look new, and you get duplicate webhooks.

It also says sync runs a separate Redis command per message in a folder, so latency between the app and Redis matters a lot.

If I were building something similar, I'd copy that and check it at boot instead of trusting the docs. Something like this in TS:

import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

export async function assertRedisIsADatabase() {
  // CONFIG GET returns [key, value]
  const [, policy] = (await redis.config("GET", "maxmemory-policy")) as string[];
  if (policy !== "noeviction") {
    throw new Error(
      `maxmemory-policy is "${policy}". set it to noeviction or sync state can vanish`
    );
  }

  const info = await redis.info("cluster");
  if (/cluster_enabled:1/.test(info)) {
    throw new Error("redis cluster is not supported, use a single primary");
  }
}
Enter fullscreen mode Exit fullscreen mode

EmailEngine shows warnings about these on its dashboard. For a side project, failing loud on boot is probably enough.

one process, many worker threads

server.js is the main thread and it spins up pools of worker_threads. The workers folder has one file per job type: api.js, imap.js, submit.js, webhooks.js, smtp.js, imap-proxy.js and export.js. Each pool size has its own env var, EENGINE_WORKERS for the IMAP workers and EENGINE_WORKERS_WEBHOOKS, EENGINE_WORKERS_SUBMIT and so on for the others.

The IMAP side is where it gets fun. Every connected mailbox is an "account", and the main thread assigns each account to one IMAP worker. There's a small file, lib/account-assignment.js, that does the bookkeeping. The core pick is short: sort workers by load, take the first one below the target per worker, otherwise the least loaded one. When a worker exits, its accounts go back to an "unassigned" set and get picked up in the next pass.

Here's my own TypeScript take on that idea, stripped down:

import { Worker } from "node:worker_threads";

type AccountId = string;

const workers = new Set<Worker>();
const load = new Map<Worker, Set<AccountId>>();
const assigned = new Map<AccountId, Worker>();
const unassigned = new Set<AccountId>();

function pickLeastLoaded(target: number): Worker | undefined {
  const byLoad = [...workers].sort(
    (a, b) => (load.get(a)?.size ?? 0) - (load.get(b)?.size ?? 0)
  );
  return byLoad.find((w) => (load.get(w)?.size ?? 0) < target) ?? byLoad[0];
}

function assignPending() {
  if (workers.size === 0) return;
  const total = assigned.size + unassigned.size;
  const target = Math.ceil(total / workers.size);

  for (const account of unassigned) {
    const w = pickLeastLoaded(target);
    if (!w) break;
    w.postMessage({ cmd: "assign", account });
    load.get(w)!.add(account);
    assigned.set(account, w);
    unassigned.delete(account);
  }
}

function spawnImapWorker() {
  const w = new Worker(new URL("./imap-worker.js", import.meta.url));
  workers.add(w);
  load.set(w, new Set());

  w.on("exit", () => {
    // give its mailboxes back to the pool
    for (const account of load.get(w) ?? []) {
      assigned.delete(account);
      unassigned.add(account);
    }
    load.delete(w);
    workers.delete(w);
    spawnImapWorker();
    assignPending();
  });

  return w;
}
Enter fullscreen mode Exit fullscreen mode

The real file handles way more edge cases than this. A worker can die while an assign call is still in flight, accounts get deleted mid-pass, and there are retry timers and a rebalance lock in server.js. The comments read like a list of bugs someone actually hit in production, which is honestly the best kind of comment.

Why one account per worker? An IMAP connection is long-lived and stateful (IDLE, folder state, reconnects). Pinning an account to one thread means only one place owns that connection, and a crash in one worker only affects the accounts on it.

webhooks go through a queue

Webhooks have their own worker. In workers/webhooks.js there's a BullMQ worker consuming the notification queue, with its concurrency read from an env var and defaulting to 1. That's the boring correct choice: a slow or dead customer endpoint retries on its own schedule and doesn't block mail sync.

A minimal version of that pattern:

import { Queue, Worker } from "bullmq";

const connection = { url: process.env.REDIS_URL! };
export const webhooks = new Queue("webhooks", { connection });

// producer, called from the sync side
export function emit(event: string, account: string, data: unknown) {
  return webhooks.add(event, { event, account, data, date: new Date().toISOString() }, {
    attempts: 10,
    backoff: { type: "exponential", delay: 5_000 },
    removeOnComplete: 1000,
  });
}

// consumer, its own worker thread or process
new Worker(
  "webhooks",
  async (job) => {
    const res = await fetch(process.env.WEBHOOK_URL!, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(job.data),
    });
    if (!res.ok) throw new Error(`webhook failed with ${res.status}`);
  },
  { connection, concurrency: Number(process.env.WEBHOOK_CONCURRENCY) || 1 }
);
Enter fullscreen mode Exit fullscreen mode

Same Redis, so you don't add any new infra.

what I'm taking from it

  • for infra people self-host, fewer moving parts wins. Node plus one Redis, no Postgres, no native modules
  • if Redis is your database, say it loudly and check the config
  • long-lived connections belong to exactly one owner. a worker pool with explicit assignment is simpler than it sounds
  • anything that calls a customer's URL goes through a queue with retries
  • you don't need TypeScript to ship a serious product. I'd still write mine in TS, but this codebase is clean JS with good comments and it clearly works

The thing I keep thinking about is that most of the hard parts here, IMAP, SMTP, MIME parsing, sit on the author's own libraries. The product is years of open source email work with a REST API and an ops layer on top.

sources

I post about indie apps and the code behind them on X https://x.com/felipe_rohde and Instagram https://instagram.com/feliperohde.dev.

Top comments (0)