AhaSend

Idempotency keys for email APIs: stop duplicate emails after a timeout

Which email APIs support idempotency keys, how to pick a key per send, and what a retry returns after a timeout, a 409 or a 5xx. With AhaSend code samples.

Farhad Hedayatifard
Farhad Hedayatifard
Guides
On this page

Your app sends a password reset, the request times out, and your code tries again. Now the customer has the same email twice.

A timeout does not prove that the first send failed. The email API may have sent the email and lost only the answer. Idempotency keys solve this.

An idempotency key is a unique string that you send with an API request. The server uses it to recognize a repeat of the same request, and returns the first result instead of doing the work again.

This only works when every retry uses the same key. A new random key on each retry looks like a new request and protects nothing.

Does AhaSend support idempotency keys? Yes, on Free, Pro and Max. API v2 send calls take an Idempotency-Key header, and email sent over SMTP takes an ahasend-idempotency-key header.

If you retry with the same key after a timeout or a server error, AhaSend sends the email at most once. A key lives for 24 hours from its first use.

Which email APIs support idempotency keys?

This table shows how three email APIs handle a key on a send, as of November 2026.

Email APICalls that take a keyKey kept forKey over SMTPRetry after an unclear server error (5xx)
AhaSendAPI v2 sends, template sends, conversation sends, campaign sends and more24 hoursYes, with the ahasend-idempotency-key headerThe send happens at most once, and the retry gets its result
ResendSend Email, Send Email Batch, and sending, replying and forwarding from inboxes24 hoursYes, with the Resend-Idempotency-Key headerNot documented
BrevoBatch transactional email (idempotencyKey in the headers object)30 minutesNot documentedNot documented

Postmark does not offer an idempotency key. Brevo answers a request with a key from the last 30 minutes with a duplicate_parameter error instead of the first result. The idempotency docs of Resend and Brevo do not say what a retry gets after a server error with an unclear result. With AhaSend, the send happens at most once and the retry gets its result.

Want to compare European providers on more than retries? See our comparison of European transactional email providers.

What happens when you retry with AhaSend

AhaSend takes the Idempotency-Key header on API v2 calls such as Create Message, Create Template Message, Create Conversation and Send Campaign. The idempotency docs list every call that takes a key. Email sent over SMTP uses its own header, which the SMTP section below explains.

Within 24 hours of the key's first use, a retry with the same key and the same request gets the stored result. The answer has the original status and body, so it holds the same message IDs. It also has the header Idempotent-Replayed: true, so your code can tell a replay from a new send.

The answers to handle: 409, 503, 429 and 422

Most retries get the stored result. A few answers need a different step, and this table shows what each one means and what to do.

AnswerWhat it meansWhat to do
409 with Idempotent-Replayed: false and Retry-AfterThe first request with this key is still runningWait for Retry-After, then retry with the same key
503 "The result of this request is not known yet" with Retry-After, on Create Message, Create Template Message and Create ConversationAhaSend does not know the result of the send yetWait for Retry-After, then send the same request with the same key
Other 5xxA server error. AhaSend does not store this answerWait for Retry-After if the answer has one, or back off. Then retry with the same key
429Rate limit: too many requestsWait for Retry-After, then retry with the same key
422The key was used with a different body, endpoint or resourceUse a new key, or send the original request
Any other 409A conflict with the resource, such as a campaign whose status does not allow the requestFix the conflict, then use a new key

How long a key lasts: 5 minutes and 24 hours

A request that is still running holds its key for up to 5 minutes, and a retry during that time gets the 409 above. If the first request was cut off and never finished, the key unblocks after those 5 minutes. The next retry then goes ahead, and the send still happens at most once.

A key lives for 24 hours from its first use. After that AhaSend treats it as new, so a request with an expired key sends the email again.

How to choose a key for each send

Use one stable key for each logical send: one email that your app means to send once, such as the receipt for order 123. Build the key from your own ID, such as order-123-receipt, so that every retry, from any process, uses the same key.

Follow these rules:

  • A key can be any string up to 255 characters, and is scoped to your account.
  • Use a key again only with the exact same request and endpoint. AhaSend matches the account, the key, the method and path, and a hash of the body, so a different request with the same key gets a 422.
  • Use different keys for sandbox and live sends. The sandbox flag is part of the body, so a key from a sandbox send gets a 422 on the live send.

Good sources for a key are the order ID, the message ID from your queue, or the ID of the event that triggers the send. Queues and webhooks can deliver the same message more than once. If the second delivery builds the same request with the same key within 24 hours, AhaSend does not send a second email.

Webhooks are a common case: our post why your webhook fired twice explains why the same event can arrive more than once.

Code samples: TypeScript, Go and the AhaSend CLI

Each sample sends a receipt with a key built from the order ID, and tags the email with that ID for the check later in this post.

TypeScript

Install the Node.js and TypeScript SDK with npm install @ahasend/sdk. The SDK takes your key in the options object of each call:

import { AhaSendClient } from "@ahasend/sdk";

const ahasend = new AhaSendClient({
  apiKey: process.env.AHASEND_API_KEY!,
  accountId: process.env.AHASEND_ACCOUNT_ID!,
});

const result = await ahasend.messages.send(
  {
    from: { email: "[email protected]" },
    recipients: [{ email: order.customerEmail }],
    subject: "Your receipt for order " + order.id,
    html_content: "<p>Thank you for your order.</p>",
    tags: ["order-" + order.id],
  },
  // The same key for every retry of this receipt
  { idempotencyKey: "order-" + order.id + "-receipt" },
);

The SDK retries timeouts, network errors, 408, 429, 5xx and a 409 in progress, and every retry of a call uses the same key. Without your own key, the SDK makes a new key for each call, which covers only the retries of that call. For retries from your own queue, or after your app restarts, pass your own key, as in this sample.

Go

Install the Go SDK with go get github.com/AhaSend/ahasend-go and pass your own key with api.WithIdempotencyKey. The Go SDK retries network errors, 429 and 5xx with the same key, and returns a 409 in progress to you as api.ErrorTypeIdempotencyConflict, with RetryAfter in seconds. This loop waits that long, then retries with the same key:

// sendReceipt sends one receipt. Every attempt uses the same key and the same request.
func sendReceipt(ctx context.Context, client *api.APIClient, accountID uuid.UUID, orderID, email string) error {
    message := requests.CreateMessageRequest{
        From: common.SenderAddress{Email: "[email protected]"},
        Recipients: []common.Recipient{
            {Email: email},
        },
        Subject:     "Your receipt for order " + orderID,
        HtmlContent: ahasend.String("<p>Thank you for your order.</p>"),
        Tags:        []string{"order-" + orderID},
    }
    key := "order-" + orderID + "-receipt"

    for attempt := 1; attempt <= 5; attempt++ {
        _, _, err := client.MessagesAPI.CreateMessage(ctx, accountID, message, api.WithIdempotencyKey(key))

        var apiErr *api.APIError
        if errors.As(err, &apiErr) && apiErr.Type == api.ErrorTypeIdempotencyConflict {
            // The first request with this key is still running: wait, then retry
            time.Sleep(time.Duration(apiErr.RetryAfter) * time.Second)
            continue
        }
        return err
    }
    return errors.New("result not known yet: retry later with the same key")
}

AhaSend CLI

The AhaSend CLI sends email from your terminal or a script. Install it with brew install ahasend/tap/ahasend, or with one of the other methods on its installation page, and pass your key with --idempotency-key:

ahasend messages send \
  --from [email protected] \
  --to [email protected] \
  --subject "Your receipt for order 123" \
  --html "<p>Thank you for your order.</p>" \
  --tag order-123 \
  --idempotency-key order-123-receipt

Without --idempotency-key, the CLI makes a new key for each run. To retry a send, run the same command again with the same key within 24 hours. The docs of the messages command list every flag.

Idempotency keys over SMTP

For email sent over SMTP, add an ahasend-idempotency-key header to each message. Make the key before the first send and save it with the message in your app. If your client does not get the answer to a send, which can happen when the connection closes, send the same message again with the same key.

Over SMTP, the key works differently from the API:

  • A repeat is a second message with the same account, key and recipient, within 24 hours of the first. AhaSend accepts the repeat but does not send it.
  • AhaSend does not compare the content of the messages, so each new message needs a new key.
  • AhaSend checks each recipient of a message on its own.
  • A key can be 1 to 255 bytes. A sandbox message uses up its key, so use different keys for sandbox and live sends.

This table shows the answers to a message with a key, and what to do.

AnswerWhat it meansWhat to do
250 that ends with duplicates=<count>AhaSend accepted the message, and did not send that number of copies. Each of these copies repeats an earlier message with this key to the same recipientDo not send the message again
451 4.3.0 A message with this idempotency key is in progress. Try again later.AhaSend cannot tell yet if it accepted an earlier message with this keySend the message again later, with the same key. This answer can last up to 5 minutes
550 5.6.0 The idempotency key is longer than 255 bytes.AhaSend refused the message, because the key is too longUse a key of 255 bytes or less

In the AhaSend CLI, ahasend smtp send sets the key with --header 'ahasend-idempotency-key: YOUR_KEY'.

When you still need your own check

Three cases need your own check before you send again:

  • Sends through API v1. API v1 has no idempotency key.
  • SMTP messages without an ahasend-idempotency-key header.
  • A retry more than 24 hours after the first try. By then the key has expired, and a retry sends the email again.

For these cases, tag each send with your own ID, such as order-123: the tags field in API v2, or the ahasend-tags header over SMTP. Before you send again, look for the email with List Messages, which filters by recipient, subject, tags, Message-ID header or time range. Send again only when the email is not there.

Idempotency keys are on every AhaSend plan, the free plan included. The idempotency docs list every call that takes a key and every answer. Start for Free.