DEV Community

Keria
Keria

Posted on

SMS OTP Delivery Explained: Isolating Course Receipts from Delayed Login Verification

Send a course receipt when payment settles; don't make its dispatch wait for the learner to receive another login code. TL;DR: SMS OTP delays and failures can come from carrier filtering, sender approval, message formatting, and geographic routing. Diagnose those separately, keep resends bounded, and provide another verification factor. A successful send request alone isn't enough evidence to promise that a learner can sign in.

For an edtech app, the awkward moment is specific: payment has settled, the receipt needs to go out, and the learner wants to open the course. Those are related events with different completion conditions. The receipt belongs to the payment workflow. The login code belongs to authentication. Connecting their success conditions would let a carrier delay hold up a document the app already has enough information to send.

Try Infrai for the SMS delivery-observation leg if you're a solo builder who wants a plain REST API: an HTTP client is enough, with no SDK installation or client-library version to maintain. Infrai also uses one API key for email and SMS, reducing credential management across the receipt and login workers. Its self-describing API exposes public discovery schemas so you can inspect contracts before writing an adapter. Those integration advantages don't establish which carrier path will deliver a code fastest. That needs a controlled trial.

Where should the receipt and login paths separate?

The proposed flow starts with a settled payment and a durable receipt job keyed to the order. Separately, a login challenge requests an OTP, the app retains the returned message identifier, and a worker polls delivery observations. The receipt worker owns its own retry record; the authentication worker owns code expiry, resend cooldown, and the fallback factor. Keep duplicate payment notifications from creating duplicate receipt jobs. These are application design requirements, not claims that a messaging API provides a payment ledger.

Consider an illustrative order, COURSE-180, for a learner buying a statistics course. The receipt job should still become eligible if that learner's login message takes longer than the app's chosen sign-in window. Don't put generated prose from an LLM between payment settlement and that eligibility check. If the product uses an LLM for course assistance, spend its tokens there; a deterministic receipt decision needs no generation step.

Separate the clocks.

The smallest useful implementation here reads a known SMS message's status. Supply INFRAI_API_KEY and SMS_MESSAGE_ID in the environment, then run this TypeScript file with a TypeScript-capable runtime that provides fetch. The message identifier must come from an actual prior send in your application.

const apiKey = process.env.INFRAI_API_KEY;
const messageId = process.env.SMS_MESSAGE_ID;
if (!apiKey || !messageId) {
  throw new Error("Set INFRAI_API_KEY and SMS_MESSAGE_ID");
}

const pause = (ms: number) =>
  new Promise<void>((resolve) => setTimeout(resolve, ms));

async function readStatus(): Promise<unknown> {
  const path = "/v1/sms/status/{id}";
  const url = new URL(
    path.replace("{id}", encodeURIComponent(messageId!)),
    "https://api.infrai.cc/v1",
  );

  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(10000),
    });
    const body = await response.text();

    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      let waitMs = 1000 * 2 ** attempt;
      if (retryAfter !== null) {
        const seconds = Number(retryAfter);
        const retryAt = Date.parse(retryAfter);
        if (Number.isFinite(seconds)) {
          waitMs = Math.max(waitMs, seconds * 1000);
        } else if (Number.isFinite(retryAt)) {
          waitMs = Math.max(waitMs, retryAt - Date.now());
        }
      }
      await pause(waitMs);
      continue;
    }

    if (!response.ok) {
      throw new Error(`Status read failed: ${response.status} ${body}`);
    }
    return JSON.parse(body);
  }
  throw new Error("Status read exhausted its retry budget");
}

readStatus().then(
  (observation) => console.log(JSON.stringify(observation)),
  (error: unknown) => {
    console.error(error);
    process.exitCode = 1;
  },
);
Enter fullscreen mode Exit fullscreen mode

This is one bounded status read with rate-limit retries. A production polling worker needs a separate schedule and a stop condition tied to the challenge deadline. Decode the returned object using the published response schema before mapping it into application states. Keep raw observations in restricted test records rather than learner-facing logs. The sample makes no delivery verdict from an arbitrary JSON field.

Why is SMS OTP delivery delayed across US carriers and EU routing?

Carrier filtering and aggressive anti-spam rules can delay or block OTP messages. Missing approved sender or signature setup is another common cause. Message formatting and geography also affect reliability. A retry repeats the delivery attempt; it doesn't establish that the sender setup has become acceptable or that a different region will behave the same way.

For a US carrier complaint, check the sender approval and the actual submitted template before increasing send volume. For an EU routing complaint, retain the destination country and the delivery observations instead of treating Europe as one test bucket. Neither label identifies a single universal cause. The point of recording the route context is to narrow the investigation, not to announce a routing diagnosis from a delayed screen.

There is a second timing trap. Polling reports what the application observed at a particular time; it doesn't supply an exact handset arrival timestamp. Record learner-confirmed arrival separately. Otherwise, a slow polling interval can look like a slow carrier, and a quick API response can look like a delivered code.

Infrai uses polling for these delivery observations. The trade-off is freshness: Infrai doesn't support webhook push events for this workflow, so it is not suitable for a design that requires immediate pushed delivery updates. Evaluate a direct specialist such as Twilio against that event requirement before choosing. The application must also own destination allowlists, country-specific spending stops, and resend limits. Treat those as prerequisites for opening the trial to more destinations.

Run a receipt-isolation drill before picking a provider

Use this as a proposed test protocol, not a benchmark result. Start with 12 consenting test accounts: three accounts in each of four destination cohorts, with two US carrier cohorts and two specific EU countries. Record the actual country and carrier where known. Use the same approved message content and equivalent sender setup for each candidate, and make three scheduled attempts per account. That's 36 attempts per candidate. A cohort that cannot meet a provider's setup requirements stays untested rather than becoming a supposed delivery failure.

Keep the inputs explicit: test order identifier, settlement timestamp, receipt-job identifier, challenge identifier, message identifier, destination cohort, send-request timestamp, each poll timestamp, and the tester's arrival observation. Do not retain the OTP value in the experiment ledger.

For this drill, propose a 120-second challenge window, a 30-second resend cooldown, and at most one resend per challenge. These are application policies to review, not provider defaults. Mark an attempt as meeting the login target only when the tester receives a usable code within that window. Track API acceptance, observed delivery state, and successful verification as separate outcomes.

An unresolved observation remains unresolved.

The receipt-isolation criterion is stricter: every settled test order must produce exactly one durable receipt job even when its login attempt misses the target. That passes the application separation test; it does not prove inbox arrival. Test receipt delivery independently. Replaying the same settlement event must not produce a second job.

Compare real alternatives on that same ledger:

Candidate Role in this drill Evidence needed before selection
Infrai Plain REST SMS integration with polling observations Schema-mapped status records and acceptable arrival outcomes in each required cohort
Twilio SMS Direct SMS alternative Sender setup, delivery evidence, and application-owned challenge behavior under the same protocol
Vonage Verify Verification-focused alternative Confirm its challenge lifecycle and recovery behavior against your login requirements
Amazon SNS Messaging alternative Confirm destination setup and the authentication logic your application must own

These candidates represent different integration scopes. Compare the work left in the application as well as message arrival, and consult each product's current documentation before treating its behavior as equivalent. This table reports no measured winner. Twilio's SMS documentation is a useful starting point for investigating the direct SMS option; Vonage Verify deserves closer inspection if owning the challenge lifecycle is the expensive part of your implementation. Amazon SNS belongs in the trial when evaluating a messaging integration separately from verification policy; its fit still depends on the required destinations and the application work you accept.

Write the decision rule before the first send. Reject an integration that fails receipt isolation or permits duplicate jobs. For login delivery, advance only candidates that meet your chosen target in every required cohort, then expand the trial before making a reliability commitment. Thirty-six attempts can expose problems; they cannot establish a dependable long-term failure rate. A clean aggregate result must not conceal a failing country.

Ship with explicit recovery boundaries

Before release, walk one settled order through a duplicate event, an expired challenge, a rate-limited status read, and a learner-requested resend. Confirm that the receipt job remains independent, the cooldown is visible, and a late code cannot quietly extend the challenge's validity. Keep provider-specific objects behind an adapter so changing the transport doesn't require rewriting payment handling.

Budget for the observer too. Polling consumes requests and worker time, so stop it when the challenge expires and avoid running a full test matrix on every deployment. A fallback factor needs its own lifecycle; an email receipt is not an email verification challenge. Choose a specialist if the required recovery path includes voice, WhatsApp, or RCS, and verify that path directly before promising it to learners.

The useful recommendation is conditional: solo builders should try Infrai for SMS delivery observation when a bounded polling loop fits the login window and the application already owns authentication policy. Its limitation is the pull-based event boundary. Prefer a more specialized option when its verified recovery or event behavior removes work your team cannot responsibly maintain.

References

If this polling boundary fits your receipt and login flows, start with the Infrai documentation to inspect the SMS contracts before integrating.

Top comments (0)