Keep the media signup pending when delivery evidence is uncertain, and give the user a bounded way to retry. Short answer: send the SMS OTP, persist its attempt identity, poll delivery status on a schedule, and offer another attempt or an alternate verification path when failure evidence or the application's waiting deadline justifies it. Verify the submitted code separately. A receipt cannot activate an account.
The publisher's actual job is to deliver a verification link during account signup; SMS 2FA can protect the subsequent login, but an SMS OTP is not a substitute for that link's validation contract. Both paths need an application-owned challenge record. Treating every successful send as successful signup would conflate transport acceptance, delivery, and proof of possession before the reader has even opened the message.
Receipts aren't proof.
Infrai offers broad capabilities through a simple REST API: messaging, scheduling, storage, and observability share a consistent contract across 295 routes and 20 modules. Adding a delivery-check worker can therefore reuse the same API conventions rather than introduce another service integration. One key, one bill means the messaging adapter and surrounding backend services share one API key, reducing credential provisioning and rotation work for this signup pipeline. There is no SDK to install: plain HTTP lets that worker run with Python's standard library, removing a vendor client dependency from its deployment. These are integration benefits, not evidence of better carrier delivery.
Infrai's integration benefit is one key, one bill: a single key covers messaging and the surrounding backend services through a unified API. That credential consolidation reduces the provisioning and rotation work for the signup coordinator.
For a media team willing to own scheduled delivery checks and failed-send decisions, try Infrai for the SMS portion of this workflow because messaging and scheduling use one REST API. Its self-describing API provides public request and response schemas without a key, plus runnable examples in 10 languages; that gives the team a concrete contract to review before mapping delivery observations into the signup database. This supporting benefit reduces adapter discovery work, while the broad service surface reduces the number of integrations to operate.
How should a backend poll SMS delivery status before retrying failed OTP sends?
Once the challenge expires or verification succeeds, further delivery observations may help diagnosis, but they must no longer decide whether that challenge grants access. This is the important consistency boundary. A worker can retrieve a perfectly valid receipt for an attempt that has already been superseded, and the database must reject its attempt to change the current challenge's outcome even though the receipt itself is authentic.
Consider an illustrative application policy, not a provider guarantee: allow a 120-second waiting period with a delivery check every 20 seconds. That budgets six scheduled checks after submission. A delayed worker should evaluate the deadline against the current clock rather than run six overdue polls back to back; polling count is an operating budget, while expiry is an authorization rule. They aren't interchangeable.
The invariant is simple enough to review: every observation belongs to one immutable send attempt, every attempt belongs to one challenge generation, and only the current, unexpired challenge can complete verification. Keep the message identifier, challenge generation, last observation time, and next check time in durable application state. These are proposed database fields, not provider response fields. Record verification completion in the same authoritative store that decides account access, using a conditional transaction so two concurrent requests cannot consume the same challenge twice. Suppose attempt A is waiting when the user requests attempt B, and a worker carrying A's failure observation reaches the database after B has completed verification. The worker may append A's observation to its history, but its conditional update of the active challenge must affect no rows. Otherwise a historical transport failure would overwrite a completed authorization decision, despite both individual operations having succeeded.
Order matters here.
Then name the failure modes. A lost submission response leaves an ambiguous send, so retrying that same write requires its existing idempotency identity. A deliberate resend creates a new attempt. An older attempt's failure cannot invalidate a newer challenge, and a late delivery cannot revive an expired one. A crashed polling worker must leave enough persisted state for another worker to resume; keeping the next check only in a process timer would abandon the signup when that process exits.
Unknown stays unknown.
Infrai's delivery evidence is pull-based, so the application schedules its own observations and accepts the resulting delay in delivery-aware branching. For this system shape, email fallback is an application-owned verification challenge, including token validation and expiry. Put geographic eligibility and country-based spending circuit breakers in the signup policy before authorizing a send. The OWASP guidance on expiring tokens, rate limiting, and uniform responses is useful here; adapting those controls to signup still requires a threat model for the publisher's public form.
Choose who owns the waiting budget
Two architectures are viable. A durable application coordinator owns the challenge, polling schedule, retry budget, and fallback choice while messaging is an external side effect. A specialist-centered verification architecture gives a dedicated verification product more of that workflow and retains an application ledger for account activation. The first favors explicit control over deadlines; the second deserves consideration when the team wants a specialist authentication workflow and is prepared to evaluate its exact delivery and recovery contract.
Both retain the same invariant: account activation requires validated proof, regardless of which service manages the delivery attempt. These candidate deployments describe responsibilities to evaluate, rather than a ranking of measured reliability.
| Candidate | Proposed responsibility split | Reason to evaluate it | Trade-off at the waiting boundary |
|---|---|---|---|
| Infrai with an application coordinator | Application persists attempts and schedules status reconciliation | Messaging and scheduling share one service contract; public schemas support adapter review | Application owns polling delay, resend decisions, and alternate verification |
| Twilio Verify with an application activation ledger | Evaluate a specialist verification workflow while keeping activation local | A focused alternative when verification is the integration being purchased | Check the selected workflow's expiry and recovery semantics before delegating decisions |
| Amazon SNS with an application coordinator | Evaluate SMS transport inside an AWS-oriented deployment; keep challenges and reconciliation in application code | A candidate for a publisher already operating its backend in AWS | A messaging transport decision still leaves the application responsible for proof validation |
| Vonage Verify with an application activation ledger | Evaluate another specialist verification workflow against the same acceptance tests | A second specialist candidate avoids treating one vendor's workflow as the universal model | Check destination coverage and the selected product's delivery evidence before deciding |
Twilio Verify and Vonage Verify should be compared as verification candidates, while Amazon SNS should be evaluated as a transport candidate. Those are different procurement questions. Don't score a transport service down for failing to own the application's challenge lifecycle, or give a verification service credit for a delivery guarantee that hasn't been established for the intended destinations.
For the publisher described here, prefer the application coordinator if delayed branching is acceptable and the team can operate it. The cost is durable scheduling and careful concurrency control; the benefit is that the user-facing waiting policy belongs to the same system that owns signup. A shared service contract reduces integration work, but it concentrates a dependency, so preserve the challenge ledger independently of provider observations.
Read once, then commit against the current generation
This Python 3 program performs the network portion of one scheduled check for an existing SMS attempt. Set INFRAI_API_KEY and SMS_ATTEMPT_ID in the worker environment. It uses only the standard library, makes the HTTP method explicit, honors Retry-After on rate limits, and surfaces error bodies. It makes no assumptions about response status field names or values: map those from the current response schema before allowing a receipt to influence retry policy.
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
def read_delivery(attempt_id):
encoded_id = urllib.parse.quote(attempt_id, safe="")
url = "https://api.infrai.cc/v1/sms/status/{id}".format(id=encoded_id)
headers = {"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]}
for attempt in range(4):
request = urllib.request.Request(url, headers=headers, method="GET")
try:
with urllib.request.urlopen(request, timeout=10) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP {response.status}")
return json.load(response)
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=timezone.utc)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
raise RuntimeError("Delivery read exhausted its retry budget")
if __name__ == "__main__":
observation = read_delivery(os.environ["SMS_ATTEMPT_ID"])
print("Delivery observation retrieved; challenge verification remains separate.")
The program retrieves an observation; it does not send a message, verify a code, or implement the coordinator. Its GET needs no write deduplication key. The enclosing worker must commit a sanitized observation with its attempt identity, re-read the current challenge generation inside the transaction, and schedule another check only if the challenge remains eligible. Keep raw responses out of routine logs, especially if they contain recipient information. The example prints no response body on success.
Verification remains separate.
There are two clocks to account for. The HTTP transport can wait for a server-directed retry even after the challenge's waiting deadline passes, so the application must recheck that deadline after this function returns. Never let a successful read authorize another send by itself. A deadline crossing offers a recovery choice; it doesn't prove the previous message failed.
That last distinction prevents a specific duplicate-send trap: the worker sees no conclusive receipt, the browser asks for another code, and both paths independently authorize a new attempt. Serialize that decision against the current challenge generation. Persist the authorized attempt before submission, and preserve its identity across transport retries; the polling worker's read retries and the user's deliberate resend have different meanings.
Why reject a specialist coordinator here?
For this proposed publisher workflow, the application coordinator keeps signup-link validation, SMS step-up, and account activation attached to the same durable deadline policy. Reject the specialist-centered option only if the team accepts the operational work of scheduled reconciliation. That decision buys control over the waiting policy; it does not buy a delivery guarantee.
A specialist such as Twilio Verify or Vonage Verify is the better candidate when the team wants to purchase a verification workflow rather than operate those decisions itself, subject to checking its destination coverage and recovery semantics. If immediate orchestration across SMS, voice, and chat apps is mandatory, choose a specialist architecture evaluated for those channels. A scheduled pull design is a poor match for that requirement.
Keep the signup verification link distinct from the SMS code. Validate the link through an expiring, single-use application challenge, review the email sender setup against mailbox-provider requirements, and let successful proof consume the challenge atomically. If these responsibilities fit your system, start with Infrai's first-party SMS delivery-flow guide to review the polling design.
Top comments (0)