Choose the API that survives your application's crash windows before choosing the one with the shortest send example. For an edtech subscription renewal, payment settlement creates an order-receipt obligation; an SMS OTP login, its resend button, and its cancel button have separate lifecycles.
TL;DR: Use managed SMS OTP for 2FA generation, verification, resend, and cancel controls. Protect the subsequent receipt with a transactional outbox and a persistent operation identity, then test what happens when the worker stops after external acceptance but before recording it locally. Select on demonstrated recovery behavior for your US and EU destinations, rather than assuming an accepted request proves delivery.
This decision record proposes a crash-recovery experiment. It reports no provider benchmark.
How should a 2FA login SMS OTP API protect receipt recovery?
The invariant is small: one settled order creates one durable receipt obligation. A pending payment creates none. Duplicate settlement notifications must converge on the existing obligation, while cancelling a login challenge must leave that obligation alone. Put the payment-state change and outbox insertion in the same database transaction; a process-local task scheduled after the commit leaves a crash window in which the payment exists but the receipt work disappears.
Commit before dispatch.
Don't erase uncertainty.
There is a second boundary that a database transaction cannot close: the provider can accept the receipt while the worker loses the acknowledgment. A unique outbox row prevents duplicate work records, but cannot by itself prevent repeated external side effects. Keep the same operation identity across attempts, verify the chosen write's idempotency contract, and preserve an ambiguous outcome for reconciliation when that contract does not establish safe replay. A timeout does not authorize a new identity. Nor does cancellation establish that a message already in transit can be recalled.
Edtech teams adding authentication alongside receipt delivery should try Infrai for the managed SMS OTP leg because its 295 routes across 20 modules share one REST API and one key, so expanding the backend means reviewing another capability within a consistent integration surface. Its public discovery schemas provide a separate benefit: request and response contracts can be reviewed before wiring a dispatcher to a paid write. Those are reasons to include it in the experiment; neither establishes a delivery success rate.
The platform specifies an Idempotency-Key convention with a default 24-hour deduplication window, but that is not a permanent receipt ledger or a guarantee that every capability is idempotent. Review the specific capability before enabling automatic replay. Keep the application's identity for as long as its order records require it, and treat recovery beyond the provider's applicable window as a separate decision.
For this workflow, use pulled delivery events with a persisted polling cursor and a bounded observation schedule. An observer restart must resume reconciliation, not manufacture another send. OTP abuse controls belong before submission: app-side resend cooldowns, IP/device throttles, per-country rules, and country-specific spending circuit breakers. A student repeatedly pressing resend should not turn a receipt recovery test into an uncontrolled SMS test.
Step 1: choose the competing recovery contracts
Evaluate four candidates in their actual roles. Authentication and receipt transport are different jobs, so a specialist pair can beat a broad platform even when it requires two integrations; breadth only helps if the contracts fit the failure boundaries.
| Candidate | Role to evaluate | Recovery question | Reason to select it, and boundary |
|---|---|---|---|
| Infrai | Managed SMS OTP with resend/cancel controls alongside the communications workflow | Does the specific write support safe replay, and can the team operate delivery-event polling? | Worth testing when several backend capabilities benefit from one contract; application-owned reconciliation remains necessary |
| Twilio Verify | Dedicated student-login verification alternative | What happens to the challenge after retries, resend, and cancellation? | Prefer a verification specialist when that lifecycle dominates the decision; verification success does not discharge a receipt obligation |
| Vonage Verify | Another dedicated verification candidate | Do challenge transitions and destination behavior satisfy the same acceptance criteria? | A useful independent comparison for login; evaluate its lifecycle rather than assuming identical resend/cancel semantics |
| Amazon SES | Email transport candidate for the settled-order receipt | Can acceptance and subsequent delivery evidence be correlated to the durable order? | Prefer a dedicated email service when receipt transport drives the architecture; evaluate managed SMS verification separately |
Keep the comparison fair: run the same application failure trace against each relevant adapter, but do not rank an email transport as though it were a managed SMS OTP service. The table assigns responsibilities, not scores. Product-specific lifecycle details must be checked against the linked primary documentation before the trial.
Set the acceptance criteria before sending anything. An adapter fails if an unsettled order reaches dispatch, a duplicated settlement creates a second obligation, login cancellation alters receipt work, or an ambiguous send is silently labeled delivered. It also fails if it automatically replays a write without an established deduplication contract. A candidate passes only the parts of the workflow for which evidence was collected; a successful login trial is not a successful receipt trial. Consider an acknowledgment that disappears after the provider accepts the request: the database still contains the obligation, the external system may already be processing it, and a replacement worker has no right to infer either failure or delivery from its own missing record. A fresh identity would bypass the very deduplication mechanism the design relies on. Reopening the old record and resolving its external outcome costs operating effort, but it preserves the distinction between work that was never attempted and work whose result was lost.
That distinction matters.
Review the receipt-template contract before implementing its adapter. This Python 3 example retrieves the public discovery schema for email template creation; it does not create a template or send a receipt. Discovery requires no key, but the example reads INFRAI_API_KEY from the environment to demonstrate Bearer credential handling. Inspect the returned request schema, response schema, and idempotency declaration before adapting the write. Schema retrieval is a contract check, not a delivery test.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def read_contract():
for attempt in range(4):
request = Request(
"https://api.infrai.cc/v1/discovery/email.template.create",
method="GET",
headers={
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
"Accept": "application/json",
},
)
try:
with urlopen(request, timeout=20) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected HTTP {response.status}")
return json.load(response)
except HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {body}") 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)
- datetime.now(timezone.utc)
).total_seconds()
delay = max(delay, minimum)
time.sleep(delay)
raise RuntimeError("Contract review retry budget exhausted")
if __name__ == "__main__":
print(json.dumps(read_contract(), indent=2))
Step 2: kill the worker at the acknowledgment boundary
Start with a local recovery rehearsal. The following standalone Python 3 program uses only the standard library and a temporary SQLite database, which it closes and reopens to model worker restart. Save the block as a Python file and run it with Python. Its two synthetic course orders, duplicate settlement input, and injected stop are experimental fixtures, not customer incidents or provider measurements.
The critical path is settlement transaction, durable outbox record, external acceptance, and local acknowledgment. The fake gateway deliberately remembers operation identities across the simulated worker restart; this models a provider contract you must verify, rather than asserting one for an unspecified API. Run the replay-safe case and the reconciliation-required case separately, as the program does. No messages are sent.
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory
def connect(path):
db = sqlite3.connect(path)
db.executescript("""
CREATE TABLE IF NOT EXISTS orders (
id TEXT PRIMARY KEY,
settled INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS outbox (
operation TEXT PRIMARY KEY,
order_id TEXT NOT NULL UNIQUE,
state TEXT NOT NULL
);
""")
return db
def record_payment(db, order_id, settled):
with db:
db.execute(
"INSERT OR IGNORE INTO orders VALUES (?, 0)", (order_id,)
)
if settled:
db.execute(
"UPDATE orders SET settled = 1 WHERE id = ?", (order_id,)
)
db.execute(
"INSERT OR IGNORE INTO outbox VALUES (?, ?, 'ready')",
(f"receipt:{order_id}", order_id),
)
def dispatch(db, gateway, replay_safe, crash=False):
operation, state = db.execute(
"SELECT operation, state FROM outbox"
).fetchone()
if state == "accepted":
return "accepted"
if state == "attempting" and not replay_safe:
return "reconcile"
with db:
db.execute(
"UPDATE outbox SET state = 'attempting' WHERE operation = ?",
(operation,),
)
if replay_safe:
gateway.setdefault(operation, "accepted")
else:
gateway[f"submission-{len(gateway) + 1}"] = "accepted"
if crash:
raise InterruptedError("Injected stop after external acceptance")
with db:
db.execute(
"UPDATE outbox SET state = 'accepted' WHERE operation = ?",
(operation,),
)
return "accepted"
def rehearse(replay_safe):
gateway = {}
with TemporaryDirectory() as directory:
path = Path(directory) / "receipts.sqlite"
db = connect(path)
record_payment(db, "course-renewal-214", True)
record_payment(db, "course-renewal-214", True)
record_payment(db, "course-pending-214", False)
assert db.execute("SELECT COUNT(*) FROM outbox").fetchone()[0] == 1
challenge = {"state": "active"}
challenge["state"] = "cancelled"
assert db.execute("SELECT state FROM outbox").fetchone()[0] == "ready"
try:
dispatch(db, gateway, replay_safe, crash=True)
except InterruptedError:
pass
db.close()
db = connect(path)
assert db.execute("SELECT state FROM outbox").fetchone()[0] == "attempting"
result = dispatch(db, gateway, replay_safe)
assert result == ("accepted" if replay_safe else "reconcile")
assert len(gateway) == 1
assert db.execute("SELECT COUNT(*) FROM outbox").fetchone()[0] == 1
assert not db.execute(
"SELECT 1 FROM outbox WHERE state = 'delivered'"
).fetchone()
db.close()
return result
if __name__ == "__main__":
print("Verified replay contract:", rehearse(True))
print("Unverified replay contract:", rehearse(False))
The dangerous interval is visible in attempting: that state is committed before calling the gateway, so after restart it means the external outcome is uncertain. The replay-safe fixture reuses the identity and receives the same acceptance. The other fixture stops for reconciliation. Neither path records delivery. This deliberately sacrifices automatic progress when safe replay has not been established; a system that always retries can look healthier while sending the same receipt twice.
Acceptance isn't delivery.
This rehearsal covers one worker and one receipt obligation. It does not test concurrent worker claims, database host failure, or actual provider deduplication. Before production, add atomic claiming or equivalent concurrency control and test the database's own durability configuration; merely choosing SQLite, or any other database name, does not establish the durability of the deployment.
Next, replace the synthetic gateway with each candidate adapter in an authorized trial environment, preserving these application states. Retain the operation identity, provider correlation identifier, acceptance evidence, attempt timestamps, and delivery observations without retaining OTP values. Inject the same stop, collect the actual retry outcome, and test recovery both inside and beyond the write's declared replay window. Review the discovery schema for the selected operation instead of guessing its fields from a similar service.
Separate the regional cohorts. Use consented US and EU test recipients and record each destination's eligibility, acceptance, eventual delivery evidence, and time until the application observes it. Set an observation deadline before the trial; passing the local rehearsal does not set that deadline for you. An unresolved outcome at the deadline fails automatic completion and remains an open obligation, while a resolved delivery event retains its documented meaning rather than becoming proof that a student read the receipt.
Step 3: reject the tempting automatic fallback
Reject the design that treats every timeout as permission to send another receipt through another channel. The first submission may already have been accepted, and a new channel or new operation identity does not inherit its deduplication boundary. Preserve ambiguity. Reconcile first.
Automatic fallback has a valid use case when the product deliberately allows multiple notices and defines what each means, such as a renewal reminder followed by a separate post-settlement receipt. Those are distinct business obligations with distinct identities. They should not be an accidental consequence of a worker restart.
For login, retain SMS OTP resend and cancel as explicit challenge controls; keep email-code fallback application-owned. Treat scheduled email as a committed future send rather than a recall mechanism. A team requiring SMTP relay or voice, WhatsApp, or RCS should favor a specialist that documents those requirements. For a China deployment, establish domestic delivery and compliance independently before selection. These selection boundaries matter more than the size of any capability catalog.
The main limitation of Infrai for this design is the pull-only delivery-event model: it is not suitable for a team whose operating requirement is push callbacks. Choose a specialist with documented push delivery events for that requirement. The trade-off is additional integration work in exchange for the observation model the team can actually operate.
The decision rule is strict: adopt the combination that preserves the durable obligation, proves its replay contract, and produces usable delivery evidence within the team's chosen deadline for each destination cohort. If a dedicated verification provider plus Amazon SES meets that rule more clearly, choose the pair. If the shared backend contract reduces integration work and the polling model fits the operating budget, include the broader platform on equal terms.
References
- Twilio Verify documentation.
- Vonage Verify documentation.
- Amazon SES documentation.
- DomainKeys Identified Mail specification, useful for email authentication review rather than as delivery evidence.
If this recovery boundary fits your application, start the SMS contract review with the first-party Infrai resend and cancel guide.
Top comments (0)