Prompt
How do I process delivery events from an email provider?
Latest observation
To process delivery events from an email provider, treat them as webhooks: your provider sends your app HTTP notifications when an email is accepted, delivered, bounced, opened, clicked, etc.
1) Set up a webhook endpoint
Create an HTTPS endpoint in your app, for example:
POST /webhooks/email-events
It should:
- accept JSON payloads
- return a fast
200 OK - be idempotent
- verify the sender/authenticity of the event
2) Verify the event
Before trusting the payload, validate it using one or more of:
- webhook signature header
- HMAC secret
- provider-issued token
- IP allowlist
- timestamp/replay protection
This prevents forged events.
3) Parse the event type
Providers usually send an event like:
deliveredbouncedeferredopenedclickedcomplainedunsubscribed
Typical fields include:
message_idrecipientevent_typetimestampreasonorerrormetadata/ custom args
4) Store the event
Save raw events in a database or queue for audit/debugging. Keep:
- provider event id
- message id
- recipient
- event type
- timestamp
- payload
- processed status
This helps with retries and duplicate events.
5) Update your application state
Map events to your internal records. For example:
delivered→ mark message as deliveredbounce→ mark recipient as invalid or failedcomplained→ suppress future sendsclicked/opened→ track engagement
Use the provider’s message identifier to relate the event back to the original email send.
6) Handle duplicates and ordering
Email providers often retry webhooks and may deliver events out of order. Make your handler:
- idempotent: ignore duplicate event IDs
- order-tolerant: don’t assume “opened” arrives after “delivered”
- state-aware: only advance status when appropriate
Example:
- if a message is already marked
bounced, don’t overwrite it withdelivered
7) Process asynchronously
For reliability, do minimal work in the webhook request:
- verify and parse
- enqueue event
- return
200 OK
Then have a worker process the queue and update your database. This avoids timeouts and supports retries.
8) Log and monitor
Track:
- invalid signatures
- failed parses
- webhook retries
- queue backlog
- processing errors
Set alerts for spikes in bounces/complaints.
Example flow
- You send email with
message_id = abc123 - Provider later sends webhook:
{ "event_type": "delivered", "message_id": "abc123", "recipient": "user@example.com", "timestamp": "2026-09-23T12:34:56Z" } - Your webhook:
- verifies signature
- stores event
- marks
abc123as delivered - returns
200 OK
Suggested database model
emails
idprovider_message_idrecipientstatussent_atdelivered_atbounced_at
email_events
idprovider_event_idprovider_message_idevent_typepayloadcreated_at
If you want a robust implementation
I can provide:
- a sample webhook handler in Node.js, Python, or Go
- a database schema
- event-processing logic for a specific provider like SendGrid, Mailgun, Amazon SES, or Postmark