DEV Community

BrantLockwood468
BrantLockwood468

Posted on

Node.js SMS Notification Evidence: Templates Connect Delivery Status Polling to Resend

TL;DR: For a B2B SaaS password-reset flow, keep template ownership, expiry, and resend authorization in the application. Use SMS as a secondary or urgent notification channel. Poll delivery status for transport evidence, then join that evidence to the exact template revision and reset deadline. A delivered message can still arrive too late to help. Country allowlists, per-user cooldowns, and spending thresholds belong beside that decision.

The useful question is specific: which version of the reset instructions did this user receive, and was the reset still usable? A dashboard that counts delivered SMS messages cannot answer it alone. Neither can a template name that points to whatever copy happens to be current.

Start with template ownership. The team responsible for password recovery should approve the wording and the rules that decide when it may be sent. The messaging adapter carries those decisions to a provider. This makes an expired reset explainable without logging its secret.

Before and after: give the message a business clock

Before: reset requested → SMS accepted → delivery status displayed.

After: reset requested → immutable template revision and expiry recorded → country, suppression, cooldown, and budget checks → send → provider identifier recorded → status polling → delivery evidence joined to reset validity.

Keep both clocks.

The provider clock describes transport. The application clock describes whether the reset authorization remains valid. The UI can show sent, delivered, failed, or undeliverable as transport states while separately explaining that a reset has expired. Don't turn a delivery receipt into evidence that someone successfully reset a password.

Consider an illustrative configuration: a reset lasts 300 seconds, and repeat sends have a 60-second cooldown. Those are application choices, not provider guarantees or a claim about typical delivery time. With that configuration, a recoverable transport failure at second 290 leaves ten seconds of validity. A resend might satisfy the cooldown and still make a poor recovery experience. The product owner must decide whether to require a fresh reset request; the transport adapter cannot infer that policy from a failed status. This is a trade-off between reusing a valid authorization and giving the user enough time to act on it.

A mutable template creates another trap. If a support screen renders the latest wording next to an older message, the screen may describe instructions the recipient never saw. Save an application-owned revision with each attempt. Retain enough nonsecret business metadata to connect the reset request, message attempt, provider identifier, and expiry, with access and retention appropriate to an authentication flow. Keep reset tokens, full message bodies, and recipient phone numbers out of routine diagnostic logs.

How should Node.js SMS alerts use delivery status polling before a resend?

Enforce the decision before sending. The following TypeScript example is an application policy boundary, runnable with a TypeScript runner; it makes no network requests and needs no credentials. All identifiers, times, and thresholds are illustrative. It receives country and budget decisions from the application instead of pretending that a phone prefix establishes jurisdiction or that a delivery status establishes spending authorization.

type Attempt = {
  templateRevision: string;
  expiresAtMs: number;
  lastSentAtMs: number | null;
  suppressed: boolean;
  countryAllowed: boolean;
  budgetReserved: boolean;
  recoverableFailure: boolean;
};

type Decision =
  | { allowed: true; templateRevision: string }
  | { allowed: false; reason: string };

function authorize(
  attempt: Attempt,
  nowMs: number,
  resend: boolean,
): Decision {
  if (nowMs >= attempt.expiresAtMs) {
    return { allowed: false, reason: "expired" };
  }
  if (attempt.suppressed) {
    return { allowed: false, reason: "suppressed" };
  }
  if (!attempt.countryAllowed) {
    return { allowed: false, reason: "country_blocked" };
  }
  if (!attempt.budgetReserved) {
    return { allowed: false, reason: "budget_blocked" };
  }
  if (
    attempt.lastSentAtMs !== null &&
    nowMs - attempt.lastSentAtMs < 60_000
  ) {
    return { allowed: false, reason: "cooldown" };
  }
  if (resend && !attempt.recoverableFailure) {
    return { allowed: false, reason: "failure_not_recoverable" };
  }
  return { allowed: true, templateRevision: attempt.templateRevision };
}

const startedAtMs = Date.parse("2026-11-24T10:00:00Z");
const attempt: Attempt = {
  templateRevision: "password-reset-r7",
  expiresAtMs: startedAtMs + 300_000,
  lastSentAtMs: startedAtMs,
  suppressed: false,
  countryAllowed: true,
  budgetReserved: true,
  recoverableFailure: true,
};

for (const elapsedSeconds of [30, 90, 301]) {
  const decision = authorize(
    attempt,
    startedAtMs + elapsedSeconds * 1_000,
    true,
  );
  console.log({ elapsedSeconds, decision });
}
Enter fullscreen mode Exit fullscreen mode

At 30 seconds, this attempt is blocked by the cooldown. At 90 seconds, the policy permits a resend. At 301 seconds, it is expired. The same template revision follows the allowed decision. That makes the example useful for teaching without inventing a provider payload or response schema.

There is a production boundary here. A pure function does not serialize concurrent requests. In a real sender, reserve the attempt and its spending allowance atomically in application storage, then use one stable idempotency identity for retries of that attempt. Two workers must not each pass a read-only cooldown check and send independently. A new user-authorized resend is a separate attempt; a retry after a rate-limit response remains the same attempt.

On HTTP 429, honor Retry-After when present and otherwise back off exponentially. Recheck expiry before the next attempt. Waiting is part of the reset's lifetime, and a retry timer doesn't extend it. Surface response errors to the worker rather than marking the SMS sent just because the request finished.

Here is the companion read operation for an existing SMS identifier. Set INFRAI_API_ORIGIN to the service's HTTPS API origin, INFRAI_API_KEY to your credential, and SMS_ID to the identifier recorded after sending. Run this TypeScript as a module with a TypeScript runner. It polls once successfully, with bounded retries for rate limiting; the application scheduler owns subsequent polls. It prints only the response's structural keys, leaving transport-state normalization to an adapter checked against the current response schema.

async function readStatus(): Promise<void> {
  const origin = process.env.INFRAI_API_ORIGIN;
  const apiKey = process.env.INFRAI_API_KEY;
  const id = process.env.SMS_ID;
  if (!origin || !apiKey || !id) {
    throw new Error("Set INFRAI_API_ORIGIN, INFRAI_API_KEY, and SMS_ID");
  }
  const base = new URL(origin);
  if (base.protocol !== "https:") {
    throw new Error("The API origin must use HTTPS");
  }
  const url = new URL(`/v1/sms/status/${encodeURIComponent(id)}`, base.origin);
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(10_000),
    });
    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const dateMs = retryAfter === null ? NaN : Date.parse(retryAfter);
      const waitMs = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1_000)
        : Number.isFinite(dateMs)
          ? Math.max(0, dateMs - Date.now())
          : 1_000 * 2 ** attempt;
      await response.body?.cancel();
      if (waitMs > 30_000) {
        throw new Error("Reschedule the status poll after Retry-After");
      }
      await new Promise<void>((resolve) => setTimeout(resolve, waitMs));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Status request failed (${response.status}): ${await response.text()}`);
    }
    const result: unknown = await response.json();
    console.log({
      observedAt: new Date().toISOString(),
      responseKeys: result !== null && typeof result === "object"
        ? Object.keys(result)
        : [],
    });
    return;
  }
}

readStatus().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

This GET does not create a message. Keep the send and resend authorization checks in the first example on the write side; a status poll can remain useful for investigating an expired reset even after sending is forbidden.

Let polling produce evidence, not a second source of truth

Use status and event polling to update transport state after the initial send. Store the provider identifier alongside the application attempt identifier. Keep the poll's observation time distinct from an event timestamp returned by the provider; discovering a state now does not establish that it happened now.

The useful log record is small: application attempt, template revision, reset deadline, normalized transport state, observation time, and policy decision reason. Use attempt identifiers for investigation. Aggregate metrics by bounded dimensions such as template revision and decision reason rather than creating a metric label for each recipient. This is a proposed instrumentation design, not a provider response format.

An alert should lead to a decision. A rise in expiry blocks means recovery attempts are reaching the sender too late or users are asking to repeat expired instructions. Investigate the application timeline. A rise in failed delivery evidence points toward a different investigation. Preserve both signals instead of combining them into one red delivery counter, which would make the owner of the template responsible for transport behavior the copy cannot fix.

Polling has a limitation: the UI has an observation delay. Show the last observed state and its observation time. Choose a bounded polling schedule that stops according to the reset's lifetime and your evidence-retention policy. Don't promise immediate cross-channel status propagation. If inbound STOP or help replies are part of the workflow, poll inbound messages and carry opt-outs into suppression checks before another send.

Cancellation needs its own meaning. Use cancel only for a pending scheduled SMS that the product permits the user to stop. An immediate message already handed off for delivery is not a scheduled task waiting for cancellation. Expiring the reset authorization remains an application action.

Compare providers through the template owner's responsibilities

Twilio, Amazon SNS, and Vonage are real alternatives to evaluate. Treat the table as a comparison of evaluation paths, not a feature certification: the linked documentation establishes where to check each product, while a pilot must establish how its current behavior fits this recovery flow. No delivery benchmark is implied.

Infrai combines a single API key and unified billing with a plain REST API: no SDK to install or client-library version to manage. That shared credential and consolidated bill can reduce handoffs when password recovery uses other backend services too. The trade-off is that this application must own its polling schedule and business guardrails.

Option Evaluation focus for this reset flow Boundary to keep explicit
Twilio Start with its messaging documentation and trace one approved revision through send and delivery evidence. Accept it only after the adapter preserves the application's expiry and resend decisions.
Amazon SNS Start with the SMS documentation and test the same policy inside the proposed AWS integration. Existing infrastructure familiarity doesn't replace a test of country controls and evidence retention.
Vonage Start with its SMS documentation and replay the same initial-send, expired-reset, and suppression cases. Confirm the chosen product's status semantics before mapping them into the UI.
Plain REST option above Any language with HTTP support can call it; the shared credential can cover other backend services. Keep template approval, polling orchestration, country allowlists, and spending thresholds in the application.

The comparison is about ownership. Teams already committed to one of the first three options have a reason to test their existing integration before introducing another dependency. A team seeking a plain HTTP boundary has a different priority. Neither preference proves delivery speed, regulatory suitability, or recovery success. Run the same acceptance cases against every candidate and select the one whose documented behavior and operational workflow your team can explain. If immediate pushed events are a hard requirement, a polling-based integration is not a good fit; evaluate a provider's documented event interface before choosing it.

For EU and US destinations, configure explicit permitted countries and spending thresholds. Don't treat “EU” as a phone-number country or infer compliance from API availability. Maintain your own business metadata for spending attribution and template revisions. Per-call evidence is useful input; the application still owns the aggregation and the decision to stop authorizing new sends.

Two objections worth resolving before rollout

“Could the provider own the templates instead?” It can be reasonable to store rendering assets with a messaging provider when that fits the team's editing workflow. The application should still record which approved revision an attempt used and own the reset's expiration. Keep the copy short and deterministic. A provider template identifier alone is insufficient evidence if its contents can change without a corresponding application revision.

“Could email make the SMS lifecycle unnecessary?” Email can be part of recovery, but adding a channel does not move authorization out of the application. Build the reset or email-code lifecycle in the product, including expiry and suppression decisions, and evaluate channel interfaces separately. Don't assume SMTP relay, voice, WhatsApp, or RCS support from the existence of an SMS API. The practical release gate is modest: demonstrate that an expired reset cannot authorize a new message attempt, that an opt-out blocks a repeat send, and that support can identify the approved template revision without exposing a credential.

The next engineer should be able to explain what happened.

Further reading

References for provider evaluation and email delivery planning:

Top comments (0)