Appearance
ADR 0017 — E-mail delivery feedback: the module records and publishes, the product reacts
- Status: Accepted
- Date: 2026-11-10, delivery recorded the same day
- Baseline inspected:
develop,1b4bcfaf(GrydNotifications as of 11.2.0/11.3.0) - Related: ADR 0012, ADR 0011, ADR 0007
- Request answered: Nexio P10, "control e-mail bounce": a product must learn, without an operator, that an e-mail it sent did not reach the mailbox.
- Backlog:
backlog/notifications-email-bounce.md - Guide: Delivery feedback
Delivery status
Everything below is delivered, in one additive minor. Some decisions changed during delivery; the text below already describes the delivered design:
- Per-recipient state. It is an append-only table (
email_delivery_feedback), not new columns onNotificationRecipient. The recipient stays immutable. Each report is its own row, and the outcome is the fold of those rows. - Publication. It goes through the module's own outbox and worker, not the generic Core processor (see decision 6).
- Proposed items left out of v1:
- no
Abandonedoutcome on dead-letter; - no read endpoint and no change to the detail DTO;
- no telemetry counter for unmatched reports, only a structured log.
- no
Context
Some products use e-mail as a control, not as a courtesy. The Nexio warns a supplier's previous finance contact that the bank account is about to change. That e-mail is the only way the contact can say "it was not me", so the change's waiting period must not run on an e-mail that never arrived.
What the module did before this ADR:
- The send result was acceptance, not arrival.
SmtpEmailSenderandSendGridEmailSenderreturnedSentwhen the relay or the API accepted the message. Most bounces arrive later, as a DSN or a provider webhook, and the module had no path for either. - Bounces were never classified. Every caller of
MarkAsFailedpassedUnknown. A synchronous550becameEMAIL_SMTP_ERRORand was retried until dead-letter. In durable mode it was even parked asReconciliationRequired, although nothing had been sent. - Nothing could correlate a late signal. The MIME
Message-IDand the SendGridX-Message-Idwere lost. - The module's events reached no one. No
IDomainEventDispatcherwas registered. - Reconciliation was manual. An operator's declaration could not serve a control that must react on its own within hours.
Options considered
| Option | Verdict |
|---|---|
| A. The module ingests every provider's feedback (webhooks, return mailbox) and publishes it | Correlation and publication are generic, but every provider plus DSN parsing in the core is a large, brittle surface |
| B. The module offers only a port; each product brings its own capture | Every product would repeat correlation, idempotency and webhook verification, without the data only the module holds |
| C. The core records, correlates and publishes; each provider's capture is an opt-in adapter | Chosen |
Decision
1. Ownership
The module owns delivery feedback: correlating a report to a notification and a recipient, recording it, and publishing every change. The product owns the reaction: falling back to another address, cancelling a waiting period, suppressing an address. The framework never suppresses an address on its own.
2. Correlation written at send time
- Every e-mail carries
X-Gryd-Notification-Id(EmailMessage.NotificationId). A payload frozen before the field existed gets it at send time, and the stored payload does not change. - SMTP. The sender sets the MIME
Message-IDto<notification id>@<sender domain>, so it is the same on every retry. The notification records it asProviderMessageId. - SendGrid. The sender adds the custom argument
gryd_notification_id, so every event echoes the id. It also records the response'sX-Message-Id. - Matching. A report is matched by the echoed id, or else by
ProviderMessageId. A report that matches nothing is logged without its address and writes nothing.
3. Outcome per recipient
| Outcome | Meaning | Terminal |
|---|---|---|
| (none) | Accepted by the relay or API | No |
Delivered | The recipient's server accepted it | No: a later permanent bounce still wins |
TransientBounce | Temporary refusal (4.x.x, mailbox full, greylisting) | No |
PermanentBounce | Definitive refusal (5.x.x, unknown mailbox, provider drop) | Yes, absorbing |
EmailDeliveryOutcomePrecedence.Supersedes is the single rule:
- a permanent bounce wins over a delivery and is absorbing;
- a delivery wins over a transient bounce;
- a transient bounce replaces nothing.
Effects of a report:
- Every report is recorded. Only a report that changes the outcome is marked
ChangedOutcomeand published. - Status. The notification moves from
SenttoDeliveredonce every recipient isDelivered. No newNotificationStatusvalue is added for bounces. - Retries. A bounce never re-enqueues the notification or consumes a retry.
- Stored data. The diagnostic is a code (enhanced status or provider reason), truncated to 64 characters. The raw DSN or webhook body is never stored.
4. Synchronous SMTP classification
SmtpEmailSender classifies a SmtpCommandException with RecipientNotAccepted:
5xxfails withEMAIL_RECIPIENT_REJECTED, which maps to reasonBounced. The sender also reports aPermanentBounceforex.Mailboxthrough the port of decision 5. Its event id is the notification, the status and a hash of the address, so every retry's refusal is recorded once.4xxfails withEMAIL_RECIPIENT_DEFERRED, which maps to reasonProviderUnavailable.
DeliveryFailureCodes.ReasonOf is the one mapping, used by every caller of MarkAsFailed and by provider telemetry. Bounced joins the default non-retryable reasons.
In durable mode a refusal heard in the conversation is certain: nothing was sent. So it skips ReconciliationRequired. A 5xx is dead-lettered, and a 4xx is retried until the attempt budget runs out.
Limit. This covers direct submission refusals only. Behind a relay, a host on plain SMTP gets no asynchronous feedback, and the guide says so.
5. One inbound port
IEmailDeliveryFeedback.RecordAsync(EmailDeliveryReport) is the single entry for every source: the SMTP sender, the SendGrid webhook, and a product's own capture. It is registered whenever notifications are persisted.
- Idempotent. A report is recorded once per
(Provider, ProviderEventId). The unique index includes soft-deleted rows. - Serialized per notification. An advisory transaction lock per notification lets the outcome fold see every earlier report.
- Tenant. A webhook has no tenant. The notification is found by one narrow read across tenants (
FindNotificationAsync, listed inbuild/ignore-query-filters-exceptions.txt), and only its id and tenant leave that read. Every write then runs under that notification's tenant, throughITenantAmbient, so the tenant interceptor checks it like any other write. The caller never supplies a tenant, and its own scope is restored afterwards.
6. Publication after commit
Each change is staged in the same transaction that records it, as an intent of kind notification.email-feedback.v1 in notifications.outbox:
- the id and the aggregate are the feedback row;
- the sequence is 1, so the intent never waits behind a send;
- it is a local effect, with 10 attempts.
The module's DurableNotificationProcessor claims the intent under the notification's tenant. It hands an EmailDeliveryFeedbackNotice to every IEmailDeliveryFeedbackHandler registered in the host. The handlers, a DeliveryReceipt and the acknowledgement commit together. A handler that throws rolls the receipt back, and the notice is retried with backoff, then dead-lettered. Delivery is at least once, so the handler is idempotent by FeedbackId. Notices of one recipient may arrive out of order, and a permanent bounce is final.
Why not the generic Core processor (ADR 0012). The generic processor admits messages without a payload row, and every legacy notification.send.v1 row has none. Composing notifications.outbox as a generic producer would hand those sends to it. The module already drains its table with leases, receipts and reconciliation, so the notices stay in its own mechanism. Queue depth counts send intents only.
Scope of publication.
- Publication requires
DurableDelivery=true. Without it, reports are recorded but not published. - A notification with no tenant is published under platform scope, like its send.
- The aggregate's in-memory domain events are not wired to a dispatcher by this ADR.
7. Provider adapters, opt-in
SendGrid ships in the existing GrydNotifications.Infrastructure.SendGrid package, which now references the ASP.NET Core framework. MapGrydSendGridEventWebhook maps an anonymous POST receiver:
- Signature. It is verified with the library's
SendGrid.Helpers.EventWebhook.RequestValidatorover the raw body. - Limits. The timestamp tolerance defaults to 5 minutes and the body limit to 1 MiB.
- Responses.
401,413or400before anything is recorded. A verified batch answers200, even when some events match nothing; a recording failure answers500, so SendGrid resends. - Mapping:
delivered→Delivered;bounce→PermanentBounce, orTransientBouncewhen itstypeisblocked;blocked,deferred→TransientBounce;dropped→PermanentBounce;- other events are ignored.
SES via SNS: when a product asks for it. Return-mailbox DSN reader (IMAP): not planned. Relay DSNs vary too much to parse reliably.
8. Guidance to products
The absence of a bounce is not proof of delivery. A control that must know the e-mail arrived:
- starts on
Delivered; - treats
PermanentBounceas non-arrival; - keeps its own timeout for "no signal".
Plain SMTP behind a relay cannot satisfy such a control.
Consequences
- Additive minor. A new table, one nullable column, a new outbox kind, a port, a handler and an endpoint. A host that ignores the feature behaves as before, except for the synchronous
5xxchange below. - Synchronous
5xx. It is no longer retried, and in durable mode it is dead-lettered instead of waiting for reconciliation. - Personal data. E-mail addresses are stored per report and travel in notices. They are deleted with the notification.
- New unauthenticated surface. The SendGrid webhook's only trust is the provider signature. Hosts should add rate limiting.
- Conflicts with parallel work. The delivery-policy work also changes the Notifications model, so the model snapshot of whichever PR merges second must be regenerated.
Proofs
Each proof below is covered by automated tests in this delivery.
A synchronous
550for one recipient recordsPermanentBouncewith reasonBouncedand no retry; a450keeps the retry. These run against MailKit and an in-process SMTP server.A report matched by notification id and one matched by provider id update the right recipient in the right tenant. This holds for a caller with no tenant and for a caller in another tenant. An unmatched report changes nothing.
The same provider event twice is recorded once.
The precedence of decision 3 holds for every pair of outcomes.
A committed change reaches the handler after commit, under the tenant, with a receipt. A throwing handler gets the notice again.
Queue depth ignores feedback intents. A durable
5xxis dead-lettered and a4xxis retried.The SendGrid webhook refuses each of these, and maps each event type as in decision 7:
- a bad or malformed signature;
- a stale timestamp;
- an oversized body, with or without
Content-Length; - a body that is not an event array.
The signature is a real P-256 signature.