To send email from Node.js reliably, put each message on a BullMQ queue (backed by Redis) and let a separate worker call Nodemailer. Set attempts and an exponential backoff on the job, a limiter and concurrency on the worker, a deterministic jobId to avoid duplicates, and throw UnrecoverableError for failures that retrying cannot fix.
This guide provides a working producer and worker, explains each setting, shows how to separate temporary from permanent SMTP errors, how to shut down cleanly and what to monitor. BullMQ and Nodemailer options change between releases, so check their documentation for the versions you use.
Why queue email at all
Sending inside a request handler ties the user's response time to a remote server, loses the message if the process restarts and gives you no control over bursts. A queue decouples these concerns: the web process records the intent in Redis within milliseconds, and workers deliver at a pace your provider accepts, retrying failures. It also makes the system easier to scale and observe. See reliable sending queues for the wider design.
Install
npm install bullmq nodemailer
# Redis must be running and persistent (appendonly yes) if jobs must survive restartsShared Redis connection and queue (producer)
// queue.js
import { Queue } from 'bullmq';
export const connection = {
host: process.env.REDIS_HOST || '127.0.0.1',
port: Number(process.env.REDIS_PORT || 6379),
// If you pass your own ioredis instance to a Worker, create it with maxRetriesPerRequest: null.
};
export const emailQueue = new Queue('email', {
connection,
defaultJobOptions: {
attempts: 6,
backoff: { type: 'exponential', delay: 5000 }, // 5s, 10s, 20s, 40s, 80s
removeOnComplete: { age: 3600, count: 1000 },
removeOnFail: { age: 7 * 24 * 3600 },
},
});
export async function enqueueWelcome(user) {
// Deterministic jobId: adding the same id again is ignored while that job still exists
return emailQueue.add(
'welcome',
{ userId: user.id, to: user.email, name: user.name },
{ jobId: `welcome-${user.id}` },
);
}Keep the payload small and free of secrets: an ID and the few fields you need. The worker can load the rest from the database, so it always uses current data. Do not enqueue until your database transaction has committed.
The worker with Nodemailer
// worker.js
import { Worker, UnrecoverableError } from 'bullmq';
import nodemailer from 'nodemailer';
import { connection } from './queue.js';
const transporter = nodemailer.createTransport({
host: 'smtp.migosmtp.com',
port: 587,
secure: false, // false for 587: connect plain, then upgrade
requireTLS: true, // fail if STARTTLS is not available
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
pool: true,
maxConnections: 5,
maxMessages: 100,
connectionTimeout: 15000,
socketTimeout: 30000,
});
function isPermanent(err) {
const code = err.responseCode;
if (err.code === 'EAUTH') return true; // bad credentials
if (code && code >= 500 && code < 600) return true; // 5xx reply
return false; // network errors and 4xx
}
export const worker = new Worker(
'email',
async (job) => {
const { to, name } = job.data;
try {
const info = await transporter.sendMail({
from: 'Example App <[email protected]>',
to,
subject: 'Welcome to Example',
text: `Hello ${name}, your account is ready.`,
html: `<p>Hello ${escapeHtml(name)}, your account is ready.</p>`,
});
return { messageId: info.messageId };
} catch (err) {
if (isPermanent(err)) {
throw new UnrecoverableError(`permanent: ${err.responseCode || err.code} ${err.message}`);
}
throw err; // temporary: BullMQ will retry with backoff
}
},
{
connection,
concurrency: 5,
limiter: { max: 10, duration: 1000 }, // at most 10 jobs started per second
},
);
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
worker.on('failed', (job, err) => {
console.error(`email job ${job?.id} failed (attempt ${job?.attemptsMade}): ${err.message}`);
});With secure: false and port 587, Nodemailer starts in plain text and upgrades with STARTTLS; requireTLS refuses to continue unprotected. For implicit TLS use port 465 with secure: true. Pooling reuses connections, which saves handshakes for bursts. See the Nodemailer SMTP guide and which SMTP port to use.
What each setting does
| Setting | Where | Effect |
|---|---|---|
attempts | Job option | Total tries including the first |
backoff: { type: "exponential", delay } | Job option | Wait delay x 2^(attempt-1) ms before the next try |
concurrency | Worker | Number of jobs processed in parallel by this worker |
limiter: { max, duration } | Worker | At most max jobs per duration across all workers on the queue |
jobId | Job option | Unique identifier; a duplicate add is ignored while the job exists |
removeOnComplete and removeOnFail | Job option | Controls how long finished jobs stay in Redis |
UnrecoverableError | Thrown in processor | Moves the job to failed without further retries |
The BullMQ limiter is shared by all workers on the queue, unlike per-process limits, so it caps your total throughput. Set it from your provider's documented sending rate and connection limits, and keep concurrency within the Nodemailer maxConnections to avoid workers waiting for a free connection. See rate limits, retries and backoff.
Handling provider throttling
When the SMTP server replies with a temporary rate-limit response such as 421 or 450, retrying after the normal backoff may be too aggressive. BullMQ can pause the whole queue's processing for a while: call worker.rateLimit(ms) and throw Worker.RateLimitError() so the job is retried without consuming an attempt.
if (err.responseCode === 421 || err.responseCode === 450) {
await worker.rateLimit(30_000); // pause this queue's processing for 30 seconds
throw Worker.RateLimitError(); // job returns to the queue, attempt not consumed
}Add this inside the catch block before the generic temporary-error path. See 421 try again later for why servers throttle and how to respond.
Idempotency and duplicates
- Deterministic job IDs stop the same logical email being enqueued twice while the first job exists. Include the event type and the entity:
receipt-order-4567. - Retention matters. After a completed job is removed, the same ID can be added again. Keep completed jobs long enough for your duplicate window, or store sent keys in your database.
- At-least-once delivery. If a worker dies after the SMTP server accepted the message but before the job was marked complete, BullMQ can retry it, which may send twice. A rare duplicate is the price of not losing mail; use a database record keyed by message ID for stricter control.
- Never use random IDs for emails that must be unique.
Priorities, delays and separate queues
Not all email is equal. A password reset or login code should never wait behind ten thousand newsletter jobs. The simplest and most robust approach is separate queues with separate workers: one for transactional mail, one for bulk. Each gets its own limiter and concurrency, and a flood of bulk jobs cannot starve the urgent ones. BullMQ also supports job priorities and delays within a queue, for example { priority: 1 } for urgent jobs or { delay: 60000 } to send a reminder a minute later, but isolation by queue is easier to reason about under load. See separating transactional and marketing streams.
export const transactionalQueue = new Queue('email-transactional', { connection, defaultJobOptions: { attempts: 6, backoff: { type: 'exponential', delay: 3000 } } });
export const bulkQueue = new Queue('email-bulk', { connection, defaultJobOptions: { attempts: 4, backoff: { type: 'exponential', delay: 30000 } } });Use shorter backoff for transactional mail, where users are waiting, and longer backoff for bulk mail, where gentleness toward the provider matters more than speed. Use different SMTP credentials or sending domains for the two streams if your provider allows it, so that bulk reputation does not affect transactional delivery.
Testing the queue
Test three things separately. First, the enqueue function: assert that it adds a job with the expected name, data and jobId. Second, the processor function: export it from the worker module so that you can call it with a fake job and a stubbed transporter, and assert that a 550 reply becomes an UnrecoverableError while a connection reset is rethrown unchanged. Third, the whole path: run Redis and a local SMTP catcher in your CI environment, enqueue a job and wait for the message to appear. Nodemailer also offers a stream transport for testing that builds the message without any network connection.
Graceful shutdown
async function shutdown() {
await worker.close(); // waits for active jobs to finish, stops taking new ones
transporter.close(); // closes pooled SMTP connections
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);Closing the worker lets running jobs finish, which avoids abandoning an email halfway through SMTP. Give your process manager or container a stop timeout longer than your job time limit. BullMQ also detects stalled jobs (for example from a crashed process) and moves them back to the queue, which is another reason jobs must be safe to run twice.
Monitoring
- Alert when waiting jobs grow or the oldest waiting job gets older than your tolerance.
- Alert on the failed set size, and review failures by error code.
- Log the job ID, recipient domain and Message-ID, never the message body or credentials.
- Use Bull Board or a similar dashboard in a protected admin area to retry or inspect jobs.
- Process bounce and complaint webhooks from your provider and suppress bad addresses so they do not re-enter the queue.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Jobs stay waiting | No worker running, or a different queue name or Redis | Start the worker and check names and connection |
| Error about maxRetriesPerRequest | ioredis instance created for a Worker with defaults | Pass connection options, or set maxRetriesPerRequest: null |
| Connection timeout to SMTP | Port blocked or wrong TLS mode | Check port 587 versus 465 and secure. See SMTP timeout and TLS errors |
| EAUTH errors repeat | Retrying bad credentials | Treat as permanent, alert and fix the secrets |
| Duplicate emails | Random job IDs or removed history | Use deterministic IDs and a longer retention |
| Sending too fast, 421 replies | Concurrency or limiter too high | Lower limiter.max and concurrency |
Next steps
Start with one queue, one worker and the settings above, then load test against a local SMTP catcher before pointing at production. Tune the limiter to your provider's published limits, monitor queue age and failures, and add webhook handling for bounces so your queue never keeps mailing dead addresses.
Deliver your queue output reliably Use SMTP on ports 587 or 465, or the REST API, with webhooks for delivery and bounce events.
References and further reading
Frequently asked questions
How do I retry failed emails in BullMQ?
Set attempts and an exponential backoff in the job options. BullMQ retries thrown errors until attempts are used up.
How do I stop retrying a permanent failure?
Throw UnrecoverableError from the processor, for example for a 5xx recipient rejection or an authentication error.
How do I rate limit email sending in BullMQ?
Set a limiter on the Worker, such as max 10 per 1000 ms, and keep concurrency within your provider limits.
How do I avoid duplicate emails?
Use a deterministic jobId such as receipt-order-4567 and keep job history long enough, since BullMQ is at-least-once.
Does Nodemailer need pooling?
It is optional but helps bursts by reusing SMTP connections. Set pool: true and keep maxConnections within provider limits.