Prompt
How do I build multi-tenant email sending into a SaaS app?
Latest observation
To build multi-tenant email sending into a SaaS app, design it so each customer/tenant can send email through their own identity, settings, limits, and compliance rules—while your system still uses one shared platform.
Here’s a practical architecture and implementation approach.
1) Decide the tenancy model
There are usually three common models:
A. Shared sending infrastructure, tenant-specific identities
- One backend system sends all mail.
- Each tenant has its own:
- From name/address
- Domain
- DKIM/SPF/DMARC setup
- Templates
- Suppression list
- Sending limits
- Best for most SaaS products.
B. Tenant brings their own email provider account
- Tenant connects their own SES/SendGrid/Mailgun/SMTP account.
- You act as a control plane.
- Pros: clean billing separation, better deliverability ownership.
- Cons: more setup complexity.
C. Fully isolated per tenant
- Separate infrastructure, queues, keys, and sometimes separate sending subaccounts.
- Needed for enterprise, regulated, or high-volume customers.
Most SaaS apps start with A, then add B for larger customers.
2) Model tenant email configuration
Store per-tenant settings in your database. Example fields:
tenant_idsending_enabledfrom_namefrom_emailreply_to_emailcustom_domainverification_statusprovider(ses,sendgrid,mailgun,smtp, etc.)provider_credentials_refdkim_statusspfd_statusdmarc_statusbounce_handling_enabledunsubscribe_domaindaily_send_limitmonthly_send_limitrate_limit_per_minutesuppression_policytracking_enabled
Keep credentials in a secret manager, not plain DB.
3) Separate “compose” from “send”
Your app should not send email directly from request threads.
Use this flow:
- App creates an email intent:
- tenant
- template
- recipients
- dynamic data
- priority
- metadata
- Store it in a durable queue or table.
- Background worker picks it up.
- Worker resolves tenant config.
- Worker renders template.
- Worker sends via the correct provider/account.
- Worker records status and provider message ID.
This gives you:
- retries
- rate limiting
- auditability
- better performance
- tenant isolation
4) Use tenant-aware queueing
You need to prevent one noisy tenant from starving others.
Common patterns:
Option 1: Single queue + tenant-aware worker throttling
- One queue
- Each job includes
tenant_id - Worker checks per-tenant quotas before sending
Option 2: Queue per tenant or per tier
- Separate queues for premium, standard, enterprise
- Easier to control priority
- More operational complexity
Option 3: Central queue + partitioned processing
- Messages grouped by
tenant_id - Workers process partitions independently
For most apps, single queue + per-tenant rate limiting is enough.
5) Implement tenant-aware deliverability
Deliverability is a major concern in multi-tenant sending.
Use custom domains
Let tenants send from their own domain:
noreply@tenant.cominstead of your shared domain.
Set up authentication
For each tenant/domain:
- SPF
- DKIM
- DMARC
Optionally use subdomains
Instead of root domain, use:
mail.tenant.comnotify.tenant.com
This makes DNS setup cleaner.
Isolate reputations
If possible, separate:
- subaccounts
- sending IP pools
- mail streams/categories
That way one tenant’s bad reputation doesn’t hurt everyone else.
6) Handle bounces, complaints, and unsubscribes per tenant
You need tenant-scoped suppression handling.
Track:
- hard bounces
- soft bounces
- complaints
- unsubscribes
- invalid recipients
Design:
- global suppression table
- tenant suppression table
- merge rules when sending
Example:
- If an address unsubscribed from tenant A, it should not necessarily be suppressed for tenant B unless your product policy says otherwise.
- For compliance emails vs marketing emails, keep separate suppression categories.
Use provider webhooks to ingest events:
- bounce
- complaint
- delivery
- open/click if needed
Always map incoming events back to:
tenant_idmessage_idrecipienttemplatecampaign
7) Make templates tenant-scoped
Allow tenants to:
- customize branded templates
- upload logos
- choose colors
- set localized content
- manage signatures/footers
Store:
- template body
- tenant-specific variables
- localization variants
- version history
Best practice:
- use a shared base template system
- let tenants override allowed sections only
- validate HTML to prevent broken or unsafe markup
8) Build a safe email API
Expose an internal API like:
POST /tenants/{tenant_id}/emails
{
"template_id": "invoice_paid",
"to": ["user@example.com"],
"variables": {
"first_name": "Ava",
"amount": "$42.00"
},
"metadata": {
"order_id": "12345"
}
}
The API should:
- authenticate the tenant
- enforce permissions
- validate recipient domains if needed
- enforce quotas
- create an email job
- return a tracking ID
Do not let tenants specify arbitrary sender domains unless verified.
9) Design for provider abstraction
You’ll probably need one abstraction layer:
EmailProvider
- send(email)
- verifyDomain(domain)
- getDeliveryStatus(messageId)
- handleWebhook(event)
Implement adapters for:
- AWS SES
- SendGrid
- Mailgun
- Postmark
- SMTP
- Tenant-owned provider credentials
This makes provider switching easier and supports per-tenant provider choice.
10) Secure secrets and tenant access
If tenants connect their own provider credentials:
- encrypt credentials at rest
- store in a secret manager or KMS-encrypted vault
- never log secrets
- rotate keys
- scope permissions minimally
Also ensure:
- tenant A cannot see tenant B templates, logs, stats, or webhook events
- all queries are tenant-scoped
- add database-level safeguards if possible
11) Add quotas, abuse prevention, and safeguards
Multi-tenant email platforms can be abused.
Controls:
- per-tenant send limits
- recipient validation
- domain verification required before sending
- warm-up limits for new tenants
- content scanning for phishing/spam indicators
- manual review for suspicious tenants
- IP/domain reputation monitoring
Also consider:
- blocklist management
- suspicious spike detection
- anomaly alerts
12) Observability and audit trail
For every email, record:
- tenant
- sender config used
- recipient
- template version
- timestamp
- queue/job ID
- provider
- provider message ID
- status transitions
- error reason
- webhook events
This helps with:
- support
- debugging
- compliance
- billing
Build dashboards for:
- sends per tenant
- bounce rate
- complaint rate
- delivery latency
- suppressed recipients
- queue backlog
13) Suggested database tables
A simple schema might include:
tenantstenant_email_settingsemail_templatesemail_jobsemail_eventsemail_recipientssuppression_listprovider_accountsdomain_verificationswebhook_events
14) A good request-to-send flow
Example sequence:
- Tenant API request to send email
- Validate tenant, permissions, quota
- Create
email_job - Enqueue job
- Worker loads tenant email settings
- Check suppression and compliance rules
- Render template
- Send via provider/subaccount
- Persist provider message ID
- Update status
- Receive webhook events
- Update delivery/bounce/complaint status
15) Recommended implementation choices
If you want a pragmatic setup:
- Backend: your normal API stack
- Queue: SQS, RabbitMQ, Kafka, or Redis queue
- Workers: background job workers
- DB: Postgres
- Secrets: KMS + secret manager
- Provider: SES or SendGrid to start
- Webhooks: dedicated endpoint per provider
- Monitoring: metrics + logs + alerting
16) Common pitfalls
Avoid these:
- sending synchronously in web requests
- shared global suppression only
- no tenant-level rate limits
- mixing template data across tenants
- no webhook mapping to tenant context
- storing provider credentials insecurely
- allowing unverified sender domains
- ignoring complaint/bounce processing
- one shared IP/domain with no reputation controls
17) If you want the simplest viable version
Start with:
- one email provider
- one shared sending account
- tenant-specific
fromname and reply-to - tenant-scoped templates
- queue + worker
- webhook event tracking
- per-tenant send limits
- bounce/complaint suppression
Then add:
- custom domains
- subaccounts
- tenant-owned provider credentials
- advanced reputation isolation
If you want, I can also give you:
- a reference architecture diagram,
- a Postgres schema, or
- sample code for a multi-tenant email service in Node, Python, or Go.