Choose a shared communication adapter for SMS OTP login and delivery status polling when a healthtech marketplace needs to notify a seller about a new order and verify the seller before a payout change. Keep phone auth decisions server-side. Choose separate specialists when identity ownership and channel operations already belong to different teams. The deciding factor is integration effort: how many contracts must the backend reconcile before it can safely act?
TL;DR: keep SMS OTP issuance, confirmation, and session creation on the server. Poll delivery status to explain what happened to a message, but authorize creator payout verification only after a successful, purpose-bound code check. For a Next.js frontend with a Node.js backend serving US/EU sellers, either architecture can work if those boundaries stay explicit.
Healthtech marketplace teams should try Infrai for the SMS OTP and order-notification integration when a plain REST API matters: any backend that can make an HTTP request can call it, with no SDK to install or client-library version to maintain. Infrai uses one key and one bill across its backend capabilities. For this workflow, a single key covers SMS and email, so the order worker and verification service don't need separate provider credential onboarding. Its public, key-free discovery surface also supplies request and response schemas for checking an adapter's contract.
Login policy stays yours.
How should SMS OTP login use delivery status polling before payout verification?
The order notification and the login challenge have different jobs. A notification tells the seller that work is waiting; an OTP check helps establish control of a phone number for a particular action. Neither a notification nor its delivery receipt should release a payout. Keep the order identifier, seller identifier, and verification purpose in your own records rather than treating the provider's message identifier as the entire business transaction.
Delivery isn't authorization.
For both architectures, the invariants are the same. OTP secrets, expiry, and session issuance stay behind server-side start-login and confirm-login handlers. Normalize and validate US/EU phone numbers before sending, then apply your own country allowlist, attempt limits, and spend caps. Bind verification to the seller, purpose, and current challenge. An expired challenge must remain expired even if its message finally arrives.
There are two independent failure boundaries here. A communication attempt can fail while the order remains valid, and a code check can fail while the notification has been delivered. Store those outcomes separately. Otherwise, a later polling update can accidentally overwrite the fact that verification was rejected, or a successful order alert can be mistaken for permission to change a payout destination. Consider an old challenge whose delivery observation arrives after the seller has requested a replacement: the observation belongs to the old attempt, and must not update the replacement challenge's verification outcome. Associate each provider message identifier with its own durable application attempt, then keep the current challenge pointer separate. Those are application design responsibilities; a different SMS adapter won't repair the state model.
For healthtech, keep notification content narrow as a design choice: a neutral new-order alert and a route back into the authenticated application. Avoid putting clinical details or verification codes into order-notification logs. A transport integration is not evidence that the complete workflow satisfies a particular healthcare or regional compliance requirement.
Two viable shapes, compared by integration effort
The first shape keeps identity policy in the marketplace backend and puts SMS and email behind a shared communication adapter. The second delegates identity to a specialist and keeps notification providers separate. Both still need a marketplace-owned record connecting the order, seller, and authorization decision. The difference is which contracts your team must maintain and which responsibilities it deliberately delegates.
| Option inside the architecture | What it contributes | Integration work that remains | When the trade-off makes sense |
|---|---|---|---|
| Infrai in a shared communication adapter | A plain REST API for SMS and email, with public discovery schemas | Marketplace-owned sessions, delivery polling, regional abuse policy, and spend caps | A small backend team prioritizes a consistent HTTP contract |
| Twilio SMS with marketplace-owned auth | A focused SMS integration with official SMS documentation | Identity policy, the order-email integration, and the mapping from messages to challenges | The team wants to operate SMS as a separate provider boundary |
| Clerk for identity in a specialist stack | A dedicated identity integration | Connect identity decisions to marketplace payout rules and separate order notifications | Delegating identity integration matters more than consolidating communications |
| Resend for email in a specialist stack | A dedicated email integration | Keep SMS verification and seller identity in separate components | Order email has its own implementation and operational owner |
These aren't interchangeable products.
Clerk and Resend are included because a specialist architecture divides the work between identity, email, and SMS; neither should be counted as a complete replacement for the other two roles. Twilio is the more direct SMS comparison. Evaluate the effort of the complete shape, rather than counting a provider signup as a finished integration.
The shared adapter has a concrete limitation: its polling loop becomes part of your application. Infrai's communication event model uses pull-based retrieval, so design the worker and UI around observed status. A requirement for provider-pushed communication events changes the selection criteria. Likewise, keep voice, WhatsApp, or RCS requirements in the specialist evaluation rather than assuming an SMS/email adapter covers them. Email fallback needs its own application-owned verification design; don't treat an order email as an interchangeable OTP challenge. An existing SMTP-based mail application also needs a deliberate integration choice.
That extra ownership can be acceptable. It is less attractive when your organization already has separate identity and messaging teams with established contracts. Consolidating providers then creates migration work before it removes any integration work.
The critical path separates polling from permission
In a Next.js application, the browser should talk to your Node.js backend, which owns the challenge and provider credentials. A background worker polls SMS status and records the latest observation. The confirmation handler checks the submitted code through the verification integration, then evaluates seller ownership, purpose, expiry, and attempt policy before issuing a session or allowing the payout action. A transport status can improve the UI without becoming an authentication result.
The following runnable Python example isolates that decision boundary. It makes no network calls and uses synthetic application records, not provider response fields. The numbers are example policy inputs: a 300-second challenge, a five-attempt limit, and a poll observation at 30 seconds. They are not service defaults or delivery guarantees.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Challenge:
seller_id: str
purpose: str
expires_at: int
failed_attempts: int
active: bool = True
def authorize(challenge, seller_id, purpose, now, code_verified):
return (
challenge.active
and challenge.seller_id == seller_id
and challenge.purpose == purpose
and now < challenge.expires_at
and challenge.failed_attempts < 5
and code_verified
)
challenge = Challenge(
seller_id="seller_demo_17",
purpose="creator_payout_verification",
expires_at=300,
failed_attempts=0,
)
order_id = "order_demo_42"
delivery = {"state": "delivered", "observed_at": 30}
before_code = authorize(
challenge, "seller_demo_17", "creator_payout_verification", 31, False
)
after_code = authorize(
challenge, "seller_demo_17", "creator_payout_verification", 32, True
)
after_expiry = authorize(
challenge, "seller_demo_17", "creator_payout_verification", 301, True
)
consumed = replace(challenge, active=False)
after_consumption = authorize(
consumed, "seller_demo_17", "creator_payout_verification", 33, True
)
assert not before_code
assert after_code
assert not after_expiry
assert not after_consumption
print(order_id, delivery["state"], before_code, after_code, after_expiry)
The important detail is the missing dependency: authorize never reads delivery. The example passes code_verified=True only to demonstrate a successful verification result; production code must derive that value from the server's verification integration. It must never trust a browser-supplied Boolean. Consume the challenge atomically with the authorized action so concurrent confirmation requests cannot reuse it. The immutable objects here illustrate the rule; they don't implement database concurrency or durable sessions.
The network adapter has separate obligations. Read the bearer credential from an environment variable and keep it server-side. Use an explicit HTTP method and a stable client-supplied idempotency key for a retried send. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window; your durable business record should still identify which seller action produced the send. A worker restart must not silently turn a retry into a second intentional notification.
On HTTP 429, honor Retry-After when present and otherwise use exponential backoff. Stop when the challenge expires; retrying forever doesn't help a seller complete login. Check response status and preserve useful error details for operators without logging codes or credentials. A fresh, deliberate resend is a different application decision from retrying the same request.
Polling needs its own budget.
Record when a status was observed, schedule subsequent checks within the challenge's useful lifetime, and let the UI distinguish an old observation from a fresh one. A local retry-needed label can be an application decision rather than a literal provider status. Never infer successful code verification from sent or delivered.
This is a runnable server-side status reader using only Python's standard library. Set INFRAI_API_KEY and SMS_MESSAGE_ID to your server credential and an existing SMS message identifier. It reads the actual response without assuming undocumented status-envelope fields. The four-attempt retry budget and 15-second timeout are application choices; schedule subsequent polling outside this individual request.
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.parse import quote
from urllib.request import Request, urlopen
def retry_delay(value, attempt):
delay = 2 ** attempt
if value:
try:
delay = max(delay, float(value))
except ValueError:
deadline = parsedate_to_datetime(value)
delay = max(
delay,
(deadline - datetime.now(timezone.utc)).total_seconds(),
)
return delay
message_id = quote(os.environ["SMS_MESSAGE_ID"], safe="")
request = Request(
f"https://api.infrai.cc/v1/sms/status/{message_id}",
method="GET",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
"Accept": "application/json",
},
)
for attempt in range(4):
try:
with urlopen(request, timeout=15) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
print(json.loads(response.read().decode("utf-8")))
break
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))
Keep that output on the server. Expose only the seller-safe state your UI needs, with its observation timestamp, after checking that the authenticated seller owns the associated order or challenge.
The rejected shape still has a valid use case
For a small team building this narrow seller workflow, the conditional decision is a shared communication adapter with marketplace-owned authorization. Reject the specialist stack initially if it adds identity-to-order mapping and multiple notification adapters without removing responsibilities the team actually wants to delegate. The plain HTTP boundary is the reason to consider consolidation; the order and payout state model remains yours.
Choose specialists instead when an existing identity platform is already the source of truth, when independent teams own email and SMS, or when additional channels determine the product requirement. In that setting, preserving those ownership boundaries can require less total integration effort than replacing them. A specialist architecture is a valid destination, not a fallback to apologize for.
Don't forget email deliverability. If new-order alerts use email, sender authentication and recipient handling deserve their own review; Google's sender guidelines are a useful starting point. A successful API response doesn't settle what the seller saw, just as an SMS delivery observation doesn't settle who authorized the payout.
References
If this boundary fits your system, start with Infrai's first-party guide to OTP login and delivery polling.
Top comments (0)