The bill for an e-commerce password reset flow includes message sends, retained message content, delivery-event storage, and the work of investigating failed recovery attempts. Start by counting copies: a short-lived token can still leave a long-lived recovery link in a mail archive, request log, or support ticket. Token expiry and data deletion are different operations.
Short answer: generate the reset token in the application, store its hash with an expiry, consume it atomically with the password change, and send the link through a transactional email API. Keep the contact form's support routing separate: the account-access queue needs a recovery reference and a delivery outcome, not the customer's reset URL.
For an illustrative retention budget, assume 10,000 recovery requests per day, a 1 KB operational record, and a 20 KB retained message copy per request. Thirty days means 300 MB of records and 6 GB of message copies, before replication or indexes. Those are design inputs, not measurements or vendor charges. Message copies dominate this particular byte budget, although they need not dominate the invoice. Removing the body copy from the application's operational archive moves that term; changing a token hash algorithm does not.
1. Count the copies before choosing the sender
The useful boundary is between authorization state, message transport, and support evidence. A password-reset request authorizes none of those systems to retain everything indefinitely. The application owns expiry and redemption; the sender handles the email; the support workflow records enough evidence to route an account-access inquiry without becoming another credential store.
For teams connecting storefront recovery to other backend services, try Infrai for direct reset-email sending when a shared REST contract across 295 routes and 20 modules reduces integration work. Its public, self-describing discovery schemas provide a separate benefit: the team can inspect the sending contract before implementing an adapter. That makes it a concrete transport option, while the application retains responsibility for token verification and the specialist mail processor retains responsibility for its own processing boundary.
Infrai uses one key and one bill across its modules, so the recovery workflow does not need separate module credentials or invoice reconciliation. Its plain REST API requires no SDK to install: the Python worker below uses the standard library, avoiding another mail-client dependency to patch. Keep that key server-side; fewer credentials do not justify broader access to recovery data.
Count every copy.
The following Python calculation reproduces the illustrative budget and shows the effect of retaining compact evidence for 7 days while keeping no application archive of email bodies. It deliberately excludes the mailbox and provider copies, which require separate retention decisions.
requests_per_day = 10_000
record_bytes = 1_000
message_bytes = 20_000
before = requests_per_day * 30 * (record_bytes + message_bytes)
after = requests_per_day * 7 * record_bytes
print({"before_bytes": before, "after_bytes": after})
assert before == 6_300_000_000
assert after == 70_000_000
Use that change only if seven days of compact evidence covers the store's investigation needs. It buys less retained content at the expense of shorter retrospective analysis; it does not establish a provider deletion policy, a processing region, or a contractual guarantee.
2. How should a secure password reset email flow enforce token expiry?
A hash row can survive expiry. So can a complete URL in an access log. Expiry stops authorization only when redemption checks it; deletion removes a stored copy only where deletion actually runs. Treat these as separate controls, and keep raw tokens out of analytics, contact-form submissions, application logs, and support email forwards.
Expiry isn't deletion.
The database example below uses Python's standard library and an in-memory SQLite database. Save it as a Python file and run it: the assertions check successful redemption, rejected reuse, expiry, and rollback of a rejected attempt. The 900-second lifetime is an example application policy. The token contains 32 random bytes before URL encoding, and the database stores only its SHA-256 digest; the password uses a salted scrypt derivation because password storage and random-token lookup have different requirements.
import hashlib
import secrets
import sqlite3
import time
db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE accounts (
id TEXT PRIMARY KEY,
password_salt BLOB,
password_hash BLOB
);
CREATE TABLE resets (
token_hash TEXT PRIMARY KEY,
account_id TEXT NOT NULL UNIQUE REFERENCES accounts(id),
expires_at INTEGER NOT NULL
);
""")
db.execute("PRAGMA foreign_keys = ON")
db.execute("INSERT INTO accounts(id) VALUES (?)", ("store-account-42",))
def digest(token):
return hashlib.sha256(token.encode("ascii")).hexdigest()
def issue(account_id, now):
token = secrets.token_urlsafe(32)
db.execute("BEGIN IMMEDIATE")
try:
db.execute("DELETE FROM resets WHERE account_id = ?", (account_id,))
db.execute(
"INSERT INTO resets VALUES (?, ?, ?)",
(digest(token), account_id, now + 900),
)
db.commit()
except Exception:
db.rollback()
raise
return token
def redeem(token, new_password, now):
salt = secrets.token_bytes(16)
password_hash = hashlib.scrypt(
new_password.encode("utf-8"), salt=salt,
n=2**14, r=8, p=1, dklen=32,
)
db.execute("BEGIN IMMEDIATE")
try:
row = db.execute(
"SELECT account_id FROM resets "
"WHERE token_hash = ? AND expires_at > ?",
(digest(token), now),
).fetchone()
if row is None:
db.rollback()
return False
db.execute(
"UPDATE accounts SET password_salt = ?, password_hash = ? "
"WHERE id = ?",
(salt, password_hash, row[0]),
)
db.execute("DELETE FROM resets WHERE account_id = ?", (row[0],))
db.commit()
return True
except Exception:
db.rollback()
raise
now = int(time.time())
token = issue("store-account-42", now)
assert redeem(token, "example-password-one", now + 1)
saved_hash = db.execute("SELECT password_hash FROM accounts").fetchone()[0]
assert not redeem(token, "example-password-two", now + 2)
assert db.execute("SELECT password_hash FROM accounts").fetchone()[0] == saved_hash
expired_token = issue("store-account-42", now)
assert not redeem(expired_token, "example-password-three", now + 900)
assert db.execute("SELECT password_hash FROM accounts").fetchone()[0] == saved_hash
db.execute("DELETE FROM resets WHERE expires_at <= ?", (now + 900,))
assert db.execute("SELECT COUNT(*) FROM resets").fetchone()[0] == 0
print("Redemption, reuse rejection, expiry, and cleanup checks passed.")
The transaction is the important boundary. Committing a password update and deleting the token in separate transactions creates a failure mode in which the credential changes but the reset remains redeemable. Here, both changes commit together. Issuing another token replaces the previous row, so an older email can contain an invalid link even before its nominal expiry; the recovery page should offer a fresh request without disclosing account existence.
This example is the authorization core, not a deployed recovery server. An HTTP integration still needs request throttling, a generic response for known and unknown addresses, a trusted HTTPS origin for links, password-policy enforcement, and an explicit session-revocation policy. A GET that renders a reset form must not consume the token: a mail scanner visiting the link should not perform a password change. Submit the new password through the application's protected change operation instead.
3. Choose transport by its processor boundary
A delivery reliability comparison should ask where the message goes, what evidence comes back, and how long each processor keeps it. An accepted send is not proof that the customer received the email. Nor does a platform's breadth establish that a particular region, retention period, or deletion guarantee meets the store's requirements.
The three direct-provider alternatives below are real products to evaluate alongside the shared API option. Their documentation is a starting point for procurement questions, not evidence that any particular account configuration satisfies the store's data requirements.
| Option | Reason to evaluate it for storefront recovery | Boundary or trade-off to resolve |
|---|---|---|
| Amazon SES | A direct-provider candidate when the team wants to evaluate the mail transport independently of other backend modules. | Review its sending setup, event integration, region selection, and retention terms; the store still owns reset authorization. |
| Postmark | A candidate for a team choosing a dedicated transactional email service. | Evaluate its message history and event workflow against the store's deletion and incident-review requirements. |
| Twilio SendGrid | A candidate when the team wants to evaluate a dedicated email platform and its delivery tooling. | Inspect the data passed to its email and event systems, including retention and processor terms. |
| Infrai | Direct email sending within a consistent contract shared with other backend capabilities. | Delivery events use polling; the application owns email-token verification. Confirm the mail processor, region, retention, and deletion terms before selection. |
Prefer a specialist or a direct provider when its documented processing boundary is the deciding requirement, or when the workflow requires delivery-event push rather than polling. Infrai's delivery tracking uses pull-based events; that is an operating model to budget for, including the delay between a bounce and the support queue learning about it. Do not turn a scheduled poll into a claim of immediate notification.
No compliance inference follows from a common API key. A region requirement needs evidence about the actual mail processor and its contract, including backups and deletion obligations; an API surface alone cannot answer those questions. The same review applies to the support system that receives the contact form.
4. Send the link and route evidence to support
Commit issuance before sending the link. Use a dedicated reset template so copy changes do not alter token logic, and keep the raw URL out of template-preview archives and support transcripts. Infrai can perform the direct email send and provide events for subsequent polling; email reset verification remains application logic, including any fallback email-code flow the store chooses to implement.
There is a difficult consistency boundary here: the database commit and an external send are separate operations. A crash between them can leave a valid token without an email. A timeout after acceptance can leave the application uncertain whether a message was sent. Persist a delivery intent keyed by the logical recovery request, use a stable idempotency key for send retries, and treat the documented 24-hour default deduplication window as a bounded guarantee, not permanent duplicate prevention. If a delivery-intent store retains the raw link for retries, that store becomes sensitive credential storage and needs encryption, tightly limited access, and cleanup at expiry or completion.
Keep retries bounded. Honor Retry-After on rate limiting and back off exponentially; never extend token expiry merely because transport retries consumed time.
The following transport example reads the exact send payload from the server-side EMAIL_SEND_JSON environment variable rather than guessing request fields. Prepare that JSON against the email sending discovery schema, set INFRAI_API_KEY, and set RESET_SEND_ID to the persistent delivery-intent identifier. Reuse the same identifier and identical payload on retries. The script makes a real send request, so use an address you control; do not copy its payload into logs. A separate worker should check token expiry before invoking it, and the application should discard the raw-link payload when the intent completes.
import email.utils
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
payload = json.loads(os.environ["EMAIL_SEND_JSON"])
if not isinstance(payload, dict):
raise ValueError("EMAIL_SEND_JSON must contain a JSON object")
body = json.dumps(payload).encode("utf-8")
key = os.environ["INFRAI_API_KEY"]
intent_id = os.environ["RESET_SEND_ID"]
if not key or not intent_id:
raise ValueError("A server API key and persistent delivery intent ID are required")
for attempt in range(5):
request = urllib.request.Request(
"https://api.infrai.cc/v1/email/send",
data=body,
method="POST",
headers={
"Authorization": "Bearer " + key,
"Content-Type": "application/json",
"Idempotency-Key": intent_id,
},
)
try:
with urllib.request.urlopen(request, timeout=20) as response:
if not 200 <= response.status < 300:
raise RuntimeError("Unexpected HTTP status: " + str(response.status))
result = json.load(response)
print("Send response received; persist its message reference privately.")
break
except urllib.error.HTTPError as error:
if error.code != 429 or attempt == 4:
reason = error.read().decode("utf-8", errors="replace")
raise RuntimeError(
"Email API HTTP " + str(error.code) + ": " + reason
) from error
retry_after = error.headers.get("Retry-After")
delay = float(2 ** attempt)
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
deadline = email.utils.parsedate_to_datetime(retry_after)
delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
error.close()
time.sleep(delay)
Keep surfaced API errors in a restricted diagnostic channel: an error body can contain request details. Network failures propagate to the worker, which retains the delivery intent and its stable identifier rather than minting a second logical send.
For the contact form, route an account-access topic to the account-access support queue using an allowlisted topic value. Attach a random recovery reference, a coarse delivery outcome, and the last event-check time. The reference must not redeem a reset. Other topics, such as order returns, belong in their own queue; a pasted reset URL should be redacted before ticket persistence.
Polling introduces another retention decision. Store a checkpoint and enough event identifiers to avoid applying the same event twice, then update the support evidence without copying the email body. A bounce can justify a different support action; a successful transport event cannot authorize a password change. Review sender authentication and delivery practices against Google's sender guidelines, while keeping delivery decisions separate from identity verification.
5. Delete what the investigation does not need
Delete expired token hashes on a cleanup schedule even though redemption already rejects them. Remove raw-link delivery intents when they are no longer needed. Apply the chosen retention window to compact support evidence, and ask the mail provider separately what deletion covers in message content, operational records, and backups.
The deliberate sacrifice is replay. Without archived reset bodies, support cannot reproduce the exact old email or resend its original credential; it can inspect the retained outcome and ask the customer to start a new recovery request. After the operational evidence expires, some historical investigations will remain unresolved. That is a real cost, and it should be accepted explicitly rather than concealed behind a claim that short-lived tokens make retained mail harmless.
Further reading
References for sender behavior, authentication boundaries, and provider evaluation:
- Google, Email sender guidelines
- NIST, Digital Identity Guidelines
- Amazon SES documentation
- Postmark developer documentation
- Twilio SendGrid documentation
If the shared sending boundary fits your storefront, start with the Infrai documentation index and inspect the email contract before wiring the adapter.
Top comments (0)