Sub topic 15
Tracking delivery status and feedback
A notification is not done when your worker hands it to a provider. The provider may accept the message and still fail to deliver it. The phone may be off, the email address may not exist, or the push token may have expired. This chapter covers how to record what happened to each notification and how to feed that information back into the system.
This chapter assumes you have read the earlier chapters on provider integration and retries. It also assumes you can read short Python snippets and know how webhooks (HTTP callbacks that a provider sends to your server) work.
Why "sent" is not "delivered"
Your worker calls a provider API and gets a success response. That response usually means only "I accepted your request." Delivery happens later, and the provider reports it separately.
| Signal | What it proves | Typical source |
|---|---|---|
| Queued | Your system accepted the event | Your own pipeline |
| Sent | The provider accepted the request | Synchronous API response |
| Delivered | The provider's downstream handed it to the device or mailbox | Webhook, delivery receipt |
| Opened or clicked | The user interacted with it | Tracking pixel, link redirect, app callback |
| Failed or bounced | Delivery did not happen | Webhook, error response |
Channels differ in how much you can learn. SMS carriers often return a delivery report. Email gives you bounces and complaints, and opens only through tracking pixels that many clients block. Push services such as APNs and FCM tell you little about whether the user saw the message. In-app messages are the exception, because your own client can report that it displayed them.
The delivery lifecycle
Model each channel send as its own record with a status. One event for one user may fan out to push and email, and those can end in different states.
Keep two levels of data:
- A delivery attempt log, which is append-only. Each row stores the send ID, channel, provider, provider message ID, attempt number, status, error code and timestamp. Retries create new rows.
- A current status on the send record, which is what dashboards and support tools read.
Store the provider's message ID on every attempt. It is the only reliable way to match a later webhook to your record.
Receiving provider feedback
There are three ways to learn the outcome.
- Synchronous responses. The send call returns success or an error. Use this to classify errors as transient (retry, as in the retries chapter) or permanent (stop).
- Webhooks. The provider calls your endpoint with delivery receipts, bounces and complaints. This is the main source for email and SMS.
- Polling. Some providers or older carrier APIs require you to fetch status by message ID. Poll with a delay and a limit, and stop after a deadline.
Webhook endpoints are public, so treat them as untrusted input. Verify the provider's signature before reading the body. Return a 2xx quickly and do the real work off the request path, because providers retry slow or failing webhooks.
Handling out-of-order and duplicate receipts
Providers deliver webhooks at least once, with no ordering guarantee. A "delivered" receipt can arrive before the "sent" update you write after the API call returns. The same receipt can arrive twice. If you simply overwrite the status with each message, the record can move backward.
The fix is to treat status as a state machine that only moves forward. Give each status a rank and ignore any update that does not advance it. Failures need a rule too: a bounce is meaningful only if the send had not already been delivered.
import hashlib
import hmac
RANK = {"queued": 0, "sent": 1, "delivered": 2, "opened": 3}
FAILURES = {"failed", "bounced"}
def verify_signature(secret: bytes, body: bytes, signature: str) -> bool:
"""Check an HMAC-SHA256 signature in constant time."""
expected = hmac.new(secret, body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)
def next_status(current: str, incoming: str) -> str:
"""Return the status to store after receiving an update."""
if current in FAILURES:
return current
if incoming in FAILURES:
return incoming if current in ("queued", "sent") else current
return incoming if RANK[incoming] > RANK[current] else current
status = "queued"
for update in ["delivered", "sent", "delivered", "opened"]:
status = next_status(status, update)
print(update, "->", status)Running this shows that the late "sent" update and the duplicate "delivered" update change nothing. The final status is "opened".
In a real system, do the read and write as one atomic step, for example UPDATE sends SET status = :new WHERE id = :id AND rank(status) < :new_rank. Otherwise two webhook workers can race and one can overwrite the other.
Deduplicate webhooks by the provider's event ID when one exists. The idempotency chapter's approach applies here too: claim the event ID before processing it.
Closing the loop: feedback that changes behavior
Tracking is only useful if the results change what you do next. Each kind of feedback should trigger a specific action.
| Feedback | Meaning | Action |
|---|---|---|
| Push: unregistered or invalid token | The app was uninstalled or the token rotated | Delete or deactivate the device token |
| Email: hard bounce | The address does not exist | Add to a suppression list and stop sending |
| Email: soft bounce | Mailbox full or server down | Retry later with a limit, then suppress |
| Email: spam complaint | The user marked it as spam | Suppress the address and mark email as opted out for that type |
| SMS: carrier rejected, number invalid | Wrong or disconnected number | Mark the number invalid and stop sending |
| SMS: STOP reply | The user opted out | Record the opt-out in preferences immediately |
Check the suppression list in the routing step, before a message reaches the queue. Sending repeatedly to dead addresses damages your sender reputation, and mailbox providers then route even your good email to spam. Many providers also suspend accounts whose bounce or complaint rate is too high.
Practical design points
- Set a deadline for "no news." If a send stays in "sent" with no receipt after a defined time, such as 24 hours for email, mark it as "unknown" instead of leaving it open forever. Some carriers never return receipts, so absence of a receipt is not a failure.
- Separate send metrics from delivery metrics. Report "sent" and "delivered" rates per channel and provider. A drop in the delivered ratio while the sent count stays flat points to a provider or carrier problem, and the monitoring chapter builds on this.
- Keep tracking data proportionate. Open and click tracking records user behavior, so make it subject to consent and retention limits, as covered in the privacy chapter.
- Use one internal status vocabulary. Providers name states differently ("accepted," "dispatched," "undelivered"). Map each provider's values to your own statuses in the provider adapter, so the rest of the system never sees provider-specific terms.
- Handle failover carefully. If you retry on a second provider after a failure, create a new attempt row with the new provider message ID. A late receipt from the first provider can still arrive and must not corrupt the new attempt.
Common errors
- Marking a send "delivered" when the provider API returns 200.
- Matching webhooks by user ID and time instead of provider message ID.
- Overwriting status without checking order.
- Returning a non-2xx response for webhook events you do not recognize, which triggers endless provider retries. Acknowledge and ignore unknown event types.
- Skipping signature verification, which lets anyone forge bounces and suppress your users.
Exercise
A send is in status "sent." Your webhook endpoint receives three events for it, in this order: "opened," "delivered," "bounced." Using the rules in next_status, what status does the send end in, and why? What would go wrong if you simply stored each event as it arrived?
Show answer
Starting from "sent," "opened" has rank 3 and is higher than 1, so the status becomes "opened." The following "delivered" has rank 2, which does not advance past 3, so it is ignored. The "bounced" event is ignored too, because the current status is not "queued" or "sent" and the message was evidently delivered. The final status is "opened." If you stored each event as it arrived, the record would end as "bounced," which is wrong. It would show a delivered and opened message as failed, and it could wrongly add the address to the suppression list.
Exercise
Name two pieces of feedback from providers and the action each should trigger in your system.
Show answer
An invalid or unregistered push token response should deactivate that device token. An email hard bounce or spam complaint should add the address to the suppression list so the routing step stops sending to it. An SMS STOP reply should be recorded as an opt-out in the user's preferences.