Design a secure SMS OTP login flow for settled-payment receipts by recording admission decisions before delivery and enforcing retry limits before another message is sent. The bill consists of admitted message attempts, the evidence retained about them, and the work of reconciliation; for the delivery component, the controlling quantity is initial sends plus accepted resends. In an illustrative policy, one initial send followed by four resends creates five delivery requests for a single login challenge. Allowing one resend instead makes that two. These are request counts, not measured costs or a claim about vendor pricing.
TL;DR: Put per-user, per-IP, and per-device limits, country admission rules, short expiry, attempt limits, replay prevention, and temporary lockouts in the business backend. Keep a compact audit trail of those decisions. A hosted OTP service handles its documented delivery and verification responsibilities; the application still owns the authorization to view an order receipt and the evidence connecting that receipt to a settled payment.
The concrete system here is a fintech payment backend serving an automotive service business: after a repair payment settles, the backend sends an order receipt, while the customer uses SMS OTP login to access the receipt history. A service update is a separate notification purpose. Neither a valid phone challenge nor a message delivery event proves that money settled.
How should a secure SMS OTP login flow preserve compliance evidence?
Start with three controls: admission, challenge consumption, and evidence retention. Their order matters. Limiting expensive dispatches after the provider has accepted them leaves the amplification term unchanged, while retaining every raw message indefinitely expands the evidence store without proving that the admission decision was correct. Admission should therefore precede the outbound call, and its durable record should identify the rule version that allowed or denied the request.
Consider an explicitly illustrative configuration: three admitted sends per account in a 15-minute window, a maximum of five failed verification attempts per challenge, and a five-minute challenge lifetime. These are proposed application settings, not provider defaults or a compliance prescription. IP and device budgets require their own thresholds because shared networks and resettable device identifiers make either signal inadequate as the sole boundary. Apply the budgets together, using an atomic reservation so two workers cannot each spend the same final allowance.
Reserve before dispatch.
A suppression check belongs in this admission path: repeatedly attempting delivery to a blocked or opted-out number is an avoidable source of unwanted traffic. Country allowlists or deny rules and a country-sensitive spending ceiling also belong in business policy. Derive the country from the destination number rather than assuming an IP location describes its telephone routing, and decide explicitly what happens when classification is uncertain. A US/EU deployment needs this decision recorded alongside its processing and retention choices; a region label alone establishes no legal compliance.
Keep send throttling distinct from verification throttling. A resend consumes a delivery allowance; an incorrect code consumes an attempt allowance. A temporary lockout should carry an expiry and a reason, and a resend must not erase failed attempts or permit a caller to extend a challenge indefinitely. Avoid revealing account existence through distinct public errors, even though the internal audit record should preserve the precise rejection reason. That separation improves both abuse handling and later investigation.
Reconcile settlement before authorizing a receipt
The receipt workflow begins with the authoritative settlement transition. Commit the receipt intent with the ledger's settlement record through a transactional outbox, then let a worker dispatch the notification. This is a proposed architecture, not a claim that any communications vendor supplies ledger transactions. The order identifier, settlement identifier, and receipt revision form a business identity that remains stable when a worker retries.
The distinction is small but consequential: a transport retry repeats an existing intent, whereas a customer-requested resend is a new admitted action under the current budget. Reusing an idempotency identity for the former and allocating an explicitly related identity for the latter makes reconciliation possible without confusing repeated network attempts with new customer instructions. Keep the intent until its outcome is reconciled. If an acknowledgment is lost, an immediate new send can create another receipt even though the first request succeeded.
Exactly once is the business invariant. It is not a delivery assumption.
For login, bind the challenge to its account, purpose, and authentication session, and consume successful verification atomically before issuing the session credential. An expiry check without a consume transition permits two concurrent requests to succeed. A fresh OTP must not authorize access to an arbitrary order identifier supplied by the caller: retrieve the order's account relationship and enforce that authorization separately. Likewise, payment settlement does not grant permission to send unrelated service updates.
Reconciliation needs separate states for settlement recorded, receipt intent committed, dispatch accepted, and delivery evidence observed. Poll-based event collection can populate that final state, provided the application retains a polling cursor and tolerates repeated observations. Delivery evidence has a narrower meaning than recipient acknowledgment, and neither event is a substitute for the ledger.
Compare evidence boundaries before choosing a delivery service
The useful comparison is the responsibility each integration leaves with the payment backend. The following alternatives are real products, but this table is an architectural comparison rather than a claim that their security controls, regional coverage, or contractual assurances are equivalent. Consult their primary documentation and obtain the relevant contractual evidence before selecting a US/EU processing arrangement.
| Option | Useful fit | Boundary to evaluate |
|---|---|---|
| Twilio Verify | A dedicated verification service when the application wants a hosted verification workflow. | Evaluate its verification and service-rate-limit model against account, IP, and device admission; receipt settlement and order authorization remain application concerns. |
| Vonage Verify | A verification product worth evaluating when choosing who owns challenge delivery and checking. | Review the documented workflow and supported channels for the intended destinations; retain the backend's authorization and audit policy. |
| Amazon SNS | Direct SMS messaging when the application deliberately owns the challenge lifecycle. | Budget for generating, expiring, checking, and consuming challenges in the application; a messaging primitive does not itself establish the login policy. |
| Common REST option | A plain REST API callable from any HTTP-capable language, without installing or maintaining an SDK; consistent per-call request metadata can support reconciliation. | Public, self-describing discovery supports schema review before integration; use documented OTP and suppression capabilities within business-owned abuse controls, with event polling as part of reconciliation. |
The dedicated verification products are the more direct candidates when delegating the verification lifecycle is the main objective. Direct messaging is a reasonable choice when the application intentionally owns that lifecycle and can demonstrate its correctness. The common REST option fits a backend that values a small HTTP integration surface and can retain its own admission evidence. None of these choices eliminates the need to prove which settled order caused a receipt.
Infrai is a plain REST API requiring no SDK, with one key and one bill across backend capabilities. Any HTTP-capable language can call it without maintaining a client library; the shared credential and consolidated billing reduce separate credential inventories and invoice reconciliation for a payment team using several services. The trade-off is that the shared credential needs careful access governance. This administrative benefit does not establish the correctness of a receipt or replace business-layer audit trails.
Channel scope also changes the design. Evaluate SMTP relay, voice, WhatsApp, or RCS as explicit requirements when considering alternatives; do not assume an email-and-SMS integration covers them. If email becomes a login fallback, establish who generates and checks the email challenge. Keep scheduled receipt content minimal and its business authorization durable, so correctness does not depend on a later cancellation request. For aggregate reporting, retain application-level purpose labels rather than making auditability depend on a provider's tag reporting or template inventory interface.
Audit schema changes before a migration
The retention problem is easiest to see in a deliberately synthetic example. Assume 100,000 challenge records in a review window. Keeping a 2,048-byte raw payload for each requires 204,800,000 payload bytes; keeping a 256-byte decision record instead requires 25,600,000. Those chosen sizes exclude indexes, replicas, encryption overhead, and backups. They illustrate the dominant storage term, record count multiplied by retained bytes, rather than estimating a production database or a monetary saving.
Migration changes what that compact record means. Archive the reviewed contract version with the application release, and compare request and response schemas before changing the adapter; a new field should enter the evidence store only if its purpose and retention rule are approved. If an adapter changes which identifier it treats as the dispatch identity, old and new records need an explicit mapping for reconciliation. This is a governance review with a concrete release artifact, rather than an instruction to log whole responses whenever their shapes change.
Secrets expire sooner.
Before deciding what to retain, inspect the actual OTP contract. This standalone Go program reads the public discovery schema, checks the response, and prints valid JSON; it sends no OTP and invents no OTP request fields. Set COMM_API_ORIGIN to the chosen service's HTTPS API origin and INFRAI_API_KEY to a key supplied through the environment. Discovery itself is public and does not require that key, but the example keeps authentication explicit for integration review. The origin is configuration rather than an embedded vendor link.
package main import ( "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "time" ) func run() error { origin, err := url.Parse(os.Getenv("COMM_API_ORIGIN")) if err != nil || origin == nil || origin.Scheme != "https" || origin.Host == "" || origin.User != nil || origin.RawQuery != "" || origin.Fragment != "" || (origin.Path != "" && origin.Path != "/") { return fmt.Errorf("COMM_API_ORIGIN must be an HTTPS origin without a path") } key := os.Getenv("INFRAI_API_KEY") if key == "" { return fmt.Errorf("INFRAI_API_KEY is required by this example") } origin.Path = "/v1/discovery/sms.otp" client := &http.Client{ Timeout: 15 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } for attempt := 0; attempt < 3; attempt++ { req, err := http.NewRequest(http.MethodGet, origin.String(), 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, 2<<20)) 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.Atoi(value); err == nil && seconds >= 0 { if seconds > 60 { return fmt.Errorf("retry deferred: Retry-After=%s", value) } if wait := time.Duration(seconds) * time.Second; wait > delay { delay = wait } } else if at, err := http.ParseTime(value); err == nil { if wait := time.Until(at); wait > delay { delay = wait } } if delay > time.Minute { return fmt.Errorf("retry deferred: Retry-After=%s", value) } time.Sleep(delay) continue } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("discovery HTTP %d: %s", resp.StatusCode, body) } if !json.Valid(body) { return fmt.Errorf("discovery response is not valid JSON") } fmt.Println(string(body)) return nil } return fmt.Errorf("retry budget exhausted") } func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } An illustrative 30-day evidence window is a policy input, not a universal retention period for financial records, authentication evidence, or customer communications. Those record classes can require different schedules, and clearing an OTP challenge should not erase a receipt obligation. Preserve unresolved work for reconciliation and check legal holds before deletion; selection and deletion need concurrency control if either status can change during the operation. A successful schema fetch proves none of those application properties.
Retain decisions, retire secrets
Keep an internal correlation chain between settlement, receipt intent, dispatch identity, provider request identifier where available, and the reconciled outcome. For login decisions, retain the rule version, timestamp, result, and suitably protected account linkage under a separate retention schedule. Restrict access to this evidence and make changes auditable. A table called an audit log is insufficient if the same unrestricted writer can silently rewrite its history.
Compliance has limits. NIST's digital identity guidance constrains the use of PSTN out-of-band authentication, including single-use and validity requirements; it does not certify a fintech application's full US/EU compliance. GDPR's storage-limitation principle also does not establish a blanket duration for every receipt or challenge record. Legal obligations, lawful processing, destination coverage, and processor arrangements require their own review. A vendor's readiness status or country availability cannot supply that review.
Preserve the distinction.
Deliberately stop keeping raw OTP values after their operational purpose ends, avoid copying receipt bodies into authentication logs, and expire unnecessary full phone numbers and request payloads under the approved schedule. This sacrifices some forensic detail: after payload deletion, an investigator may be able to prove that a policy admitted a particular intent without reconstructing the exact text shown on a handset. Keeping an immutable template revision reference can narrow that gap, but it cannot prove what the recipient read.
That is the retention trade-off to approve: enough evidence to reconcile a settled receipt and explain a login decision, with an explicit loss of message-level reconstruction once sensitive payloads expire.
Further reading
References:
- NIST SP 800-63B, Digital Identity Guidelines, including out-of-band authentication: 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
- Amazon SNS SMS documentation: https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html
- GDPR, including Article 5 storage limitation: https://eur-lex.europa.eu/eli/reg/2016/679/oj

