DEV Community

BartholomewVance6831
BartholomewVance6831

Posted on

Node.js Password Reset Email API Timeout Handling With Durable Seller Dispatch

Use a durable dispatch record to control password reset email retries in a serverless Node.js gaming marketplace. Reuse the same mechanism for new-order seller notifications. The deciding constraint is what survives an API timeout: the permission to send another email must remain attached to the original business operation.

TL;DR: record the intent before sending, preserve its identity across retries, and reconcile uncertain sends through message status where possible. A timeout means an unknown outcome. Creating a fresh reset token or seller notification on each retry defeats duplicate prevention.

Consider order order_187, which should notify seller_42 about a marketplace sale. That seller may also request a password reset before opening the order page. These are separate intents. Neither should acquire a new identity because an API takes longer than the caller's deadline.

What changes after an email API request timeout?

The useful question is whether the first request was accepted. A caller's timeout cannot answer it. That changes the build from a send function into a small state machine with a durable record: ready, submitting, accepted, or uncertain. These are application states, not provider response fields.

Start with two business keys. A seller notice belongs to the order and seller. A password reset belongs to the account and current token issuance. Store the issuance reference rather than the secret token in the dispatch record. An atomic insert or claim must decide which concurrent invocation owns the send. A read followed by an unguarded write leaves a race between two serverless invocations.

Keep the record.

If a response includes a message identifier, persist it before acknowledging the work item. If the request times out before that identifier reaches the application, mark the record uncertain. Poll message status where an identifier is available. Where it is missing, preserve the uncertainty; a nearby timestamp cannot prove that a message belongs to this reset request.

For resets, also gate requests by user and recent token issuance. That guard serves a different purpose from transport idempotency. Two HTTP requests can describe the same repeated click, while a later legitimate reset can require a new issuance. Choose the window as an application policy. Don't silently turn it into a permanent block.

For seller notices, retrying the same order notification keeps the same dispatch key. A later cancellation notice is another operation and gets another key. No sender can infer that distinction from an email address. Consider two workers receiving the same order event: both can build valid mail payloads, and both can finish before either sees the other's response. The database claim must reject the second worker before either timeout policy becomes relevant. Otherwise, exponential backoff merely spaces out two independently authorized messages. Trading a little database coordination for a clear send boundary is more useful here than adding more retry configuration.

The smallest scheduler to mailer handoff

Infrai fits when the marketplace needs jobs and email behind a unified REST API covering 295 routes across 20 modules. Adding a capability reuses the HTTP integration rather than introducing another SDK. Its single API key and consolidated bill also mean the scheduler and mailer need one credential injected into the worker. A separate advantage is its self-describing API: public discovery requires no API key and supplies request and response JSON Schema plus runnable examples in 10 languages, including TypeScript. For the seller notification adapter, that lets a developer inspect the exact mail payload before configuring credentials instead of guessing fields from a marketing example.

This executable TypeScript adapter submits an already prepared email payload. The scheduler-to-mailer handoff is the stable dispatch identity; a scheduling receipt is not proof of delivery, so it doesn't belong in the seller's email merely to demonstrate integration.

The worker must first atomically claim a durable dispatch record. That record supplies DISPATCH_KEY.

Generating a random identifier inside the script would discard the identity needed for duplicate prevention. This example implements the transport portion after that claim; it does not implement the database or reset token issuer.

Save it as handoff.ts and run it with a TypeScript-capable Node.js runtime. Set API_BASE_URL to the service's documented v1 API base, and supply INFRAI_API_KEY and DISPATCH_KEY through the worker environment. Set EMAIL_PAYLOAD_JSON to a complete email request validated against public discovery, addressed to the seller. Keeping the verified payload external avoids inventing request field names.

Enable this adapter's automatic rate-limit retries only after verifying that the send capability supports the documented idempotency contract. A platform convention does not prove that every write supports the same guarantee. Preserve the stable key and application guard, and keep replay inside the capability's documented deduplication window.

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

const baseURL = required("API_BASE_URL").replace(/\/$/, "");
const apiKey = required("INFRAI_API_KEY");
const dispatchKey = required("DISPATCH_KEY");
const payload: unknown = JSON.parse(required("EMAIL_PAYLOAD_JSON"));
const pause = (ms: number) =>
  new Promise<void>((resolve) => setTimeout(resolve, ms));

async function send(): Promise<unknown> {
  const deadline = Date.now() + 15000;
  for (let attempt = 0; attempt < 3; attempt++) {
    const remaining = deadline - Date.now();
    if (remaining <= 0) throw new Error("Dispatch budget exhausted");
    const response = await fetch(baseURL + "/email/send", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        "Idempotency-Key": dispatchKey,
      },
      body: JSON.stringify(payload),
      signal: AbortSignal.timeout(Math.min(4000, remaining)),
    });
    const text = await response.text();
    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const dateDelay = retryAfter === null ? NaN : Date.parse(retryAfter) - Date.now();
      const serverDelay = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(dateDelay) ? dateDelay : 0;
      const delay = Math.max(500 * 2 ** attempt, serverDelay, 0);
      if (delay + 4000 >= deadline - Date.now()) {
        throw new Error(`Defer rate-limited dispatch; retry after ${delay}ms`);
      }
      await pause(delay);
      continue;
    }
    if (!response.ok) throw new Error(`${response.status}: ${text}`);
    return JSON.parse(text) as unknown;
  }
  throw new Error("Retry budget exhausted");
}

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

A timeout propagates to the worker. The worker must persist an uncertain outcome rather than mint another key. The three-attempt budget, four-second request deadline, and 15-second overall budget are example settings, not benchmark results or a universal serverless recommendation. Budget response reads and Retry-After delays against the invocation's remaining execution time. If a delay exceeds that budget, persist the next attempt time and return the task to durable scheduling. A definitive rejection can follow a different recovery path from an interrupted request; don't flatten every thrown error into permission to resend.

That last distinction matters more than another retry knob.

Which integration earns its configuration?

An Inngest plus Resend stack separates workflow coordination from the mail service. The application still connects order identity to workflow identity, hands seller data to the sender, persists the response, and reconciles uncertain outcomes. A cron plus Resend setup moves the scheduling integration into the hosting environment; it does not remove the dispatch record.

Option Integration surface Setup work to budget Appropriate fit Main boundary
Combined backend API described above REST without a required SDK One credential plus the durable dispatch adapter Marketplace adding scheduling and messaging together Poll email events; own reset issuance
Inngest plus Resend Workflow integration plus email API or SDK Connect workflow identity to the mail adapter Team choosing workflow and email separately Application still reconciles uncertain sends
Amazon SES AWS email integration through API or SDK Wire the existing job runner to the email service Marketplace already choosing AWS for email Own the job-to-email handoff and duplicate guard
Twilio SMS Messaging API or SDK Add SMS-specific content and channel policy Seller notice explicitly requires SMS GSM-7 versus UCS-2 segmentation affects message construction

Resend is a reasonable boundary when the team wants a dedicated email integration. Amazon SES belongs in the comparison when the team wants the AWS email service and is prepared to own the job-to-email adapter. Twilio is relevant when the seller workflow requires SMS; its GSM-7 versus UCS-2 segmentation makes message content an integration concern. Translating an email template verbatim is a poor SMS plan. None of these options eliminates the application's order identity or reset issuance policy.

Compare the configuration and application glue for the channel you actually need. A combined scheduler and mailer covers more scope than an email-only sender. Conversely, broad coverage is no reason to replace a scheduler and mail adapter that already work for the application.

The combined approach concentrates trust and billing in one vendor. Make that trade-off explicit.

Benchmark this as an integration exercise. Measure time to the first accepted seller notice, credentials injected into the worker, and code needed to recover one deliberately interrupted request. Then run two concurrent password reset requests for the same issuance and inspect how many send permissions the database grants. Record acceptance separately from delivery. These are proposed checks, not results from a completed experiment.

Count the glue.

What I would change at scale

Use a durable outbox tied to the order transaction, plus a separate reset issuance record. Make the claim atomic and give abandoned claims an explicit recovery policy. Standard queues can deliver work at least once, so the consumer must recheck the record before sending. A queue acknowledgment is not an email delivery receipt.

For longer reconciliation work, use a cron trigger and queue worker rather than holding one scheduled invocation open; keep cron execution within its 900-second timeout limit.

Email events in the combined interface are pulled. Recovery needs polling and cannot assume an instant delivery callback will arrive before the serverless deadline. Put a finite reconciliation horizon on uncertain records and surface unresolved ones for review. Sending again merely to clear the queue is not reconciliation.

Password resets also need application-owned email token issuance. An SMS OTP interface does not supply managed email OTP. Scheduled send cancellation is not a sound basis for immediate reset deduplication. Prevent the duplicate before submission.

Keep the first build small: one durable record, one stable operation identity, and a clear uncertain state. Choose the combined API when eliminating another credential and adapter helps. Keep a dedicated stack when its existing integration already earns its place.

References

Top comments (0)