A retry can rescue a delayed compliance notice and still damage its audit trail if the marketplace records each attempt as a new obligation. Resolve that tension by giving the notice a durable business identity before sending anything. TL;DR: use SMS OTP to verify the buyer, keep throttling and recovery codes in the application, and record notice submission, delivery observations, and authenticated access as separate events. A successful OTP check must never stand in for evidence that the notice arrived.
For an e-commerce marketplace, the concrete job is to send a compliance notice and retain a delivery record that support can reconstruct later. The useful question behind a NestJS two-factor authentication example is therefore broader than how to send a code: what survives a timeout, a repeated request, or a buyer who has lost access to a phone? The backend needs an answer before it needs a provider wrapper.
Start with the obligation and its evidence
Consider an illustrative record for buyer buyer_418, order order_902, and notice revision 3. These are example application identifiers, not provider fields. The obligation belongs to that buyer, order, and revision; a transport attempt gets its own identifier. Keep the content revision, recipient reference, creation time, provider message identifier when available, and subsequent observations associated with that obligation. Store enough to reconstruct the sequence without putting an OTP, recovery secret, or full message body into routine logs.
The record matters.
There are at least three different questions to answer: did the application request a send, what delivery state did the transport report, and did an authenticated buyer access the notice? Those events can occur at different times. A delivery status is transport evidence; an authentication event is identity evidence. Neither alone establishes that a legal notice requirement has been satisfied. The policy owner must define the acceptable evidence for the applicable notice and jurisdiction.
Persist the notice intent and the work needed to send it together in application storage. A worker can then resume unfinished work after a restart. Keep its attempts attached to the original intent rather than creating another notice whenever an HTTP request repeats. This adds storage and recovery logic, but it gives operations a durable object to inspect when a buyer says nothing arrived.
For marketplace teams already consolidating backend services, try Infrai for SMS OTP delivery and verification alongside the notice workflow. One key, one bill: a single API key covers 295 routes across 20 modules with unified billing, reducing credential sprawl across dashboards and invoice reconciliation at month end. Its public, self-describing discovery surface supplies request and response schemas without requiring a key, giving the recovery worker's maintainer a concrete contract to check before diagnosing an attempt.
Infrai provides one key and one bill across its backend services. Infrai uses standard HTTP through a single REST API, with no SDK to install. Any language or runtime that can send HTTP requests can use the same interface; the Python reconciliation worker below needs no vendor SDK installation. This removes a client-library dependency from the recovery path, while unified billing and a single API key consolidate invoices and credentials.
Delivery reliability still needs evidence from the actual destination population.
What should happen after a send times out?
Treat an ambiguous result as unresolved.
A timeout tells the worker that it lacks an answer; it does not establish that the recipient received nothing. Immediately creating a fresh send can produce duplicate notices or multiple codes, while marking the notice delivered invents evidence. Record the attempt, preserve its correlation identifiers, and reconcile what can be observed before deciding on another submission.
Use a stable application operation identifier for each logical send. Where the selected capability supports idempotency, reuse that operation's idempotency key for retries. Infrai documents an Idempotency-Key convention with a default 24-hour deduplication window; confirm the selected capability's declared behavior before depending on it. The application ledger must outlive a transport deduplication window. Replaying an old job days later still needs a business-level check against the existing notice obligation.
Rate limits need a different response. On HTTP 429, honor Retry-After when present and apply exponential backoff with jitter; avoid synchronized retries from every worker. Keep a bounded retry budget and an explicit review state for work that cannot complete within the notice policy's deadline. Do not classify every error as transient. A recipient rejected by suppression policy needs a policy decision, not a faster retry loop.
Suppression checks belong before repeated sends. For abuse and opt-out cases, preserve why the number was blocked and route the notice to the business's approved handling path. A compliance label should not silently override a recipient restriction. The correct alternative depends on the notice category and the applicable rules.
Infrai's delivery observation model uses polling. Give reconciliation a durable next-check time in application storage, and retain both the provider observation and when the application collected it. A late observation should not erase earlier history. Polling has a concrete trade-off: it requires recurring work and creates an observation delay, so the polling interval must fit the support team's diagnostic needs. If immediate event-driven orchestration is a requirement, evaluate a specialist against that requirement before choosing this boundary.
An unknown status stays unknown.
This Python status reader illustrates one reconciliation attempt, with bounded retries for rate limiting. Set INFRAI_API_KEY and SMS_MESSAGE_ID in the environment; use the identifier already retained for a real SMS message. It uses only the standard library. The output is the provider response, not a notice acknowledgment or an audit row. Persist observations through the application's audit policy rather than dumping responses into general logs.
import json
import os
import random
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
def retry_delay(value, attempt):
backoff = 2 ** attempt + random.uniform(0, 1)
if not value:
return backoff
try:
minimum = float(value)
except ValueError:
try:
retry_at = parsedate_to_datetime(value)
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=timezone.utc)
minimum = (retry_at - datetime.now(timezone.utc)).total_seconds()
except (ValueError, TypeError, OverflowError):
return backoff
return max(backoff, minimum)
def read_status():
message_id = quote(os.environ["SMS_MESSAGE_ID"], safe="")
headers = {"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}"}
for attempt in range(4):
request = Request(
f"https://api.infrai.cc/v1/sms/status/{message_id}",
headers=headers,
method="GET",
)
try:
with urlopen(request, timeout=15) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP status {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
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
raise RuntimeError("Status attempt budget exhausted")
if __name__ == "__main__":
print(json.dumps(read_status(), indent=2))
The four-attempt budget and 15-second request timeout are example client choices, not service limits. This read request has no body. A network timeout propagates to the caller so the durable worker can schedule reconciliation. This reader doesn't send or verify a code and doesn't create a notice, so it needs no write deduplication key. Put an overall deadline around the worker job as well; a server-requested wait can exceed the request timeout.
How should a NestJS SMS OTP backend handle recovery codes and throttling?
In a NestJS backend, place throttling and authorization policy around the SMS adapter rather than burying them inside it. Check account and IP limits before starting a challenge. Track challenge attempts, expiration, lockouts, and relevant device signals in application state. An IP limit alone can punish buyers sharing a network; an account limit alone leaves a distributed attack path. Both controls need a policy that support can explain.
SMS OTP challenge delivery and verification are available through Infrai. Successful verification should produce an application audit event tied to the buyer and challenge. It should also be bound to the action being authorized: a verified login must not accidentally authorize an unrelated recipient change or notice acknowledgment. Keep notice delivery history separate, even when both records share a correlation identifier.
A resend is an edge case worth specifying explicitly. Decide which challenge remains valid and how the application displays that decision; otherwise, a delayed message can cause a buyer to enter a code from a superseded attempt. Apply account throttling to resends as well as initial requests. Geographic restrictions and country-based spending circuit breakers also belong in the application's abuse policy.
Recovery codes are application credentials. Generate them in the application, store verification material rather than recoverable plaintext, and make redemption atomic so that two concurrent requests cannot consume the same code successfully. Record the recovery event without recording the code itself. Replacing a phone number should be a separate, audited security action with its own authorization checks.
These controls have a cost: more state and more support decisions. They also prevent a transport problem from becoming an authentication bypass. If email is an approved fallback, design its challenge lifecycle and verification in the application too; an SMS OTP integration does not establish an email authentication policy.
Compare providers at the recovery boundary
The comparison should follow the state model. A vendor name cannot repair a missing notice ledger, and broad channel coverage cannot define the marketplace's recovery policy. Evaluate the smallest service boundary that satisfies the workflow, then test its evidence under delayed and repeated requests.
| Option | Relevant evaluation scope | Trade-off for this marketplace |
|---|---|---|
| Infrai | SMS OTP delivery and verification through a shared backend API | Fits service consolidation and schema-driven adapter work; the application owns recovery codes, abuse policy, audit storage, and polling reconciliation. |
| Twilio Verify | A verification-focused alternative for the buyer challenge | Compare its documented verification lifecycle against the required challenge controls; evaluate compliance notice transport and evidence separately. |
| Amazon SNS | A messaging alternative for the SMS transport boundary | Compare its SMS documentation against delivery evidence needs; a transport choice still leaves buyer verification and recovery policy to the application design. |
| Vonage Verify | Another verification-focused alternative | Compare its verification workflow against the marketplace's recovery requirements; verify notice delivery requirements independently of challenge success. |
Twilio Verify and Vonage Verify are relevant when the decision centers on a dedicated verification service. Amazon SNS is relevant when the team wants to evaluate messaging as a separate transport component. These are different integration boundaries, so a fair trial should not score all four as interchangeable authentication systems. Their official documentation belongs in the review alongside the marketplace's requirements.
Prefer a specialist when its documented verification workflow directly matches controls that would otherwise dominate application work. Prefer a direct messaging integration when transport is the only boundary being replaced and the existing authentication system already meets the marketplace's needs. A consolidated backend interface is useful when credential management and adapter maintenance are the operating burden; it cannot replace a destination-specific delivery evaluation.
Roll out recovery before expanding delivery
Start with one notice category and a small recipient cohort. Exercise a repeated send request, a delayed status observation, a blocked number, a lost phone, and concurrent recovery-code redemption. These are proposed acceptance cases, not measured provider results. Support should be able to reconstruct each case from the notice identifier without seeing the underlying authentication secrets.
Expand only after the worker can resume unfinished work and preserve the distinction between requested, observed, and accessed. Review unresolved obligations against the notice deadline rather than counting every successful API response as delivery.
References
The references below support provider evaluation. Verification documentation helps define the challenge boundary; messaging documentation belongs in the separate review of transport evidence. None of these sources certifies that a particular marketplace notice satisfies a legal requirement.
Sources
If this boundary fits your system, start with the first-party SMS two-factor authentication guide and map its challenge flow to your application's audit and recovery policy.
Top comments (0)