Gate seller SMS OTP resends in the backend, record why each attempt was allowed, and release an authenticated session only after verification succeeds. TL;DR: the resend button displays a deadline; the server enforces it. For an edtech marketplace notifying an instructor about a new order, phone login evidence and order-notification evidence belong in separate records, even when the same phone number receives both messages.
A successful SMS request cannot establish that the seller has authenticated, and a valid code cannot establish that an order alert reached its destination. Those distinctions determine what the audit trail can honestly say. The useful implementation target is a backend that can explain its decisions across US and EU routing policies, with a browser countdown that survives refreshes without becoming an authorization control.
This guide uses Go for executable policy examples. A Next.js server action or API route can put the same boundary in front of its provider adapter, returning a masked destination and retry-after metadata. The examples exercise application policy locally; they don't send messages or create production sessions.
1. How should phone login SMS OTP verification handle a backend resend countdown?
Start with the dangerous signal: an application session exists without a successful verification result, or an operator cannot explain which routing policy permitted the attempt. Either signal warrants stopping new challenges for the affected application route while preserving the evidence already collected.
Delivery is separate.
For a hypothetical instructor selling a calculus course, an evidence record should connect an application-generated challenge identifier, a seller identifier, the routing-policy version, decision timestamps, and the provider correlation identifier when one is available. Record the outcome of verification without storing the submitted OTP in operational logs. The order alert should reference the order and seller, rather than inherit a claim that phone verification means an order was received. These are proposed application records, not promised provider response fields. Country allowlists and routing decisions belong in the application; a country code by itself doesn't prove processing location, lawful purpose, or an approved retention arrangement. Obtain that evidence through the procurement and compliance review appropriate to the deployment.
The buy-versus-build decision follows from the evidence you need to retain:
| Option | Useful starting point | Trade-off and selection boundary |
|---|---|---|
| Twilio Verify | Managed verification, when the desired purchase is the challenge lifecycle | Confirm supported channels, country controls, evidence access, and the contract for the intended deployment. |
| Amazon SNS | Messaging, when the application will own verification state | Budget engineering and on-call time for the challenge lifecycle and evidence store. |
| Firebase Authentication | Phone authentication, when identity management is the desired purchase | Check the fit between its identity lifecycle, seller accounts, session handling, and evidence export requirements. |
| Infrai | 295 routes across 20 modules under one key, allowing communications and adjacent backend capabilities to share a consistent REST contract; per-call request, vendor, and latency metadata can support correlation | Keep resend limits and country routing in application policy, and budget for status/event polling in the evidence pipeline. |
| Application-owned policy and evidence store | Direct control of decision records and release criteria | Your team owns concurrency, retention, recovery, and the pager when the decision store is unavailable. |
The limitation of buying a broad backend surface is that integration consistency doesn't establish compliance evidence for a particular deployment. Choose Twilio Verify when an outsourced verification lifecycle is the better fit; evaluate Firebase Authentication when the intended purchase includes identity management, or SNS when the application deliberately owns verification. None of these names is a certification ranking. A platform roadmap should count the operational work each purchase removes alongside the identity model and integration boundary it introduces.
Capacity planning belongs here, before someone adds a poller to every open browser tab. Save the following standalone Go program as main.go and run it with go run main.go to estimate polling load for a proposed concurrency level:
package main import "fmt" func main() { activeChallenges := 1200 pollIntervalSeconds := 15 pollsPerMinute := (activeChallenges*60 + pollIntervalSeconds - 1) / pollIntervalSeconds fmt.Printf("Planning load: %d polls/minute\n", pollsPerMinute) } Those are scenario inputs, not traffic measurements or provider limits. They imply 4,800 polls per minute before retries; if the poller cannot afford that workload, coalesce observations in a backend worker and let the UI read application state. Set a separate evidence-freshness SLO, then choose a polling interval that fits both the SLO and the available request budget. A delivery-latency claim needs delivery measurements.
2. Implement the countdown as a server decision
Use an absolute server deadline for resends. A remaining-seconds value is useful for display, but the next request must be checked against authoritative state, including the attempt limit and current country policy; otherwise two tabs can each appear entitled to send the next code.
The following program is a runnable state-transition model. It chooses a 60-second cooldown and a maximum of 5 code submissions as example application policy. Neither number is a vendor default. The masked destination is application-generated, and the retry delay is rounded up so that a fractional second doesn't tell the UI to retry too early. Save it separately as main.go and run it with go run main.go.
package main import ( "fmt" "math" "time" ) type Challenge struct { NextResend time.Time Attempts int Verified bool } type Decision struct { Allowed bool RetryAfterSeconds int MaskedDestination string Reason string } func resend(c *Challenge, now time.Time, countryAllowed bool) Decision { d := Decision{MaskedDestination: "+1 ******0100"} switch { case !countryAllowed: d.Reason = "country_policy_denied" case c.Verified: d.Reason = "challenge_already_verified" case c.Attempts >= 5: d.Reason = "verification_attempt_limit" case now.Before(c.NextResend): d.Reason = "cooldown" d.RetryAfterSeconds = int(math.Ceil(c.NextResend.Sub(now).Seconds())) default: d.Allowed = true d.Reason = "resend_reserved" c.NextResend = now.Add(60 * time.Second) } return d } func recordVerification(c *Challenge, codeValid bool) bool { if c.Verified || c.Attempts >= 5 { return false } c.Attempts++ if !codeValid { return false } c.Verified = true return true } func main() { now := time.Date(2026, time.November, 22, 12, 0, 0, 0, time.UTC) c := Challenge{NextResend: now.Add(30 * time.Second)} fmt.Printf("Early click: %+v\n", resend(&c, now, true)) fmt.Printf("Eligible click: %+v\n", resend(&c, now.Add(30*time.Second), true)) fmt.Printf("Duplicate click: %+v\n", resend(&c, now.Add(30*time.Second), true)) sessionEligible := recordVerification(&c, false) fmt.Println("Session eligible after invalid code:", sessionEligible) sessionEligible = recordVerification(&c, true) fmt.Println("Session eligible after valid code:", sessionEligible) } Expect the early and duplicate clicks to be denied, the eligible click to reserve a resend, and the invalid verification result to leave session eligibility false. The verification function consumes a validation result; it doesn't validate an OTP itself. In the deployed backend, call the provider's verification operation on form submission, check the response, and supply a successful result only when validation actually succeeds. Bind that result to the intended challenge and seller before creating the application session. A caller must never be allowed to submit its own valid boolean.
This distinction matters.
For production, move the transition into a transaction or equivalent atomic operation in shared storage, add challenge expiry and a separate send-attempt budget, and persist the dispatch reservation before a worker sends anything. An in-memory struct cannot arbitrate concurrent requests across server processes. The sample isolates the countdown decision so it can be checked without implying that a local variable is a durable authentication system.
Give each logical dispatch an application identifier, and reuse it across retries. Where the provider operation supports idempotency, carry the same key into that operation; retain the association in the outbox so a worker restart cannot turn one reservation into multiple independent sends. Treat an ambiguous network result as a reconciliation problem, since immediately inventing a new dispatch identifier discards the protection you just built.
The adapter must explicitly set its HTTP method, check status before accepting a response, and surface the provider's error reason to restricted operational records. On HTTP 429, honor Retry-After when supplied and use bounded exponential backoff rather than a tight retry loop. Keep provider details out of the browser response. Its useful contract is a masked destination, challenge reference, and a retry deadline or delay, with field names owned by your application.
For this workflow, poll message status or events into the evidence store. Tie every observation to the original dispatch, retain the observation timestamp, and distinguish the last known delivery state from the time at which the application learned it. A stale observation should breach the evidence-freshness SLO without rewriting a failed verification as a successful login.
This standalone status probe makes a read-only provider call without guessing an OTP request schema. Set SMS_API_ORIGIN to the approved HTTPS API origin without a path, INFRAI_API_KEY to the server-side key, and SMS_MESSAGE_ID to an existing provider message identifier. Save it separately as main.go and run go run main.go in a restricted operational environment. Its raw response is evidence for an operator, not a browser payload; interpret delivery fields against the provider's response schema before updating application state. No session is released by this probe.
package main import ( "context" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) func retryDelay(value string, fallback time.Duration) time.Duration { if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 { return time.Duration(seconds) * time.Second } if deadline, err := http.ParseTime(value); err == nil { if delay := time.Until(deadline); delay > 0 { return delay } } return fallback } func main() { origin := os.Getenv("SMS_API_ORIGIN") key := os.Getenv("INFRAI_API_KEY") id := os.Getenv("SMS_MESSAGE_ID") u, err := url.Parse(origin) if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || key == "" || id == "" { panic("Set an approved HTTPS origin, server key, and existing message ID") } path := strings.Replace("/v1/sms/status/{id}", "{id}", url.PathEscape(id), 1) endpoint := strings.TrimRight(origin, "/") + path ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() client := &http.Client{ Timeout: 10 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } for attempt := 0; attempt < 3; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+key) resp, err := client.Do(req) if err != nil { panic(err) } body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() if readErr != nil { panic(readErr) } if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 { delay := retryDelay(resp.Header.Get("Retry-After"), time.Second<<attempt) timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() panic(ctx.Err()) case <-timer.C: } continue } if resp.StatusCode < 200 || resp.StatusCode >= 300 { panic(fmt.Errorf("status request %s: %s", resp.Status, body)) } fmt.Println(string(body)) return } } The probe retries only rate-limited reads, with a bounded attempt count and an overall deadline. If Retry-After exceeds that deadline, it exits rather than issuing an early retry. A write adapter needs the additional durable reservation and idempotency behavior described above.
3. Verify release criteria and rehearse rollback
The countdown logic needs a clock-controlled test, but rollout also needs an explicit decision about missing evidence. A reasonable application policy is to stop new challenges when country approval is absent, keep failed verification attempts from creating sessions, and pause seller order alerts when the association between seller and destination cannot be established.
Set the release criteria before the first send. For example, require a decision record for every attempted challenge and zero sessions created from rejected codes in the staging test set; those are proposed acceptance criteria, not measured service guarantees. Track verification success separately from dispatch acceptance and delivery observation.
Save this release-gate check separately as main.go and run go run main.go. Every case must finish without a panic:
package main import "fmt" func release(countryApproved, evidenceStored, verificationPassed bool) bool { return countryApproved && evidenceStored && verificationPassed } func main() { cases := []struct { name string country, evidence, verified bool want bool }{ {"approved seller", true, true, true, true}, {"missing country approval", false, true, true, false}, {"missing evidence", true, false, true, false}, {"rejected code", true, true, false, false}, } for _, tc := range cases { got := release(tc.country, tc.evidence, tc.verified) if got != tc.want { panic(tc.name) } fmt.Println(tc.name, got) } } That test checks the chosen release predicate. It cannot prove the deployed adapter, database transaction, or session endpoint obeys it. Exercise those boundaries in staging with two simultaneous resend requests, a refreshed browser, a worker restart after dispatch, a rejected code, and a delayed status observation. The evidence should explain each outcome without including the code itself.
Rollback should disable new challenge dispatches through application configuration, preserve existing decision records, and let the reconciliation worker continue observing already-issued messages. Don't drain a backlog by blindly replaying every send. Before restoring dispatch, confirm the routing-policy version, the worker's deduplication behavior, and the observed freshness of its status records.
Keep the order-notification workflow visible during that exercise. An instructor who successfully signs in still needs a separately traceable notification about the course order; rolling back phone-login changes must not manufacture a successful delivery record for that alert. If an email fallback is required, design its identity checks and evidence contract explicitly rather than assuming a shared address makes it equivalent to phone verification.
Buy the provider capability that fits the seller identity workflow and procurement evidence, while owning the resend authority and the meaning of the audit trail. The browser can count seconds. The backend has to justify them.
References
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- Amazon SNS documentation: https://docs.aws.amazon.com/sns/latest/dg/welcome.html
- Firebase phone authentication documentation: https://firebase.google.com/docs/auth/web/phone-auth
- RFC 6376, DomainKeys Identified Mail: https://datatracker.ietf.org/doc/html/rfc6376