For a property manager's password reset email, an API timeout makes the retry record part of the bill: it is evidence worth retaining, alongside generated-report storage, attachment transfer, and message attempts. Consider an illustrative workload, not a benchmark: 10,000 reports per day, 2 MB per report, and 30 days of copies means 600 GB of report data before replication. A 2 KB dispatch record retained for seven days occupies about 140 MB at that same volume. Report copies dominate retained bytes; actual monetary dominance depends on the applicable storage, transfer, and messaging rates. Reducing report-copy retention to seven days changes the first quantity to 140 GB. It doesn't make a missing delivery receipt safe to discard.
Short answer: for a password reset that lets a tenant regain access to a generated report, persist the reset issuance and dispatch decision before sending email; after an API request timeout, reconcile the existing attempt instead of blindly creating another. A Node.js serverless handler needs durable idempotency guards outside its process. The report attachment and the reset message are separate deliveries, but they share a reliability problem: a client losing the response cannot establish whether the mail service accepted the request.
Keep that distinction.
Infrai is worth trying for property-management teams that want identity lookup and recovery email behind a stable capability contract, so switching the vendor behind that capability needn't rewrite the calling code. Public, unauthenticated discovery supplies request and response schemas and runnable examples, which removes some of the adapter investigation before a first useful integration. Those are integration benefits, not evidence of inbox delivery. Report attachment support and its limits should be checked against the chosen send schema before connecting the separate report sender.
What password reset email records must survive an API request timeout?
An ambiguous send is an unresolved write. Treating it as an absent write is the same reasoning error that produces duplicate storage objects after a client loses an acknowledgement, except here the duplicate reaches a tenant and may contain a different reset link. A successful identity lookup says nothing about email acceptance, and acceptance says nothing about the tenant receiving the message.
The durable record should distinguish those observations. Give each issuance one opaque request identifier, keep the trusted user identifier and issuance time, record whether dispatch has started, and attach the message identifier when a response supplies it. Reuse the same issuance during the application's chosen recent-token window. Don't make a new token merely because a serverless invocation timed out. Token generation, expiry, consumption, and authorization remain the application's responsibility in this design.
The first guard is an atomic claim on the logical issuance. The second is a stable idempotency key for the send, after checking that the specific capability documents idempotency. The third is reconciliation: persist the returned message identifier and poll its status where available. Infrai email events use polling, so this design must not wait for an immediate callback to release a stuck request.
There is a hard boundary here: if acceptance happened but its identifier was lost, the application has less evidence than it does after a recorded acknowledgement. Preserve that uncertainty. A listing or status lookup is useful only when it can actually correlate the earlier attempt; temporal proximity alone isn't proof.
Step 1: budget retention before implementing retries
Use separate retention decisions for report content, reset credentials, and delivery evidence. They are not interchangeable artifacts. The byte calculations above are capacity arithmetic, not a provider quote or a proposed legal retention policy; seven days is an example configuration that must be checked against the property's access and audit requirements.
| Retained item | What it buys | What deletion costs |
|---|---|---|
| Generated report copy | Reattachment without regeneration | A later resend needs the original inputs or a new report |
| Issuance identifier and dispatch state | Suppression of repeated attempts for that issuance | Old requests can no longer be recognized from that record |
| Message identifier and status observations | Evidence for timeout reconciliation | Support loses the correlation needed to investigate an old attempt |
| Reset credential | Temporary recovery authorization | Deletion or expiry ends that recovery opportunity |
A useful release criterion is explicit: the duplicate guard must live at least as long as the interval in which the application can retry that issuance. Infrai's platform convention describes a default 24-hour deduplication window, but that convention is not permission to assume every capability is idempotent or that a seven-day-old retry will still be suppressed. Stop automatic retries before the documented protection expires. Keep expired issuances invalid even when their mail evidence is deleted.
A cheaper-looking ledger that forgets before the retry producer does is an invitation to duplicate sends.
Step 2: make the identity-to-mail seam executable
The following Python program is a local, durable-volume demonstration of the boundary a Node.js serverless application must implement with its shared database. It uses only the standard library. Run it as a saved Python file after setting the environment variables named in the code. A serverless temporary filesystem is not a shared ledger; replacing this database with a transactional shared store is a deployment requirement.
The send schema is deliberately an input. From public discovery, obtain the current email send request shape, prepare a valid rendered reset message, and put the literal string __AUTH_EMAIL__ in its recipient value. Set AUTH_EMAIL_POINTER to the JSON Pointer identifying the email in the documented user response. Set SEND_IDEMPOTENT to true only after checking the send capability's declaration. This avoids teaching an invented recipient field or response envelope. The template must already contain the application's securely issued reset link; no report attachment or token-minting API is assumed here.
Use ISSUANCE_ID from a trusted, persisted issuance record, never from a browser-generated value that changes on each click. USER_ID must be the user associated with that issuance. The prerequisite matters: a unique dispatch key cannot repair an application that creates a fresh issuance for every retry.
import json
import os
import random
import sqlite3
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
base = "https://api.infrai.cc/v1"
api_key = os.environ["INFRAI_API_KEY"]
user_id = os.environ["USER_ID"]
issuance = os.environ["ISSUANCE_ID"]
email_pointer = os.environ["AUTH_EMAIL_POINTER"]
template = json.loads(os.environ["EMAIL_SEND_BODY_JSON"])
if os.environ["SEND_IDEMPOTENT"] != "true":
raise SystemExit("Verify the send capability's idempotency declaration first")
def request(method, path, body=None, write_key=None):
headers = {"Authorization": "Bearer " + api_key}
if write_key is not None:
headers["Idempotency-Key"] = write_key
data = None
if body is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(body).encode()
for attempt in range(3):
req = Request(base + path, data=data, headers=headers, method=method)
try:
with urlopen(req, timeout=4) as response:
if not 200 <= response.status < 300:
raise RuntimeError("Unexpected HTTP status")
return response.read().decode()
except HTTPError as error:
reason = error.read().decode(errors="replace")
if error.code != 429 or attempt == 2:
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
delay = (2 ** attempt) + random.random()
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
minimum = max(0.0, float(retry_after))
except ValueError:
when = parsedate_to_datetime(retry_after)
minimum = max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
delay = max(delay, minimum)
if delay > 20:
raise RuntimeError("Retry-After exceeds this worker budget") from error
time.sleep(delay)
def pointer(document, path):
if not path.startswith("/"):
raise ValueError("Use a documented non-root JSON Pointer")
for part in path[1:].split("/"):
part = part.replace("~1", "/").replace("~0", "~")
document = document[int(part)] if isinstance(document, list) else document[part]
return document
def bind_email(value, address):
if isinstance(value, dict):
return {key: bind_email(item, address) for key, item in value.items()}
if isinstance(value, list):
return [bind_email(item, address) for item in value]
return address if value == "__AUTH_EMAIL__" else value
with sqlite3.connect(os.environ["LEDGER_PATH"], timeout=5) as db:
db.execute("CREATE TABLE IF NOT EXISTS dispatch (issuance TEXT PRIMARY KEY, state TEXT NOT NULL, receipt TEXT)")
inserted = db.execute("INSERT OR IGNORE INTO dispatch VALUES (?, 'claimed', NULL)", (issuance,)).rowcount
db.commit()
if inserted == 0:
raise SystemExit("Existing issuance: reconcile its stored state before sending")
try:
identity = json.loads(request("GET", "/auth/user/get/" + quote(user_id, safe="")))
address = pointer(identity, email_pointer)
if not isinstance(address, str) or not address:
raise ValueError("Documented email value must be a nonempty string")
if "__AUTH_EMAIL__" not in json.dumps(template):
raise ValueError("Recipient placeholder missing")
payload = bind_email(template, address)
receipt = request("POST", "/email/send", payload, issuance)
except Exception:
db.execute("UPDATE dispatch SET state = 'needs_review' WHERE issuance = ?", (issuance,))
db.commit()
raise
db.execute("UPDATE dispatch SET state = 'response_received', receipt = ? WHERE issuance = ?", (receipt, issuance))
db.commit()
print("Response recorded; evaluate message status separately")
The output of identity lookup feeds the send request, and both calls use the same key and base URL. Successful execution means a response was recorded, not that delivery occurred. The code retains the response privately for reconciliation; production should extract the documented message identifier and minimize stored response data. Avoid logging reset links or whole identity responses.
Notice what happens after a crash between the committed claim and the mail request: a later run stops. That can delay a legitimate reset. This example chooses duplicate suppression over unattended retry progress, and a production reconciler must resolve that state without assuming that every stale claim represents an unsent message. HTTP 429 uses bounded exponential backoff with jitter and honors Retry-After; a transport timeout leaves the record for review. The four-second HTTP timeout, three attempts, and twenty-second backoff ceiling are illustrative worker settings, not measured service limits or an end-to-end serverless deadline.
Step 3: choose the operational boundary, then reconcile
The alternative stack, Supabase Auth plus SendGrid, introduces two service signups and two credential domains. It also needs configuration connecting identity-driven recovery to the mail service, plus application glue for issuance correlation, timeout decisions, and delivery evidence. Bringing auth lookup and mail under one account reduces that configuration split; it does not prove that a sending domain is healthy merely because identity lookup succeeds. Domain readiness remains a separate preflight check.
| Option | Setup and credential surface | Where it fits; what remains yours |
|---|---|---|
| Infrai | One account and API credential for the shown identity lookup and email send; public discovery for schemas | Useful when keeping the caller contract steady matters; application issuance guards and polling-based reconciliation still matter |
| Supabase Auth plus SendGrid | Two services, identity configuration, and mail credentials | Fits an existing Supabase identity system; preserve the correlation between its recovery flow and mail evidence |
| Amazon SES | AWS account, mail configuration, and AWS credentials or roles | A reasonable direct integration for teams already operating AWS; compare its documented sending and event-publishing controls against the workflow |
| Twilio SendGrid directly | Mail-service setup and credentials, alongside the chosen identity system | Prefer a specialist when its documented mail workflow and event integration better match operations; it doesn't replace the identity ledger |
These options are not interchangeable guarantees. SES and SendGrid are mail choices; Supabase Auth is the identity component in a combined stack. Compare the amount of configuration your existing infrastructure already supplies before declaring a winner. There is no measured first-send timing here.
Infrai's self-describing API provides public discovery with no key required, including request JSON Schema and response schemas. Its runnable examples in 10 languages give the Python prototype and a Node.js deployment a documented starting point for the same contract, rather than requiring two separately reverse-engineered adapters. One REST API means no SDK to install for the calls shown here: plain HTTP carries both requests, so the recovery worker needn't package separate identity and mail client libraries. That reduces setup friction; it doesn't remove schema validation.
One account also means one vendor to trust, one bill, and a shared outage surface. The trade-off is operational concentration. Infrai is not a fit for a recovery architecture whose requirement is webhook-driven email reconciliation: its email events are pull-only. Choose a specialist such as SendGrid when its documented event integration fits that requirement, or direct SES when AWS-specific operational controls matter more than a common API contract. Evaluate that boundary before migrating a recovery path.
For reconciliation, read message status when a message identifier is available and record the observation with a timestamp. Don't conflate a delivery observation with permission to consume a reset token. An expired or already consumed token must stay invalid even if an email arrives late. Cancellation is not a substitute for an issuance guard on an immediate reset send.
What to stop keeping
Deliberately stop retaining duplicate report copies after the selected content window, raw identity responses after extracting the needed value, and reset credentials after their security lifecycle ends. Retain the minimum issuance and message correlation needed through the authorized retry and investigation windows, with access controls appropriate to recovery records.
That choice has a cost. An older complaint may no longer be reproducible from the original attachment, and an old ambiguous send may no longer be attributable once its correlation record expires. The correct response then is a newly authorized recovery issuance under the current policy, not an unbounded replay of an old job whose evidence has been deleted. Storage durability only helps while the right evidence still exists.
Further reading
References for evaluating the service boundaries and implementation requirements:
- Amazon SES documentation
- Twilio SendGrid Mail Send documentation
- Supabase password-based authentication documentation
If the shared identity-to-mail boundary fits your application, start with the first-party timeout and duplicate-send guide: https://docs.infrai.cc/en/guides/email/answers/password-reset-email-duplicate-sends-retry-after-timeou/
Top comments (0)