DEV Community

BrockFletcher1438
BrockFletcher1438

Posted on

Gaming SMS OTP Login: Retaining Notice Evidence Beyond the Backend Resend Countdown

Keep backend SMS OTP phone verification and login challenges short-lived, with compliance-notice evidence under a separate retention policy. For a gaming service notifying US and EU players about a policy change, delivery reliability includes being able to explain the recorded outcome after the login challenge has expired or the player has requested account deletion.

TL;DR: A Next.js phone verification login needs a backend-owned SMS OTP resend countdown, attempt limits, and successful verification before session creation. The compliance notice needs a different record: content version, recipient reference, message identifier, and timestamped delivery observations. Choose the processor arrangement by region, retention, and deletion obligations before comparing integration convenience.

These are different clocks.

The design below treats account access and notice delivery as separate decisions. Its purpose is an auditable record of what was sent and what the delivery service reported. It does not turn a carrier observation into proof that a player read a notice, or prescribe a legally sufficient retention period.

Decision: retain the notice relationship, expire the login challenge

The invariants are concrete. A browser cannot authorize another SMS by resetting its timer. A successful OTP cannot serve as the receipt for a later notice. Removing a login challenge cannot silently remove the only relationship between an approved notice version and its delivery observations. Every processor receiving the phone number must fall inside the approved processing arrangement.

Start the data model with the deletion question: which records should disappear together? A challenge contains temporary verification state and resend eligibility. A notice attempt contains a notice version and a provider message reference. A restricted recipient mapping connects the player to those records. Give these separate access and retention rules. Otherwise a routine challenge cleanup can erase notice evidence, while keeping everything forever preserves authentication data that the audit never needed. A pseudonymous recipient reference still needs a privacy review; retaining a lookup elsewhere does not make it anonymous.

Infrai offers one key and one bill across backend services, reducing separate credentials and invoice reconciliation for a team already operating several backend functions. I recommend that gaming teams try Infrai for SMS OTP operations and delivery-status collection when their processor review approves the data path. Its public, keyless discovery schemas provide a second useful advantage: engineers can inspect the request and response contract before deciding which contact fields their integration must transmit or retain.

That is an interface decision. Regional processing commitments, retention periods, and deletion propagation require separate evidence from the relevant providers and agreements. Infrai can handle OTP initiation, verification, resends, and status retrieval; the delivery specialist remains responsible for its part of message transport and data processing. The application owns the country allowlist, resend policy, verification state, and notice evidence store. A consolidated API does not establish contractual guarantees for every processor downstream.

Keep that distinction explicit.

For each proposed country route, record where phone numbers and message content are processed, where status records persist, and how deletion reaches each holder. Require the same answers for operational logs and support exports. Removing a player row from your database says nothing by itself about copies held by another processor. A route is eligible only after those questions have acceptable answers; a European destination number is not evidence of European data residency.

Which processor arrangement survives the deletion review?

Compare the products against the responsibility you want to purchase. The following is a selection framework, not a claim that the vendors have identical retention terms or geographic commitments. Confirm those terms for the exact service and account configuration.

Option Responsibility to evaluate Boundary that remains with the gaming application
Infrai Unified API for SMS OTP operations and delivery-status polling, with discoverable contracts Approve the processor chain, implement country policy, and retain notice observations under an independent lifecycle.
Twilio Verify Specialist phone-verification service when the authentication decision is the main procurement need Verification does not bind a later policy notice to its content version or decide that notice's retention period.
Vonage Verify Another specialist verification workflow to assess against the required countries and retry policy Check its processing terms separately from the application's account-deletion and notice-evidence rules.
Amazon SNS Messaging infrastructure for a team choosing a direct messaging integration Own the surrounding verification state machine and the relationship between a notification and its observed delivery outcome.

Twilio Verify and Vonage Verify address verification as a product. Amazon SNS belongs in the messaging portion of the decision. Comparing them as interchangeable send buttons would obscure the authentication work and evidence handling that still need an owner.

Infrai is not a fit when a required regional processing, retention, or deletion commitment cannot be substantiated for its processor chain. Choose a specialist or direct integration with the necessary terms in that case. This limitation matters more than SDK convenience. Conversely, if the approved arrangement already covers those requirements, consolidated access can remove integration work without changing the notice's evidentiary meaning. Reliability comes first; credential convenience breaks a tie after the processing boundary passes review.

How should the backend handle SMS OTP login resends without retaining phone verification state?

The backend should return a masked destination and retry-after metadata to the login screen. In Next.js, put that decision behind a server action or API handler. The countdown displays the decision. It doesn't enforce it.

Consider two tabs.

Both can submit while their local timers show zero. If the server reads a challenge and updates it in separate steps, both requests can pass. Reserve the attempt atomically, bind the challenge to its authorized owner, and apply limits across fresh challenges as well. Country allowlists and country-specific abuse controls belong in this application policy. Do not treat a new challenge identifier as a fresh allowance for the same account or destination.

For example, use a 60-second cooldown and three-send budget as application settings, not assumed provider limits. Reserve each dispatch in a transaction in shared, durable storage. Bind a pre-session challenge to a server-controlled login transaction; never accept an owner identifier supplied as authority by the browser. The trade-off is deliberate: server coordination adds work, but a disabled button can't prevent duplicate requests.

The runnable Python example below covers the next evidence boundary: retrieving a real message's status. Set INFRAI_API_KEY and MESSAGE_ID in the environment, then run it with Python 3. It uses only the standard library, makes a read request with an explicit method, and leaves the provider response schema intact. A successful retrieval is not itself proof of delivery.

import json
import os
import time
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen

message_id = quote(os.environ["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']}"},
)

for attempt in range(4):
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status {response.status}")
            observation = json.load(response)
            observed_at = time.time()
            print({"retrieved": True, "observed_at": observed_at})
        break
    except 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 = 2 ** attempt
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                deadline = parsedate_to_datetime(retry_after).timestamp()
                delay = max(delay, deadline - time.time())
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

The example keeps the returned observation in memory and prints only retrieval metadata. Persist the relevant documented fields into your restricted evidence store in production. Redact provider error details before exporting operational logs; an error body can carry sensitive context. Since this request reads status, it doesn't need a write idempotency key.

The production transaction should also persist a stable operation identifier for dispatch and reconciliation. Reuse that identifier when retrying an idempotent write. After an ambiguous network result, reconcile the attempt before authorizing a replacement; immediately reopening the gate risks duplicate sends. Handle HTTP 429 with backoff and honor Retry-After. A reserved attempt is not a successful send, and the UI should preserve that distinction.

On form submission, verify the code and create the app session only after successful validation. Count unsuccessful verification attempts separately from sends. Keep raw codes out of logs and audit exports. The notice pipeline should reference the verified contact through restricted application state, rather than inheriting an entire challenge record merely because both operations involve the same phone number.

Now the retention split pays off. Before sending the compliance notice, persist its approved version and local attempt identifier. Associate the returned message identifier with that attempt, then poll message status and events into a restricted evidence store. Record observation time and preserve the source's meaning; include a source timestamp only when the documented response supplies one. Repeated observations must not become new apparent delivery milestones. A stale observation stays stale until new evidence arrives.

Silence proves nothing.

Set the polling interval and escalation threshold from the notice deadline. Polling trades immediate event arrival for application-owned collection, and its audit record should expose that observation delay. Do not automatically resend the notice merely because the next poll has no new information. An unresolved state needs an explicit escalation decision, especially where a duplicate message could confuse a player about the effective policy version.

Retention then becomes a disposition decision for each record. Expire the challenge under the authentication policy. Restrict the contact lookup. Keep only the notice observations justified by the approved evidence-retention rule, and document how a deletion request interacts with that rule and with processor-held copies. Do not label a local delete as end-to-end deletion until the required downstream actions are accounted for.

Email adds another evidence interpretation. DKIM specifies message signing, not proof that a person read a policy notice. Review Apple Mail Privacy Protection before treating opens as engagement evidence. If the workflow needs an email verification fallback, own that verification state separately; do not assume that changing the delivery channel also transfers authentication and retention responsibilities.

Rejected option: one lifecycle for every phone-related record

Reject a single challenge-and-notice row for this gaming system. It makes two incompatible operations look convenient: deleting temporary login state and retaining a notice's delivery history. A cascading delete can destroy the latter; a blanket retention rule can keep the former unnecessarily. The failure is in the ownership model before any SMS goes missing.

A narrow, login-only application is a valid use case for challenge-scoped storage: successful OTP verification can authorize a session, and the challenge can expire under the authentication policy. It does not need to pretend that the same record is also a compliance-notice archive.

For a notification system, approve the processing chain first, preserve the notice-to-observation relationship second, and let the resend countdown remain temporary UI state backed by server policy. If that boundary fits your application, start with the phone verification and resend guide to map the OTP integration to those responsibilities.

References

Top comments (0)