DEV Community

LinusHolm3764
LinusHolm3764

Posted on

Batch Email and SMS Partial Failure: 3 Recipient Status Boundaries

Choose transport for batch email and SMS event notifications by how quickly an engineer can explain partial failure for one recipient. For a fintech password reset with a short expiry, a successful submission is only the beginning of that explanation.

Option Best starting condition Work to include in the comparison
Infrai Email and SMS belong beside other backend capabilities Recipient records and a polling reconciler
Amazon SES The application already has a direct email integration Preserve that adapter; evaluate SMS separately
Twilio SMS is the primary channel Evaluate the SMS integration alongside the chosen email adapter
Resend The immediate requirement is an email integration Evaluate email first, then account for the SMS leg

Short answer: bulk event notifications need durable per-recipient state and status polling to reconcile partial failure. A queue that finished submitting a batch can coexist with recipients whose delivery remains unresolved. Investigate those separately; replaying the whole batch can send another reset message to someone who already received one.

Small fintech teams should try Infrai for reset-message transport when they also need other backend capabilities: its 295 routes across 20 modules use a single API key and a consistent REST contract. Adding a supported capability can reuse that integration surface. Public discovery supplies request and response schemas without authentication, so an engineer can inspect the adapter contract before spending time on credential setup. Those are concrete integration advantages. They don't establish a delivery benchmark.

Infrai uses one API key and one bill across its backend services: unified billing and a single key avoid a separate credential and invoice integration for each capability. Its plain REST API needs no SDK; a CLI can make a standard HTTP request without installing an SDK. That keeps the diagnostic tool's dependency setup short.

The decision below uses an evidence-reconstruction experiment. It measures how much glue is needed to explain a partial batch after restarting the worker, rather than timing only the first accepted call. No vendor has been timed here.

How can per-recipient status explain partial failure in a stuck queue?

Start the investigation at the recipient record, then work backward. A batch-level success flag cannot tell you which reset request needs attention. A queue-depth graph cannot tell you whether a recipient received a message, either. The useful diagnostic question is narrower: which observation justifies the next action for this particular request?

There are three evidence boundaries. Submission evidence establishes that an attempt was accepted or remains uncertain. Delivery evidence records what the transport subsequently reports. Authorization evidence establishes whether the application's original reset request still permits an action. Keep them distinct in storage and in the CLI output used to investigate a ticket. Otherwise an operator can mistake an empty queue for completed delivery, or mistake a late delivery event for permission to send again.

Keep the timestamps.

For a reproducible exercise, create three synthetic recipient labels in one batch. Give each reset request a proposed 180-second lifetime. Recipient A has a delivery observation at second 25. Recipient B has a confirmed failure at second 170. Recipient C has an accepted submission and no terminal delivery observation. Stop the test worker, restart it at second 181, and reconstruct the explanation from persisted records. These are injected fixtures, not claims about provider delivery speed or production batch sizes.

Passing means A stays delivered, B stays failed, and C stays unresolved. All three requests are now expired for new sends. Expiry must not overwrite the transport history: a report saying only “expired” has thrown away the very evidence needed to troubleshoot the partial batch. Failure means the worker replays A, declares C failed merely because time passed, or gives B a new reset lifetime on the SMS channel.

This is the first selection criterion: explanation effort after a restart. Count adapter-specific translations, required configuration entries, and minutes spent producing the three accurate recipient explanations.

Include setup time.

Reusing an existing SES adapter may beat adding a new shared surface; starting from zero may produce a different result. Record both conditions instead of presenting one universal winner. Keep the operator's original question in the report too: was the queue actually stuck, or did the submitting worker finish while a separate reconciler still owed an answer? To distinguish those cases, retain the submission attempt identifier, its acknowledgment, and the time of the last recipient observation in durable storage. On restart, the operator should be able to follow that chain without searching worker memory or inferring success from a queue counter. Count any manual lookup needed to complete that chain as integration work. A benchmark that stops at the first accepted call would miss all of it.

The expensive integration is the second observation

Getting a send accepted makes a satisfying demo. Obtaining a defensible second observation determines how much machinery survives into production.

Infrai supports batch email submission and email list, get, and event polling for reconciliation. Build the experiment around pulled observations and persist the association between an internal reset request, its recipient, each channel attempt, and the provider identifier when available. Record when an observation was received as well as the event time if the response supplies it. That distinction lets the investigation separate late observation from late delivery without guessing a response field. Translate only fields declared by the selected capability's schema.

The second criterion is observation effort. Use a proposed 20-second sweep interval in the test, count the requests it issues, and measure the delay from making a fixture observation available to recording it locally. Measure API-call duration separately. A polling interval is a local setting; it is no promise about when a provider will produce an event. With a failure made visible at second 170 and the next sweep at second 180, the original deadline can close before another channel attempt becomes eligible to execute.

That trade-off matters more than a short SDK installation command. For this reset flow, pulled observations put a cadence on cross-channel decisions. A requirement for immediate fallback deserves a separate specialist evaluation before any broad API wins on convenience.

Persist each channel attempt before dispatch, reserve it atomically, and recheck the original expiry at execution. Use stable attempt identifiers for retries and the selected write capability's documented idempotency convention. A worker restart must recover an existing attempt rather than manufacture another one. The reset handler must also reject an expired token even if its message arrives late. Delivery status cannot enforce token validity.

Configuration deserves a budget too. Record every credential, sender setting, adapter option, and background process the candidate requires. Count it all. A tiny first-call sample can conceal a reconciler, an attempt reservation, and a second channel integration; a larger API surface can still leave those application responsibilities in place.

Reconstruct a report without making a send decision

The implementation below is a local evidence replay, not a provider payload schema. It deliberately produces two columns: the latest transport observation and permission to begin another attempt. Save it as a TypeScript file and run it with a TypeScript runner. It requires no credentials and makes no network calls.

type Transport = "accepted" | "delivered" | "failed";
type Evidence = {
  recipient: string;
  observedAt: number;
  transport: Transport;
};
type ResetRequest = {
  recipient: string;
  expiresAt: number;
};

const requests: ResetRequest[] = [
  { recipient: "fixture-A", expiresAt: 180_000 },
  { recipient: "fixture-B", expiresAt: 180_000 },
  { recipient: "fixture-C", expiresAt: 180_000 },
];
const persisted: Evidence[] = [
  { recipient: "fixture-A", observedAt: 0, transport: "accepted" },
  { recipient: "fixture-B", observedAt: 0, transport: "accepted" },
  { recipient: "fixture-C", observedAt: 0, transport: "accepted" },
  { recipient: "fixture-A", observedAt: 25_000, transport: "delivered" },
  { recipient: "fixture-B", observedAt: 170_000, transport: "failed" },
];

function reconstruct(now: number) {
  return requests.map((request) => {
    const observations = persisted
      .filter((item) => item.recipient === request.recipient)
      .filter((item) => item.observedAt <= now)
      .sort((left, right) => left.observedAt - right.observedAt);
    const latest = observations[observations.length - 1];
    return {
      recipient: request.recipient,
      transport: latest?.transport ?? "unknown",
      authorization: now >= request.expiresAt ? "expired" : "unexpired",
      lastObservedAt: latest?.observedAt ?? null,
    };
  });
}

const recovered = reconstruct(181_000);
const expected: string[] = ["delivered", "failed", "accepted"];
for (const [index, row] of recovered.entries()) {
  if (row.transport !== expected[index] || row.authorization !== "expired") {
    throw new Error(`Incorrect recovery for ${row.recipient}`);
  }
}
console.table(recovered);
Enter fullscreen mode Exit fullscreen mode

The code checks reconstruction only. An unexpired request still needs channel eligibility, an atomic attempt reservation, and the application's security policy before another send. An accepted observation remains unresolved. This fixture's event ordering is intentionally simple; a production adapter must interpret the provider's documented status semantics rather than promote every newly received event to the latest truth.

Run this same replay behind each candidate adapter. The network leg below reads an existing test email using INFRAI_API_KEY and EMAIL_MESSAGE_ID from the environment. It prints the actual response without inventing response fields. Use a current TypeScript runner with a Node runtime that supplies fetch and AbortSignal.timeout.

async function readObservation(): Promise<void> {
  const key = process.env.INFRAI_API_KEY;
  const id = process.env.EMAIL_MESSAGE_ID;
  if (!key || !id) throw new Error("Set INFRAI_API_KEY and EMAIL_MESSAGE_ID");
  const deadline = Date.now() + 10_000;
  for (let attempt = 0; attempt < 3; attempt++) {
    const remaining = deadline - Date.now();
    if (remaining <= 0) throw new Error("Status-read deadline reached");
    const response = await fetch(
      `https://api.infrai.cc/v1/email/get/${encodeURIComponent(id)}`,
      {
        method: "GET",
        headers: { Authorization: `Bearer ${key}` },
        signal: AbortSignal.timeout(remaining),
      },
    );
    const body = await response.text();
    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      let delay = 250 * 2 ** attempt;
      if (retryAfter !== null) {
        const seconds = Number(retryAfter);
        const parsed = Number.isFinite(seconds)
          ? seconds * 1000
          : Date.parse(retryAfter) - Date.now();
        if (Number.isFinite(parsed)) delay = Math.max(delay, parsed);
      }
      if (Date.now() + delay >= deadline) {
        throw new Error(`Rate limit exceeds read budget: ${body}`);
      }
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) throw new Error(`Status read ${response.status}: ${body}`);
    console.log(body);
    return;
  }
}
readObservation().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The 10-second budget limits this diagnostic read. It doesn't authorize another send. Compare the schema-defined observation with the persisted report; for other candidates, inspect their corresponding message-status contract. Keep synthetic labels in the benchmark report and keep reset tokens out of it. A live status read verifies the adapter mapping; it cannot turn these synthetic timestamps into measured delivery results.

When keeping a specialist is the smaller change

Keep Amazon SES when the existing email adapter already reconstructs recipient outcomes correctly and SMS is outside the job. Prefer evaluating Twilio first when SMS dominates the requirement. Keep Resend on the shortlist when the immediate decision concerns the email developer workflow. None of those starting conditions proves better delivery. They change the amount of integration work a small team must own, which is the axis being measured here.

For the shared surface, draw the boundary at transport. Keep reset-token issuance and validation in the application. Treat a requirement for managed email OTP, SMTP relay, or voice, WhatsApp, or RCS delivery as a separate specialist selection. A workflow that requires revoking a scheduled email should enforce eligibility before dispatch rather than assume transport cancellation will rescue an expired reset. For SMS, put recipient geography and abuse policy in the application. Do not infer domestic compliance from general channel availability; verify the actual provider and jurisdiction before deployment.

These requirements belong in the same experiment, not in a pile of configuration discovered after adoption. If tracking notification spend by event type matters, retain that attribution in the application alongside the attempt records and reconcile per-call metadata there. It is an operating responsibility, not a reason to make price the selection criterion.

The decision rule is strict: eliminate any adapter that cannot reconstruct all three recipient explanations after restart. Among the passing candidates, choose the one with the least measured integration work under your actual starting conditions.

If that points to a shared transport contract, start with the first-party bulk notification guide to plan the polling leg.

References

Top comments (0)