How do I stop an AI agent from sending the same email twice?
Give every send an idempotency key derived from the business event, such as order-1042-receipt, and reuse that same key on every retry, so the provider returns the first result instead of sending again. Back it with your own ledger that records the key before the call, and add a loop guard and a daily cap so a runaway agent stops early.
By AISend. Updated . Also as markdown.
Why it happens
Duplicates come from the gap between "the request was sent" and "I know the result". A network timeout, a 502 from a proxy, a worker restart or a model that decides to "try again" all leave the caller not knowing whether the first request worked. If the caller sends again without a stable identifier, the provider cannot tell a retry from a new email, and the recipient gets two.
Agents add three failure modes of their own. The model may call the send tool again because the tool result was long or ambiguous. The harness may retry a whole task after a crash, replaying every tool call in it. And two agents, or two runs of the same scheduled agent, may act on the same event concurrently. A random key generated fresh on each attempt defeats the protection, because every attempt then looks new.
You can recognise your case by the pattern in the logs: identical subject and recipient, seconds apart, with a timeout or error between them (retry), minutes apart after a restart (replay), or at the same second from two runs (race).
How to make sends safe to repeat (any provider)
- Derive the key from the business event, not the attempt. The key should name the thing that happened and the message kind: order-1042-receipt, invoice-2026-11-reminder-1. Anything that is stable across retries and unique across different emails works. A fresh random UUID per call does not, unless you generate it once, persist it with the task, and reuse it. Stripe's idempotency documentation suggests random strings with enough entropy for its API and advises against putting personal data such as email addresses into a key, so use internal IDs.
- Record the key in a ledger before the send call. Insert a row with a unique constraint on the key first. Only the process whose insert succeeds goes on to send; the others see the conflict and stop. This also stops concurrent runs from racing, which a provider-side key alone only partly covers.
create table email_ledger ( key text primary key, status text not null default 'pending', -- pending | sent | failed email_id text, created_at timestamptz not null default now() ); -- claim the key; zero rows back means someone already owns it insert into email_ledger (key) values (:key) on conflict (key) do nothing returning key; - Send with the key as an Idempotency-Key header and reuse it on retries. Pass the same key on every attempt for that email. A provider that supports it returns the first result for a repeated key instead of sending a second message. Check that your provider does: not all email APIs do, and for those the ledger is your only protection.
curl https://api.example.com/emails \ -H "Authorization: Bearer $KEY" \ -H "Idempotency-Key: order-1042-receipt" \ -H "Content-Type: application/json" \ -d '{"from":"Acme <hello@acme.com>","to":"customer@example.com", "subject":"Your receipt","html":"<p>Thanks for your order.</p>"}' - Retry only what is safe, with the same key and a backoff. Retry network errors, timeouts, 429 and 5xx with exponential backoff and a hard attempt limit, always with the same key. Do not retry other 4xx errors unchanged: a 422 or 403 will fail identically. If one key is reused with a different body, many providers return an error rather than send, and that is a bug in your key derivation, not something to bypass with a new key.
- Treat the ledger as the source of truth after an ambiguous failure. After a timeout, mark the row pending, then reconcile: retry the same key (safe if the provider dedupes) or look up the email by the ID you stored. Update the row to sent with the returned email ID. A pending row older than a few minutes is safe to retry only when the provider honours the key; otherwise investigate by hand.
- Move the key out of the model's hands where you can. If the agent sends through a tool, have the harness supply or validate the key from the event ID instead of trusting the model to invent a stable one. Where the tool schema makes the model choose the key, tell it in the instructions to derive it from the event ID and to reuse it after any error.
- Add a loop guard and caps as a backstop. Limit tool calls per task, limit sends per recipient and template per day in your own layer, and set a global daily cap that stops the agent and alerts you. These do not replace idempotency, but they bound the damage from a bug you have not met yet.
- Test it by sending the same key twice. In staging, call the send path twice with the same key and assert one email and one ledger row; then call it concurrently from two processes. Do this for the restart case too: kill the worker mid-send and resume.
When to use AISend
AISend's send_email tool and POST /api/v1/emails both take an idempotency key, and send_email requires one (up to 255 characters, sent as the Idempotency-Key header). Retrying with the same key and the same request returns the first result and sends nothing new. Reusing a key for a different request fails with HTTP 409 and code IDEMPOTENCY_KEY_REUSED. The key is stored with the email, so a repeat is recognised in the database and not only in a 24-hour cache. If the content gate held the first send as quarantined, a retry returns that same record instead of queuing a second one.
AISend's daily caps also act as a backstop: an OAuth-created assistant connection is limited to 100 emails a day, and every account has its plan's daily cap and a lower ramp-up cap while new. The caps limit volume; they do not stop two identical emails to the same person, so keep the key discipline above.
- Any provider that accepts an Idempotency-Key header gives the same protection; Stripe documents the pattern for its own API. Check your email provider's documentation before relying on it.
- If your provider has no idempotency support, the ledger and a single-writer queue are the fix; switching providers only for this is not necessary.
- Use a durable job queue with exactly-once semantics for business-critical fan-out; an email API key cannot replace that.
Copy-paste prompt for an AI assistant connected to AISend
Connect an assistant first (setup for ChatGPT, Claude, Cursor and Gemini CLI), then paste:
Assign to AISend: I need to email the receipt for order 1042 to customer@example.com from a verified domain. Call list_domains and pick the verified one, then draft the message and use idempotency_key order-1042-receipt. Show me what you did so I can approve the exact message before you call send_email. If any call errors or times out, retry only with the same idempotency_key, and use get_email_status or list_emails to check before trying anything else. Never create a new key for the same order.Frequently asked questions
Can I use a random UUID as the idempotency key?
Only if you generate it once per email, store it with the task and reuse it on every retry. A new UUID per attempt makes each retry look like a new email, which is exactly how duplicates happen. Deriving the key from the business event avoids the storage step.
What happens if I reuse a key with a different subject or body?
With AISend the request fails with HTTP 409 and the code IDEMPOTENCY_KEY_REUSED, and Stripe's API likewise errors when parameters differ from the original. Use a new key for a genuinely different email, or include a revision number in the key.
Does an idempotency key stop two agents from racing?
A provider that enforces the key atomically usually handles that, but you should still claim the key in your own ledger first, so the second agent never reaches the send call.
How long does the provider remember a key?
It varies. Stripe's documentation says keys can be removed once they are at least 24 hours old. AISend stores the key with the email and checks it in the database, so a repeat after a day still returns the first result. Check your provider rather than assuming.
Sources
- Stripe API reference: Idempotent requests (checked 2026-11-13)