DEV Community

SilasFletcher5857
SilasFletcher5857

Posted on

2026 SMS 2FA Login: Backend Templates Beat Hosted Templates for Delivery Status

A signup verification alert needs to tell the on-call which backend obligation is overdue. Consider a proposed page: an account is still waiting for its verification link, its SMS 2FA login flow has no useful delivery status update, and the signup deadline is approaching. The dashboard shows accepted send attempts. That doesn't explain whether the customer can finish creating an account.

TL;DR: Choose application-owned templates and a small backend state machine when your B2B SaaS team owns signup copy, link security, and failed-send decisions. Send the verification link, track the associated SMS 2FA attempt, and schedule status checks before offering a bounded retry or an alternate login method. Hosted templates fit better when another team must publish copy independently. Delivery status informs the decision; successful verification authorizes access.

The operational choice is where the template contract lives. A transport can accept a request while the application still owes the customer a usable verification path. Put that obligation on the dashboard.

How should a backend poll SMS 2FA login delivery status before paging?

Start with the alert above and work backward. This is a design exercise, not an incident report: the proposed failure is that nobody notices an aging verification attempt until the signup deadline expires. The earlier signal should be the age of the oldest unresolved attempt, accompanied by the age of its last successful status observation. Those are different clocks. A healthy poller can keep receiving an unresolved result; a stalled poller can leave the application staring at an old one.

Separate the clocks.

For the signup link, record the application attempt identifier, template revision, link expiry, send acceptance time, and verification outcome. For its SMS 2FA companion, record the provider message identifier, last status check, next check deadline, and the backend's retry decision. These are proposed application fields, not a vendor request schema. Keep the link token, OTP, email address, and phone number out of metric labels. An opaque attempt identifier belongs in restricted diagnostic records when investigation needs it.

An accepted send is evidence of submission. A delivery observation is transport evidence.

Neither proves possession.

The backend must still validate the challenge before changing account access. This distinction matters during recovery: treating a delivered SMS as a completed login would turn an observability shortcut into an authorization error.

Template ownership makes this trace useful. With application-owned rendering, the attempt can record the exact revision selected by the release. With hosted templates, define how the team records which published revision the send used. In either arrangement, keep the challenge's security rules in the backend rather than letting a copy edit define token lifetime.

App-owned versus hosted templates changes the runbook

For this workflow, prefer application-owned templates if engineering already approves signup behavior through code review. A release can carry the link placement, explanatory copy, and expected variables together. The trade-off is operational: a harmless wording correction may need the same deployment process as other application changes. A centralized copy team may reasonably reject that delay and choose hosted templates instead.

The following products are distinct candidates, not interchangeable bundles. Evaluate their current documentation against the same ownership test; this comparison does not assert a measured delivery advantage for any of them.

Candidate Relevant role in this decision Boundary to resolve before adoption
Twilio Verify A verification-focused candidate for the SMS challenge portion Decide how its challenge workflow maps to the application's signup-link state and template approval process. It is a different scope from an email template service.
SendGrid An email candidate to evaluate when hosted template ownership is the deciding requirement Check how published template revisions are identified in application records. Keep SMS verification and account authorization responsibilities explicit.
Amazon SES An email candidate to evaluate when the application team owns the surrounding send workflow Determine where rendering, revision approval, and delivery reconciliation will run. Email transport alone does not specify the SMS login policy.

Infrai is another strong fit when the team wants email, SMS, scheduling, and observability through one REST API with a single API key: its discovery surface covers 295 routes across 20 modules, so adding a capability means another endpoint under the same contract. Its specified idempotency convention is a useful supporting advantage for retry discipline, subject to the individual capability's schema; choose it here when scheduled status polling and application-owned fallback decisions satisfy the signup requirements.

That fit has a boundary. A requirement for immediate orchestration across SMS, voice, and chat applications calls for a different evaluation. For the polling design here, keep destination eligibility and country-based spending limits in business logic. Treat an alternate email verification path as application authentication work, with its own token validation and expiry, rather than assuming that switching transports completes verification.

The recommendation stays conditional: app-owned templates win when a release must explain exactly what a customer received. Hosted templates win when independent publishing is a stronger requirement and the team can preserve revision evidence. Neither ownership model removes the need for a delivery runbook.

Instrument the obligation, then schedule the check

Add the measurement at attempt creation, before sending anything. The durable attempt record is the source for the unresolved-age signal. Add the provider message identifier after submission, then let a scheduled worker reconcile status and events for pending SMS attempts. Persist the next deadline as well as the latest observation. A request log by itself cannot tell a replacement worker what work remains.

Use two identifiers. One identifies the logical verification attempt and remains stable through a transport retry. Another identifies a deliberate resend decision. Otherwise a double-click and a new user-requested challenge can collapse into the same operation, or a timeout retry can become an unintended second message. Persist the decision before submitting the write, and use the supported idempotency mechanism for the selected operation.

For example, a staging exercise could create 100 synthetic signup attempts with template revision signup-link-r7. Leave one attempt unresolved and pause reconciliation for another. These are test inputs, not production measurements. The first should make unresolved age grow while observation freshness remains healthy; the second should make the freshness signal deteriorate. Then verify that two workers racing on one retry decision produce one logical send decision. Extend the exercise by changing the template revision while those attempts remain open. A worker recovering an older attempt should retain its original revision evidence, while a newly authorized send records the revision actually used. Finally, complete verification before releasing a delayed status check. That observation must not reopen the attempt. This sequence tests the interaction between template ownership and recovery rather than merely checking that an alert expression becomes true. Without it, the alert may work perfectly while the recovery action duplicates delivery or obscures which link instructions the customer received.

Keep scheduling policy small enough to inspect. In that staging exercise, test a freshness allowance of 30 seconds and an attempt budget of 120 seconds. These are illustrative test settings, not delivery guarantees or recommended universal thresholds. A stale observation should direct investigation toward reconciliation; an overdue attempt with fresh observations should direct investigation toward delivery and the next permitted verification option.

Don't resend yet.

The first diagnostic action can be a read. This Go program checks one existing SMS message and prints the response without assuming any undocumented status fields. Configure INFRAI_BASE_URL with the service's documented versioned API base, ending in /v1; inject INFRAI_API_KEY through the environment and set SMS_MESSAGE_ID to the message being investigated. Save the program as status.go and run it with go run status.go. It performs no send or resend. A production worker should persist its next poll deadline rather than occupy a process while waiting.

package main

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

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

func run() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    id := os.Getenv("SMS_MESSAGE_ID")
    parsed, err := url.Parse(base)
    if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
        parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||
        parsed.Path != "/v1" || key == "" || id == "" {
        return fmt.Errorf("set an HTTPS versioned API base, API key, and message ID")
    }
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    // GET /v1/sms/status/{id}; this read does not create a message.
    endpoint := base + "/sms/status/" + url.PathEscape(id)
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequest(http.MethodGet, 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(io.LimitReader(resp.Body, 1<<20))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                candidate := time.Duration(seconds) * time.Second
                if candidate > delay {
                    delay = candidate
                }
            } else if until, err := http.ParseTime(retryAfter); err == nil {
                if candidate := time.Until(until); candidate > delay {
                    delay = candidate
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("status check returned HTTP %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("status check retry budget exhausted")
}
Enter fullscreen mode Exit fullscreen mode

The worker still needs the persisted challenge expiry, current account state, retry budget, and concurrency guard. Recheck those conditions when claiming work. A scheduled check can run after the user has already verified the link.

For rate-limited requests, respect the provider's retry guidance and use backoff rather than a tight polling loop. Maintain a bounded observation schedule that ends when the application attempt closes or expires. If the process restarts, reconstruct pending work from durable deadlines. Do not depend on an in-memory timer surviving deployment.

Recovery must preserve the template evidence

When an alert fires, first determine whether observations stopped or delivery remains unresolved. Restore reconciliation in the first case. In the second, inspect the attempt's latest transport evidence and challenge validity before deciding on retry or alternate verification. Do not restart every pending attempt merely because its dashboard row is old.

A template correction is a separate decision from a resend. If a link is expired, changing the email wording cannot revive it. If wording is unclear, blindly regenerating a challenge may make the customer's earlier message misleading. Record the revision on every new send and define which outstanding challenges remain valid. Keep that policy identical across worker recovery and user-triggered resend.

One small runbook rule prevents a large class of confusion: a successful verification closes the application obligation, even if a later delivery observation arrives. Process late observations for audit without reopening access decisions.

Transport events should not roll account state backward.

This is also the point to distinguish a signup problem from a sender problem. Review email sender requirements separately from application retries. A retry policy cannot substitute for correct sender configuration, and a template platform does not own the application's authorization boundary.

Tune the page against its false-positive cost

Start with the user-facing verification deadline and the expected observation schedule. Set a warning early enough for an operator or automated recovery step to act before expiry. Use a separate freshness condition to expose missing reconciliation. Choose concrete thresholds through controlled tests and observed traffic; the illustrative values above establish neither a service objective nor a provider performance claim.

Then measure the cost of being wrong. An aggressive age threshold can wake an operator while the customer is still reading the email. If the same threshold automatically resends, it can also create extra messages, challenge confusion, and more support work. A loose threshold lets abandoned signup attempts remain invisible until recovery is no longer useful.

Keep the first warning informational until the recovery policy proves it can distinguish a slow customer from stale delivery evidence. Page on an actionable breach of the verification objective. The useful outcome is a completed, correctly authorized signup with an explainable template revision. Every unnecessary page spends attention that the next failed signup may need.

Further reading

References for the verification, template, and sender-policy review:

Top comments (0)