密碼重設電郵 API 逾時時的模板治理與重複發送防範
Template Governance for Password Reset Email API Timeout and Retry Prevention
文章提出,密碼重設電郵 API 請求逾時時,應由應用程式保留寄送意圖和已選模板版本,不能因逾時或模板更新而授權重新寄送。文中的 SQLite 本機測試展示,同一用戶的待處理記錄會保留原有的發行識別和模板版本;正式環境則需要共享持久儲存、原子預留及明確的近期 token 發行政策。若已記錄訊息識別碼,可在可行情況下查詢狀態;逾時、指數退避和 Retry-After 只管理請求節奏,不能單獨授權重發。
A template release must not change the meaning of an email already waiting for a send receipt. That constraint matters in a developer tool that sends a generated report as an email attachment, and it becomes sharper when the same application handles password recovery. A password reset email API request timeout leaves an uncertain send outcome. Deploying new copy during that uncertainty must not authorize another token or another message.
TL;DR: let the application own the send intention, even if another team owns the template. Store the selected template revision with a durable reset request record, gate duplicate sends by user and recent token issuance, and reconcile message status where possible. Short API timeouts and exponential backoff help manage attempts; they don't establish permission to resend. For generated reports, bind the report artifact and attachment reference to the same intention before dispatch.
The proposed experiment has a strict acceptance condition: a replay after a template release must preserve the original content identity. This is a release-governance decision, with duplicate prevention as its observable consequence. It is not a delivery benchmark.
Freeze the intention.
How should template ownership govern a password reset email API request timeout?
It shouldn't. Consider two illustrative template revisions, reset-v3 and reset-v4. A request selects the first revision and reaches the sender, but the caller times out before recording a receipt. Then a deployment activates the second revision. An implementation that starts again from the current template can accidentally treat the replay as new work. If rendering also mints a token, presentation changes have acquired authority over account recovery.
The simple approach puts everything in one function: choose the latest template, issue a token, send, and repeat on an exception. Its attraction is understandable in a notebook. There is little state to inspect. The problem appears at the release boundary, because an exception says what the caller observed, not what the sender accepted. The chosen design separates template selection from permission to dispatch. An existing intention keeps its revision; a genuinely new intention may select the new revision after the application's issuance policy allows it.
That distinction also gives report delivery a concrete contract. A message for report-42 should retain its attachment reference and selected copy across a retry. Regenerating the report because a send response was lost can change the artifact the recipient receives. Treat report generation, template selection, and delivery as separate decisions with recorded identities. The email template owner may change presentation, but must not silently replace the artifact on pending work.
These are proposed design rules, not claims about an incident or measured results.
A release collision captured in one small fixture
The focused example below models the ownership rule locally. Its SQLite constraint allows only one active reset record per user, so presenting a different issuance identifier cannot bypass the guard. The pending row owns its token issuance and template revision. A template deployment has no permission to replace either value.
All identifiers are fixture data. No token is generated and no email is sent.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""
CREATE TABLE active_reset (
user_id TEXT PRIMARY KEY,
issuance_id TEXT NOT NULL,
template_revision TEXT NOT NULL,
send_state TEXT NOT NULL
)
""")
def reserve(user_id, issuance_id, template_revision):
with db:
result = db.execute(
"INSERT INTO active_reset VALUES (?, ?, ?, ?) "
"ON CONFLICT(user_id) DO NOTHING",
(user_id, issuance_id, template_revision, "reserved"),
)
return result.rowcount == 1
assert reserve("developer-42", "issuance-7", "reset-v3")
with db:
db.execute(
"UPDATE active_reset SET send_state = ? WHERE user_id = ?",
("unknown", "developer-42"),
)
assert not reserve("developer-42", "issuance-7", "reset-v4")
assert not reserve("developer-42", "issuance-8", "reset-v4")
assert db.execute("SELECT * FROM active_reset").fetchall() == [
("developer-42", "issuance-7", "reset-v3", "unknown")
]
db.close()
The assertions specify the expected result: both replays fail to acquire a new reservation, and the original revision survives. The unknown state stays visible. That matters more than making the retry function return success.
The notebook-to-prod step is substantial. An in-memory database cannot coordinate serverless invocations or retain the record after the process exits. Production needs shared durable storage, an atomic reservation, and an explicit policy for recent token issuance. This fixture deliberately keeps a user's record active indefinitely. A real lifecycle must decide when a new recovery intention is allowed, without treating an ambiguous send as a reason to discard the old record. Otherwise the guard either blocks future recovery forever or admits a duplicate as soon as a worker expires.
There is also a worker boundary. A reservation proves ownership, not that transmission happened. A worker can stop before dispatch or after acceptance but before saving a receipt. Preserve that distinction in the record. If a message identifier was captured, retrieve its status where possible; if none was captured, leave the outcome unresolved until the recovery policy has enough evidence to act. A fresh template revision supplies no such evidence.
Choose the sender after assigning release authority
Application-owned templates fit a report pipeline whose artifact and email copy should move through the same review. Provider-owned templates are worth evaluating when presentation needs a separate release process. The trade-off is another version boundary: the application must still identify which revision belongs to pending work. Before adopting either model, require a demonstration that changing the current template does not alter an already recorded intention. That is an acceptance test for the selected integration, not a guarantee shared by every sender.
Infrai combines a plain REST API with unified auth and billing: an HTTP client can call it without installing an SDK or maintaining a client-library version. Unified authentication and a single bill can reduce credential handoffs and invoice reconciliation between report generation and delivery. Public, self-describing discovery provides request and response schemas that can help review the boundary between the renderer and the sender. Email events are retrieved by polling, so plan reconciliation around pulled status rather than immediate delivery callbacks; keep token issuance and duplicate-send authorization in the application.
Compare that fit with the actual alternatives. The following comparison separates what is established from what the team still needs to verify; it does not assert interchangeable attachment, template, or retry guarantees.
| Option | Relevant role in this decision | Release question to settle |
|---|---|---|
| Amazon SES | An email service candidate for report delivery and password recovery. | Validate the chosen email integration against its official documentation, including how application-rendered content remains fixed across attempts. |
| SendGrid | An email candidate for evaluating application ownership against provider template ownership. | Verify template revision behavior, attachment handling, and retry semantics before assigning presentation releases to a separate owner. |
| Twilio SMS | A separate recovery-channel option with character limits and segmentation rules. It does not fulfill the job of sending a generated report as an email attachment. | Review recovery copy as a distinct channel artifact; an email template cannot be assumed to have the same content constraints. |
The first two belong on an email shortlist. The third tests a different product decision: whether a recovery flow should offer another channel. It should not receive credit for satisfying the attachment requirement. Conversely, a convenient email adapter should not receive credit for governing token issuance. Those responsibilities belong in the application design regardless of which candidate is selected.
No price ranking is needed to resolve this ownership question.
Measure release behavior before copying the choice
An eval-driven review should cross the template-release boundary deliberately. Use three fixtures: an overlapping request for the same user, a replay after the active template changes, and recovery after a message identifier has been stored. Interrupt the flow before the response is recorded. Check which component can authorize another dispatch, which revision remains attached to the intention, and whether reconciliation updates the existing record instead of creating another one. These are proposed tests; there are no measured delivery rates here.
For report attachments, add an artifact-identity assertion. The pending message must keep its recorded report and attachment reference. For password recovery, assert that recent token issuance gates duplicate sends even when two callers propose different request identifiers. Count unauthorized reservations separately from actual duplicate messages: zero new reservations in a local fixture is useful evidence about the guard, but it does not prove end-to-end delivery behavior.
Then measure operational recovery: time spent unresolved, availability of a stored message identifier, and the number of attempts needed to reconcile a record. Choose the API timeout inside the worker's execution budget and space recovery attempts with exponential backoff. Honor Retry-After for HTTP 429 responses where supplied. Backoff controls pressure; a durable intention and the sender's documented retry semantics control whether another write is permitted. Do not equate a timed-out API request with a failed send.
For a captured receipt, this read-only Python probe exercises the status-retrieval boundary. Configure EMAIL_API_ORIGIN with the service's HTTPS API origin, INFRAI_API_KEY with its credential, and EMAIL_MESSAGE_ID with the stored identifier. The example permits 3 attempts and waits up to 5 seconds per request; these are fixture settings to evaluate, not measured service limits. It prints the returned record without assuming an undocumented status field. Only use a trusted API origin for the bearer credential.
import json
import os
import time
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote, urlsplit
from urllib.request import Request, urlopen
origin = os.environ["EMAIL_API_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if parts.scheme != "https" or not parts.hostname:
raise ValueError("A trusted HTTPS API origin is required")
if parts.path or parts.query or parts.fragment or parts.username:
raise ValueError("Configure an origin without a path or credentials")
message_id = quote(os.environ["EMAIL_MESSAGE_ID"], safe="")
request = Request(
origin + "/v1/email/get/{id}".format(id=message_id),
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
method="GET",
)
for attempt in range(3):
try:
with urlopen(request, timeout=5) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
print(json.dumps(json.load(response), indent=2))
break
except HTTPError as error:
reason = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 2:
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
delay = 2 ** attempt
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
minimum = float(retry_after)
except ValueError:
minimum = parsedate_to_datetime(retry_after).timestamp() - time.time()
delay = max(delay, minimum)
time.sleep(delay)
A missing receipt remains a separate case. This probe cannot reconstruct an identifier that the application never recorded, and it never authorizes another send.
Keep the AI boundary narrow, too. A prompt-cost aware report pipeline reuses the generated artifact while delivery is uncertain, instead of asking a model to recreate the attachment or its copy on every transport retry. The token issuance decision should remain deterministic. Model output may contribute to report content, but it should not decide that an unresolved password reset deserves a new token.
The adoption criterion is practical: the content owner can release a new template without taking ownership of pending recovery decisions. If that property fails, fix the authority boundary before tuning retry delays.
Sources
References for the email-service evaluation and the separate SMS content boundary follow. The code above is a local design fixture, not a provider API example.
- Amazon SES official documentation: https://docs.aws.amazon.com/ses/latest/dg/Welcome.html
- SendGrid official documentation, for validating the candidate integration: https://www.twilio.com/docs/sendgrid
- Twilio SMS character limits and segmentation: https://www.twilio.com/docs/glossary/what-sms-character-limit
來源:DEV Community · dev.to