Use a managed SMS OTP API for healthtech SaaS login recovery, with application-owned expiry and a durable record of the password-reset authorization decision.
TL;DR: Let the service generate and verify codes; keep abuse controls, reset authorization, and evidence retention in the application. For US/EU SaaS login recovery, choose the simplest API whose verification contract and documentary evidence satisfy the organization's requirements. A delivery receipt cannot authorize a password change.
This decision record uses a proposed 120-second recovery window, not a provider default. The selection axis is compliance evidence: can the team explain which challenge authorized a reset, under which policy, without retaining the code or copying patient information into operational logs? No messaging API alone establishes healthcare compliance.
Infrai provides one REST API with no SDK required, one API key and one bill across 295 routes in 20 modules, and a stable capability contract that lets the backend vendor change without changing application code. Public, self-describing discovery lets engineers inspect the schema before connecting the recovery adapter. Those integration advantages do not prove processing location, retention terms, or a healthcare agreement.
Demand the evidence.
What must an SMS OTP API prove for SaaS login recovery?
The application needs three distinct observations: a challenge was requested, a delivery observation was obtained, and verification succeeded. Only the last can contribute to reset authorization, and it still needs an application-side deadline check. For a Node.js SaaS backend, keep that policy behind an application contract rather than letting transport response shapes spread into account recovery. The executable Python example below isolates deadline-bounded transport retries without inventing a provider's request fields.
Expiry wins.
Treat the reset grant like a consumable database record. A successful verification establishes an input to the decision; it must not create an indefinitely reusable permission. Persist the original deadline, check it when changing the password, and consume the grant in the same database transaction as the password update. A retry must not start a new 120-second window. A duplicate delivery event must not create a second grant. If two workers race to consume the same challenge, the storage layer must permit at most one password change, regardless of the number of successful HTTP responses elsewhere in the system.
Those are application invariants, not claims about any particular provider's implementation.
There are two evidence boundaries. First, a messaging service accepting a send does not prove handset delivery or control of the account. Second, writing an operational event does not prove that a password transaction committed. Store the authorization record alongside the account mutation, then export a redacted event through an outbox. A separate export can lag; the local record must remain sufficient to reconstruct the decision. An outbox makes publication recoverable, but an ordinary mutable database is not automatically an immutable audit archive. Define access, retention, deletion, and any independent preservation requirements explicitly.
Before requesting a code, enforce recipient and account throttles, destination-country policy, and per-country spend cutoffs in the business layer. Separate these controls from HTTP 429 handling: provider backoff is not an account-abuse policy. Keep the recovery response independent of account existence, and exclude codes, phone numbers, reset links, password material, and clinical context from the evidence event.
Step 1: Compare the evidence burden before choosing a sender
Use the same procurement questions for each candidate. The table compares the responsibility being evaluated; it does not assert a certification, contractual commitment, processing region, delivery rate, or default expiry for any product. The linked product documentation is the starting point for checking a particular configuration.
| Candidate | Workflow to evaluate | Evidence needed before approval | Reason to accept or reject the design |
|---|---|---|---|
| Twilio Verify | A managed verification service, rather than an application-built code lifecycle. | Verification lifecycle documentation, retry behavior, correlation records, and the applicable processing and retention terms. | A useful candidate when managed verification is the priority; its service-specific lifecycle still needs mapping into the reset policy. |
| Vonage Verify | A second managed verification candidate for the same short-expiry recovery contract. | Challenge expiry and attempt semantics, destination coverage for the actual deployment, and records available to the application. | Compare its verification workflow with the application's deadline and evidence needs; do not assume identical semantics because both products verify codes. |
| Amazon SNS | SMS messaging as the transport for an application-owned verification flow. | Messaging delivery observations, account configuration, and a separate review of the application's code generation and verification design. | Appropriate when the verification service already exists; it leaves more security-sensitive application ownership than the managed-OTP approach. |
| Amazon SES | A candidate for the email fallback transport, evaluated separately from SMS verification. | Domain authentication configuration, sending records, and the application's independent email-code policy. | Compare it when email is an accepted recovery channel; an email transport does not replace the managed SMS verification decision. |
For the stable-contract option described above, use status and event polling to collect delivery observations. Budget those reads against the service's allowed request rate and the recovery deadline. A delayed observation should remain labeled as a delayed observation; it must not overwrite a completed verification decision. The trade-off is polling latency and additional reads. This pull model is not suitable for a workflow requiring immediate multi-channel event propagation; choose a different orchestration design and review its evidence contract.
Email fallback deserves its own decision. An application-owned email code flow needs code generation, expiry, attempt limits, single-use consumption, and evidence retention; adding another sender does not provide those semantics. Keep the accepted scope to SMS recovery and an explicitly designed email fallback. Do not make assumptions about additional channels or relay protocols.
Request the relevant agreements, processing-location evidence, retention terms, and security documentation before approval. Review US and EU destinations separately where the organization's obligations require it. A vendor name or readiness indicator cannot answer these questions. NIST's authenticator guidance is relevant to the authentication threat model; it is not a healthcare compliance certificate, and DMARC addresses email-domain authentication rather than proving possession of an account.
Step 2: Bound transport retries by the original recovery deadline
Run the following block as a Python 3.11 or later script. It uses only the standard library and sends one OTP request. Configure INFRAI_BASE_URL with the documented HTTPS API base ending in /v1, supply INFRAI_API_KEY through the environment, and set RECOVERY_OPERATION_ID and RECOVERY_DEADLINE_EPOCH from the durable pending record. The latter is the absolute deadline, not a duration to restart on every invocation.
Supply SMS_OTP_REQUEST_JSON as a complete request object reviewed against the capability's current request schema. This configuration boundary is intentional: request fields are not guessed here. Confirm that the selected write contract supports the platform's idempotency convention before enabling retries. The script preserves its operation identifier and payload across HTTP 429 retries and prints only the native envelope's request identifier; it never prints the request body or a secret.
import json
import math
import os
import random
import time
import urllib.error
import urllib.parse
import urllib.request
from email.utils import parsedate_to_datetime
BASE = os.environ["INFRAI_BASE_URL"].rstrip("/")
KEY = os.environ["INFRAI_API_KEY"]
OPERATION = os.environ["RECOVERY_OPERATION_ID"]
DEADLINE = float(os.environ["RECOVERY_DEADLINE_EPOCH"])
payload = json.loads(os.environ["SMS_OTP_REQUEST_JSON"])
target = urllib.parse.urlsplit(BASE)
if target.scheme != "https" or target.path != "/v1":
raise ValueError("Use the documented HTTPS v1 API base")
if not target.netloc or target.query or target.fragment or target.username:
raise ValueError("Invalid API base")
if not OPERATION or not math.isfinite(DEADLINE) or not isinstance(payload, dict):
raise ValueError("A stable operation, finite deadline, and JSON object are required")
def remaining():
value = DEADLINE - time.time()
if value <= 0:
raise TimeoutError("Recovery deadline reached")
return value
def retry_after_seconds(value):
if value is None:
return 0.0
try:
seconds = float(value)
except ValueError:
seconds = parsedate_to_datetime(value).timestamp() - time.time()
if not math.isfinite(seconds):
raise ValueError("Invalid Retry-After")
return max(0.0, seconds)
def send_otp():
encoded = json.dumps(payload).encode("utf-8")
for attempt in range(3):
request = urllib.request.Request(
BASE + "/sms/otp",
data=encoded,
method="POST",
headers={
"Authorization": "Bearer " + KEY,
"Content-Type": "application/json",
"Idempotency-Key": OPERATION,
},
)
try:
with urllib.request.urlopen(request, timeout=min(10.0, remaining())) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP status {response.status}")
result = json.loads(response.read().decode("utf-8"))
remaining()
return result
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 2:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = max(
retry_after_seconds(error.headers.get("Retry-After")),
(2 ** attempt) + random.uniform(0.0, 0.25),
)
if delay >= remaining():
raise TimeoutError("Retry would exceed recovery deadline")
time.sleep(delay)
raise RuntimeError("Retry budget exhausted")
result = send_otp()
request_id = result["metadata"]["request_id"]
if not isinstance(request_id, str) or not request_id:
raise ValueError("Missing request identifier")
print(json.dumps({"operation_id": OPERATION, "request_id": request_id}))
The expected result is a correlation record, not a reset grant. The script makes at most three attempts and does not automatically replay transport timeouts. Surface error details to a controlled diagnostic boundary with redaction; do not forward them to public recovery responses or unrestricted logs. A late response may mean a send happened after the application stopped waiting. The original pending record remains the reconciliation anchor.
After the user submits a code, the trusted adapter must bind the managed service's verification result to the challenge, account, and recovery purpose. Never accept a verification-success boolean from a browser. Use server-controlled time for the deadline; a client's clock cannot extend a grant. Define clock-skew handling for the deployed database and application. Neither an HTTP timeout setting nor a send response implements atomic grant consumption.
Connecting transport is the next integration boundary, not a reason to relax the storage rules. Persist a pending send with a stable operation identifier before dispatch. On HTTP 429, honor Retry-After and apply bounded exponential backoff; stop when the original deadline leaves insufficient time. Preserve the same idempotency identity when retrying a write whose documented contract supports it. A timeout after dispatch has an uncertain outcome: reconcile using the operation record rather than immediately creating another challenge with a fresh identity. Do not infer send failure from the absence of an evidence export.
Keep outbox export independently retryable using the event identifier. Export acceptance and password-change authorization remain different facts. A worker crashing after export but before acknowledging its outbox row can repeat the export; the receiving evidence system needs deduplication, or the review process must recognize duplicates by identifier. Record the policy version so a later review can interpret the decision under the rules that actually applied.
Step 3: Reject delivery-driven authorization, then document its valid use case
Reject a design that issues a reset grant when a delivery poll reports success. It crosses the wrong trust boundary: delivery progress is an observation about a message, while the application needs a verified challenge and an unexpired, unconsumed authorization record. A storage transaction cannot repair an incorrect authorization predicate.
Delivery polling still has a valid role. Use it for progress displays, support investigation, and bounded decisions about offering a separately secured recovery path. Keep those observations out of the password mutation predicate.
The other rejected shortcut is choosing raw SMS transport solely because the first send looks easier. Amazon SNS remains a reasonable option for a team that already operates an audited verification service and wants a messaging component. For a beginner building this healthtech flow, managed OTP removes code-generation and code-checking ownership, while the application retains the expiry, abuse, storage, and evidence obligations demonstrated here. Approve the sender only after its account-specific documentary evidence passes review; a compact SDK example cannot stand in for that decision.
Top comments (0)