Production-oriented email microservice that accepts send requests over HTTP, queues them reliably, and delivers mail through SMTP with rate limiting, retries, circuit breaking, and full observability.
Infrastructure (RabbitMQ, Redis, MongoDB, Prometheus, Grafana) runs in Docker. The API and worker run on your laptop (or any Node.js host) for fast local development.
- Overview
- Architecture
- How it works
- Components
- Reliability features
- Monitoring & logging
- Laptop installation guide
- API reference
- Management UIs
- Project structure
- Scripts
| Concern | Approach |
|---|---|
| Ingress | Express HTTP API with API-key auth |
| Queuing | RabbitMQ durable priority queue + dead-letter queue |
| Delivery | SMTP via pooled connections (Gmail, SES, SendGrid, etc.) |
| State & limits | Redis (circuit breaker, adaptive SMTP rate, metrics) |
| Credentials | MongoDB (API keys, admin keys) |
| Observability | Prometheus metrics + Grafana dashboards |
Design principle: The API never blocks on SMTP. It validates, authenticates, and enqueues. A separate worker consumes the queue and talks to the mail provider. That keeps the API fast and lets delivery scale independently.
Emailer runs as two separate processes. They never call each other directly. They only meet through RabbitMQ.
npm run dev npm run worker
┌─────────────┐ ┌──────────────┐
│ Emailer API │ ───► │ Email Worker │ ───► SMTP ───► Inbox
└─────────────┘ └──────────────┘
│ │
└──────────┬───────────┘
▼
RabbitMQ queue
(holds email jobs)
- API = take the order and put it on the shelf
- Worker = pick from the shelf and deliver the mail
- If the worker is down, emails wait safely in the queue. If the API is busy, sending still continues.
flowchart TB
Client["Your app<br/>POST /api/v1/send"]
subgraph API_SIDE["PROCESS 1 — Emailer API · npm run dev"]
direction TB
A1["Receive HTTP request"]
A2["Auth: validate API key<br/>MongoDB"]
A3["Guard: is circuit breaker OPEN?<br/>Redis — if yes → 503"]
A4["Publish email job<br/>to RabbitMQ"]
A5["Return 202 Accepted + jobId<br/>API is done — does NOT send SMTP"]
A1 --> A2 --> A3 --> A4 --> A5
end
subgraph BRIDGE["SHARED QUEUE — RabbitMQ"]
Q["email.queue<br/>priority jobs wait here"]
DLQ["email.deadletter<br/>failed after retries"]
end
subgraph WORKER_SIDE["PROCESS 2 — Email Worker · npm run worker"]
direction TB
W1["Consume next job<br/>from email.queue"]
W2["Check rate limiter<br/>+ circuit breaker · Redis"]
W3["Send via SMTP<br/>connection pool"]
W4{"Result?"}
W5["Success → ACK<br/>mail delivered"]
W6["Fail → retry with backoff<br/>or move to dead-letter"]
W7["Too many SMTP service fails<br/>→ OPEN circuit · pause consumer"]
W1 --> W2 --> W3 --> W4
W4 -->|OK| W5
W4 -->|retryable| W6
W6 --> W1
W4 -->|permanent fail| DLQ
W4 -->|SMTP broken| W7
end
Client --> A1
A4 --> Q
A5 --> Client
Q --> W1
W5 --> Inbox["Recipient inbox"]
W3 --> SMTP["SMTP provider"]
SMTP --> Inbox
| Emailer API | Email Worker | |
|---|---|---|
| Start with | npm run dev |
npm run worker |
| Talks to client? | Yes (HTTP) | No |
| Sends SMTP? | No | Yes |
| Main steps | Auth → circuit check → enqueue → 202 |
Dequeue → rate/circuit → SMTP → ACK / retry / DLQ |
| Uses MongoDB | API keys | — |
| Uses Redis | Read circuit state, write metrics | Rate limit, circuit breaker, metrics |
| Uses RabbitMQ | Publish to email.queue |
Consume email.queue, dead-letter on give-up |
| Service | Used by | For |
|---|---|---|
| MongoDB | API | Store API keys / admin keys |
| Redis | API + Worker | Circuit breaker, adaptive rate, metrics |
| RabbitMQ | API + Worker | Job handoff between the two processes |
| Prometheus / Grafana | Scrapes API /metrics |
Dashboards (queue, circuit, throughput) |
| Resource | Name |
|---|---|
| Exchange | email.exchange |
| Main queue | email.queue (priority 0–10) |
| Dead-letter queue | email.deadletter |
- Client calls the API with an API key and email body.
- API validates the key (MongoDB) and checks the circuit breaker (Redis).
- API publishes a job to RabbitMQ and returns
202+jobIdimmediately. - Worker (separate process) pulls that job from the queue.
- Worker applies rate limiting + circuit breaker, then sends SMTP.
- Success → ACK. Failure → retry, dead-letter, or open the circuit and pause.
The API never waits for Gmail/SES. The worker never serves HTTP. The queue connects them.
- Express + Helmet + CORS
- JSON body limit: 10 MB
- Default port:
3002(EMAILER_PORT) - Returns typed HTTP errors (400 / 401 / 429 / 502 / 503)
| Type | Purpose |
|---|---|
| API keys | mail_sk_live_… stored as bcrypt hashes in MongoDB; passed in request body as apiKey |
| Admin keys | Headers x-admin-email + x-admin-key for key creation and health |
Seed an admin key once:
npm run seed:admin-keySave the printed admin key securely; it is shown only once.
Orchestrates validate → circuit check → build job → publish to queue.
- Publisher for single and bulk jobs
- Consumer with ACK/NACK, delayed requeue, DLQ
- Priority support (0–10; higher number = higher priority)
| Piece | Detail |
|---|---|
SMTPClient |
Raw SMTP (STARTTLS / SMTPS), AUTH PLAIN |
ConnectionPool |
Max 1 connection per worker, idle timeout 30s |
EmailBuilder |
Builds MIME/DATA payload |
Works with any standard SMTP host (Gmail App Password, Amazon SES, SendGrid, Mailgun, custom MTA). Set MAILER_SMTP_* accordingly.
- Adaptive SMTP rate limiter
- Shared circuit breaker state (all workers see the same state)
- Metrics storage (30-day TTL)
- Global send counters (observability)
- API keys and admin credentials
- Host port in main compose: 27018
Shared across API and workers via Redis.
| Setting | Value |
|---|---|
| Failure threshold | 5 service failures |
| Open → half-open | 30 seconds (resetTimeout) |
| Half-open → closed | 2 successes |
| Metric values | 0 closed · 1 half-open · 2 open |
What counts as a service failure: connection/auth/timeout issues and SMTP codes such as 421, 503, 535.
What does not open the circuit: typical user/content errors (e.g. 550) and pure throttling (handled by the rate limiter).
API behavior: While state is open, POST /api/v1/send returns 503 CircuitBreakerOpenError so the system does not pile more work onto a broken SMTP path.
Worker behavior: When open, the consumer pauses. After the timeout it enters half-open, probes SMTP, then closes or reopens based on results.
Redis keys: circuit_breaker:state, :failures, :successes, :last_failure_time, :last_success_time.
| Scenario | Backoff | Limit |
|---|---|---|
| Normal / service errors | Exponential: ~2s, 4s, 8s | Default 3 retries |
| SMTP throttling | Longer: ~5s, 10s, 20s | Same max retries |
| Circuit breaker requeue | 30s × 2ⁿ (capped at 5 min) | Max 10 CB requeues, then DLQ |
| Permanent / protocol 451 | — | Immediate DLQ (no retry) |
After exhausting retries, messages are NACK’d without requeue and land in email.deadletter.
The worker learns provider limits from real SMTP responses:
- Starts around 1 email/second (override with
SES_SENDING_RATE) - Increases after sustained success; decreases on throttling
- Soft pre-check: prefers learning from real SMTP over hard-rejecting at the API
Keeps a warm SMTP connection where possible, with health checks and idle cleanup to avoid stale sockets.
When the circuit is open, the worker stops consuming so messages stay safely in RabbitMQ. When the circuit recovers, consuming resumes automatically (polled about every 5 seconds).
- Endpoint:
GET http://localhost:3002/metrics - Scrape target: Prometheus →
host.docker.internal:3002every 10s - UI: http://localhost:9090
- Retention: 30 days
Notable series:
| Metric | Meaning |
|---|---|
emailer_emails_sent_total |
Successful deliveries |
emailer_emails_failed_total |
Failures by reason |
emailer_queue_size |
Depth of the mail queue |
emailer_circuit_breaker_state |
0 / 1 / 2 |
emailer_connection_pool_size |
Idle / active SMTP connections |
emailer_api_key_validations_total |
Auth outcomes |
- URL: http://localhost:3000
- Default login:
admin/admin - Pre-provisioned Emailer dashboard (throughput, queue size, circuit breaker, errors, pool)
If Grafana fails to start with invalid setting [alerting].enabled, ensure monitoring/grafana/grafana.ini uses [unified_alerting] (legacy [alerting] is rejected by modern Grafana).
# Admin headers required
curl -H "x-admin-email: YOU@example.com" -H "x-admin-key: YOUR_ADMIN_KEY" \
http://localhost:3002/healthChecks SMTP, RabbitMQ (email.queue), and Redis. Overall healthy only if all three pass.
Console-based operational logging (no external log stack required for local use):
- API: timestamped request lines (
GET /metrics,POST /api/v1/send, …) - Worker: processing, retry, circuit, and rate-limit events
- Errors: typed
MailerErrorsubclasses with codes suitable for API responses
For production, forward stdout/stderr from API and worker processes to your log aggregator of choice.
| Error | Code | Typical HTTP |
|---|---|---|
ValidationError |
VALIDATION_ERROR |
400 |
AuthenticationError |
AUTH_ERROR |
401 |
RateLimitError |
RATE_LIMIT_ERROR |
429 |
SMTPError |
SMTP_ERROR |
502 |
QueueError |
QUEUE_ERROR |
503 |
CircuitBreakerOpenError |
CIRCUIT_BREAKER_OPEN |
503 |
- Node.js 18+ and npm
- Docker Desktop (Docker Compose)
- An SMTP account (Gmail App Password, or any SMTP provider)
cd /path/to/Emailerdocker-compose up -d
docker-compose psExpected containers:
| Service | Host port(s) |
|---|---|
| RabbitMQ | 5672, management UI 15672 |
| Redis | 6380 |
| MongoDB | 27018 |
| Prometheus | 9090 |
| Grafana | 3000 |
npm installcp .env.example .envEdit .env (align ports with docker-compose.yml):
# SMTP — use an App Password for Gmail, not your login password
MAILER_SMTP_HOST=smtp.gmail.com
MAILER_SMTP_PORT=587
MAILER_SMTP_USER=your-email@gmail.com
MAILER_SMTP_PASS=your-16-char-app-password
MAILER_SMTP_SECURE=false
# RabbitMQ
RABBITMQ_URL=amqp://admin:password@localhost:5672
RABBITMQ_USER=admin
RABBITMQ_PASS=password
# Redis (host port 6380)
REDIS_HOST=localhost
REDIS_PORT=6380
# MongoDB (host port 27018)
MONGO_URI=mongodb://admin:password@localhost:27018/emailer?authSource=admin
MONGO_USER=admin
MONGO_PASS=password
MONGO_DB=emailer
# App
EMAILER_PORT=3002
NODE_ENV=developmentGmail note: Enable 2-Step Verification, create an App Password, and put that 16-character value in MAILER_SMTP_PASS. Restart the worker after any .env change.
npm run seed:admin-keyStore the printed admin email and key.
npm run devnpm run workerWithout the worker, emails remain queued and are not delivered.
# Create API key (admin auth)
curl -X POST http://localhost:3002/api/v1/keys \
-H "Content-Type: application/json" \
-H "x-admin-email: YOUR_ADMIN_EMAIL" \
-H "x-admin-key: YOUR_ADMIN_KEY" \
-d '{"name":"local-dev","expiresInDays":365}'
# Send email (use returned apiKey; priority is required 0–10)
curl -X POST http://localhost:3002/api/v1/send \
-H "Content-Type: application/json" \
-d '{
"apiKey": "mail_sk_live_...",
"from": "your-email@gmail.com",
"to": ["recipient@example.com"],
"subject": "Hello from Emailer",
"html": "<p>It works</p>",
"priority": 5
}'Expect 202 and a jobId. Confirm delivery in the worker logs and the recipient inbox.
npm run build
npm start # API from dist/
npm run worker # still use tsx worker, or run compiled worker entry if you wire one| Method | Path | Auth | Description |
|---|---|---|---|
GET |
/ |
— | Service info |
GET |
/health |
Admin | Dependency health |
GET |
/metrics |
— | Prometheus exposition |
POST |
/api/v1/keys |
Admin | Create API key |
DELETE |
/api/v1/keys/:id |
— | Revoke API key |
POST |
/api/v1/send |
API key (body) | Queue single email → 202 |
POST |
/api/v1/send/bulk |
API key (body) | Queue up to 10,000 emails |
GET |
/api/v1/stats |
— | Pool + circuit breaker stats |
A typed HTTP client is available at src/api/client.ts (EmailerClient) for integrating from other Node services.
| Tool | URL | Credentials |
|---|---|---|
| API | http://localhost:3002 | API / admin keys |
| RabbitMQ | http://localhost:15672 | admin / password |
| Prometheus | http://localhost:9090 | — |
| Grafana | http://localhost:3000 | admin / admin |
In RabbitMQ UI, open Queues → email.queue / email.deadletter to inspect depth and consumers.
Emailer/
├── src/
│ ├── api/ # Express server + HTTP client
│ ├── auth/ # API keys & admin auth
│ ├── circuitBreaker/ # Redis-backed circuit breaker
│ ├── config/ # Environment & SMTP config
│ ├── errors/ # Typed errors
│ ├── health/ # Health checks
│ ├── metrics/ # Prometheus / Redis metrics
│ ├── queue/ # RabbitMQ publish & consume
│ ├── rateLimit/ # Adaptive SMTP + counters
│ ├── smtp/ # Client, pool, email builder
│ ├── index.ts # Emailer core
│ └── server.ts # API entrypoint
├── worker/
│ └── emailWorker.ts # Worker entrypoint
├── scripts/
│ └── seedAdminKey.ts
├── monitoring/
│ ├── prometheus/ # scrape config
│ └── grafana/ # dashboards & provisioning
├── docker-compose.yml
├── package.json
└── README.md
| Command | Description |
|---|---|
npm install |
Install dependencies |
npm run dev |
Start API with hot reload (tsx) |
npm run worker |
Start email worker |
npm run build |
Compile TypeScript to dist/ |
npm start |
Run compiled API |
npm run seed:admin-key |
Create/rotate admin key in MongoDB |
npm run clean |
Remove dist/ |
docker-compose up -d |
Start infrastructure |
docker-compose down |
Stop infrastructure |
ISC