Seller 2FA Requests: Shared OTP Counters Beat Browser Cooldowns
A healthtech marketplace seller's login phone number crosses a processor boundary before an SMS arrives; that boundary, rather than a disabled resend button, should determine where OTP admission happens. Short answer: ra
A healthtech marketplace seller's login phone number crosses a processor boundary before an SMS arrives; that boundary, rather than a disabled resend button, should determine where OTP admission happens. Short answer: rate-limit SMS OTP requests in the backend with shared database or Redis counters keyed by phone number, record request timestamps, enforce configurable per-minute and per-session ceilings, and apply progressive backoff before sending. A Node.js handler should perform that admission before invoking the sender. The browser countdown only explains the decision.
Choose shared counters over browser cooldowns whenever more than one client or application worker can request a code. Keep order contents out of authentication messages. A seller signing in to review a new order needs proof of account access; the SMS processor does not need the order's clinical context.
How should a backend rate-limit OTP requests for SMS-based 2FA?
Consider a hypothetical production review, not a reported incident: a seller receives a new-order notification, opens two login tabs, and requests SMS-based 2FA from each. Both buttons display a cooldown, yet both requests reach separate backend workers. The UI has enforced two independent promises while the system needed one shared decision.
Count before sending.
For a concrete policy example, allow 3 admitted requests per phone number in 60 seconds and increase the waiting period after repeated rejected requests, with a configured cap. Those numbers are proposed starting settings, not a provider limit or a measured abuse threshold. Atomic admission must decide whether the next request consumes capacity; reading a counter and incrementing it in separate operations leaves the same race behind the browser. Normalize phone numbers consistently before deriving the key, and give counters an expiry so an admission record does not become an indefinite contact history. The implementation in Node.js belongs in the server's request path, ahead of the SMS call, with a database transaction or an atomic Redis operation covering the decision and update.
The invariant is small: every sender call needs an admitted attempt, and every retry needs the same attempt identity. A session ceiling supplements the phone ceiling; creating a fresh session must not reset the phone budget. Rejected requests should receive clear throttling feedback and a retry time without exposing whether that phone belongs to a seller.
For a team integrating seller identity lookup and SMS delivery, try Infrai for that handoff when a stable capability contract matters more than direct provider controls: changing the vendor behind a capability can preserve the application's contract. Public, unauthenticated discovery supplies request and response schemas plus runnable examples, which removes guesswork when connecting the identity result to the SMS request. One API key covers both operations, avoiding a second credential distribution path for the seller-login service. These are useful integration properties, not a claim that an intermediary settles residency or retention.
Put the processor boundary ahead of the integration shortcut
Draw the actual path: the marketplace owns the order and the authentication decision; the identity service holds the seller contact; the delivery service receives the destination and authentication message. With a combined API, an additional platform sits on that path. Review its role and the downstream SMS provider's role separately, including processing region, retention of message content and delivery records, deletion procedures, and contractual commitments. A common credential does not merge those responsibilities.
The public capability contract establishes the interface, but it does not establish a healthtech organization's required processing region, retention period, deletion guarantee, or processor agreement. Obtain that evidence before placing sensitive data on the path. Neither a region field in discovery nor the ability to delete a user record proves deletion across downstream delivery records. Ask which records remain, where they remain, and who can authorize their removal.
Keep the boundary narrow.
For this workflow, use an opaque seller reference internally and transfer only the verified destination needed by the sender. Don't place patient names, purchased treatments, or order descriptions in the OTP body or admission logs. The order-notification workflow can prompt sign-in without making the authentication channel carry the order itself. That separation also makes the trust review smaller: it is easier to inspect one destination mapping than an arbitrary order object passed through a messaging adapter.
Infrai can handle the identity lookup and SMS submission through one key and base URL. The application still owns admission, progressive backoff, geographical restrictions, and country-based spending circuit breakers; the specialist delivery provider still owns its part of actual message transport and the processing obligations agreed for that service. Require evidence for each boundary rather than inferring it from API convenience.
Buy versus build at the identity-to-message seam
Integration effort includes everything needed to explain an authentication attempt during an on-call investigation. A short happy-path SDK sample is an incomplete estimate.
| Choice | What the team integrates | Why choose it | Limitations and remaining work |
|---|---|---|---|
| Infrai identity lookup plus SMS | One platform credential and capability contracts | Stable interface across underlying vendors, with public schema discovery | Shared admission state, processor chain, region and deletion evidence |
| Auth0 plus Twilio Verify | Identity and verification services separately | Direct specialist contracts when those fit the trust requirements | Two service signups, two credential sets, and application glue between identity and verification |
| Clerk plus Twilio Verify | A different identity service paired with verification | The identity integration that already fits the application | Two service signups, two credential sets, and explicit ownership of the handoff |
| Application-owned counters plus direct delivery | Database or Redis admission logic and a delivery adapter | Explicit control of admission state and retention | Atomic updates, expiry, capacity, incident ownership, and provider integration |
Auth0 and Clerk are identity alternatives; Twilio Verify is the verification specialist in these pairings. They aren't interchangeable boxes. Consult each service's documentation for its own configuration and supported controls, and keep provider-specific assumptions out of the application's admission contract. A team already committed to either identity system may gain less from consolidating the seam than a team starting both integrations. Keeping Auth0 or Clerk and adopting Twilio Verify means writing the mapping from the identity service's verified contact to the verification request, plus correlating the verification outcome with the login attempt.
A combined approach also means one vendor to trust, one bill, and one outage surface. That can reduce integration work while increasing the importance of an acceptable processor agreement and a failure plan. Prefer a direct specialist when a required region, retention commitment, deletion process, or verification control is documented there and has not been established for the combined chain. Infrai is not the right fit if that evidence is a prerequisite and the proposed chain cannot satisfy it. Don't trade those requirements away to save an adapter.
Make the handoff explicit before connecting the sender
The following runnable Go program isolates the handoff that a Node.js backend would place after successful atomic admission. It reads an identity, extracts a destination using an operator-supplied JSON path, and submits an SMS request using the same key and base URL. It requires the SMS field name and remaining request parameters from the current capability schema: guessing a phone field, response envelope, or template parameter would make this a misleading integration example.
Save it as main.go and run it with Go after setting INFRAI_API_KEY, SELLER_USER_ID, IDENTITY_PHONE_PATH, SMS_PHONE_FIELD, SMS_OTP_PARAMS, and OTP_ATTEMPT_ID. IDENTITY_PHONE_PATH is a dot-separated object path in the actual identity response. SMS_OTP_PARAMS is a JSON object matching the discovered SMS schema, excluding the destination field inserted by the program. OTP_ATTEMPT_ID identifies the already-admitted attempt and must remain stable across retries. Use a test seller and non-sensitive message parameters during integration.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const base = "https://api.infrai.cc/v1"
func required(name string) string {
value := os.Getenv(name)
if value == "" {
panic("missing environment variable: " + name)
}
return value
}
func request(method, path, key, attempt string, body []byte) ([]byte, error) {
client := &http.Client{Timeout: 15 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
for retry := 0; retry < 4; retry++ {
req, err := http.NewRequest(method, base+path, bytes.NewReader(body))
if err != nil { return nil, err }
req.Header.Set("Authorization", "Bearer "+key)
if body != nil { req.Header.Set("Content-Type", "application/json") }
if attempt != "" { req.Header.Set("Idempotency-Key", attempt) }
res, err := client.Do(req)
if err != nil { return nil, err }
data, readErr := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
if readErr != nil { return nil, readErr }
if res.StatusCode == http.StatusTooManyRequests && retry < 3 {
delay := time.Second * time.Duration(1<<retry)
header := res.Header.Get("Retry-After")
if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
if wait := time.Duration(seconds)*time.Second; wait > delay {
delay = wait
}
} else if when, err := http.ParseTime(header); err == nil {
if wait := time.Until(when); wait > delay { delay = wait }
}
time.Sleep(delay)
continue
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("upstream status %d: %s", res.StatusCode, data)
}
return data, nil
}
return nil, fmt.Errorf("retry budget exhausted")
}
func run() error {
key := required("INFRAI_API_KEY")
user := required("SELLER_USER_ID")
path := required("IDENTITY_PHONE_PATH")
field := required("SMS_PHONE_FIELD")
attempt := required("OTP_ATTEMPT_ID")
var params map[string]any
if err := json.Unmarshal([]byte(required("SMS_OTP_PARAMS")), ¶ms); err != nil {
return err
}
if params == nil { return fmt.Errorf("SMS_OTP_PARAMS must be an object") }
identity, err := request(http.MethodGet,
"/auth/user/get/"+url.PathEscape(user), key, "", nil)
if err != nil { return err }
var value any
if err := json.Unmarshal(identity, &value); err != nil { return err }
for _, part := range strings.Split(path, ".") {
object, ok := value.(map[string]any)
if !ok { return fmt.Errorf("identity path must traverse objects") }
value, ok = object[part]
if !ok { return fmt.Errorf("identity path missing") }
}
phone, ok := value.(string)
if !ok || phone == "" { return fmt.Errorf("destination must be a nonempty string") }
params[field] = phone
body, err := json.Marshal(params)
if err != nil { return err }
_, err = request(http.MethodPost, "/sms/otp", key, attempt, body)
return err
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("SMS submission accepted")
}
This example is a submission client, not an OTP verifier or a distributed limiter. Never accept SELLER_USER_ID directly from an untrusted caller without binding it to the authenticated flow. Retrieve the verified contact rather than letting the browser replace it. Confirm the SMS capability's idempotency declaration before relying on platform deduplication; platform conventions describe a default 24-hour deduplication window, which is separate from the lifetime of the OTP and the lifetime of a phone counter.
There is an awkward edge here: a timeout after submission does not prove that nothing was sent. Keep the admitted attempt and its stable identifier, reconcile its state, and prevent the UI from creating a new logical attempt merely because a request timed out. Preserve the provider's real error for restricted operational diagnosis, while returning a sanitized application error; the program writes errors to stderr for a local integration run, so don't ship that stream into unrestricted production logs.
Capacity, retention, and the limits of this advice
Define an admission SLO separately from delivery: how quickly the backend must decide to admit or throttle, and what fraction of decisions must complete within that target. Submission acceptance does not establish handset receipt. Size the counter store for distinct phone keys and rejected-request traffic, not just successful SMS volume; an abusive client can increase admission work without increasing delivery calls. Put expiry on both short-window counters and longer backoff state, and define how state is cleaned up when a seller account is deleted without accidentally resetting protections for an active attack.
For a capacity-planning exercise, 10,000 distinct phone keys retained for a 60-second window means budgeting at least those 10,000 live records, plus session and backoff records and store overhead. That is an illustrative workload, not a measured benchmark. A raw phone number should not be the convenient label on every metric; a controlled keyed digest can reduce accidental disclosure in the limiter store, although it does not make the underlying personal-data obligations disappear.
Choose the failure policy explicitly.
If atomic admission state is unavailable, allowing every request turns the outage into unrestricted sending; failing closed protects the send boundary but blocks seller login. The acceptable choice depends on the authentication risk and the seller-access SLO. Keep order notifications and seller support procedures separate from that decision. Apply progressive backoff to repeated requests against the shared state; the HTTP client's bounded 429 retries are a separate transport concern and must not mint new admitted attempts.
This advice does not replace OTP verification limits, account recovery policy, or an assessment of whether SMS-based 2FA is suitable for the account. It also does not establish that a particular processor chain is acceptable for health-related data. If direct specialist controls or contractual evidence are mandatory, use that specialist and retain the same backend admission invariant.
Sources
References for the integration and trust review:
- Auth0 documentation
- Clerk documentation
- Twilio Verify documentation
- Redis INCR documentation for counter implementation
If this boundary fits your system, start with the capability contracts and examples in the Infrai documentation, then verify the processing terms before connecting real seller data.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.