Prompt
How should I store email delivery status?
Latest observation
A good rule is: store the delivery outcome as an immutable event log, and keep the current state as a small summarized record.
Recommended approach
1. Keep a per-recipient delivery record
If one email goes to multiple recipients, store status per recipient, not just per message.
Typical fields:
message_id/email_idrecipientprovider_message_idstatus
e.g.queued,sent,delivered,deferred,bounced,complained,opened,clickedstatus_reasonorerror_codestatus_detail/provider_responsetimestampattempt_numberupdated_at
2. Use a status model with clear lifecycle states
A simple lifecycle might be:
queued -> sent -> delivered
with failure branches:
queued -> deferred -> sentqueued -> bounceddelivered -> complained
If you need analytics, track engagement separately:
openedclickedunsubscribed
3. Store events separately from current state
Best practice:
- Event table: append-only log of all webhook/provider events
- Current status table: one row per recipient/message with the latest known state
This helps with:
- retries
- auditing
- deduplication
- handling out-of-order provider webhooks
4. Make status updates idempotent
Email providers often send duplicate or out-of-order events. Store:
- provider event ID
- event timestamp
- processed-at timestamp
Only update current state if the incoming event is newer or represents a valid transition.
5. Distinguish transport vs engagement
Don’t mix:
- delivery: accepted by provider, sent, delivered, bounced
- engagement: opened, clicked, unsubscribed
A message can be delivered but never opened.
Example schema
email_messages
idsubjectbodycreated_at
email_recipients
idemail_message_idrecipient_emailstatuslast_event_atprovider_message_idfailure_codefailure_reasondelivered_atbounced_atopened_atclicked_at
email_delivery_events
idemail_recipient_idprovider_event_idevent_typeevent_payloadoccurred_atreceived_at
If you want something simpler
For a small system, a single table can work:
statusstatus_updated_atfailure_reasonprovider_message_id
But once you have webhooks, retries, or multiple providers, an event log becomes very valuable.
Practical advice
- Use enum/status codes rather than free-text status strings.
- Keep the raw provider payload for debugging.
- Track one latest status plus history.
- Separate recipient-level status from message-level status.
If you want, I can suggest a concrete SQL schema for Postgres or a model for a specific email provider like SES, SendGrid, or Postmark.