A seller waiting for a new order notification needs to understand when OTP requests for SMS-based 2FA are throttled. Rate-limit those requests in the backend before sending. Template ownership matters: the team writing the SMS and the team enforcing authentication limits must agree on what each message promises.
TL;DR: To rate-limit OTP requests for SMS-based 2FA in Node.js, keep backend counters and request timestamps per phone number in a database or Redis. Apply a configurable request limit plus progressive backoff before requesting an SMS. Return a clear throttle reason and retry delay. Keep the authentication template separate from the marketplace's new-order template, so an order notification never becomes an accidental path around the OTP budget.
Count before sending.
The example is a developer-tools marketplace: a seller signs in to inspect a new order. Authentication owns the OTP policy. The marketplace team owns the order copy. Their shared artifact should be a small decision record that explains why an SMS request was admitted, rather than a dashboard that treats every missing SMS as a delivery failure.
How should we rate-limit OTP requests for SMS-based 2FA and explain the decision?
Before: the browser disables a resend button, the backend receives a request anyway, and the sender's response becomes the only evidence of what happened. A second browser can bypass that local countdown. An order message and a login message may also look similar enough that a seller expects either one to contain a code.
After, in words: seller requests a code → backend resolves the phone and template purpose → shared limiter makes an admission decision → admitted work reaches the SMS sender → the application records the outcome. A rejected request stops at admission. It shouldn't appear as a failed delivery.
That distinction matters.
Use separate outcomes such as admitted, phone_window, and cooldown in application telemetry. These names are your own schema, not provider response fields. An admission counter answers how much work the backend permitted; a send-result counter answers what happened after the sender was called. Neither proves that the seller received or read a code. For the UI, a useful message is “Please wait before requesting another code,” accompanied by the server's retry delay. Don't claim that a new code was sent when admission was denied.
Keep phone numbers, OTP values, and message bodies out of metric labels. Put the template purpose and policy revision there instead. A request identifier can connect restricted diagnostic records without turning a phone number into a dashboard dimension. This is an application design recommendation, not a claim about a messaging vendor's logging defaults.
Template ownership changes the provider decision
Choose who owns the authentication flow before choosing how to send its messages. A transport integration leaves your backend responsible for more policy. A verification product or an authentication platform moves the boundary, so its retry behavior needs to be understood alongside your application's admission rules. Evaluate the template workflow with the person who will actually approve and change the text.
| Option | Relevant boundary | Template ownership question and tradeoff |
|---|---|---|
| Twilio Verify | A verification service | Assess its verification templates and customization rules against seller login copy. A managed verification flow fits teams willing to adopt that product's message workflow. |
| Amazon SNS | SMS publishing | Assess sender and message requirements for the destinations you serve. Your application retains authentication policy and connects message content to its own OTP lifecycle. |
| Firebase Authentication | Phone authentication within an authentication platform | Assess its phone sign-in message settings and supported flow. It fits an application that wants phone verification inside that authentication model; it is a broader choice than an SMS transport. |
| SendGrid | An email alternative to evaluate for the new-order notification | Review its template workflow with the marketplace team if order notices belong in email. This is a separate channel decision; it doesn't replace the SMS login admission policy. |
Infrai combines one key and one bill with a single REST API, no SDK required, covering 295 routes across 20 modules with public self-describing discovery and runnable examples in 10 languages. The shared credential and billing boundary reduces key sprawl and invoice reconciliation across marketplace workers. Plain HTTP lets the authentication worker and order-notification worker use consistent integration conventions without installing SDKs. Public request JSON Schema gives the template owner and backend owner a concrete contract to review together before changing the seller message. These are integration and review advantages; the application still owns its admission policy.
For that option, keep geographic restrictions and destination-based spending circuit breakers in your application, and design communication-event monitoring around polling. Treat email recovery-code generation as application-owned work. A workflow requiring SMTP relay, voice, WhatsApp, or RCS needs a provider supporting those channels; don't infer domestic compliance from the existence of an integration. These selection boundaries matter more than a large capability count when they are requirements for the seller journey.
A small Node.js admission example
Here is an executable TypeScript demonstration of that loop. The numbers are illustrative policy settings: at most 3 admitted requests per 60 seconds, with resend delays of 5, 10, and 20 seconds. They aren't vendor limits or a security standard. Rejected attempts don't extend the cooldown, which avoids letting a stream of denied requests continuously move the seller's next eligible time.
The example uses a Map so the decision and its state update are easy to inspect. Run it in a TypeScript-capable Node.js environment. It makes no network calls and sends no SMS. Simulated timestamps let you see the behavior immediately.
import { performance } from "node:perf_hooks";
type State = { startedAt: number; admitted: number; nextAt: number };
type Decision = {
allowed: boolean;
reason: "admitted" | "phone_window" | "cooldown";
retryAfterSeconds: number;
};
const policy = {
windowMs: 60_000,
maxRequests: 3,
initialBackoffMs: 5_000,
maxBackoffMs: 60_000,
};
const states = new Map<string, State>();
function admitOtp(phone: string, now = performance.now()): Decision {
let state = states.get(phone);
if (!state || now >= state.startedAt + policy.windowMs) {
state = { startedAt: now, admitted: 0, nextAt: now };
states.set(phone, state);
}
const full = state.admitted >= policy.maxRequests;
const eligibleAt = full
? Math.max(state.startedAt + policy.windowMs, state.nextAt)
: state.nextAt;
if (now < eligibleAt) {
return {
allowed: false,
reason: full ? "phone_window" : "cooldown",
retryAfterSeconds: Math.ceil((eligibleAt - now) / 1_000),
};
}
const delayMs = Math.min(
policy.maxBackoffMs,
policy.initialBackoffMs * 2 ** state.admitted,
);
state.admitted += 1;
state.nextAt = now + delayMs;
return { allowed: true, reason: "admitted", retryAfterSeconds: 0 };
}
const seller = {
id: "seller-demo-17",
phone: "+12025550147",
orderId: "order-demo-247",
templatePurpose: "seller-login-otp",
};
for (const atMs of [0, 1_000, 5_000, 15_000, 16_000, 60_000]) {
const decision = admitOtp(seller.phone, atMs);
console.log({
sellerId: seller.id,
orderId: seller.orderId,
templatePurpose: seller.templatePurpose,
atMs,
...decision,
});
}
At 1 second, the cooldown rejects the request. Requests at 5 and 15 seconds are admitted; the attempt at 16 seconds hits the window limit. At 60 seconds a fresh window starts. These are deterministic example decisions, not delivery measurements. The order ID supplies scenario context in the demonstration; production metric labels shouldn't contain an ever-growing set of order IDs.
The critical production change is shared, atomic state. This function runs synchronously in one process, but a Map can't coordinate multiple Node.js instances and loses its contents on restart. Use a database transaction or an atomic Redis operation to check and update the phone's counter and timestamps together. Normalize the phone before looking it up, expire inactive state, and use a consistent clock for the shared decision. Otherwise, two workers can each admit a request against the same old counter. For example, if both read an admitted count of 2 before either writes, each may consider itself the third allowed request. The limit has already failed before the sender sees either operation. An atomic reservation prevents that race; a dashboard can only reveal it afterward. That's the concurrency trap worth reviewing before connecting the sender.
Make admission atomic.
Reserve admission before making the send call. A sender failure should remain visible as a distinct result; automatically refunding every failed attempt can let repeated failures bypass the intended abuse budget. Decide that behavior explicitly. The demonstration covers admission, so it avoids inventing an OTP payload or provider response schema. Connect the admitted branch to your sender only after validating its request contract. Transport retries need a stable operation identifier and an idempotent send contract, so one logical send doesn't become multiple messages. Back off on HTTP 429 and honor Retry-After; distinguish that transport response from the application's own admission decision.
The sender below is a separate executable TypeScript file for an already admitted operation. Set SMS_OTP_URL to the selected platform's absolute HTTPS OTP endpoint, INFRAI_API_KEY to the secret, and SMS_OTP_PAYLOAD to a JSON object validated against that endpoint's discovery schema. Set OTP_OPERATION_ID once per logical send and persist it across retries. The payload is external because template selection and required fields must follow the actual request contract. This program makes a real send request.
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
}
async function sendAdmittedOtp(): Promise<string> {
const endpoint = new URL(required("SMS_OTP_URL"));
const expectedHost = ["api", "infrai", "cc"].join(".");
if (
endpoint.protocol !== "https:" || endpoint.hostname !== expectedHost ||
endpoint.port !== "" || endpoint.username || endpoint.password ||
endpoint.pathname !== "/v1/sms/otp" || endpoint.search || endpoint.hash
) {
throw new Error("Configure the documented HTTPS OTP endpoint");
}
const apiKey = required("INFRAI_API_KEY");
const operationId = required("OTP_OPERATION_ID");
const payload: unknown = JSON.parse(required("SMS_OTP_PAYLOAD"));
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
throw new Error("The OTP payload must be a schema-validated JSON object");
}
for (let attempt = 0; attempt < 3; attempt += 1) {
const response = await fetch(endpoint, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": operationId,
},
body: JSON.stringify(payload),
redirect: "error",
signal: AbortSignal.timeout(15_000),
});
const result = await response.text();
if (response.ok) return result;
if (response.status !== 429 || attempt === 2) {
throw new Error(`OTP send ${response.status}: ${result}`);
}
const retryAfter = response.headers.get("Retry-After");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const dateMs = retryAfter === null ? NaN : Date.parse(retryAfter);
const requestedMs = Number.isFinite(seconds)
? Math.max(0, seconds * 1_000)
: Number.isFinite(dateMs) ? Math.max(0, dateMs - Date.now()) : 0;
const delayMs = Math.max(1_000 * 2 ** attempt, requestedMs);
if (delayMs > 60_000) {
throw new Error(`Defer this operation for ${delayMs} ms`);
}
await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("Retry budget exhausted");
}
sendAdmittedOtp().then(
() => console.log("Sender accepted the operation; delivery is separate"),
(error: unknown) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
},
);
An acceptance response isn't delivery evidence. Keep detailed error bodies in restricted diagnostics, and give the seller a safe status message. A retry delay above this example's 60-second worker budget exits for later scheduling; preserve the operation identifier and wait the full delay before resuming.
Would a provider limit or one shared template be enough?
A provider limit and an application limit answer different questions. The application knows this is the seller's login attempt after an order notification. It can distinguish that purpose before handing work to a sender. Keep backend admission even if the selected service also has controls, and document which layer produces the retry delay shown to the seller. A browser countdown can display that decision; it can't enforce it across devices.
Separate the templates.
Reusing the new-order template for login may look like less review work, but it couples two owners with different promises. Order copy says an order exists. OTP copy explains an authentication action. The marketplace team should be able to edit the first without changing the second's purpose or allowing an order-triggered resend to consume the login budget. Put the purpose and policy revision in the decision record, and review that record alongside the text. That is the useful before-and-after: support can tell a throttled request from an admitted send without guessing from the seller's screenshot.
Sources
References for the comparison boundaries and implementation mechanics:
- Twilio Verify overview: https://www.twilio.com/docs/verify
- Amazon SNS SMS publishing: https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html
- Firebase phone authentication: https://firebase.google.com/docs/auth/web/phone-auth
- SendGrid documentation for reviewing the email alternative: https://www.twilio.com/docs/sendgrid
- Redis transactions: https://redis.io/docs/latest/develop/interact/transactions/
- HTTP Retry-After semantics: https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.3
Top comments (0)