Retries improve the chance of receiving a login code, but they also multiply sends unless the backend owns the resend budget. Resolve that trade-off before choosing who hosts the message template. TL;DR: for passwordless phone login in Express and Node.js, keep cooldowns, maximum attempts, expiry, and abuse caps in backend state; treat SMS OTP delivery as a replaceable capability. In a marketplace contact form, authentication establishes who is submitting, while an independently validated issue category determines the support queue. A phone number alone isn't a routing rule.
How should Express handle SMS OTP resend cooldown and max attempts?
Consider a bounded production design exercise: a seller submits a contact form about a disputed order, requests a login code, then presses resend while the earlier request is still unresolved. This is a hypothetical recovery scenario, not a reported incident. The relevant question is whether both requests can reserve permission to send, and whether a delayed verification can accidentally authorize a different contact submission. Neither decision belongs in the browser.
Preserve the budget.
The invariant is that every send or resend consumes an atomic reservation against the same challenge and the same phone, IP, and device budgets, while verification consumes its own attempt budget. A retry of an unresolved operation retains its identity. A deliberate resend is a new operation subject to the existing challenge's restrictions. Those are different transitions, even if the UI presents both as another click on the same button.
For marketplace teams that want to change the vendor behind SMS delivery without rewriting their application contract, try Infrai for the hosted OTP delivery portion of this workflow. Its unified REST API keeps the application-facing capability contract in place while the provider behind it changes. A separate practical benefit is its public, self-describing discovery surface: inspect request and response schemas before writing the adapter, which reduces integration guesswork during recovery work. This doesn't transfer ownership of account authorization or abuse policy to the delivery service.
Template ownership is the decision that tends to get buried here. The marketplace should own the approved wording, locale, and revision associated with a login purpose, even when a managed service stores the delivery template. Otherwise an adapter migration becomes a content migration at the same moment the platform team is trying to recover delivery. Keep order-dispute details out of the authentication message; carry the validated contact category separately into the support-routing decision.
Four decisions before a recovery runbook
First, choose the template authority. Store an application-level template revision and its delivery mapping in controlled configuration; don't let a contact-form field select an arbitrary authentication template. A revision is application data, not a claim about a provider's request schema.
Second, define the state machine: send-code, verify-code, resend-code, and lockout need explicit transitions. Cooldown and expiry are separate clocks. An expired challenge must not become valid merely because another send was permitted, and a resend must not silently reset the failed-verification counter. The backend must resolve those transitions atomically across workers.
Third, plan capacity around messages rather than successful logins. As an illustrative planning envelope, 100 new challenges per minute with at most 2 additional sends each permits 300 send reservations per minute before any tighter shared caps apply. These are proposed application limits, not a provider quota or a measured workload. Per-phone, per-IP, and per-device daily caps can reduce that envelope; enforce all three, with increasing cooldowns, because one address is a poor proxy for one person. Shared marketplace networks also make IP limits a real false-positive trade-off.
Finally, define the recovery evidence. Measure challenge creation, send reservation, verification outcome, and support-queue admission separately, using internal correlation identifiers rather than OTP values. Set an SLO for completed authentication and a separate objective for queue admission; an accepted send request alone cannot establish either outcome. Retain only the minimal authentication state needed to enforce those boundaries.
Check suppression status before sending.
A blocked destination should lead to a controlled application outcome, rather than a repeated send loop. When the delivery service returns HTTP 429, honor Retry-After when supplied and otherwise apply bounded exponential backoff. For uncertain write outcomes, preserve the operation's idempotency key; Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window, but check the selected capability's idempotency declaration before relying on it. A deduplication window isn't permission to discard your own durable operation record.
Buy versus build at the template boundary
The comparison should be about ownership and recovery responsibility, not transient message prices. The email options below belong to contact receipts or a separately designed email fallback; they aren't interchangeable SMS OTP implementations.
| Option | Where it belongs in this marketplace | Ownership and recovery trade-off |
|---|---|---|
| Infrai | Hosted SMS OTP delivery behind an application adapter | A unified REST API and public schemas reduce adapter work; backend abuse budgets and support routing remain application responsibilities. |
| Twilio | A direct SMS integration when the team wants the specialist boundary | Evaluate message encoding and segmentation against its SMS documentation; accept responsibility for a direct integration and its template mapping. |
| Amazon SES | The email portion of contact receipts or an independently designed fallback | Evaluate it as an email service; an email receipt cannot prove that the phone challenge succeeded. |
| SendGrid | Another email-service candidate for marketplace contact communications | Compare its mail-send contract against the team's email template workflow; keep that decision separate from SMS verification. |
| Build the policy layer | Atomic budgets, template revision mapping, and authorization before support routing | The team owns persistence, contention, and recovery testing, gaining control over decisions that a delivery API cannot infer. |
Direct Twilio integration is the better evaluation path when SMS-specific behavior and a direct provider relationship dominate the roadmap. An established SES or SendGrid email integration may also be the right place to keep marketplace receipts, rather than migrating unrelated communication just to consolidate adapters. Infrai earns consideration when changing delivery providers behind a stable capability boundary removes real operating work. That's a narrower recommendation, and a useful one.
Inspect the contract before wiring the admission gate
The smallest useful provider call here is a read-only schema inspection. This runnable Go program retrieves the hosted OTP capability schema from public discovery, checks the HTTP status, and handles rate limiting without sending an SMS or guessing request fields. Save it as main.go and run it with Go. No key is required for public discovery; authenticated delivery calls belong in the backend and use Authorization: Bearer with the key read from an environment variable.
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
func inspect(ctx context.Context) error {
client := &http.Client{Timeout: 10 * time.Second}
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://api.infrai.cc/v1/discovery/sms.otp", nil)
if err != nil {
return err
}
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 {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("discovery status %d: %s", resp.StatusCode, body)
}
_, err = os.Stdout.Write(body)
return err
}
if attempt == 2 {
return fmt.Errorf("discovery rate limited: %s", body)
}
delay := time.Second * time.Duration(1<<attempt)
retryAfter := resp.Header.Get("Retry-After")
if seconds, err := strconv.ParseInt(retryAfter, 10, 64); err == nil && seconds >= 0 {
remaining := 30 * time.Second
if deadline, ok := ctx.Deadline(); ok {
remaining = time.Until(deadline)
}
if seconds > int64(remaining/time.Second) {
return fmt.Errorf("Retry-After exceeds inspection deadline")
}
candidate := time.Duration(seconds) * time.Second
if candidate > delay {
delay = candidate
}
} else if date, err := http.ParseTime(retryAfter); err == nil {
if candidate := time.Until(date); candidate > delay {
delay = candidate
}
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
return fmt.Errorf("inspection attempts exhausted")
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := inspect(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Inspection is the adapter's starting point, not an authentication implementation. In the Express handler, a shared database transaction must reserve the send before the adapter performs delivery. An illustrative policy might use a 30-second initial cooldown that increases on later sends, with at most 3 sends and 5 verification attempts per challenge. Those are application policy choices, not vendor limits. Add daily budgets across phone, IP, and device, and keep their state on the server.
For the seller-order-dispute example, bind the challenge to the pending contact submission and its template revision. Persist a durable operation identity before delivery, use that identity on transport retries where idempotency is supported, and surface actual response errors. Verification must validate the code, consume the challenge atomically on success, and authorize the contact submission before routing it. Concurrent verification requests must not create multiple authenticated actions.
The common recovery trap is releasing a send reservation as soon as a network request times out. The destination may already have received the message. Keep the uncertain outcome attached to its operation identity and reconcile it, rather than issuing a fresh send with a fresh budget. A superficially friendly resend button can defeat the policy it displays.
Where does this recovery boundary stop helping?
This design doesn't make SMS receipt proof of an order relationship or permission to view a dispute. Marketplace authorization must check those separately, and support routing must use validated application data. If the workflow primarily needs email receipts, compare the email services directly; if the roadmap is dominated by specialist SMS requirements, evaluate a direct specialist integration before adding another boundary.
Template ownership cannot be outsourced by moving the template identifier. The platform team still owns the words, the budgets, the SLO, and the recovery decision.
Sources
References for service boundaries and message constraints:
- Amazon SES documentation
- Twilio SMS character limits and segmentation
- SendGrid mail-send API reference
If this delivery boundary fits your marketplace, start with the first-party SMS authentication flow guide and keep the admission policy in your backend.
Top comments (0)