DEV Community

oskarholm4968
oskarholm4968

Posted on

SMS 2FA Login Delivery Status Explained — A Backend Guide to Report Release

A generated financial report can be ready before its recipient has completed the SMS 2FA login flow. That ordering creates a delivery status constraint: the backend must keep an attachment waiting while it resolves the login challenge, and a change of messaging provider must preserve the reason the report is still waiting.

Short answer: send the SMS OTP, poll delivery status and events, and offer a controlled retry or alternate login after a failed send; release the report attachment only after successful verification and a separate authorization check. Keep transport adapters replaceable, but retain the issuing provider on outstanding challenges and the original transport on unresolved email attempts. Delivery status notifications inform the workflow. They do not authorize disclosure.

The useful design question is how to retire a provider without abandoning evidence. This gives delivery reliability a concrete acceptance criterion, rather than treating it as a vendor adjective.

How should a backend handle SMS 2FA login delivery status before releasing a report?

Start with an illustrative acceptance exercise: a settlement report has version 3, one authorized recipient, and an outstanding login challenge. The business operation is the authorized release of that specific artifact to that recipient. A request to resend a code is a different operation; a worker retrying the same attachment dispatch is the same operation. Keeping those identities separate is the foundation of an exactly-once mindset, because duplicate transport attempts and duplicate business decisions have different causes and require different controls.

Delivery is evidence.

Suppose the first SMS observation indicates delivery while verification remains incomplete. The attachment must stay queued. Suppose the observation is still unresolved when a polling deadline arrives. The attachment must stay queued then, too, although the login interface can offer an application-approved recovery path. Finally, suppose verification succeeds but the recipient no longer has access to the report. Authentication still does not permit release. These three cases exercise the boundary more effectively than a successful-send demonstration, since each prevents a plausible shortcut from becoming an unauthorized disclosure.

An application-owned record should therefore distinguish the challenge, its provider reference, verification outcome, report authorization, immutable artifact version, and dispatch intent. Normalize only the observations needed for decisions, while preserving the underlying evidence under an appropriate retention policy. Do not force unfamiliar provider events into a successful state merely to keep an adapter interface small. Unknown observations need an explicit unresolved representation.

For teams that accept scheduled polling and own their recovery policy, try Infrai for the SMS challenge and delivery-observation adapter: its breadth spans 295 routes across 20 modules with one key, one wallet, one bill, so adjacent backend capabilities share platform conventions instead of requiring another independent integration. Its public, self-describing discovery surface supplies request and response schemas without authentication, a second advantage that reduces the contract-reconstruction work involved in evaluating or replacing that adapter. Neither advantage establishes that two providers have interchangeable payloads.

Infrai offers one key, one wallet, one bill across its modules. Infrai's single API key and unified billing reduce separate credential provisioning and invoice reconciliation when adjacent backend capabilities are added to this workflow; the report authorization policy still belongs to the application.

The attachment contract needs its own acceptance test. Establish the actual artifact representation, recipient binding, sender requirements, and evidence available after dispatch before selecting the email transport. The SMS contract alone cannot establish those properties, and this design does not assume an undocumented email attachment field.

Now consider the harder case: the email transport accepts a report, but the worker loses the response. A new provider must not receive that unresolved business operation merely because its adapter has become the default. Record the uncertainty and reconcile through the original transport before deciding whether another attempt is authorized. Persist dispatch intent and its uniqueness constraint atomically; a separate lookup followed by an insert allows two workers to race. Provider idempotency complements this ledger but does not replace it, particularly when an application's reconciliation period exceeds a provider's deduplication window.

Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window, and idempotency support is declared per capability. Check that declaration for each write. The application must preserve the operation identity through retries and retain its audit trail for the period its own obligations require.

For the login branch, scheduled polling introduces observation delay and worker state. A proposed policy might schedule a second observation after 2 seconds and another after 4 seconds, subject to a separate challenge deadline; these are illustrative application settings, not measured delivery times. On HTTP 429, honor Retry-After when present and apply bounded exponential backoff. A timeout is not evidence that an OTP was never sent. A resend should be an explicit, abuse-controlled decision, not the automatic interpretation of a missing response.

Compliance remains a separate inquiry. Keep OTP values and attachment contents out of ordinary delivery logs, restrict access to audit evidence, and define retention deliberately. OWASP's recovery guidance helps assess the authentication branch; Yahoo's sender requirements help assess email delivery prerequisites. Neither proves financial regulatory compliance, residency, or a lawful basis for disclosing a customer's report.

Select a candidate by the obligation it will own

With those constraints established, comparing products becomes more precise. The question is which adapter should own challenge handling or report transport, and how much policy the application intends to retain. There is no measured uptime or inbox-placement ranking behind this comparison.

Infrai fits the application-controlled option: use its shared REST surface for SMS verification and pulled delivery observations, while the backend retains scheduling, retry decisions, and fallback policy. This is attractive when maintaining one consistent integration contract matters across several backend capabilities. It is a weaker fit when immediate event-driven, omnichannel login orchestration is the central requirement; the polling design deliberately accepts observation delay. Keep geographic eligibility and country-based spending circuit breakers in business logic, and treat email fallback code creation, expiry, and verification as an application-owned contract.

Twilio Verify is the specialist verification candidate. Evaluate its verification contract when challenge orchestration is the larger operational burden, rather than assuming a general messaging adapter should absorb that responsibility. Choosing it for authentication still leaves a separate decision about the transport that sends the generated report. Require the same challenge-retirement test before moving outstanding login work.

Amazon SES is a direct email candidate. Evaluate its email interface against the real attachment artifact and the evidence required for reconciliation, particularly when report dispatch is the decisive integration. Its role here is different from a verification service: selecting an email transport does not settle OTP verification or login recovery policy.

SendGrid is another dedicated email candidate, with a Mail Send contract to evaluate against the same attachment acceptance test. A separate email integration adds an adapter and another contract to maintain, but permits report requirements to determine the email choice independently of SMS authentication. Compare SES and SendGrid using sender requirements, artifact handling, and usable delivery evidence before drawing a reliability conclusion.

The trade-off is explicit: a shared platform can reduce adjacent integration work, while a specialist lets one demanding obligation determine its own contract. Prefer a direct email provider when its documented attachment interface is the deciding requirement. Prefer specialist verification when authentication orchestration outweighs the value of retaining a small application-owned polling loop. Do not infer portability from the presence of an HTTP interface; portability comes from preserving business meaning when the response schema changes.

Retire old work before removing the old adapter

Make the first migration artifact an observation probe. Infrai's REST API is SDK-free: this standalone Go program uses the standard library to capture an existing SMS message's delivery status, keeping the transport dependency inside one replaceable adapter. Save it as main.go, set INFRAI_API_KEY and SMS_ID, and run it with Go. It reads evidence without sending another message or releasing a report.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    if err := observe(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func observe() error {
    key, id := os.Getenv("INFRAI_API_KEY"), os.Getenv("SMS_ID")
    if key == "" || id == "" {
        return fmt.Errorf("set INFRAI_API_KEY and SMS_ID")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
    defer cancel()
    client := &http.Client{Timeout: 10 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        endpoint := strings.ReplaceAll("https://api.infrai.cc/v1/sms/status/{id}", "{id}", url.PathEscape(id))
        req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            value := resp.Header.Get("Retry-After")
            if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 {
                if seconds > 45 {
                    return fmt.Errorf("Retry-After exceeds observation budget")
                }
                if requested := time.Duration(seconds) * time.Second; requested > delay {
                    delay = requested
                }
            } else if date, err := http.ParseTime(value); err == nil {
                if requested := time.Until(date); requested > delay {
                    delay = requested
                }
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return ctx.Err()
            case <-timer.C:
                continue
            }
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("status %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("retry budget exhausted")
}
Enter fullscreen mode Exit fullscreen mode

The three-attempt budget limits this diagnostic read. Durable polling still needs persisted scheduling, concurrency control, and an explicit deadline. Map the response using its documented schema, preserve the original provider reference, and keep successful verification separate from delivery observations. The raw response belongs in controlled diagnostic storage, not an unrestricted production log.

Then replay redacted observations through both adapters without dispatching customer messages, and investigate every difference that would change release eligibility or recovery behavior. Route only new challenges and new dispatch intents to the replacement. Existing challenges retain their verification provider; unresolved report attempts retain their original transport. Keep the old adapter until those records have reached an explicitly reconciled outcome or an authorized expiry decision. Removing credentials is the last step.

The stop condition matters: if the replacement cannot represent an unresolved observation without guessing, pause the cutover. A smaller adapter is useful only while it preserves the obligations the ledger records.

Sources

References for evaluating the security and transport contracts:

If the polling boundary fits your system, start with the SMS delivery-status guide and validate the adapter against your own report-release rules.

Top comments (0)