Design a secure SMS OTP login flow by defining which application transaction is allowed to grant a seller access to a new order, before choosing the delivery integration. A message accepted for delivery cannot make that decision, and a successful code check still needs a single-use authorization boundary.
TL;DR: Design a secure SMS OTP login flow around atomic state transitions: apply per-user, per-IP, and per-device rate limiting before sending; preserve attempt counts across retries; enforce short expiry and temporary lockout; consume a verified challenge once to prevent replay. For US/EU SaaS, put destination allowlists or deny rules and destination-specific spending circuit breakers in the backend. The integration decision is how much challenge management to buy while retaining these business controls.
Keep the order notification separate. Its link can lead the seller into login, but an order identifier must never serve as proof of phone possession or permission to view that order.
How should a secure SMS OTP login flow handle concurrent checks?
The signal to investigate is a mismatch between successful verification responses and committed authentication outcomes. An application can receive two valid responses for overlapping requests, or receive a response after its challenge has expired, without either response being permission to create another session. Trace the application transaction, challenge identifier, attempt reservation, and final consumption decision together; exclude raw codes and phone numbers from routine diagnostic labels.
Count grants separately.
Four races deserve explicit release tests: two send workers passing the same remaining quota, a resend resetting the guessing allowance, two verification workers consuming one challenge, and a delayed verification result arriving after lockout or expiry. These are application failure modes to prevent, not claims about any particular provider. They expose integration work that a successful first API call leaves invisible: shared counters, conditional writes, reconciliation, and a durable record of the authentication outcome.
Use the buy-versus-build table as a scope discussion before implementation. The comparison concerns responsibility, not measured delivery speed; confirm the selected product's current contract rather than assuming its use of the word “verification” matches your application's lifecycle.
| Option | Buy | Build or explicitly verify | Suitable integration boundary |
|---|---|---|---|
| Twilio Verify | A verification-oriented service | Map verification lifecycle and service rate-limit controls to seller, IP, and device policy; retain order authorization | Evaluate when managed verification is the component you want to purchase |
| Vonage Verify | A verification workflow | Check workflow progression, retry behavior, and cancellation semantics against your expiry and resend rules | Evaluate when the provider's workflow can replace application orchestration |
| AWS End User Messaging SMS | SMS messaging | Own challenge generation and checking if choosing a messaging-only integration, plus session binding | Evaluate when the platform deliberately owns authentication logic and already operates AWS infrastructure |
| Shared REST platform | Hosted SMS OTP over HTTP | Own destination abuse policy and the durable authorization boundary | Fits an existing shared-state design where the application retains authentication policy |
A shorter adapter can reduce integration effort, but purchasing delivery while quietly assigning authentication state to an on-call team is still a build decision. Choose a verification service when its documented workflow removes work you would otherwise maintain; choose the narrow HTTP boundary when the application already owns that state. Check the actual responsibility transfer.
Infrai provides a plain REST API with a single key and unified billing: one key, one wallet, one bill across 295 routes and 20 modules. Any HTTP-capable backend can call it without an SDK or a client-library version to maintain. For new-order email and SMS login, the shared credential reduces separate rotation work. Its self-describing API provides public discovery schemas without authentication, so the team can inspect the request and response contract before committing adapter work.
The trade-off is ownership of shared authentication state. A delivery adapter is not a fit for a team that won't operate durable attempt counters and replay protection; evaluate Twilio Verify or Vonage Verify against those responsibilities before choosing. Messaging-only integration requires more application lifecycle work, even when the HTTP client is small.
Reserve the attempt before asking for verification
Start with an application-owned authentication transaction bound to the seller, login purpose, and challenge. Before dispatching SMS, atomically reserve capacity under the account, trusted-ingress IP, and device signals, then apply destination policy and check suppression for blocked or opted-out numbers. A device identifier is an abuse signal, not an authentication factor. Give legitimate sellers behind a shared network a considered IP policy instead of treating one network address as one person.
Do not reset counters.
Each verification request must reserve an attempt in shared state before making the external check. Record a unique attempt identifier so its completion can be reconciled without counting it twice. After receiving a trusted verification result, recheck expiry, lockout, and challenge consumption inside the transaction that records the authentication outcome. A request admitted before expiry can finish after it. A correct code does not erase that elapsed time.
For an illustrative policy, use a 3-minute challenge lifetime, at most 5 attempts, and a 10-minute temporary lockout after the failure threshold; these are proposed application settings, not provider defaults or a compliance prescription. A resend should pass admission again and should not reset the account's failure history. If it replaces a challenge, invalidate the previous challenge atomically while preserving the relevant account-level controls.
The following runnable Go model isolates the completion race. Save it as a Go source file and run it with the standard Go toolchain. Its two attempt identifiers represent checks already reserved and already verified by a trusted backend; it deliberately contains no code-generation, delivery, or verification API. The mutex models one atomic completion boundary within one process. A deployed multi-worker service needs a durable transaction or conditional write with the same behavior, including an atomic session-grant record.
package main import ( "fmt" "sync" "sync/atomic" "time" ) type challenge struct { mu sync.Mutex expires time.Time lockedUntil time.Time consumed bool pending map[string]bool } func (c *challenge) complete(id string, now time.Time, verified bool) bool { c.mu.Lock() defer c.mu.Unlock() if !c.pending[id] { return false } delete(c.pending, id) if !verified || c.consumed || !now.Before(c.expires) || now.Before(c.lockedUntil) { return false } c.consumed = true return true } func main() { now := time.Now() c := &challenge{ expires: now.Add(3 * time.Minute), pending: map[string]bool{"attempt-a": true, "attempt-b": true}, } var grants int32 var workers sync.WaitGroup for _, id := range []string{"attempt-a", "attempt-b"} { workers.Add(1) go func(attempt string) { defer workers.Done() if c.complete(attempt, time.Now(), true) { atomic.AddInt32(&grants, 1) } }(id) } workers.Wait() if atomic.LoadInt32(&grants) != 1 { panic("expected exactly one completion") } expired := &challenge{ expires: now, pending: map[string]bool{"late": true}, } locked := &challenge{ expires: now.Add(3 * time.Minute), lockedUntil: now.Add(10 * time.Minute), pending: map[string]bool{"locked": true}, } if expired.complete("late", now, true) || locked.complete("locked", now, true) { panic("expired or locked challenge granted access") } fmt.Println("one completion; expired and locked completions rejected") } This demonstrates a narrow invariant. It does not implement the admission limits, attempt threshold, or session persistence described above. In production, consuming the challenge and recording a recoverable authentication outcome must commit together; otherwise a crash between those writes can strand the seller or tempt a retry handler to reopen a consumed challenge. A lost response should recover the existing outcome through the original authentication transaction, with the caller binding checked, rather than create another grant.
Transport retries are a different operation from a seller requesting another code. Keep a stable idempotency key for the same logical write, inspect response statuses, and preserve diagnostic errors internally while returning account-neutral responses to callers. On HTTP 429, honor Retry-After when present and use bounded exponential backoff with jitter; stop when the operation deadline cannot accommodate another attempt. Treat an uncertain write outcome as something to reconcile under the original operation identifier, rather than inventing a fresh send.
Before enabling writes, inspect the public hosted-OTP discovery contract with this separate Go program. It makes a real read-only API request and prints the schema for adapter review; it does not authenticate a seller. Configure INFRAI_BASE_URL as the trusted HTTPS v1 API base and INFRAI_API_KEY through secret management. Discovery is public, so credentials are unnecessary for discovery itself; the Bearer header here demonstrates the adapter's credential wiring. Redirects are disabled to keep that header at the configured origin.
package main import ( "context" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) func inspect() error { base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/") key := os.Getenv("INFRAI_API_KEY") u, err := url.Parse(base) if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "/v1" || u.RawQuery != "" || u.Fragment != "" || key == "" { return fmt.Errorf("configure a trusted HTTPS v1 base and API key") } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() client := &http.Client{Timeout: 5 * 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, base+"/discovery/sms.otp", 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 >= 200 && resp.StatusCode < 300 { fmt.Println(string(body)) return nil } if resp.StatusCode != http.StatusTooManyRequests || attempt == 2 { return fmt.Errorf("HTTP %d: %s", resp.StatusCode, body) } delay := time.Second * time.Duration(1<<uint(attempt)) if raw := resp.Header.Get("Retry-After"); raw != "" { if seconds, err := strconv.Atoi(raw); err == nil && seconds >= 0 { if seconds > 20 { return fmt.Errorf("retry exceeds operation deadline") } delay = time.Duration(seconds) * time.Second } else if date, err := http.ParseTime(raw); err == nil && time.Until(date) > delay { delay = time.Until(date) } } timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } return fmt.Errorf("retry budget exhausted") } func main() { if err := inspect(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } Verify the release with a trace, not a delivery receipt
Run a controlled seller journey from a new-order notification through authentication to the order authorization check. Duplicate the notification click, overlap verification requests, resend after a failed attempt, and deliver a successful verification result at the expiry boundary. Also exercise a suppressed destination, a disallowed destination, and a shared-IP group of eligible sellers. The acceptance evidence is the resulting application state: one consumed challenge and one recoverable authentication outcome, preserved failure history, and no send admitted after a policy rejection.
Delivery is intermediate.
Define an SLO for eligible sellers completing authentication and a separate SLO for notification dispatch. Record application throttles and suppression decisions separately so a rapid rejection does not masquerade as a successful login; choose measurement windows and targets before rollout. With a pull-based event integration, budget polling and reconciliation work explicitly instead of waiting for a webhook. An email fallback needs its own code lifecycle, and a requirement for voice or messaging-app fallback belongs in provider selection before launch.
Capacity planning should cover the state store as well as delivery. As an assumed test workload, 600 sellers making 3 overlapping verification attempts over 30 seconds require 60 attempt reservations per second on average, plus completion writes and admission checks; this is arithmetic for sizing a test, not a throughput measurement. Compress the arrivals when testing contention. An average spread across idle workers tells little about the account whose last attempt several workers are trying to reserve.
For US/EU SaaS, explicitly review destination eligibility, retention, recovery, and access to authentication records with the relevant owners. A phone prefix is a routing input. It does not establish residence or settle legal compliance, and destination-based budget enforcement remains application policy regardless of how little SDK code the integration requires.
Roll back code without rolling back security state
If release verification fails, pause admission of new challenges through a controlled application switch while leaving order notifications independently operable under their own policy. Roll back the handler only to a version compatible with the durable challenge and outcome records. Keep expiry, attempt reservations, lockouts, and consumed markers intact; do not restore an earlier snapshot that makes a used challenge appear unused.
Preserve the evidence.
Drain or reconcile in-flight operations by their original identifiers, keep temporary lockouts on their intended schedule, and resume admission only after repeating the overlap and late-completion checks. If the old version cannot honor the new state, hold new authentication work rather than clearing that state to make the old code run. The integration is ready when its recovery path preserves the same single-use rule as its happy path.
References
- NIST SP 800-63B, Digital Identity Guidelines: https://pages.nist.gov/800-63-3/sp800-63b.html
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- Twilio Verify service rate limits: https://www.twilio.com/docs/verify/api/service-rate-limits
- Vonage Verify documentation: https://developer.vonage.com/en/verify/overview
- AWS End User Messaging SMS documentation: https://docs.aws.amazon.com/sms-voice/latest/userguide/what-is-service.html
