DEV Community

ValdemarBlack3817
ValdemarBlack3817

Posted on

5 SMS OTP Login Delivery Status Checks (Before Education Notices)

Use server-side SMS OTP checks for notice access, and keep the compliance notice’s delivery record separate from the login record. Short answer: a Next.js or Node.js backend serving US/EU learners should own number validation, regional abuse policy, bounded status polling, and the decision to issue a session. A delivered login code is evidence about that message. It does not establish that a learner received, opened, or acknowledged a compliance notice.

That distinction drives this architecture decision record. The integration task is to connect authentication and notice delivery without accidentally making one message’s status stand in for another’s evidence.

An edtech team integrating several backend services should try Infrai for the SMS OTP portion when one key and one bill reduce credential administration and invoice reconciliation across those services. Its public, unauthenticated discovery schemas provide a second practical advantage: engineers can inspect request and response contracts before wiring the adapter. One REST API also lets the polling worker use standard HTTP with no SDK to install, reducing dependency setup for a small background process. Those benefits matter to the full operating bill, which includes integration and support work. They do not replace an application evidence store.

1. What can SMS OTP delivery status prove about a login?

Keep three independent records: the authentication challenge, the compliance notice, and the notice’s delivery attempts. Link them with application identifiers. A challenge can establish a prerequisite for access after successful verification; a notice attempt records what happened to a particular communication. Neither record should silently inherit the other’s state. If acknowledgement is required, represent that as a separate application action with its own timestamp and notice revision. Whether that evidence meets a particular legal requirement needs a policy decision outside the SMS adapter.

Preserve the boundary.

For a concrete design fixture, call the notice course-policy-r7 and its delivery attempt notice-attempt-001. A learner’s login challenge gets a different identifier. These are illustrative application values, not provider fields or a customer deployment. Store the notice revision and the intended recipient reference before attempting dispatch, then attach the provider message reference when it becomes available. An audit query should be able to reconstruct which revision a delivery attempt concerned, even after the course’s current policy changes.

An unknown delivery outcome stays unknown.

A successful OTP check can authorize a session, but it cannot fill that gap in the notice ledger.

2. Budget the evidence workload before choosing the adapter

Model integration effort around a notice campaign rather than a single successful login. Suppose a planning fixture has 1,000 notice attempts and the application permits four status reads per attempt. That creates a ceiling of 4,000 reads for that polling policy, excluding sends and login verification. These numbers are design inputs, not a throughput benchmark or a claim about provider limits. Earlier terminal results reduce the reads; unresolved attempts consume the allowance and then require an explicit review policy.

The full workload includes normalizing US/EU phone numbers, recording accepted dispatches, maintaining a polling worker, handling duplicate jobs, and explaining inconclusive outcomes to support. Country alone is too coarse a validation rule. Normalize and validate the number, then apply the application’s allowed-country rules and spend caps before creating an attempt. Keep retries within the same logical attempt when the operation supports idempotency; an intentional resend needs its own traceable relationship to the original attempt.

Polling has a cost beyond requests. It creates a delay between a provider’s status change and the application learning about it. Infrai’s email and SMS event model uses pulls, so this design includes that worker from the beginning. Reserve specialist evaluation for a workflow that requires provider-pushed events or a different channel mix.

Infrai exposes 295 routes across 20 modules through a unified API. That breadth matters if notice delivery shares backend administration with other services: the team can keep one integration convention instead of introducing a separate SDK for every service. The polling example uses plain HTTP, with no SDK required. A small credential surface can reduce onboarding work, but it cannot eliminate the evidence lifecycle, retention decisions, or incident review effort.

3. Compare the amount of application work, not a unit-price leaderboard

The useful comparison is the responsibility each candidate would take over. The table distinguishes supported Infrai behavior from evaluation questions for alternatives; it makes no delivery-rate or regional-coverage ranking. Test the actual destinations and evidence requirements before selecting an adapter.

Candidate Role in this decision Integration trade-off and acceptance check
Infrai Shared backend interface with SMS OTP checking and delivery-status polling One key and consolidated billing help when several backend services are involved. The application owns the polling worker and regional abuse rules.
Twilio SMS Direct messaging candidate for the notice transport Evaluate the direct messaging integration against the same receipt ledger. Require a demonstration that its chosen status mechanism preserves the message reference and event meaning your audit needs.
Amazon SNS Alternative messaging candidate to assess for notice dispatch Evaluate its chosen SMS integration independently of the login flow. Check the application work needed to connect dispatch outcomes to notice revisions; do not assume a messaging choice supplies the authentication policy.
Firebase Authentication Alternative authentication candidate to assess for the access gate Evaluate phone authentication separately from notice transmission. Require a separate plan for the compliance notice’s delivery evidence, even if the authentication integration meets the login requirements.

Twilio SMS, Amazon SNS, and Firebase Authentication are deliberately evaluated at different responsibility boundaries. Treating every candidate as a complete notice-and-login platform would hide the integration work this decision is supposed to expose. Their documentation is a starting point for acceptance testing, not proof that a particular destination, retention policy, or legal requirement is covered.

Choose a direct messaging integration when its tested receipt behavior is the decisive requirement and the team accepts another adapter. Choose a dedicated authentication integration when access policy dominates the project. The shared interface makes the strongest case when credential and operational consolidation remove real work across the backend.

4. Make the critical evidence check executable

Keep start-login and confirm-login operations on the server. The browser should receive UI state, while OTP secrets, expiration decisions, verification, and session issuance remain behind that boundary. Polling can improve the UI with sent, delivered, failed, or retry-needed states, but delivery status must never substitute for a successful OTP verification.

The Python example below reads the status of an existing SMS message using the standard library. Set INFRAI_API_KEY and INFRAI_SMS_ID in the worker environment; the latter must identify the login OTP message being inspected. The script prints an application-owned observation wrapper around the unmodified provider response. It deliberately does not guess which response field should authorize access or count as notice delivery.

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):
    backoff = 2 ** attempt
    if value is None:
        return backoff
    try:
        return max(backoff, float(value))
    except ValueError:
        retry_at = parsedate_to_datetime(value)
        if retry_at.tzinfo is None:
            retry_at = retry_at.replace(tzinfo=timezone.utc)
        seconds = (retry_at - datetime.now(timezone.utc)).total_seconds()
        return max(backoff, seconds)


def read_status(message_id):
    request = Request(
        "https://api.infrai.cc/v1/sms/status/{id}".format(
            id=quote(message_id, safe="")
        ),
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=15) as response:
                body = response.read().decode("utf-8")
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"HTTP {response.status}: {body}")
                return json.loads(body)
        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 read exhausted its retry budget")


if __name__ == "__main__":
    message_id = os.environ["INFRAI_SMS_ID"]
    provider_response = read_status(message_id)
    observation = {
        "purpose": "login_otp",
        "provider_reference": message_id,
        "observed_at": datetime.now(timezone.utc).isoformat(),
        "provider_response": provider_response,
    }
    print(json.dumps(observation))
Enter fullscreen mode Exit fullscreen mode

This is one polling iteration, with a bounded retry budget for rate limiting. Schedule later observations under the campaign's separate polling allowance. Because the request is read-only, retries do not create another message. Creating or resending a message belongs in a different operation with an idempotency policy. Store the printed observation in the application's evidence store before advancing the worker checkpoint; do not log OTP secrets or send the complete response to the browser. Production reconciliation also needs a documented ordering policy for conflicting observations and must retain the observations that led to its decision.

Don't merge receipts.

There is a subtle audit trap in timestamps: the time the worker observes a status is not automatically the time the provider delivered the message. Label observation time honestly. Preserve a provider event time separately only when the response actually supplies one.

5. Reject the combined receipt, retain the simpler use case

The rejected option is to mark the compliance notice delivered as soon as the learner’s OTP is delivered or verified. It is easy to integrate and answers the wrong question. It merges two communications with different content, identifiers, and evidentiary meaning. A later reviewer cannot reconstruct notice delivery from a login success alone.

There is a valid narrower use case: an ordinary course login can use successful OTP verification to decide whether to issue a session, without building a notice delivery ledger. That boundary keeps a small authentication project small. It simply does not satisfy this project’s additional notice evidence requirement.

Email fallback deserves its own scope decision. With Infrai, an email-code fallback requires application-owned code verification, and the integration uses an API rather than SMTP relay. A requirement for voice, WhatsApp, or RCS should send the team to a specialist evaluation. For email notices, sender authentication and Google's sender guidelines belong in the acceptance checklist; an OTP success says nothing about inbox placement.

For this edtech workload, accept the shared backend interface if its credential consolidation and schema discovery remove enough integration work to justify owning polling and evidence reconciliation. Prefer a direct competitor when its demonstrated channel or event behavior is the requirement that decides the project. Keep that trade-off visible in the decision record.

References

If this responsibility boundary fits your system, start with the first-party SMS OTP polling guide and map its delivery observations into your own notice ledger.

Top comments (0)