What happens after your email API says accepted
By Flavio
Updated
Tagged: Cloudflare
Follow one transactional email through provider acceptance, SMTP delivery, queues, duplicate and out-of-order events, reconciliation, bounces, and complaints.
When an email API returns success, all you know is that the provider accepted the message and is going to try sending it. It might deliver it right away or put it in a queue. On the other end, the recipient’s mail server might defer it, bounce it, or accept it, and the user might still mark it as spam later.
If email is part of your signup flow, password recovery, billing, or account security, checking the return value of sendEmail() only covers the first step. You need to track what happens after the handoff.
The path of one email
Even a single welcome email passes through several separate systems on its way to an inbox:
Every step between those boxes can fail, run twice, or arrive out of order. A network connection can also drop right after the other side finishes its work, leaving your app guessing about what happened.
Accepted, queued, and delivered are different
Email providers report different things right after the initial send request. With Cloudflare Email Service, the REST API splits recipients into three groups:
deliveredfor recipients handled right awayqueuedfor recipients waiting for later deliverypermanent_bouncesfor recipients that bounced permanently
The Workers binding works differently: each env.EMAIL.send() call just hands back a single provider messageId. You’ll use that ID to match the initial send request with the delivery events that arrive later.
Don’t mark an email as delivered just because the HTTP request returned 200. That status code only tells you the API accepted your request, while the SMTP delivery to the recipient’s mail server happens afterward.
Create the local attempt first
Insert a local delivery record before you even call the provider, so the attempt has an ID in your database before any network request goes out:
INSERT INTO email_deliveries (
id,
subscriber_id,
purpose,
status,
created_at
) VALUES (?, ?, 'confirm_signup', 'submitting', CURRENT_TIMESTAMP);
Once the provider accepts the message, save the messageId it returns on that row:
UPDATE email_deliveries
SET
message_id = ?,
status = 'processing',
updated_at = CURRENT_TIMESTAMP
WHERE id = ?;
If the provider rejects the request outright, mark that attempt as failed instead:
UPDATE email_deliveries
SET
status = 'failed',
terminal = 1,
detail = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?;
Give every send attempt its own row rather than storing a single delivery status on the subscriber record. A subscriber can receive many emails over time, and even the same email type might take multiple attempts.
A timeout creates an unknown state
Think about what happens when your app sends the request and the connection resets mid-flight. The provider might have already accepted the email, even though your app never got the message ID back.
Treating that like a regular failure is risky, so store it under its own state:
submission_unknown
From there, you can figure out what happened through a few different paths:
- a provider idempotency key
- a provider message search API
- a lifecycle event that shows up later
- a custom message header generated by your app and preserved by the provider
Resist the urge to fire off a retry right away, because the first email could already be on its way. A duplicate password reset is annoying, a duplicate receipt or billing alert confuses customers, and repeating a notification batch can get expensive fast.
Normalize the provider message ID
Mail systems often wrap message IDs in angle brackets like this:
<0198abc@example.com>
The catch is that the send API response and the delivery event don’t always format them the same way. If one side has brackets and the other doesn’t, your lookups won’t match. Normalize the ID before saving or comparing it:
function normalizeMessageId(value) {
const id = value.trim()
if (id.startsWith('<') && id.endsWith('>')) {
return id.slice(1, -1).trim()
}
return id
}
Store the provider name next to it as well, since message IDs are only unique within a single provider and you might switch or add providers down the road.
Delivery events form a second input
Once you hand off the email, the provider keeps working on it and emits lifecycle events as things change. Cloudflare Email Sending publishes events like these:
message.delivered
message.deferred
message.bounced
message.failed
message.rejected
message.complained
An event subscription forwards them to a Cloudflare Queue, with one subscription per sending domain. Inside each event payload, the type field uses the full prefixed name, such as cf.email.sending.message.delivered.
At this point your app has two independent streams of data about the same email:
- the immediate response from the send API
- the asynchronous lifecycle events from the queue
They arrive through completely separate paths, and your database ties them back together using the provider message ID.
Validate every incoming event
Even though a queue message comes from your own infrastructure, validate its fields before updating anything. Check the event type, source, domain, message ID, event ID, timestamp, and terminal flag:
function parseDeliveryEvent(body, expectedDomain) {
if (!body || typeof body !== 'object') return null
const type = String(body.type ?? '').replace(/^cf\.email\.sending\./, '')
if (!knownTypes.includes(type)) return null
if (body.source?.type !== 'email.sending') return null
if (body.source?.domain !== expectedDomain) return null
const messageId = normalizeMessageId(
body.payload?.messageId ?? ''
)
const eventId = body.payload?.eventId
const eventAt = body.metadata?.eventTimestamp
if (!messageId) return null
if (typeof eventId !== 'string' || !eventId) return null
if (typeof body.payload?.terminal !== 'boolean') return null
if (!Number.isFinite(Date.parse(eventAt))) return null
return {
eventId,
messageId,
type,
eventAt,
terminal: body.payload.terminal,
payload: body.payload
}
}
Using a fixed allowlist keeps unexpected or malformed provider events from turning into bogus states in your database. In the snippet above, knownTypes holds the six short event names, so we strip the cf.email.sending. prefix before checking against it.
Save the original JSON payload alongside your normalized columns. The structured columns keep day-to-day queries fast, while the raw payload is what you’ll reach for when the provider adds new fields or you’re debugging an incident. You can check metadata.eventSchemaVersion (currently 1) to know which schema a stored event uses.
The correlation race
There’s a timing window right after sending where three things happen close together:
- the provider accepts the email
- the provider emits a delivery event
- your app saves the provider message ID to the database
If step 2 lands before step 3 finishes, your queue consumer receives a valid event for a message ID that isn’t in your table yet. Instead of dropping it, retry the message after a short delay to give the original request time to commit the correlation key:
const matched = await applyDeliveryEvent(db, event)
if (!matched) {
if (message.attempts < 3) {
message.retry({ delaySeconds: 10 })
return
}
await storeOrphanDeliveryEvent(db, event)
}
message.ack()
If the delivery row still isn’t there after the final retry, park the event in an email_delivery_orphans table or route it to a dead letter queue with enough data to replay it later. Dropping it on the floor would leave you with permanent gaps in your delivery history.
Queue delivery can happen more than once
Queues deliver messages at least once, so a consumer timeout, crash, or failed acknowledgement can send you the same event again, and providers occasionally emit duplicates on their own. Put a unique constraint on the provider event ID so the database catches repeats for you:
CREATE TABLE email_delivery_events (
event_id TEXT PRIMARY KEY,
delivery_id TEXT NOT NULL,
message_id TEXT NOT NULL,
type TEXT NOT NULL,
event_at TEXT NOT NULL,
payload TEXT NOT NULL
);
Open your transaction by inserting the event with ON CONFLICT DO NOTHING. If nothing gets inserted, acknowledge the message and bail out early. Updating a status column twice is usually harmless, but triggering duplicate alerts, suppression updates, or follow-up emails isn’t, so only the first copy should drive state changes and side effects.
Put side effects in an outbox
A bounce or spam complaint usually triggers a chain of work:
- updating the delivery row
- suppressing the recipient
- creating an admin alert
- notifying another system
If you update the database first and then publish an alert in a separate call, the database write can succeed while the alert fails and gets lost. Instead, insert an outbox row inside the same database transaction:
INSERT INTO email_outbox (
id,
type,
delivery_id,
payload
) VALUES (?, 'delivery_failed', ?, ?);
A background worker can then poll unsent outbox records, publish them, and mark them done. Because both writes share a single transaction, either the status update and its queued side effect commit together, or neither does.
Events can arrive out of order
Even when the provider emits events in the right sequence, queues don’t always preserve that order:
deferred at 10:01
delivered at 10:02
Your consumer can easily receive delivered first and the earlier deferred event a second later. Guard your update query so an event only overwrites the current delivery state if it’s at least as recent as what’s already stored:
UPDATE email_deliveries
SET
status = ?,
terminal = ?,
event_at = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
AND (event_at IS NULL OR event_at <= ?);
Without that check, a late deferred event would clobber a delivered status. Keep inserting the older event into email_delivery_events either way, though, so your audit log still records the full timeline even when the current state doesn’t move backward.
Separate terminal and non-terminal states
I track delivery attempts using these states:
submitting
submission_unknown
processing
deferred
delivered
bounced
failed
rejected
complained
The first three (submitting, submission_unknown, and processing) come from our own app, while the rest come from provider delivery events.
Store the provider’s terminal flag directly instead of guessing finality from the status name alone. A deferred event is usually non-terminal because the provider plans to retry, whereas a bounce is usually terminal, and letting the event schema tell you which is which avoids hardcoding assumptions. Once an attempt is marked terminal, never let an older non-terminal event reopen it.
A state machine makes the rules visible
In the normal case, an email moves cleanly through a straight path:
submitting → processing → delivered
↓
deferred
↓
delivered | bounced
When things go wrong, or when a recipient pushes back, you’ll see a few other transitions:
submitting → failed
submitting → submission_unknown
processing → rejected
delivered → complained
That last one looks odd at first, because delivered feels like the finish line. All delivered really records is that the recipient’s mail server accepted the message, so if the person hits “Mark as spam” hours later, that complaint has to supersede it. Write down the allowed transitions explicitly and unit-test them instead of blindly accepting any event with a newer timestamp.
Delivered does not mean inboxed or read
A delivered event just means the recipient’s mail server replied with a successful SMTP code like 250. From that signal alone, you still don’t know whether:
- the email landed in the inbox or the spam folder
- the recipient ever saw it
- the recipient opened it
- the recipient clicked a link inside it
Tracking pixels don’t reliably fill that gap either, since plenty of email clients block or proxy them, and they come with real privacy tradeoffs. Keep your terminology honest:
Delivered means the recipient’s mail system accepted the message.
Even with that caveat, knowing the remote server accepted the message is miles ahead of only knowing your API call returned 200.
Bounces and complaints change future sending
A hard bounce usually means the address doesn’t exist or can’t accept mail at all. Cloudflare emits message.bounced both for permanent bounces and when it runs out of retries on a temporary failure, so check bounce.type (hard or soft) to tell them apart. A complaint means the recipient flagged the message as spam.
Neither of those should stop at a single delivery row. Track a suppression state per recipient so future sends know to skip bad or complaining addresses:
active
suppressed_bounce
suppressed_complaint
Check that suppression table before you submit any new transactional email. Suppress the address on every complaint and on any bounce where bounce.type is hard. A soft bounce only tells you the provider ran out of retries on this attempt, while a deferred event arrives with terminal: false because the provider is still trying, so leave the address unsuppressed in both cases.
Your provider might keep its own suppression list as well. Cloudflare does, and it suppresses eligible soft bounces for 24 hours by default, returning a message.rejected event with rejection.reason set to suppressed if you send to them. Keeping your own local suppression state is still worth it, because your app needs to know and explain why it skipped sending a message in the first place.
Reconciliation catches missing events
Even with retries and a dead letter queue in place, things occasionally slip through the cracks, so add a periodic reconciliation job that scans for stuck work:
submittingattempts older than a few minutessubmission_unknownattemptsprocessingattempts that haven’t seen a lifecycle event after an expected window- orphan events that now have a matching message ID in your database
- outbox records that still haven’t been published
Whenever your provider exposes logs or a lookup API, the job can query them to resolve stalled attempts while your queue consumer continues handling normal traffic.
Show failures that require action
Dumping every raw email event into an admin table is mostly noise when you’re trying to spot broken deliveries. Query for the latest failed attempt per subscriber instead:
WITH ranked AS (
SELECT
deliveries.*,
ROW_NUMBER() OVER (
PARTITION BY subscriber_id
ORDER BY created_at DESC, id DESC
) AS position
FROM email_deliveries AS deliveries
)
SELECT *
FROM ranked AS delivery
JOIN subscribers AS subscriber
ON subscriber.id = delivery.subscriber_id
WHERE position = 1
AND delivery.status IN (
'bounced',
'failed',
'rejected',
'complained',
'submission_unknown'
);
Include the email purpose, the last error message, the event timestamp, and a link to the full event history so you can jump straight into debugging. Keep in mind that a later successful send can clear an older failure, whereas a spam complaint stays worth paying attention to even if other messages got through.
The complete design
Putting all of this together takes a few tables rather than a single email_status column:
Each piece handles a specific job:
- delivery attempts hold the current state of each send
- events keep the raw history of what the provider reported
- orphans hold events that arrived before we could match them to an attempt
- outbox records keep downstream side effects tied to the same transaction
- reconciliation sweeps up anything stuck or missed between systems
What I would monitor
Once this tracking is in place, you’ll want alerts on a few concrete signals:
- a rising hard-bounce rate
- any complaint on low-volume transactional email
- old
submission_unknownattempts - a growing orphan-event count
- a growing dead letter queue
- delayed outbox records
- processing attempts with no terminal event
- sudden increases in provider rejection
Aggregate rates are what catch reputation or configuration problems across the whole system, while the individual attempt records give you what you need when you have to fix a single account.
What the application needs to know
When you call a send API, you’re only asking whether the provider accepted the submission request. Your app also needs to know what happened to that delivery attempt afterward, and whether you need to take action.
To get there, you store the attempt before making the network call and keep unknown outcomes instead of guessing. As later events come in, you correlate them to the attempt, deduplicate repeats, reject stale state changes, and let reconciliation catch whatever gaps show up between systems. Throughout all of it, store accepted and delivered as separate facts: accepted means your API call worked, and delivered means the recipient’s mail system accepted the message.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: