DEV Community

EmersonPrice3718
EmersonPrice3718

Posted on

Seller OTP Login Evidence: Bounding SMS Polling and Email Fallback Retention

A beginner OTP login architecture for a gaming marketplace has a communications bill that includes sending seller order notices, sending SMS challenges, checking delivery, and keeping enough evidence to explain what happened. Before choosing a provider, count those operations separately. In an illustrative workload of 1,000 seller login challenges with four status checks each, polling produces 4,000 reads alongside 1,000 initial SMS sends and up to 1,000 verification submissions. Those are workload assumptions, not measured traffic or a prediction of billable charges; the dominant operation count is already the status reader.

TL;DR: For a beginner US/EU application, use SMS as the primary OTP channel, verify the entered code, offer a custom email code when SMS is unavailable, and poll delivery status only while the result can change a user decision. Keep the seller's new-order notification separate from the login challenge. A delivery record can help explain a missing message; it cannot authorize access to the order.

For a Node.js backend, integration effort depends less on the number of SDK calls than on how many channel states the application must own. Start with a small challenge record, a separate notification record, and a bounded status reader. Treat geographic controls and country-based spending cutoffs as application policy. This design suits ordinary SaaS login flows; sophisticated real-time orchestration needs a different evaluation.

What actually grows when a seller receives an order?

The marketplace has two jobs at the same moment: tell the seller that a new order exists, and authenticate the seller who follows that notice. Mixing their state creates a particularly expensive reasoning error, because the order notice can arrive while its associated login challenge expires, and a successful delivery receipt still says nothing about who entered the code. Store their identifiers separately and connect them through an internal order reference where needed. Keep phone numbers, email addresses, and codes out of the order reference itself.

Delivery isn't authentication.

An operation budget should distinguish initial sends, intentional resends, verification attempts, fallback sends, and status reads. SMS segmentation deserves its own line: Twilio's character-limit documentation explains GSM-7 and UCS-2 segmentation, so a template's visible character count alone is a poor proxy for its transport footprint. That matters when a game item name enters an order notice. Keep the authentication text focused and inspect the actual notification template rather than assuming both messages have the same shape. No particular per-message charge follows from these counts.

Retention has a different growth curve.

A mutable latest-status row stays one row per tracked message; an append-only copy of every poll response grows with every check, including checks that report no change. In the illustrative workload above, retaining every response yields 4,000 response snapshots, while retaining just the latest delivery observation yields at most 1,000 such rows. The latter loses intermediate observations. That is a deliberate evidence trade-off, not a claim that the two records answer the same questions. Consider an order notice and a login challenge that each produce several identical observations: duplicating both payload histories creates more records without providing more evidence of a transition, yet deleting both identifiers would make a later support inquiry harder to correlate. The useful boundary is a compact reference to each attempt plus the evidence that changes a decision. Decide that boundary before selecting the database layout, because a schema optimized for indiscriminate payload retention makes deletion and support access unnecessarily coupled.

The first change should therefore move the read count: with two checks instead of four, that same assumed workload produces 2,000 reads. Whether two checks are sufficient depends on the seller experience and the status semantics. Do not declare them sufficient because a spreadsheet is smaller.

Where should the integration boundary sit?

Use an application-owned challenge identifier to connect issuance, verification, fallback, and expiration, and keep a provider message identifier as delivery evidence underneath it. An abstraction is useful only if its contract says what it preserves. Provider acceptance, observed delivery, and successful verification must remain distinct states even when a wrapper makes their responses look similar.

Infrai combines one API key with unified billing: one key, one wallet, one bill for seller notices and login challenges. This single-key, single-bill model reduces credential provisioning and invoice reconciliation across SMS and email. Its unified API keeps a stable contract when providers change behind a capability, so the seller-notification worker does not need a new provider-specific integration for that change. Its public, self-describing discovery surface requires no API key and exposes request JSON Schema, response schema, billing, and runnable examples, allowing the team to inspect the send-and-status contracts before provisioning credentials. That reduces a different integration task: reconciling undocumented assumptions between the seller-notification worker and the login worker.

Shared credentials make application-side access boundaries worth defining explicitly. The plain REST API requires no SDK installation; a Node.js application and the Python reader below can use their own HTTP clients against the same contract. Runnable examples in 10 languages let the team inspect both implementations without guessing at a translation. The platform also specifies an Idempotency-Key header and a default 24-hour deduplication window for idempotent capabilities; check the selected capability's declaration before relying on that protection for a retried seller notice. A bounded deduplication window does not replace the application's durable notification identity.

Per-call metadata includes cost_usd, latency_ms, vendor, cache_hit, and request_id, so a compact attempt record can retain attribution for a seller notice without retaining the full response body. Those fields describe individual calls, not an aggregate spending report or a delivery guarantee. The pull-based status model fits a bounded reader; custom email-code issuance and verification remain application responsibilities. Accept that ownership before choosing the abstraction.

The competing choices deserve the same scrutiny. This comparison concerns the boundary to evaluate, rather than a claim that their account requirements, regional policies, or delivery semantics are interchangeable.

Candidate Relevant integration decision Trade-off or limit to resolve
Twilio Verify Evaluate a verification-oriented product when challenge handling is the main integration task. Check the documented verification lifecycle against the intended email recovery policy; a managed challenge still needs application authorization rules.
Amazon SNS Evaluate SMS messaging when the application will own the challenge lifecycle. A messaging integration must be assessed separately from code verification; do not infer OTP lifecycle behavior from message delivery.
Amazon SES Evaluate the email delivery portion of a custom fallback and seller notice flow. Email transport is only part of recovery: define code expiration, attempt limits, and identity binding in the application.

A team comparing these products should trace one seller journey through each candidate's documentation: new-order notice, login challenge, unavailable SMS, email recovery, successful verification, and a support inquiry after the delivery history has expired. This avoids awarding points for a long channel list when the actual integration burden is an ambiguous transition between two states. None of these rows establishes US/EU compliance or a universal regional winner.

How should beginner OTP login architecture bound SMS polling and email fallback?

Poll when an observation can change the next action, with a deadline and a maximum number of reads. Stop when a documented terminal state is reached or when the application's observation window ends. Keep status labels tied to the chosen provider's documented meanings; inventing a universal mapping for accepted, sent, and delivered merely relocates uncertainty into an adapter. SMS and email status observations follow a pull model, so polling cadence is an explicit integration decision rather than an assumed stream of pushed events.

The following Python program reads one existing SMS attempt. Set INFRAI_BASE_URL to the trusted service origin, INFRAI_API_KEY to your credential, and SMS_MESSAGE_ID to the message identifier from the send response. The caller owns the next scheduled check; this program only retries a rate-limited read, with a finite retry budget, and prints the returned payload without inventing status fields. Its configured request timeout is 15s, with at most four attempts and exponential backoff starting at 1s; these are example settings, not provider limits or delivery guarantees. Keep that output out of persistent logs unless it belongs in the retention policy.

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, urlsplit
from urllib.request import Request, urlopen


origin = os.environ["INFRAI_BASE_URL"].rstrip("/")
parts = urlsplit(origin)
if parts.scheme != "https" or not parts.netloc or parts.path:
    raise ValueError("INFRAI_BASE_URL must be a trusted HTTPS service origin")
message_id = quote(os.environ["SMS_MESSAGE_ID"], safe="")
request = Request(
    f"{origin}/v1/sms/status/{message_id}",
    headers={"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}"},
    method="GET",
)

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.dumps(json.load(response)))
        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
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                server_delay = float(retry_after)
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                server_delay = (retry_at - datetime.now(timezone.utc)).total_seconds()
            delay = max(delay, server_delay)
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

The storage calculation remains separate: 1,000 challenges per day, four retained poll responses per challenge, and 30 days of retention produce 120,000 observations at steady volume. Keeping only the latest observation for seven days produces 7,000. These are proposed application policies and row counts, not provider limits or byte estimates: response sizes, indexes, replication, and backups would have to be specified before making a storage estimate.

Neither calculation predicts charges.

There is a consistency trap here.

Two workers may observe the same message at different times and persist their results in the opposite order, causing an older observation to replace a newer one. Design the update rule before parallelizing polling. If the provider supplies a documented ordering field, evaluate whether it can support that rule; otherwise serialize observation work for each message rather than guessing that local write order proves provider event order.

Recovery policy needs its own durable state

When SMS is unavailable, a normal email send can carry a custom code, but the application must define its lifecycle. Bind that code to the intended account and challenge, impose expiration and attempt limits, and decide explicitly whether switching channels invalidates the previous challenge. A delivered email must never become an alternate proof of authentication merely because its delivery state is easier to retrieve. Keep order information out of the authentication message beyond what the seller needs to recognize the request.

Expiry must win.

For example, a delayed observation that reports delivery must not revive an expired challenge. Make successful verification and expiration compete through an atomic application-state transition, and reject a repeated code submission after that challenge has been consumed. These are proposed application rules, not inferred provider guarantees. An order notice needs a separate retry identity so that retrying notification work cannot issue another login challenge by accident. Where a sending capability documents idempotency, preserve the same client key across retries of that logical send; a deliberate resend is a separate decision.

For email, use Google's sender guidelines to review authentication and sender practices before treating fallback as a dependable recovery path. For SMS, implement geographic restrictions and country-based spending cutoffs in the application. Neither a unified interface nor an email delivery observation proves that the seller is authorized to access an order.

Keep the decision record, expire the observation trail

Choose retention by the question a record must answer. A challenge decision needs its own durable record; raw polling responses are temporary diagnostic evidence. The illustrative seven-day latest-observation policy above deliberately gives up the ability to reconstruct every intermediate delivery observation, and even during that window, overwriting a snapshot discards the previous value. Keeping a final decision does not restore that missing timeline.

That loss matters during support.

If a seller reports an order notice late, an expired observation trail can leave the team able to identify the notification attempt and login decision but unable to establish the sequence of delivery reports. State that limit in the support runbook. Keep order records under their own retention policy, remove expired challenge secrets, and stop copying unchanged provider responses into permanent logs. A retention deadline also needs to cover diagnostic exports and backup handling; deleting the current row alone does not establish that every copy has disappeared. The resulting system retains enough state to enforce access decisions while accepting a narrower investigation window for message delivery.

Further reading

References:

Top comments (1)

Collapse
 
dev_4_good profile image
Dev 4 Good •

The 4,000 poll snapshots versus 1,000 latest-status rows comparison stood out to me. There is a middle option worth checking: append a row only when the status actually changes. You keep the transitions that explain a missing message, and identical no-change polls add nothing to storage.

Did you consider delivery status callbacks instead of polling for the seller order notices?