Skip to content
All articles

Engineering · 12 November 2026 · 7 min read

Idempotency keys: retry email sends without sending twice

Rampsend team

Send it once, even on retry

Networks fail in the least convenient way possible: after your request reached the server but before the response reached you. Your code sees a timeout and has no idea whether the email went out. Retry, and the customer might get two receipts. Don't retry, and they might get none. Idempotency keys remove that dilemma, and they cost one header.

The failure modes retries must survive

A send request can go wrong at several points, and they don't all mean the same thing.

  • The request never left your machine. DNS failed, the connection was refused. Nothing was sent; retrying is safe even without a key.
  • The request reached the server and failed there. You get a 5xx response. Depending on where it broke, the email may or may not have been handed off.
  • The server succeeded but the response was lost. A load balancer timed out, a mobile connection dropped, your process was killed while waiting. The email was sent and you don't know it.
  • Your own code ran twice. A queue worker crashed after sending but before acknowledging the job, so the job is delivered again. A user double-clicked "Resend invoice". A cron job overlapped with the previous run.

The last two are the dangerous ones. From the caller's side they are indistinguishable from a failure, and the natural fix, retrying, produces a duplicate. Duplicate receipts look sloppy; duplicate password resets confuse people; duplicate "your payment failed" emails generate support tickets and sometimes spam complaints.

How idempotency keys work

The idea is widely used in payment APIs. You generate a key that identifies one logical operation and send it with the request. The server records the key and the outcome. When a request arrives with a key it has seen before, it doesn't do the work again; it returns the result it stored the first time.

Rampsend's /api/v1/emails endpoint follows this pattern. The behaviour, from the idempotency section of the API reference:

SituationWhat you get
First request with a new keyThe email is sent and the response is stored with the key
Same key, same body, first one finishedThe original response, with an Idempotent-Replayed: true header. Nothing is sent or charged again
Same key while the first is still running409 idempotency_conflict. Wait briefly and retry with the same key
Same key, different body422 idempotency_key_reused. This is a bug in your code, not a transient error
The first attempt ended in a 5xxNot stored, so a retry with the same key runs again

That last row matters. A server error means the request didn't complete, so the key isn't locked to a failure. Your retry gets a genuine second attempt rather than a replay of the error.

Choosing a good key

A key should identify the operation, not the attempt. The test is simple: if your code ran this step again for the same reason, would it produce the same key? If yes, duplicates are caught. If the key changes on every attempt, it protects nothing.

Good keys come from your own data: order-1042-receipt, signup-8812-welcome, invoice-INV-3391-reminder-2, or reset-request-55107 for a password reset tied to the request record you created.

Some guidelines:

  • Derive it from stable identifiers. Order id plus message type is ideal for receipts. For messages a user can legitimately request more than once, such as password resets, include the id of the request record you created, or a timestamp you stored, not the current time at send.
  • Never generate it inside the retry loop. A random UUID created per attempt defeats the purpose. If you want a UUID, create it once when the job is created and store it with the job.
  • Scope it to one message type. order-1042 alone would collide between the receipt and the shipping notice. Add the purpose.
  • Keep the body identical on retries. Build the request body once and reuse it. If a retry recomputes something that changes, like a "sent at" timestamp in the HTML, you'll get a 422 instead of a replay.

A retry loop in TypeScript

Here is a small, dependency-free helper that sends one request to POST /api/v1/emails, retries the errors that are safe to retry, honours Retry-After, and backs off exponentially with jitter.

TS
const API = "https://app.rampsend.com/api/v1/emails";type Recipient = { id: string; to: string; status: "queued" | "sent" | "suppressed" | "failed"; error?: string };type SendResponse = { id?: string; status?: string; data: Recipient[] };const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));// 0.5s, 1s, 2s, 4s… capped at 20s, with full jitterconst backoff = (attempt: number) => Math.random() * Math.min(20_000, 500 * 2 ** (attempt - 1));export async function sendEmail(body: Record<string, unknown>, idempotencyKey: string, maxAttempts = 6) {  const payload = JSON.stringify(body); // serialise once so every retry is byte-identical  for (let attempt = 1; ; attempt++) {    let res: Response;    try {      res = await fetch(API, {        method: "POST",        headers: {          Authorization: `Bearer ${process.env.RAMPSEND_API_KEY}`,          "Content-Type": "application/json",          "Idempotency-Key": idempotencyKey,        },        body: payload,        signal: AbortSignal.timeout(15_000),      });    } catch (err) {      // Timeout or network error: the outcome is unknown, so retry with the same key.      if (attempt >= maxAttempts) throw err;      await sleep(backoff(attempt));      continue;    }    if (res.ok) {      const replayed = res.headers.get("Idempotent-Replayed") === "true";      const json = (await res.json()) as SendResponse;      return { ...json, replayed };    }    const err = (await res.json().catch(() => ({}))) as { code?: string; error?: string };    const retryable =      res.status === 409 || // same key still running      (res.status === 429 && err.code === "rate_limited") ||      res.status >= 500; // not stored, so a retry runs again    if (!retryable || attempt >= maxAttempts) {      throw new Error(`Send failed (${res.status} ${err.code ?? "unknown"}): ${err.error ?? res.statusText}`);    }    const retryAfter = Number(res.headers.get("Retry-After"));    await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));  }}

And a call:

TS
const result = await sendEmail(  {    from: "Acme <receipts@mail.acme.com>",    to: "ada@example.com",    subject: "Your receipt for order 1042",    html: "<p>Thanks for your order.</p>",    tags: { stream: "receipts", order: "1042" },  },  "order-1042-receipt",);

Which errors not to retry

The helper deliberately gives up on most 4xx responses. Retrying them changes nothing and wastes your rate limit:

  • 401 invalid_api_key and 403 missing_scope need a configuration fix.
  • 403 domain_not_verified and 403 sending_paused need action in the app; a paused workspace usually means bounce or complaint rates spiked.
  • 402 insufficient_credits needs a top-up first.
  • 422 validation_error or idempotency_key_reused means the request itself is wrong.
  • 429 daily_limit_reached won't clear in seconds, so the helper treats it as final rather than hammering the API. Requeue the job for later instead.

The errors section lists every code. Branch on code, not on the human-readable message, which may change.

Respecting rate limits

Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. If you send in bulk, read X-RateLimit-Remaining and slow down before you hit zero rather than relying on 429s. When a 429 does arrive, Retry-After tells you how long to wait, and the helper uses it ahead of its own backoff.

Per-recipient results and ids

One call can address up to 50 recipients, and each one gets its own copy of the email with its own id, status and tracking. Duplicate addresses in the same call are sent once. The response has one entry per recipient in data:

JSON
{  "data": [    { "id": "0b3e…", "to": "ada@example.com", "status": "queued" },    { "id": "9d71…", "to": "grace@example.com", "status": "suppressed" }  ]}

Two practical consequences:

  • Store the per-recipient ids. They are what you pass to GET /api/v1/emails/:id to check delivery, bounces and engagement later. Map them back to your own records (order, user) at the moment you get the response.
  • A partly failed call is still a 200. If one recipient is suppressed or failed and others are queued or sent, the call succeeded. Don't retry the whole call to "fix" one failed recipient; with the same key you'd get the same stored response, and with a new key you'd email everyone else again. Send the failed recipient on its own, with its own key. If every recipient failed, the status code is 502, which isn't stored, so a retry with the same key runs again.

Suppressed recipients, meaning past hard bounces, complaints and unsubscribes, are skipped and not charged. There is more on that in how an email suppression list works.

Idempotency and AI agents

Agents retry more than people think. A model that gets a slow tool response may call the tool again, and an agent framework may replay a step after an error. If your agent sends through the REST API, have it pass an idempotency key derived from the task, such as the ticket or order it is handling. If it uses Rampsend's MCP server, the send_email tool asks the assistant to confirm with you before sending. Sending email from an AI agent covers both setups.

Summary

Treat every send as an operation with a name. Give it a key built from your own ids, store the key with the job, send the same body every time, retry timeouts, 409s, rate limits and 5xx responses, and stop on everything else. The quickstart gets you a key and a first send in a few minutes.

Frequently asked questions

Frequently asked questions

What is an idempotency key?

A unique string you send in an Idempotency-Key header to identify one operation. If the same request arrives again with the same key, the server returns the original result instead of doing the work a second time.

Should I use a random UUID as the key?

Only if you create it once, when the job is created, and store it with the job. A UUID generated on every attempt changes with each retry and prevents nothing. Keys built from your own ids, like order-1042-receipt, are easier to reason about.

What happens if I reuse a key with a different body?

Rampsend returns 422 idempotency_key_reused. It means your code built a different request under the same key, so fix the bug rather than retrying.

Is a retry after a 500 error safe?

Yes. Server errors aren't stored against the key, so a retry with the same key runs the request again. Successful responses are stored and replayed with an Idempotent-Replayed: true header.

What does a 409 idempotency_conflict mean?

A request with the same key is still running. Wait a moment and retry with the same key; once the first request finishes you'll get its stored response. See idempotency.