TL;DR: Retry a failed email API call only when the failure is plausibly temporary, cap the schedule, honor Retry-After, and persist the exact template revision beside every attempt. In a marketplace compliance workflow, template ownership is part of the delivery record: a successful HTTP response without the rendered revision is weak evidence.
The pager question is simple: what page fired, and what evidence will still exist when someone asks about it six months later? A retry loop that cannot answer those questions is an email sender with a timer attached.
It failed. That is the whole point of the record.
How should marketplace teams retry failed email API calls?
For a compliance notice, I use a delivery contract with three separate outcomes: accepted by the provider, rejected as permanent, or deferred for another attempt. A timeout, connection reset, DNS failure, and HTTP 429 or 5xx usually belong in the deferred bucket. A malformed address, an authentication failure, or a policy rejection usually belongs in the permanent bucket. The provider's response body and status code remain evidence; a generic send failed string is not.
A practical schedule might allow five attempts over roughly 15 minutes: exponential delays with full jitter, a hard per-message deadline, and a queue-level rate limit. Those are policy values, not laws. Tune them against provider guidance, mailbox-provider throttling, and the expiry of the notice itself. Never let a retry budget turn a temporary outage into a second outage caused by your own traffic.
Store an idempotency key derived from the notice ID and template revision. Store the attempt number, scheduled time, start and finish timestamps, response class, and a redacted error. If the provider accepts the request and your worker crashes before recording it, replay is safe only when the provider documents duplicate suppression for that key within the relevant retention window. A local key alone cannot prevent a second remote submission; without that guarantee, quarantine an ambiguous result for reconciliation.
Check the contract first.
Which failures deserve another attempt?
The useful question is not “did the call fail?” It is “can another call change the result without changing the legal meaning of the notice?” That distinction keeps a 400 response from becoming five identical pages in a recipient's inbox.
| Signal | Default action | Evidence to retain |
|---|---|---|
| Timeout, connection reset, DNS error | Retry within deadline | Network error class and attempt timing |
| HTTP 429 | Retry after the server's delay, then apply your cap |
Retry-After, response headers, attempt count |
| HTTP 500–599 | Retry with jitter if the request is safe to replay | Status, request ID, body hash |
| HTTP 400, 401, 403, 404 | Stop and route to correction | Status and validation detail |
| Accepted response | Mark accepted once | Provider ID, template revision, payload hash |
An HTTP 202 is an acknowledgement, not proof that a mailbox received the message. Keep the provider's acceptance ID and correlate later delivery events when the service exposes them. SPF is one part of the receiving domain's authorization story, and RFC 7208 makes clear that an SPF result does not by itself prove final delivery.
Acceptance isn't delivery.
The code below leaves the provider behind an interface. That boundary matters because the retry policy should be testable with deterministic responses, while template rendering and provider credentials belong to separate owners.
package delivery
import (
"context"
"errors"
"math/rand"
"time"
)
type Result struct {
Status int
ProviderID string
RetryAfter time.Duration
RequestID string
}
type Sender interface {
Send(ctx context.Context, idempotencyKey, templateRevision string) (Result, error)
}
func SendWithBudget(ctx context.Context, s Sender, noticeID, revision string) (Result, error) {
const maxAttempts = 5
const base = 2 * time.Second
const capDelay = 5 * time.Minute
for attempt := 1; attempt <= maxAttempts; attempt++ {
result, err := s.Send(ctx, noticeID+":"+revision, revision)
if err == nil && result.Status >= 200 && result.Status < 300 {
return result, nil
}
if !retryable(result.Status, err) || attempt == maxAttempts {
if err != nil {
return result, err
}
return result, errors.New("delivery rejected or budget exhausted")
}
delay := result.RetryAfter
if delay <= 0 {
delay = base * time.Duration(1<<(attempt-1))
if delay > capDelay {
delay = capDelay
}
delay = time.Duration(rand.Int63n(int64(delay) + 1))
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return result, ctx.Err()
case <-timer.C:
}
}
return Result{}, errors.New("unreachable")
}
func retryable(status int, err error) bool {
if err != nil {
return true
}
return status == 429 || (status >= 500 && status <= 599)
}
In production, inject a random source so tests can assert exact schedules, and validate that Retry-After cannot exceed the message deadline. The example treats every transport error as retryable; a real client should classify TLS and credential errors separately when its library exposes that detail.
Who owns the template when the retry runs?
Template ownership is the control that is easiest to skip and hardest to reconstruct. The compliance service should own the notice's semantic fields and approve a revision. A communications component can own rendering, localization, and provider formatting. The delivery worker owns attempts and evidence. At enqueue time, copy the immutable revision ID and a hash of the rendered body into the job. A later template edit must create a new revision, never mutate the bytes a pending retry will use.
That split gives reviewers a clean chain: policy decision, rendered artifact, request key, provider response, and final state. It also exposes a real trade-off. Freezing rendered content makes audits easier but increases storage and makes emergency wording changes explicit; resolving the template at send time is more flexible but can silently change a notice between attempts. For compliance mail, I choose the frozen artifact and require a new notice when the legal content changes.
Test the worker against scripted timeouts, 429 responses with and without Retry-After, repeated 503 responses, malformed addresses, and a crash after provider acceptance. Assert that the same idempotency key is reused, that no delay exceeds the deadline, and that the recorded revision matches the payload hash. Run a separate integration test for duplicate suppression; backoff tests alone cannot prove that property.
Monitor attempt age, retry volume by status class, acceptance latency, and the percentage of notices missing a provider ID. A dashboard full of green send counts can still hide a queue that is paging nobody. Alert on the question an operator can act on: “compliance notices are past their delivery deadline,” with links to the evidence record.
Rollback means stopping new retries, preserving the evidence already written, and draining or quarantining queued jobs according to the notice deadline. Do not delete failed payloads to make the graph look healthy. When the queue is safe, fix the classifier or template revision, then re-enqueue with a new attempt record and the original notice ID.
Top comments (0)