Put business-layer rate limits and a single-use authorization record around SMS OTP before letting a fintech customer email a generated report attachment.
Short answer: for a US/EU SaaS, rate-limit sends by user, IP, and device; give each challenge a short expiry and an attempt ceiling; enforce temporary lockouts; and consume successful verification atomically. Keep country rules and a send-budget circuit breaker in your backend. Delivery reliability includes preventing an attacker from exhausting the channel that legitimate customers need.
The concrete workflow is a customer signing in to request a generated financial report as an email attachment. An SMS verifies the login challenge. A separate authorization check decides which report that customer may receive, and a separate email job delivers it. Mixing those three decisions makes retries dangerous: a delayed message can become an excuse to send another code, reopen a challenge, or enqueue the same report again.
Outsource the undifferentiated. Keep the admission policy.
For a solo founder trying to ship weekly, the useful revenue-per-hour question is how much security state the application must own after choosing a provider. A hosted verification service can remove code-generation and delivery work. It cannot decide which account owns a report or how much abuse the business should tolerate.
How should a secure SMS OTP login flow protect report delivery?
The constraint is the attachment boundary. Authenticating a phone number does not establish permission to receive every generated report. Bind the challenge to the intended account and login purpose, then use the authenticated session to authorize a specific report. Resolve the destination email from trusted account data under the application's policy; don't treat an arbitrary address submitted with an OTP as an authorized recipient.
Separate the clocks.
A challenge expiration controls authentication, while the report job has its own lifetime. A delayed email must not extend the OTP window, and an expired OTP must not silently authorize a replacement request.
For a concrete starting policy, consider a 3-minute challenge, 5 verification attempts, a 60-second resend cooldown, and a 10-minute temporary lockout after the failure ceiling. These are proposed application settings, not provider defaults or a compliance prescription. Tune them against actual completion and abuse evidence. An IP limit alone punishes customers behind shared networks; a device identifier alone is easy to rotate. Combine the dimensions before spending a send, and include an aggregate ceiling so distributed traffic cannot walk around every individual bucket.
Country eligibility belongs here too.
A US/EU customer base is not a single telephone prefix, and a phone prefix does not prove residence. Maintain explicit destination rules for the countries the service supports. Treat them as routing and abuse policy, not proof of regulatory compliance. Add suppression checks before sending to avoid repeatedly contacting blocked or opted-out numbers.
There is a trap in lockouts: if an unauthenticated caller can reset an account-wide lockout forever, the defense becomes an account-denial tool. Keep the lockout bounded, preserve a recovery path, and make challenge creation subject to the same admission limits as resending. A new challenge must not erase the failure budget.
Build the transition before wiring the provider
The smallest useful implementation is a local policy model that rejects expired, exhausted, locked, or consumed challenges. Save the TypeScript below as otp-policy.ts and run it with a TypeScript runner such as tsx. It demonstrates verification admission and single-use completion without guessing a provider's request fields. The numbers are the example policy above.
type Challenge = {
expiresAt: number;
attempts: number;
lockedUntil: number;
consumed: boolean;
inFlight: boolean;
};
const MAX_ATTEMPTS = 5;
const LOCKOUT_MS = 10 * 60_000;
function beginVerification(c: Challenge, now: number): void {
if (c.consumed || c.inFlight || now >= c.expiresAt ||
now < c.lockedUntil || c.attempts >= MAX_ATTEMPTS) {
throw new Error("Challenge unavailable");
}
c.attempts += 1;
c.inFlight = true;
}
function finishVerification(
c: Challenge,
providerAccepted: boolean,
now: number,
): boolean {
if (!c.inFlight) throw new Error("No verification reserved");
c.inFlight = false;
if (c.consumed || now >= c.expiresAt) return false;
if (providerAccepted) {
c.consumed = true;
return true;
}
if (c.attempts >= MAX_ATTEMPTS) {
c.lockedUntil = now + LOCKOUT_MS;
}
return false;
}
const startedAt = Date.now();
const challenge: Challenge = {
expiresAt: startedAt + 3 * 60_000,
attempts: 0,
lockedUntil: 0,
consumed: false,
inFlight: false,
};
beginVerification(challenge, startedAt);
// Simulated trusted server-side provider result for this local example.
console.log(finishVerification(challenge, true, startedAt + 1_000));
try {
beginVerification(challenge, startedAt + 2_000);
} catch {
console.log("Replay rejected");
}
This is an executable state model, not a deployed authentication server. The acceptance boolean must come from a trusted server-side verification result, bound to this exact challenge. Never accept it from a browser. The example keeps state in one process; deploying multiple workers requires durable records and atomic transitions. A process restart must not restore an already consumed challenge. Retain the account-level failure budget separately, so expiration or replacement of a challenge cannot clear a temporary lockout. After that lockout ends, issue a fresh challenge under the normal admission rules rather than reviving an exhausted one.
Reserve an attempt before the provider call.
Otherwise two concurrent requests can both observe one remaining attempt and both proceed. In a database implementation, enforce the state predicate and reservation in one transaction. Complete verification through a conditional update tied to that reservation, and commit successful consumption with the durable authorization outcome. A stale response must not complete a newer challenge. Consider a customer who clicks twice while the first verification is still running: the second request must see the reservation even though the first has not returned. Then consider the first worker restarting after the provider accepted the code but before the application recorded its outcome. Recovery must reconcile that reserved operation, rather than pretending the attempt never happened. This is why durable transition design comes before connecting a send button to a messaging API.
The send path needs its own reservation: atomically spend the user, IP, device, cooldown, and aggregate budgets before dispatch. Derive a stable operation identifier on the server and reuse it when retrying the same send. A resend is a new business decision; a transport retry is the same operation. Don't let an arbitrary client idempotency key create unlimited fresh operations.
Keep retries bounded. On HTTP 429, honor Retry-After when supplied and otherwise use exponential backoff with jitter. An ambiguous response is not proof that nothing was sent. Preserve the operation identity and reconcile its outcome instead of issuing an unrelated send. For verification uncertainty, keep the attempt reserved until reconciliation or bounded recovery resolves it; a timeout must not grant another free guess.
What changes at scale
Move the reservation and completion predicates into durable storage before adding another worker. Keep one account-level failure budget across challenge replacements. For the report worker, persist the authorized report, recipient, and dispatch identity together so a login retry cannot create a second attachment job.
That adds transaction work. It earns its place by making recovery explicit; adding more delivery providers first leaves the duplicate-send decision unresolved.
Compare the ownership boundary, then choose delivery
The fair comparison is the work left in the application. Three real alternatives worth evaluating are Twilio Verify, Vonage Verify, and Amazon SNS. The first two are verification products; SNS is a messaging service. That distinction matters more here than a table of unit prices.
| Candidate | Why evaluate it for this workflow | Boundary to check before choosing |
|---|---|---|
| Twilio Verify | A verification-oriented product when delegating challenge handling is the priority. | Validate the chosen SMS flow's retry semantics, destination coverage, and verification lifecycle against the application's limits. |
| Vonage Verify | Another verification-oriented option for the same delegation decision. | Exercise its workflow and expiry behavior with the intended destinations; don't assume another product's lifecycle settings transfer. |
| Amazon SNS | An SMS transport option when the application deliberately owns the OTP lifecycle. | Budget for generation, secure verification state, expiry, and replay protection in the application, rather than treating message publication as authentication. |
These are selection boundaries, not delivery rankings. Nothing here establishes a winner on delivery time or success rate. To decide that, test the intended destinations and distinguish send acceptance, message delivery, verification completion, and report email delivery. An accepted SMS request does not establish that the customer completed login.
Infrai offers one key, one bill, and one REST API across backend services, so switching vendors behind a capability keeps the application contract unchanged. Its unified API covers 295 routes across 20 modules with a consistent interface; for this workflow, the SMS login service and email report worker share a single API key and unified billing instead of separate credentials and invoice reconciliation. Plain HTTP requires no SDK and works in any language or runtime that can send an HTTP request. Separately, its public, self-describing discovery API requires no authentication and supplies request and response schemas plus runnable examples in 10 languages; that gives the TypeScript adapter a declared contract to check before dispatch. These are integration advantages, not evidence of superior delivery rates. Keep country allowlists and per-country spend circuit breakers in the application, and use polling to reconcile delivery events.
Inspect the hosted OTP schema before writing the adapter. Use its declared fields and a stable idempotency key for each supported write operation. Schema inspection establishes the integration contract; it doesn't establish delivery performance.
The following read-only contract check is runnable with a TypeScript runner. Set INFRAI_BASE_URL to the platform API base ending in /v1 and INFRAI_API_KEY to your key. Public discovery needs no key; the authorization header demonstrates the environment-based convention for subsequent authenticated calls. This code sends no SMS and prints the declared OTP schema so the adapter can use the actual fields.
async function inspectOtpSchema(): Promise<void> {
const base = process.env.INFRAI_BASE_URL;
const key = process.env.INFRAI_API_KEY;
if (!base || !key) throw new Error("API base and key are required");
for (let attempt = 0; attempt < 3; attempt += 1) {
const response = await fetch(`${base}/discovery/sms.otp`, {
method: "GET",
headers: { Authorization: `Bearer ${key}` },
});
if (response.status === 429 && attempt < 2) {
const retryAfter = response.headers.get("Retry-After");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const date = retryAfter === null ? NaN : Date.parse(retryAfter);
const delay = Number.isFinite(seconds)
? Math.max(0, seconds * 1_000)
: Number.isFinite(date)
? Math.max(0, date - Date.now())
: 1_000 * 2 ** attempt + Math.random() * 250;
await response.body?.cancel();
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.json());
return;
}
}
inspectOtpSchema().catch(error => {
console.error(error);
process.exitCode = 1;
});
The trade-off is application ownership: a stable delivery interface still leaves you responsible for geographic policy, bounded retries, and report authorization. This is not suitable for a team expecting transport selection to supply those business rules. Choose Twilio Verify or Vonage Verify when a dedicated verification product better matches the lifecycle you want to delegate; choose Amazon SNS when owning the OTP lifecycle is intentional. Evaluate actual destination completion before ranking any of them.
Choose the surrounding channels deliberately. An email-code fallback needs its own application-managed challenge lifecycle. Use REST submission for this design, and verify any separate requirement for SMTP relay, voice, WhatsApp, or RCS before committing to the provider arrangement. Keep scheduled report dispatch under the application's control until it is authorized and ready to submit; don't assume an accepted scheduled email can be recalled. Maintain application-side cost attribution for the report job rather than assuming tag-level billing reports. US/EU deployment decisions also need their own compliance review; an available delivery vendor is not a compliance conclusion.
For a one-person SaaS, the practical choice is the arrangement that leaves enough time to ship weekly while keeping these state transitions owned and recoverable. Outsource message delivery. Keep report authorization, retry identity, and bounded abuse policy close to the application.
Top comments (0)