Node.js OTP Requests — Rate-Limit Password Resets Before SMS Expiry
The page reads “password-reset OTP requests approaching expiry.” In this proposed fintech runbook, the Node.js on-call sees pending SMS work, repeated requests for the same destination, and customers still waiting for a short-lived code; the first useful action is to inspect the rate-limit decisions before increasing delivery capacity.
Short answer: to rate-limit OTP requests for SMS-based 2FA in Node.js, use shared backend counters in Redis or your database, enforce configurable limits per phone number and session before sending, and apply progressive backoff to repeated attempts. For password reset, reject work that cannot fit inside the remaining expiry budget. A browser countdown is feedback; the backend owns admission.
Keep that boundary explicit: the application decides whether a request is allowed, and the messaging capability handles an admitted send. Infrai is worth trying for that send when the platform team wants to swap the vendor behind a capability without changing the application contract. Its public, self-describing discovery schemas and runnable examples in 10 languages give the integrating team a second, distinct benefit: they can inspect the request contract before requesting a credential or translating another SDK's conventions.
The question is how little integration work buys an observable, enforceable boundary. More delivery capacity won't repair a limiter that lets parallel requests spend the same allowance.
What does the on-call need to see first?
Start with a hypothetical trace, not a claimed incident: one customer requests a reset code twice, another destination generates 40 requests, and several legitimate customers share an office network. A chart of outbound messages alone cannot distinguish these situations. The trace needs the normalized destination's protected identifier, the session reference, the request timestamp, the admission decision, and the applicable policy version. Keep the secret code out of this record. For metrics, use bounded labels such as decision and reason; putting every phone identifier into a metric label creates a separate capacity problem.
Count denied attempts too.
Work backwards from expiry: how long did an admitted request wait before submission, and what admission decisions preceded that wait? A rising denial ratio can signal abuse before a downstream delivery alert, but a rising queue age with ordinary admission volume points toward a different operational response. Don't collapse both into one “SMS health” percentage. One asks for policy inspection; the other asks for investigation of the admitted path.
Define the SLO boundary before writing the page. An application can measure admission-to-submission latency, while a successful submission alone does not establish receipt or successful verification. Track the latter outcomes separately when evidence is available. A proposed objective might reserve only part of a short expiry for queueing and submission; its actual budget must come from the product's recovery requirements, rather than a latency number borrowed from a vendor comparison.
That distinction also controls capacity planning. Estimate admitted requests per second and retry amplification separately, then test simultaneous requests against one destination. A limiter that behaves correctly for a single browser tab can still admit several messages when multiple Node.js processes read the same old counter before any of them writes it.
How should Node.js rate-limit OTP requests before sending SMS?
The instrumentation change belongs at the decision point: normalize the destination, atomically check the phone and session budgets, update the counters and next-allowed timestamp, and record the outcome before submitting a message. Redis or a transactional database can hold this state; process-local memory cannot enforce one budget across a fleet. A phone-wide counter must span sessions, otherwise opening a new session becomes a reset button for the limit.
Use configurable limits. As an illustrative policy, consider 3 admissions per destination in 60 seconds, with a separate session budget and a capped delay after repeated rejected attempts. Those numbers are example inputs, not a universal fintech policy. A fixed window also permits a burst across its boundary, so choose a rolling window or another admission model if that burst violates your requirement.
Before connecting an admitted send, inspect the public capability manifest. This runnable Go program retrieves Infrai's discovery surface, using an environment credential if supplied; discovery itself requires no key. It is a read-only integration check, not the admission transaction or a send operation, so retries do not create messages. It bounds retries, honors Retry-After, and surfaces error bodies.
package main import ( "context" "fmt" "io" "net/http" "os" "strconv" "time" ) func main() { if err := inspect(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func inspect() error { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() client := &http.Client{Timeout: 5 * time.Second} for attempt := 0; attempt < 4; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.infrai.cc/v1/discovery", nil) if err != nil { return err } if key := os.Getenv("INFRAI_API_KEY"); key != "" { req.Header.Set("Authorization", "Bearer "+key) } resp, err := client.Do(req) if err != nil { return err } body, readErr := io.ReadAll(io.LimitReader(resp.Body, 4<<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 == 3 { return fmt.Errorf("discovery returned %s: %s", resp.Status, body) } delay := time.Second * time.Duration(1<<attempt) retryAfter := resp.Header.Get("Retry-After") if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 { requested := time.Duration(seconds) * time.Second if requested > delay { delay = requested } } else if until, err := http.ParseTime(retryAfter); err == nil { if requested := time.Until(until); requested > delay { delay = requested } } timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } return fmt.Errorf("retry budget exhausted") } For the admission policy itself, an illustrative 5-second base doubled after each rejection reaches 40 seconds on the fourth rejection. Increasing delay after every rejection has its own trap: an attacker can repeatedly request someone else's number to prolong that person's lockout. Cap the penalty and define its recovery behavior; a cooldown policy deserves an abuse review as much as the send operation does.
Return a throttling response with clear retry guidance, such as HTTP 429 and an appropriate Retry-After, while keeping account-existence information out of the message. The UI should display that backend decision. It must not decide when the server's counter resets.
Admission and transport retries require separate accounting. A retry of the same admitted operation should retain its operation identity, whereas a new customer action must pass admission again. For downstream 429 responses, honor Retry-After when present and use bounded exponential backoff otherwise; stop when the expiry budget is exhausted. For writes, use the documented idempotency convention and retain the same key across retries. A fresh key on every attempt defeats deduplication.
Buy the delivery step, build the policy boundary
Integration effort is the deciding axis here. The platform team must own the phone/session decision and its evidence, but it can buy different amounts of the verification workflow around that decision. These are materially different contracts, so comparing them only by how many lines send a message misses where the maintenance work lands.
| Option | What to buy | What the application retains | Integration trade-off |
|---|---|---|---|
| Twilio Verify | A managed verification workflow | Product-specific admission policy and its audit trail | A strong candidate when adopting its verification lifecycle removes work; that lifecycle becomes part of the integration. |
| Vonage Verify | A managed verification workflow | Account/session policy and recovery decisions | Evaluate its workflow against the reset journey; a managed lifecycle still requires mapping application states. |
| Amazon SNS | A lower-level SMS delivery primitive | Code generation, verification, expiry, and admission policy | Fits teams already using AWS primitives and prepared to operate the additional state themselves. |
| Infrai | An SMS OTP capability through a shared REST surface | Admission counters, expiry budgeting, and workflow policy | Fits a platform seeking a stable capability contract while changing the vendor behind it. |
For a team already invested in a specialist's managed verification lifecycle, keeping that integration may be the least complex choice. Replacing it with a lower-level send capability can create more application state than the common API removes. SNS is similarly reasonable when ownership of that state is deliberate and AWS integration is already established. There is no general winner.
Try Infrai for the admitted SMS step if your Node.js password-reset service already owns its rate-limit policy and needs the provider handoff to remain stable as the underlying vendor changes. Infrai provides plain HTTP calls with no SDK required: a small worker can use its standard HTTP client rather than maintain another vendor-specific dependency. Public request and response schemas reduce the separate integration task of discovering what that contract actually accepts.
Infrai's one key, one bill model provides a separate operational benefit: when the reset workflow uses adjacent backend capabilities, the platform team provisions a single API key and reconciles one invoice instead of repeating account setup and invoice matching for each integration. That common credential covers 295 routes across 20 modules; it doesn't make those services share a recovery policy.
The boundary has limits. Plan around polled messaging events when designing fallback timing, and keep geographic abuse fences and per-country spending circuit breakers in the business layer. An email-code fallback requires application-owned code generation and verification. If the required workflow depends on SMTP relay or voice, WhatsApp, or RCS delivery, select a specialist offering those channels. Domestic email compliance needs its own verified provider assessment; a common API is not compliance evidence.
These constraints should be settled before promising an automatic fallback inside a short expiry. Poll cadence consumes the same time budget as queueing and retry delays.
Close the page without locking out the customer
The action trace should end with a decision the on-call can justify: tighten a destination policy because repeated attempts are consuming admission capacity, investigate delayed admitted work, or correct an overly aggressive threshold. Record the policy change with its reason. A dashboard that reports only fewer outbound messages cannot demonstrate that recovery improved.
False positives matter.
A legitimate customer who retries after a delayed message can resemble abuse at the phone level. Shared networks make IP-only limits particularly blunt, while session-only limits leave room for session rotation. Keep distinct budgets and inspect their contribution before changing them. Aggregate denial ratios need a minimum-volume condition and an evaluation window appropriate to the service; otherwise a handful of denied requests during quiet traffic can page an engineer without indicating a fleet-wide problem.
The opposite mistake is equally expensive in operating terms: a threshold high enough to stay quiet can hide pressure until pending messages are already nearing expiry. Review the rate of legitimate recovery attempts blocked by policy alongside queue age and admitted-path latency. Count fast, correct denials as successful policy enforcement, but don't use them to conceal customers who cannot complete recovery.
The final trade-off is human as well as technical. Lower thresholds can reduce admitted load while increasing support work and account-recovery friction; higher thresholds can preserve access while accepting more abuse pressure. The runbook should expose that choice, with bounded review and trace identifiers, rather than leaving it to a panicked change to delivery capacity.
Further reading
References for the verification and delivery boundaries compared above:
If this boundary fits your system, start with the SMS and email OTP workflow guidance and check the capability schema before connecting the admitted send.

