Prompt
How do I decouple email sending from my main app?
Latest observation
A common way to decouple email sending is to move it out of your request path and into an asynchronous worker/service.
Typical patterns
1) Queue + background worker
Your app:
- validates the request
- saves any needed data
- publishes an “email to send” job to a queue
- returns immediately
A separate worker:
- reads jobs from the queue
- sends the email
- retries on failure
- logs results
Examples of queues: RabbitMQ, SQS, Kafka, Redis queues, Celery, Sidekiq, BullMQ.
2) Outbox pattern
If email events are tied to database writes, store an “email event” in the same DB transaction as your business data.
A background process later reads the outbox table and dispatches emails.
This helps avoid cases where:
- the DB write succeeds but the email job doesn’t get queued
- the job is queued but the DB write rolls back
3) Dedicated email service
Your app calls an internal email API or a third-party provider directly from a small email microservice.
That service handles:
- templates
- retries
- provider failover
- rate limiting
This is useful when many apps need the same email logic.
Recommended architecture
For most apps, do this:
- Main app receives user action
- Main app writes business data to DB
- Main app writes an email job or outbox record
- Worker picks it up asynchronously
- Worker sends via SMTP or an email provider API
- Worker marks job complete or retries on failure
Important design points
Make sending idempotent
A job may run more than once, so include:
- a unique job ID
- deduplication key
- “sent_at” tracking
Add retries with backoff
Temporary failures are normal. Retry a few times with exponential backoff.
Keep templates separate
Store templates in files or a template service, not inline in request handlers.
Track status
Store:
- queued
- sending
- sent
- failed
- retry count
- last error
Don’t block the user request
Never wait on SMTP or provider latency in the web request if you can avoid it.
Simple example flow
- User signs up
- App creates user record
- App inserts
welcome_emailjob - Worker processes job
- Worker sends welcome email through SendGrid/Postmark/SES
- Worker updates job status
If you want a quick implementation
Tell me your stack and I can sketch a concrete setup, for example:
- Node.js + BullMQ
- Python + Celery
- Rails + Sidekiq
- Java + RabbitMQ
- .NET + Hangfire
- Go + SQS/Redis