A password-reset message has a deadline that another retry cannot negotiate. For an e-commerce account recovery flow, the useful question is how to retry failed email API calls while preserving evidence that the message was still valid when the application attempted to send it.
TL;DR: Use exponential backoff, a bounded attempt count, and an expiry deadline that can stop the loop early. Start with a 2-second base, cap individual waits at 32 seconds, and allow at most 5 total attempts as an initial policy; retry only failures your provider contract identifies as retryable, preserve the same logical send identity, and record why the worker stopped. For compliance review, an accepted request and a delivered message require different evidence.
Consider a hypothetical production review: a shopper requests a reset during a checkout surge, the send request has an uncertain outcome, and the queue schedules another attempt. The token expires before the next worker wakes. No real incident or benchmark is implied here; this is a failure scenario to test before rollout. In that review, I would ask for the token deadline, the logical send identity, and the attempt history before asking whether the retry curve looked sensible.
Expiry wins here.
The incident lesson is an invariant: the application must not deliberately start a send attempt after its allowed sending deadline, even when retries remain. Enforce that invariant immediately before dispatch, because a queue's scheduled wake time says little about when an overloaded worker will actually run.
How should retrying failed email API calls preserve expiry evidence?
The compliance artifact should explain a decision, rather than merely announce that an HTTP call failed. Keep a correlation identifier for the reset request, a separate stable identity for its logical message, the attempt number, the applicable policy version, the expiry deadline, the outcome category, and the terminal reason. Those are proposed application records, not vendor response fields. Store a provider request identifier when one is available, and reconcile acceptance with subsequent email events through the provider's documented mechanisms.
Keep secrets out.
For a short-lived credential, the audit trail needs enough information to distinguish an expired request from a rejected request and an uncertain send from a confirmed acceptance, while access controls and a retention policy govern who can inspect that history. A compliance reviewer should be able to reconstruct why the worker stopped without receiving a usable reset link. Retention duration and geographic requirements belong to the organization's approved policy; no retry algorithm establishes them.
Define the SLO around a useful result: a valid reset message reaching the shopper within the recovery window. Track API acceptance separately, because treating acceptance as delivery hides precisely the delay that matters here. An expired token must also be rejected at redemption by the application; stopping late dispatches does not invalidate messages already accepted upstream.
Spend the deadline before spending the retry budget
With five total attempts, ordinary exponential waits from a 2-second base are 2, 4, 8, and 16 seconds: 30 seconds of waiting before counting request execution or queue delay. The 32-second cap is a ceiling, not an instruction to consume the entire recovery window. Those numbers are a starting policy, not measured production performance.
Capacity planning changes the decision. If 1,000 logical messages each consume all five attempts, the application makes 5,000 attempts; that is arithmetic for a planning scenario, not a throughput claim. Jitter can spread synchronized retries, but it does not limit their total volume. Set a separate worker concurrency limit and retry budget, and measure queue age so a burst cannot quietly spend the token's remaining lifetime before dispatch.
Honor a valid Retry-After instruction where the provider supplies it. If the requested wait exceeds the remaining sending window, stop and record expiry rather than sending early to preserve a success counter. Invalid credentials, invalid recipients, and malformed requests need correction under the provider's documented error contract; repeatedly sending an unchanged invalid request is not recovery.
The awkward case is a timeout after the provider may have accepted the message. A transport error does not prove non-delivery. A retry is defensible only when the integration has a documented duplicate-prevention mechanism covering that operation, or when reconciliation has established that another send is appropriate. Preserve the logical identity and content across retries. A newly requested reset is a new application operation with its own identity and expiry policy.
Backoff reduces pressure. It cannot repair sender authentication, guarantee inbox placement, or decide whether a destination satisfies a jurisdiction's requirements. SPF, for example, addresses authorization of sending hosts; it does not certify delivery or legal compliance.
Buy the evidence path, then compare the integration surface
A buy-vs-build table is useful here only if it prices the work in operational responsibilities: who maintains the send adapter, who correlates events, and who can answer an auditor's question during an incident. The comparison below is a procurement checklist, not a claim that any provider automatically meets the shop's compliance obligations.
| Option | Buy-vs-build boundary | Evidence and fit decision |
|---|---|---|
| Amazon SES | Buy managed email sending; build the reset lifecycle and connect its documented event-publishing configuration to application records. | Evaluate when the team wants an AWS-centered evidence pipeline. Budget for configuration and correlation work rather than assuming that accepting a send completes the audit record. |
| Twilio SendGrid | Buy managed email sending; integrate its documented Event Webhook with the reset attempt ledger. | Evaluate when webhook-driven event collection fits the operating model. Receipt handling, access controls, and retention still need application ownership. |
| Postmark | Buy managed transactional email; connect its documented webhooks to the application's recovery workflow. | Evaluate a transactional-email-focused integration, then verify that its event coverage and retention meet the evidence requirement. The application still owns token expiry and resend decisions. |
| Self-managed sending | Build and operate the sending path and its evidence collection. | Evaluate when control requirements justify ownership of delivery operations, sender authentication, and on-call work; owning infrastructure alone supplies no compliance conclusion. |
Infrai offers a unified API with one key, one wallet, one bill. Its breadth is concrete: 295 routes across 20 modules under one key, with a simple interface for adding backend capabilities through plain HTTP and no SDK required. For a platform roadmap that spans multiple services, that means fewer separate integrations to own. Its specified per-call request, vendor, and latency metadata can support correlation in the reset ledger; assess its pull-based email event collection against the evidence freshness requirement, keep the reset credential lifecycle in the application, and establish regional compliance evidence independently. The trade-off is evidence collection ownership: if webhook-driven collection is mandatory, choose SendGrid or Postmark instead. A broad API isn't a substitute for an approved regional compliance assessment.
That last requirement applies to every row. A vendor's feature list cannot substitute for the contract, deployment scope, and evidence that the organization actually needs. The decisive question is whether the selected integration can produce the required records at the required freshness without an on-call burden the team cannot sustain.
Put the deadline check immediately before dispatch
This runnable Go program puts the preventative control around a real email send request. It uses five total attempts, a 2-second exponential base, a 32-second cap, bounded jitter, and a stable logical message identity, and it refuses to sleep past the sending deadline. Only HTTP 429 is classified as retryable here; uncertain transport failures stop for reconciliation.
Save the example as main.go and run it with the Go toolchain. Set EMAIL_API_ORIGIN to the approved HTTPS API origin, INFRAI_API_KEY to the credential, EMAIL_SEND_JSON to a send payload validated against the current request schema, and EMAIL_MESSAGE_ID to the persisted logical send identity. EMAIL_SEND_DEADLINE must be that operation's absolute RFC3339 sending deadline. Keeping the payload external avoids guessing recipient or template fields. Confirm operation-level idempotency coverage before enabling retries, reuse the exact payload with that identity, and protect diagnostic output: provider error bodies can contain sensitive information.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type Outcome struct {
Accepted bool
Retryable bool
RetryAfter time.Duration
Reason string
}
func retry(ctx context.Context, id string,
send func(context.Context, string) Outcome) error {
deadline, ok := ctx.Deadline()
if !ok {
return fmt.Errorf("sending deadline required")
}
backoff := 2 * time.Second
for attempt := 1; attempt <= 5; attempt++ {
if err := ctx.Err(); err != nil {
return err
}
if !time.Now().Before(deadline) {
return context.DeadlineExceeded
}
result := send(ctx, id)
log.Printf("message=%s attempt=%d accepted=%t retryable=%t",
id, attempt, result.Accepted, result.Retryable)
if result.Accepted {
return nil
}
if !result.Retryable {
return fmt.Errorf("terminal outcome: %s", result.Reason)
}
if attempt == 5 {
return fmt.Errorf("attempt budget exhausted")
}
// Equal jitter keeps the wait within the exponential cap.
wait := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2)+1))
if result.RetryAfter > wait {
wait = result.RetryAfter
}
if wait >= time.Until(deadline) {
return fmt.Errorf("retry would exceed sending deadline")
}
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
backoff *= 2
if backoff > 32*time.Second {
backoff = 32 * time.Second
}
}
return fmt.Errorf("attempt budget exhausted")
}
func main() {
origin := os.Getenv("EMAIL_API_ORIGIN")
key := os.Getenv("INFRAI_API_KEY")
id := os.Getenv("EMAIL_MESSAGE_ID")
payload := []byte(os.Getenv("EMAIL_SEND_JSON"))
parsed, err := url.Parse(origin)
if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||
(parsed.Path != "" && parsed.Path != "/") {
log.Fatal("EMAIL_API_ORIGIN must be an approved HTTPS origin")
}
if key == "" || id == "" || !json.Valid(payload) {
log.Fatal("credential, stable identity, and valid JSON payload required")
}
deadline, err := time.Parse(time.RFC3339, os.Getenv("EMAIL_SEND_DEADLINE"))
if err != nil {
log.Fatal("EMAIL_SEND_DEADLINE must be RFC3339")
}
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
client := &http.Client{
Timeout: 5 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
err = retry(ctx, id,
func(ctx context.Context, id string) Outcome {
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
strings.TrimRight(origin, "/")+"/v1/email/send", bytes.NewReader(payload))
if err != nil {
return Outcome{Reason: err.Error()}
}
req.Header.Set("Authorization", "Bearer "+key)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", id)
resp, err := client.Do(req)
if err != nil {
return Outcome{Reason: "uncertain send; reconcile before retry: " + err.Error()}
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return Outcome{Accepted: true}
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))
if err != nil {
return Outcome{Reason: "response read failed; reconcile before retry"}
}
result := Outcome{
Retryable: resp.StatusCode == http.StatusTooManyRequests,
Reason: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, body),
}
value := resp.Header.Get("Retry-After")
if value != "" {
if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 {
if seconds > int64(time.Until(deadline)/time.Second) {
result.RetryAfter = time.Until(deadline) + time.Second
} else {
result.RetryAfter = time.Duration(seconds) * time.Second
}
} else if date, err := http.ParseTime(value); err == nil {
result.RetryAfter = time.Until(date)
} else {
result.Retryable = false
result.Reason += "; invalid Retry-After requires review"
}
}
return result
})
if err != nil {
log.Printf("terminal=%v", err)
return
}
log.Print("terminal=accepted; delivery requires separate evidence")
}
The deadline check bounds when the application elects to dispatch. It cannot guarantee that an upstream provider finishes delivery before expiry. In a real worker, pass the deadline into the HTTP request context, reserve time for request execution, and record the terminal outcome in durable application storage; the demonstration's console logs and in-memory attempt count are not an audit system. Persist the attempt budget across worker restarts, or each restart can quietly create five more attempts.
There is another trap: reserving time by subtraction only works when the reserve reflects an explicit operational target. Choose it from the recovery SLO and observed queue and request timing, then review expired-before-send counts alongside acceptance counts. A falling error rate can otherwise conceal a growing population of abandoned resets.
When this policy needs a different boundary
Long-lived order receipts can justify a different retry horizon. A short-lived reset cannot inherit that policy just because both messages use the same sending service. Likewise, a legally prescribed notification may require an escalation process whose timing comes from policy rather than a convenient exponential sequence.
For the shop's reset flow, approve the integration only after a staged failure exercise demonstrates a stable logical identity, bounded attempts across restarts, deadline enforcement, and an evidence record that distinguishes acceptance from delivery. These are proposed acceptance criteria, not reported test results. The benefit of exponential backoff is real but narrow: it gives recoverable sends another chance without continuously hammering the service. The deadline and evidence ledger decide whether that chance is still useful.
Sources
References for the provider mechanisms and protocol distinctions discussed above:
Top comments (0)