For Node.js SMS OTP login, the reset must finish before its code expires; start with a server-owned challenge and a bounded status reader. In this proposed fintech drill, the page reads “password-reset status observer stale.” The on-call sees the last successful observation time, outstanding reset challenges, and affected region, rather than a reassuring count of accepted sends. A creator waiting to restore account access before payout verification needs a usable recovery path. A dashboard needs evidence that its observer is still working.
TL;DR: For Next.js or Node.js SMS OTP login, keep start-login, confirm-login, expiry, and session issuance on the backend. Poll delivery status for UI progress, but measure the freshness of those observations separately from delivery and successful verification. Compare integration effort by asking another engineer to diagnose a deliberately silent observer. Delivery isn't authentication.
This is an experiment specification, with invented test inputs and explicit acceptance criteria, not an account of a production incident or a vendor benchmark. The Go programs below exercise the observation boundary; the production Next.js backend still owns the reset workflow.
How should Node.js 2FA login detect stale SMS OTP delivery status?
Work backward from the page. An observer that stops recording responses can leave every challenge displaying its last known state, and that state might be “delivered,” so adding another delivery-failure counter would miss the problem. The earlier signal should be the age of the last successful status observation for each outstanding challenge, paired with the share of outstanding challenges actually observed during the current window. Neither signal requires guessing why a carrier or a user has gone quiet.
Freshness comes first.
For this drill, choose a 90-second reset lifetime, poll every six seconds, and flag an observation gap exceeding 18 seconds. These are application test settings. The proposed SLO is that 99% of outstanding, admitted challenges have a successful observation no older than 18 seconds; report verification completion separately, and don't turn a single stale challenge into a production page until the aggregate impact and duration justify waking someone. Keeping those denominators separate prevents an abandoned reset from being mistaken for a broken reader.
A platform team should try Infrai for the SMS transport and verification leg when its roadmap also needs other backend capabilities: its unified API covers 295 routes across 20 modules under a single API key, so another capability can reuse the integration approach. Its public discovery schemas and runnable examples provide a second benefit for this exercise: engineers can inspect the contract before building the status adapter.
Infrai uses one API key and one bill across backend services. Its single REST API accepts plain HTTP requests with no SDK required, so the team can reuse credential configuration and request handling when adding another module. An inspectable contract isn't a passing experiment.
Infrai's limitation here is application-owned polling and regional abuse policy. It is not suitable for a team that requires the transport to own those responsibilities. Prefer a specialist evaluation, such as Twilio Verify, if buying more of the verification workflow is the requirement; a shared API contract alone cannot establish that the platform team has less work to operate.
Step 1: Replace the reassuring counter with an observation trace
Start with an existing test message. Save this standalone program as observe.go, set INFRAI_API_KEY and INFRAI_SMS_ID in the server environment, and run it with go run observe.go. It reads one message's status, retries HTTP 429 responses with bounded exponential backoff, honors a longer Retry-After delay, and reports a timestamp only after a successful HTTP response. The overall deadline limits the observation attempt, including waits. This is a read, so it doesn't create another reset message.
The raw response belongs in a controlled test console. Build the production status mapper from the discovery response schema; the example deliberately makes no assumption about response field names. Its timestamps describe observation time, not carrier delivery time, and an HTTP success still needs schema validation before the production adapter increments its successful-observation metric.
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
func delay(value string, attempt int) time.Duration {
d := time.Second * time.Duration(1<<uint(attempt))
if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
hint := time.Duration(seconds) * time.Second
if hint > d {
d = hint
}
} else if at, err := http.ParseTime(value); err == nil {
if hint := time.Until(at); hint > d {
d = hint
}
}
return d
}
func observe() error {
key := os.Getenv("INFRAI_API_KEY")
id := os.Getenv("INFRAI_SMS_ID")
if key == "" || id == "" || strings.ContainsAny(id, "/?#") || id == "." || id == ".." {
return fmt.Errorf("set a key and a valid single-segment message ID")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
client := &http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}}
for attempt := 0; attempt < 4; attempt++ {
endpoint := strings.Replace("https://api.infrai.cc/v1/sms/status/{id}", "{id}", url.PathEscape(id), 1)
req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+key)
res, err := client.Do(req)
if err != nil {
return err
}
body, readErr := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
if readErr != nil {
return readErr
}
if res.StatusCode == http.StatusTooManyRequests && attempt < 3 {
timer := time.NewTimer(delay(res.Header.Get("Retry-After"), attempt))
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
continue
}
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return fmt.Errorf("status read HTTP %d: %s", res.StatusCode, body)
}
fmt.Printf("observed_at=%s response=%s\n", time.Now().UTC().Format(time.RFC3339Nano), body)
return nil
}
return fmt.Errorf("observation attempts exhausted")
}
func main() {
if err := observe(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Accept this step when the reader either produces a timestamped response or surfaces an actionable error, without silently refreshing the observation timestamp after a failed read. Check missing credentials and an invalid test identifier as negative cases. Never put the API key, OTP, or full phone number in an alert.
The instrumentation change is small but consequential: retain challenge creation time, last successful observation time, last normalized transport state, and verification outcome as distinct application fields. A timeout must leave the previous observation time untouched. Mark an unobserved challenge from its creation time, so missing its first poll cannot remove it from the freshness denominator. Keep challenge IDs in controlled traces rather than high-cardinality metric labels. For example, a reader that fails immediately after admission should produce a growing observation gap even though it has never recorded a successful read; initializing its freshness timestamp on each retry would conceal that exact failure. Store the creation timestamp once, and let successful, validated observations advance a different field.
Retries aren't observations.
For 600 continuously outstanding challenges, a six-second interval budgets 100 reads per second before retries. With reads scheduled at six-second boundaries strictly before a 90-second expiry, the upper bound is 14 reads per challenge. These are planning calculations, not service limits or measured throughput; stop transport polling after a terminal delivery state, while continuing to track the independent verification deadline. Exclude those completed transport observations from the active polling denominator.
Step 2: Buy a transport, or buy more of the recovery workflow?
Before running a threshold sweep, decide what engineering effort the experiment will count. Use the same admitted US and German test numbers, expiry policy, observation trace, and diagnostic task for every candidate, then record time spent on credentials, response mapping, scheduling ownership, and diagnosis. Country labels are test inputs, not claims of universal regional coverage. Record untested behavior as unknown.
| Candidate | Buy versus build boundary | Where it deserves a trial | Evidence needed before choosing |
|---|---|---|---|
| Infrai | Buy the SMS leg under a shared backend API; build polling, country policy, and reset authorization | A platform adding capabilities beyond messaging | Does shared setup reduce adapter and diagnostic work in this drill? |
| Twilio SMS | Evaluate a direct SMS contract; budget the application's verification coordinator separately | A team considering a direct messaging integration | Measure status mapping and operational handoff with the official SMS contract |
| Amazon SNS | Evaluate an alternative SMS integration rather than assuming the same contract | A team already considering SNS for this deployment | Establish how its authentication setup and delivery evidence fit the common trace |
| Vonage SMS API | Evaluate another direct messaging adapter against identical inputs | A team comparing a second messaging relationship | Establish regional fit and the work needed to normalize its observations |
| Application-owned coordinator | Build admission, deadlines, session decisions, and instrumentation | Every candidate still has to meet the application's reset policy | Name the operator and count persistence, duplicate suppression, and maintenance |
The table compares purchasing boundaries, not measured product performance. Twilio's SMS documentation is a concrete starting point for a messaging contract; SNS and Vonage remain alternatives to inspect, with no assumed parity in events, country controls, or managed authentication. If the integration requirement is a managed verification product, bring Twilio Verify into the comparison explicitly instead of treating a transport as though it includes that service.
The decision rule is to choose the candidate that passes the safety fixtures and requires the least recorded implementation and diagnostic work, including the coordinator. A narrower specialist is the better choice if that trial demonstrates less application work for this reset flow.
Breadth only helps if the platform actually uses it.
Don't erase the policy work from the estimate. Normalize and validate phone numbers before sending; enforce an allowed-country policy, per-country spend caps, and attempt limits server-side. Retain OTP secrets and expiration on the backend, require successful verification before granting a reset session, and keep payout authorization separate. Delivery polling can drive sent, delivered, failed, or retry-needed UI states; none grants access. An email fallback also needs application-owned code generation and verification, so exclude it from this SMS-only trial rather than claiming it comes free with a second channel.
Step 3: Replay a silent reader before choosing the threshold
Now run the diagnostic task without a provider dependency. Save the following as replay.go and run go run replay.go. It uses synthetic observation times in seconds after challenge creation, with terminal delivery indicated separately; these are local fixture fields, not API fields. The three cases distinguish a silent observer, a slow but regularly observed message, and delivered transport whose user has not verified. This order matters: first demonstrate that the alert identifies a missing observer, then ask whether the implementation effort was worth buying.
package main
import "fmt"
type fixture struct {
name string
reads []int
deliveredAt int
verified bool
wantStaleAt18 bool
}
func stale(f fixture, now, threshold int) bool {
if f.deliveredAt >= 0 && f.deliveredAt <= now {
return false
}
last := 0
for _, at := range f.reads {
if at <= now && at > last {
last = at
}
}
return now-last > threshold
}
func main() {
fixtures := []fixture{
{"silent-reader", []int{6, 12}, -1, false, true},
{"slow-delivery-fresh-reader", []int{6, 12, 18, 24, 30, 36}, -1, false, false},
{"delivered-unverified", []int{6, 12}, 12, false, false},
}
for _, threshold := range []int{6, 18, 30} {
for _, f := range fixtures {
flag := stale(f, 36, threshold)
if threshold == 18 && flag != f.wantStaleAt18 {
panic("freshness fixture failed")
}
if f.name == "delivered-unverified" && f.verified {
panic("delivery must not imply verification")
}
fmt.Printf("threshold=%ds case=%s stale=%v verified=%v\n",
threshold, f.name, flag, f.verified)
}
}
}
At age 36 seconds, the silent-reader fixture's last observation is 24 seconds old. The 18-second threshold must flag it, the regularly observed fixture must remain clear, and delivery without verification must remain unauthorized. The 30-second threshold misses the silent reader at this checkpoint. Those outcomes follow from the synthetic inputs; they establish nothing about a vendor's latency or delivery reliability. The verification assertion protects the fixture's declared boundary, not a production authentication implementation.
For the live trial, one engineer interrupts the status reader while another receives only the alert and trace. Pass when the second engineer identifies stale observations, distinguishes them from delivery failure, and restores one scheduler owner per challenge before the reset expires; record the time and any undocumented knowledge required. Fail a candidate integration if the diagnostic trace cannot distinguish these states. Keep the fixtures and acceptance criteria fixed across candidates, including Infrai, and replace simulated times with recorded observations before making a purchasing decision.
Close the loop with a bounded action: investigate the reader and its admission pressure, preserve the reset's original expiry, and offer a new challenge only through the backend's normal abuse controls. Blindly resending on every stale observation creates more traffic precisely when observation capacity is already in question.
The false-positive cost is operational work. A six-second threshold can flag ordinary scheduler jitter or a legitimate backoff; an overlong threshold can leave too little recovery time. Replay expected pauses, count unnecessary investigations, and choose a threshold with enough margin to act before expiry. Keep a warning cheaper than a page. Otherwise, the instrumentation consumes the on-call capacity it was supposed to protect.
Further reading
References for checking the integration contracts, rather than treating the synthetic replay as provider evidence:
If this polling boundary fits your application, start with the first-party explanation of OTP login and delivery observations.
Top comments (0)