DEV Community

KillianBerg5391
KillianBerg5391

Posted on

Password Reset Email API: Why I Own FastAPI 429 Retry and Resend Cooldowns

For a healthtech application emailing generated report attachments, I would give password reset messages their own admission policy and keep 429 retries in the application. The deciding constraint is integration effort: one delivery adapter can serve both workflows, but a report resend must not consume the same per-user cooldown as an account recovery request.

TL;DR: use direct email sends for reset links, enforce an application-side resend cooldown, and honor Retry-After with bounded backoff. Keep the reset token and logical send identity stable across retries. Treat report generation, attachment preparation, and email delivery as separate steps so throttling the last step doesn't rerun the expensive first one.

This is a design experiment, not a production benchmark. Its evaluation constraint is concrete: a synthetic report send receiving a 429 must leave the generated artifact intact, schedule a later delivery attempt, and avoid generating another reset token. The same checks belong in a Node.js worker; the example here uses Python for a FastAPI-oriented workflow.

What should a report retry be allowed to repeat?

The attractive notebook version generates a report, prepares an attachment, and sends it in one function. Its retry boundary is too wide. If the send receives a rate-limit response, repeating that function can regenerate the report even though the delivery request was the only step that needed another attempt. For an AI-generated report, that couples email congestion to model calls and makes prompt-cost accounting harder to interpret. It also creates an uncomfortable question: which generated version was actually intended for the recipient? Consider the synthetic fixture: report version demo-report-v3 is already prepared, delivery is throttled, and the worker restarts before its next attempt. Recovery should reload that version and its delivery intent. Reentering generation instead would change the object being delivered and mix generation work into an email retry. The failure boundary is the delivery operation, so that is where I would place the retry boundary.

Freeze the artifact.

I would persist the report version before admitting an email job, then associate one logical delivery identifier with that artifact and recipient. This is a proposed application contract, not a provider request schema. A reset email gets a different job type and its own token lifecycle. Its transport retries reuse the same reset message; an explicit user request for another link goes through the resend policy first.

That distinction is the experiment's useful result: retry ownership belongs beside the persisted delivery intent. Putting it around the whole AI workflow makes the simplest code harder to reason about once it leaves a notebook. The extra stored state is a real integration cost, but it buys a boundary an eval harness can inspect without calling a model or sending a clinical document.

For synthetic data, use a fixture such as report version demo-report-v3, recipient patient@example.test, and separate logical identifiers for report delivery and password recovery. Never make the presence of an attachment the signal that a message is a reset request. Classify the job explicitly.

How should a password reset email API handle 429 and Retry-After?

A resend cooldown decides whether the application accepts another request from a user.

Retry-After tells a worker when an already accepted request may be attempted again after throttling. Repeated clicks should meet the first control before they create queued work; an accepted job encountering HTTP 429 should meet the second. Neither control replaces the other.

Consider a proposed 60-second resend cooldown and four total send attempts. These are fixture values, not provider limits or clinical recommendations. Two clicks within that cooldown should produce one admitted reset job. A report delivery waiting on its retry timer should remain associated with its existing artifact. Across multiple workers, admission needs an atomic shared-state decision; a timestamp stored only inside one Python process cannot enforce a service-wide cooldown.

The timer is only part of the contract. A write retry needs a stable idempotency key supported by the selected send operation, and the application needs a durable record of the logical message. Don't generate a fresh key for each attempt. Also, don't assume that a key accepted by one provider deduplicates a send through another provider. Switching delivery services after an ambiguous response needs reconciliation of the original attempt first.

For an expired reset link, abandon the delivery intent according to the application's token policy. A retry budget is permission to try again while the message remains useful; it isn't permission to deliver obsolete recovery instructions.

One small Python experiment before wiring the sender

Start with scheduling logic you can evaluate offline, then attach a narrowly scoped sender. Retry-After can express seconds or an HTTP date. The calculation treats a valid server delay as a lower bound, adds exponential backoff with jitter, and stops when the fixture's attempt budget is exhausted.

The standard-library example below sends a preconstructed message. Set EMAIL_API_ORIGIN to the service's HTTPS API origin, INFRAI_API_KEY to your credential, EMAIL_PAYLOAD_FILE to a JSON request validated against the public email-send discovery schema, and EMAIL_SEND_ID to a persisted logical delivery identifier. Prepare the payload once, using synthetic recipients and attachments for the experiment. The schema remains the authority for fields; this example doesn't invent an attachment encoding or reset-token API.

from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import json
import os
import random
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def retry_delay(retry_after, attempt, now):
    if attempt < 0:
        raise ValueError("attempt must be nonnegative")
    if attempt >= 3:
        raise RuntimeError("four total attempts exhausted")

    minimum = 0.0
    if retry_after is not None:
        value = retry_after.strip()
        if value.isascii() and value.isdigit():
            minimum = float(value)
        else:
            try:
                deadline = parsedate_to_datetime(value)
                if deadline.tzinfo is None:
                    deadline = deadline.replace(tzinfo=timezone.utc)
                minimum = max(0.0, (deadline - now).total_seconds())
            except (TypeError, ValueError, OverflowError):
                minimum = 0.0

    backoff = min(30.0, 2.0 ** attempt)
    return max(minimum, backoff) + random.uniform(0.0, 1.0)


with open(os.environ["EMAIL_PAYLOAD_FILE"], encoding="utf-8") as source:
    body = json.dumps(json.load(source)).encode("utf-8")
origin = os.environ["EMAIL_API_ORIGIN"].rstrip("/")
if not origin.startswith("https://"):
    raise ValueError("an HTTPS API origin is required")
headers = {
    "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
    "Content-Type": "application/json",
    "Idempotency-Key": os.environ["EMAIL_SEND_ID"],
}
for attempt in range(4):
    request = Request(origin + "/v1/email/send", data=body,
                      headers=headers, method="POST")
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"unexpected status {response.status}")
            print(response.read().decode("utf-8"))
        break
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 3:
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        delay = retry_delay(error.headers.get("Retry-After"), attempt,
                            datetime.now(timezone.utc))
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

The fourth failed attempt terminates this example's retry policy. Its 30s network timeout is an example setting, not a delivery-latency promise.

This standalone script sleeps; don't run it inside a FastAPI request handler. A durable worker would persist the calculated next-attempt time rather than hold a web request open. If a valid Retry-After extends beyond the message's usefulness, stop or expire the job; silently shortening that delay defeats the server's instruction. Malformed headers use the local backoff policy here. Transport errors propagate instead of triggering an unexamined retry. Before using the loop in production, add the application's expiry check and durable scheduling around the same logical send identity.

Keep the adapter responsible for inspecting the actual HTTP status and surfacing the response's error details. A 429 enters this scheduling policy. Other responses require their own classification; this function doesn't declare every failure retryable. Network ambiguity is a separate test case because a missing response doesn't establish whether the send was accepted.

This is where notebook-to-prod work gets interesting: the timer calculation is small, while durable admission, message identity, and recovery after a worker restart determine whether the design holds together.

Which delivery option reduces the integration work?

Compare Resend, Postmark, and Amazon SES against the same report-and-reset fixture. Their send-email documentation provides concrete places to inspect the delivery contract. I would use the following as selection criteria, rather than assign a universal winner without testing the application's attachment and recovery paths.

Option Reason to put it on the shortlist Boundary to evaluate
Resend A direct email API candidate for an application-owned send adapter Check the documented attachment representation, rate-limit handling, and idempotency contract against the fixture
Postmark A transactional email candidate for report and recovery messages Check how message construction and delivery status fit the existing worker and support workflow
Amazon SES An email API candidate when the application already uses AWS Account for AWS request authentication, attachment message construction, and operating the surrounding application policy

These are different starting points. An existing AWS integration can change the effort calculation for SES; an application starting with an isolated transactional sender should compare Resend and Postmark on the actual adapter work. None of those choices removes the need to define what a second reset click means. Check current vendor documentation for supported payloads and limits before implementing an attachment encoder.

Infrai offers one REST API with no SDK required and one key, one wallet, one bill for report generation and email delivery. Its unified API lets the application switch providers behind a capability without changing application code. Shared credentials and a single invoice reduce credential wiring and invoice reconciliation across those two steps. The platform spans 295 routes across 20 modules under one key; an AI report workflow can use that breadth without maintaining a separate credential for every backend capability. Its public, self-describing discovery surface exposes request and response JSON Schemas without requiring a key, and documented capabilities include runnable examples in 10 languages, including Python. That gives a notebook-to-prod workflow a concrete integration benefit: inspect the send contract and validate a synthetic payload before connecting credentials or adapting the worker. Keep that integration convenience separate from decisions about access isolation for clinical workloads. Its email integration uses HTTP directly, delivery events are retrieved by polling, and the application owns reset tokens and codes. The trade-off is limited real-time orchestration: this polling model is not suitable for a requirement that delivery events immediately trigger fallback. For that requirement, compare the event contracts of the dedicated email services before choosing the sender.

Don't interpret a common contract as proof of equivalent delivery behavior.

In this experiment, I would count the code and configuration changed during a provider substitution, then rerun the same synthetic attachment and recovery cases. A provider that needs fewer changes but cannot meet the required event timing is still the wrong fit. Likewise, a familiar API is not evidence of suitability for clinical data handling; that requires a separate review of the intended deployment and agreements.

What to measure before copying this choice

Make the acceptance criteria observable. With the proposed 60-second cooldown, two clicks inside the window should create one admitted reset job. A simulated 429 with Retry-After should move that job's next eligible attempt forward without changing its token or logical delivery identifier. Restart the worker while it waits, then confirm that the same intent survives. For the report fixture, count generation calls as well as send attempts: an email retry should add zero generation calls.

That last count matters.

An eval-driven approach keeps prompt-cost accounting attached to report generation, while delivery retries have their own attempt counter. Test both forms of Retry-After, a malformed header, the fourth throttled attempt, and a deadline beyond token expiry. Also test an ambiguous transport result before enabling any provider substitution. These are proposed acceptance cases, not claimed benchmark results.

My choice would depend on those results: use an application-owned retry and cooldown policy when it preserves the report artifact and reset intent with acceptable integration work. Choose the sender by attachment handling, delivery-event timing, and the amount of adapter work the fixture exposes. Only then move the notebook experiment into a durable worker.

References

Top comments (0)