For the complete site index, see llms.txt. Docs index: llms-docs.txt. Marketing corpus: llms-full.txt. Docs corpus: llms-full-docs.txt. Prefer markdown URLs where available (append .md).. Product skill: skill.md. Pricing: pricing.md. Docs MCP: /docs/mcp.

Engineering/

Inside Reloop's Email Delivery Pipeline: KumoMTA, NATS and BullMQ

Pranav Patel

Pranav Patel

Co-founder·11 min read

Inside Reloop's Email Delivery Pipeline: KumoMTA, NATS and BullMQ
Summary

How Reloop queues and delivers email for many tenants: an API that rejects bad sends early, KumoMTA's spool for SMTP delivery, NATS for delivery events, and BullMQ for campaigns, automations and webhooks.

Reloop doesn't push every email through one big job queue. It uses three systems, each for the job it's best at. The mail API runs every check synchronously and hands the message straight to KumoMTA, whose on-disk spool handles per-domain queueing, retries and SMTP delivery. KumoMTA publishes every delivery outcome to NATS, where independent consumers update logs, contacts, reputation and webhooks. BullMQ on Redis runs everything that needs scheduling or step-by-step pacing: campaigns, automations, webhook delivery and domain verification.

This post walks through why we split it that way and what each piece actually does, with code from the Reloop repo. The same pipeline ships in self-hosted Reloop.


The shape of the pipeline

text
1POST /api/mail/v1/send
2 │ rate limits → scope → domain → suppressions → DNS → log row
3 │ → template → tracking → reputation / quota guards
4 ▼
5KumoMTA (HTTP inject → spool → per-domain queues → SMTP)
6 │ log hook: one record per Reception / Delivery / Bounce / …
7 ▼
8NATS subject "kumomta.event"
9 ├── logs → email_log status + email_event rows
10 ├── contacts → auto-create contacts, suppress bounces/complaints
11 ├── reputation → bounce/complaint rates, auto-pause bad senders
12 └── workflow → customer webhooks (via BullMQ)
13
14BullMQ (Redis)
15 ├── campaign-send batched campaign sends
16 ├── automation-queue automation steps and delays
17 ├── workflow-queue domain DNS verification, other jobs
18 └── webhook-delivery-queue signed HTTP delivery with retries
Layer
Technology
What it owns
Admission
Elysia mail service + Redis counters
Validation, rate limits, suppression, quotas
Delivery
KumoMTA spool
Per-destination queues, SMTP retries, TLS, DKIM, IP selection
Events
NATS
Fan-out of delivery outcomes to every interested service
Background work
BullMQ on Redis
Campaign pacing, automations, webhooks, DNS checks

Why not one BullMQ queue for everything?

The obvious design is "API enqueues a job, worker sends it over SMTP." We didn't build that, for three reasons.

  1. An MTA is already a queue. SMTP delivery needs per-destination queues, connection limits, retry schedules for 4xx responses, TLS policy and spooling to disk so nothing is lost on restart. KumoMTA does all of that. Rebuilding it on top of Redis would mean writing a worse MTA.
  2. Errors should be synchronous. If the sending domain isn't verified or every recipient is suppressed, the caller should get a 400 with a reason right away, not a 202 followed by a failed job they never look at.
  3. Different work has different shapes. A password reset should leave in milliseconds. A 50,000-recipient campaign should trickle out under rate limits for an hour. A webhook needs to retry for half a day. One queue with one retry policy fits none of them well.

Stage 1: admission in the mail service

Every API send goes through a fixed sequence of steps in apps/backend/mail. Each one can reject the send with a structured error (message, why, fix, link).

Step
What it checks
Rate limit
Per-IP, per-user, per-org (per minute and per day) and global windows in Redis
Parse from
Valid address, display name
API key scope
The key is allowed to send from this domain
Verify domain
The sending domain is verified for this organization
Suppressions
Drops suppressed recipients, rejects if none are left
DNS health
Live check that the required DNS records are still published
Create log
Inserts the email_log row that every later event attaches to
Template
Resolves template.id and variables
Tracking
Rewrites links and adds the open pixel when enabled
Send
Composes MIME and injects into KumoMTA
Finalize
Publishes email.sent or email.scheduled

The rate limiter is a fixed-window counter per layer. Default limits from mail.config.ts, all overridable with environment variables:

Layer
Default
Per IP
20 / 60 s
Per user
50 / 60 s
Per organization
100 / 60 s
Per organization, daily
5,000 / day
Global
500 / 60 s
typescript
1// apps/backend/mail/src/middleware/rate-limiter.ts (simplified)
2const count = await redis.increment(layer.key); // e.g. rl:send:org:<id>
3if (count === 1) {
4 await redis.expire(layer.key, layer.windowSeconds);
5}
6if (count > layer.max) {
7 const ttl = await redis.ttl(layer.key);
8 // 429 with Retry-After = remaining window
9}

Idempotency is handled here too. If a request carries an Idempotency-Key that matches an earlier send, the API returns the original result instead of sending again. The one exception is a send whose status is failed: that only happens when nothing was delivered, so a retry with the same key is treated as a fresh send.


Stage 2: KumoMTA does the actual delivery

Once a message passes admission, the mail service composes the MIME message and posts it to KumoMTA's HTTP inject API:

typescript
1// apps/backend/mail/src/lib/kumomta-client.ts (simplified)
2const payload: InjectRequest = {
3 envelope_sender: toBareEmail(options.from),
4 recipients: [...recipientSet].map((email) => ({ email })),
5 content: rfc822Message,
6};
7
8await fetch(`${baseUrl}/api/inject/v1`, {
9 method: "POST",
10 body: JSON.stringify(payload),
11 signal: AbortSignal.timeout(30_000),
12});

Recipients across To, CC and BCC are deduplicated first, so one address never receives the same message twice.

From there, KumoMTA writes the message to its spool on disk (/var/spool/kumomta) and places it in a queue per destination domain. Its Lua policy, in apps/backend/smtp/policy, decides how each queue behaves.

Tenants map to IPs

KumoMTA's tenant field carries the TLS mode and, for organizations with a dedicated IP, the IP address and its hostname:

apps/backend/smtp/policy/egress.lua
-- 'opportunistic' shared pool (host default IP)
-- 'enforced|65.109.252.254|smtp.reloop.sh' dedicated IP

get_queue_config turns that tenant into an egress pool, and get_egress_source binds the right local address and EHLO hostname, which must match the IP's PTR record. Shared-pool senders and dedicated-IP senders never share a connection. New dedicated IPs still need an IP warming schedule before they carry full volume.

Bring-your-own SMTP

If an organization routes through its own SMTP provider, the queue config swaps the MX lookup for a smart host fetched from the domain service (cached for 60 seconds) and caps connections to that relay at 5:

lua
1-- apps/backend/smtp/policy/queue.lua (simplified)
2if provider_id then
3 local relay = get_relay(provider_id)
4 queue.protocol = { smtp = { mx_list = { byo.mx_entry(relay) } } }
5end

Over-quota mailboxes stop retrying

By default an MTA treats a 452 4.2.2 OverQuotaTemp from Gmail as temporary and retries for days. We rewrite those to a permanent 552 so the message leaves the spool and the address is suppressed:

apps/backend/smtp/policy/bounce_rewrite.lua
1kumo.on('smtp_client_rewrite_delivery_status', function(response, ...)
2 if is_over_quota(response) then
3 return 552
4 end
5 return nil -- keep default handling (greylisting, throttling still retry)
6end)

More on that in how we handle bounce processing.


Stage 3: NATS carries every outcome

KumoMTA's log hook publishes each delivery record (Reception, Delivery, Bounce, TransientFailure, Expiration, Feedback, and so on) to the NATS subject kumomta.event. Pre-queue rejections are dropped at the source because they never got an email log ID.

lua
-- apps/backend/smtp/policy/webhooks.lua (simplified)
nc:publish { subject = 'kumomta.event', payload = message:get_data() }

Four services subscribe, each in its own queue group, so every service gets every event, and each event is handled by only one replica of that service:

Consumer
Queue group
What it does
logs
logs-kumomta-worker
Updates email_log.status, writes email_event rows, pushes live updates to the dashboard
contacts
contacts-kumomta-worker
Creates contacts on delivery, suppresses hard bounces and complaints
logs reputation
logs-reputation-worker
Recomputes 24-hour bounce and complaint rates, pauses senders over the limit
workflow
webhook-dispatcher
Maps the event to email.delivered, email.bounced and friends, then fans out to customer webhooks

Every message carries an X-Email-Log-ID header stamped at admission. That's how a KumoMTA record finds its way back to the right row, organization and API key without guessing.

Adding a new reaction to delivery events means adding a subscriber. Nothing in the send path changes.


Stage 4: BullMQ for work that needs time

Everything that has to wait, pace itself or retry over hours lives in BullMQ.

Queue
Default attempts
Backoff
Worker concurrency
campaign-send
5
Exponential, 2 s base
3
automation-queue
5
Exponential, 2 s base
10
workflow-queue
3
Exponential, 1 s base (custom for DNS checks)
5
webhook-delivery-queue
7
Fixed schedule up to 10 h
10

Campaigns are a sequence, not a fan-out

The tempting way to send a campaign is to enqueue one job per recipient. That races the per-user and per-org rate limits and produces a wall of 429s. Instead, a campaign is a chain of batch jobs:

apps/backend/campaigns/src/lib/campaign/batch.ts
export const CAMPAIGN_BATCH_SIZE = 40;
export const CAMPAIGN_BATCH_DELAY_MS = 60_000;

Each batch loads the next 40 pending recipients, sends them through the same mail API as everything else, then schedules the next batch one window later. If the API answers 429, the next batch waits for the Retry-After value (never less than 60 seconds). Each campaign only ever has one active batch, so one large campaign can't crowd out another organization's sends.

Batch job IDs are deterministic (campaign-send-<campaignId>-<batchIndex>), and a batch reclaims any recipients a crashed worker left in sending. Restarting a worker mid-campaign doesn't double-send or lose recipients.

Domain verification on a schedule

When you add a domain, a job checks its DNS records seven times at roughly 10 s, 30 s, 1 min, 2.5 min, 5.5 min, 11.5 min and 21.5 min after you start verification. Most DNS changes are picked up within the first few minutes, and nobody has to click "verify" again.

Webhooks with a fixed retry schedule

Webhook delivery is its own queue with a custom backoff: 5 s, 5 min, 30 min, 2 h, 5 h and 10 h between attempts. The details are in building a webhook delivery system that actually retries.


What multi-tenancy means here

"Multi-tenant" in this pipeline comes down to four concrete mechanisms:

  1. Admission limits per org and per user in Redis, so one customer's spike gets 429s instead of slowing everyone down.
  2. Tenant-scoped egress in KumoMTA, so dedicated-IP customers send only from their own IP.
  3. One active batch per campaign, so bulk sends trickle instead of flooding.
  4. Reputation guards per org: if an organization's bounce or complaint rate crosses the threshold, its sending is paused before it damages the shared pool.

Lessons

  • Use the MTA as the delivery queue. It already solved retries, spooling and per-domain throttling.
  • Reject early, synchronously. Most "email didn't arrive" tickets disappear when the API says why at send time.
  • Publish outcomes, don't call services. NATS queue groups let us add consumers without touching the send path.
  • Pace bulk work explicitly. A chain of delayed batch jobs is easier to reason about than thousands of jobs racing a rate limiter.

For the lessons that aren't about queues, see building in public.


FAQ

No. Transactional sends go from the mail API straight into KumoMTA, which queues and delivers them. BullMQ is used for campaigns, automations, webhook delivery and domain verification.

Messages are spooled to disk before KumoMTA accepts them, so they are delivered after the restart. Delivery events are published as each attempt completes.

Yes. The per-IP, per-user, per-org and global limits are read from environment variables like RATE_LIMIT_ORG_MAX and RATE_LIMIT_USER_MAX in the mail service.

NATS queue groups give each service its own copy of every event while load-balancing within a service. That's exactly the fan-out pattern delivery events need.

W: 320.0px180R20∠45.0°

Ship your first email with Reloop
in minutes.

Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.

Reloop