# Add Retries to Resend Email Sending

Yes. An agent makes the Resend call retry on 429 and 5xx answers and network failures with backoff, tests it against the MSW mock and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-email-send-retries/resend/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the one function every email goes through. In a React Router app laid out like epicweb-dev/epic-stack, `sendEmail` in `app/utils/email.server.ts` renders a React Email component to HTML and text, builds the body with a fixed `from`, and does a single `fetch` to `https://api.resend.com/emails` with `Authorization: Bearer ${process.env.RESEND_API_KEY}`. A `response.ok` body that matches `resendSuccessSchema` returns `status: 'success'`; anything else is parsed with `resendErrorSchema`, whose `name`, `message` and `statusCode` fields come straight from Resend, and becomes `status: 'error'`. There is no retry, and a `fetch` that throws is not caught at all. The caller in `app/routes/_auth/signup.tsx` turns an error into a 500 with `formErrors: [response.error.message]`, so a person signing up during a brief Resend outage sees Resend's own error text and has to press Submit again, which creates a second verification with `prepareVerification`.

The retry stays inside `sendEmail` so every caller gets it without changing. The agent wraps the `fetch` in a small loop with a bounded number of attempts and exponential backoff, retrying when the request throws, when the status is 429, or when it is a 5xx, and never on a 4xx other than 429, because a 400, 401 or 422 will not succeed by waiting. A 2xx whose body fails `resendSuccessSchema` is treated as success-with-unknown-id rather than retried, since the message was accepted. The delays and the attempt count are module constants, with the attempt count also readable from an environment variable so a test can set it to one, and the whole loop skips when `MOCKS` is set and no `RESEND_API_KEY` exists, the branch the file already has for development.

The duplicate question is answered in the code rather than left open. If Resend accepts a message but the response is lost, a retry sends it twice, and the agent records that as the accepted trade-off in a comment above the loop: a second verification email is harmless, while a lost one blocks onboarding. The error returned after the last attempt keeps the shape `signup.tsx` and the other callers expect, with the last `statusCode` and a message that says how many attempts were made, so the form still shows something useful.

Tests use the mock server the repository already runs. `tests/mocks/resend.ts` handles `POST https://api.resend.com/emails` with `msw`, requires the `Authorization` header and writes the email to a fixture that `readEmail` in `tests/mocks/utils.ts` reads back. A new Vitest file, `app/utils/email.server.test.ts`, uses `server.use(...)` to prepend a one-time handler that answers 429, then lets the default handler succeed, and asserts one success with one fixture written; a second case answers 500 on every attempt with the count set to two and asserts the error; a third throws a network error once. `tests/setup/setup-test-env.ts` turns any `console.warn` into a thrown error, so the retry logs through the existing `console.error` only when it gives up, and the test that expects that mocks `consoleError` the way the setup file describes. The agent runs `npm run test -- --run` and `npm run typecheck`, then `npm run test:e2e:run` so the onboarding flow in `tests/e2e/onboarding.test.ts`, which reads the real mocked email, still passes.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add retries to Resend email sending. Read app/utils/email.server.ts, app/routes/_auth/signup.tsx, tests/mocks/resend.ts, tests/mocks/utils.ts, tests/mocks/index.ts and tests/setup/setup-test-env.ts first. Inside sendEmail, retry the fetch with exponential backoff when it throws or Resend answers 429 or a 5xx, never on another 4xx, with a bounded attempt count that an environment variable can override. Keep the returned shapes unchanged, keep the MOCKS branch, and write a comment stating that a lost response can send a message twice and why that is accepted. Add app/utils/email.server.test.ts using server.use with msw for a 429 then success, a persistent 500 and a thrown network error. Run npm run test -- --run, npm run typecheck and npm run test:e2e:run, quote the results and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `app/utils/email.server.ts` and adds `app/utils/email.server.test.ts`. No route changes, because every caller already handles the `status: 'error'` shape, and no change to `tests/mocks/resend.ts`, since the tests prepend their own handlers with `server.use`.

The description shows the Vitest run with the three new cases, the TypeScript check, and the Playwright summary for the onboarding and forgot-password flows that send email, plus a table of which responses retry and which do not, with the Resend status code in one column and the decision in the other. The repository's `Deploy` workflow runs its Vitest, lint, typecheck and Playwright jobs on the branch.

Before merging, a reviewer picks the attempt count and the first delay, which the agent sets to small values and names as the thing to tune, and decides whether a final failure should also report to Sentry through the server-side `Sentry.init` in `server/utils/monitoring.ts`, which today only sees thrown errors.

## Run it on every service that sends mail through one function

A team with several apps that call a mail API from one helper starts one run per repository with `POST /o/{org}/sessions`, this prompt as `input` and the repository in `resources`. Each run reads its own helper and its own mock, so an app that already retries gets only the missing tests and a note on which status codes it retries, and one that uses Resend's SDK rather than `fetch` gets the retry around the SDK call instead.

A `request_id` that is a UUID v5 of the repository's full name makes a retried call return the run it already started rather than a second one, and the key's `webhook_url` reports each run's finish with its `session_url`, so a script can open the pull requests as they land.

## Why run it on Rush?

Proving a retry means a mock that fails on purpose, a test harness that turns stray warnings into failures, and the end-to-end flow that reads the mocked email, all of which this repository has but which take a working `npm run setup` and a Playwright browser to use. The sandbox runs that setup and keeps every test's output, so the pull request opens with the three failure cases shown passing.

The run's record keeps the exact handler the agent prepended and the responses it saw, so a reviewer reads which codes retried rather than trusting a list. A company with several Epic Stack apps starts one run each, and each pull request is fitted to that app's own helper and callers.

## Frequently asked questions

### Could a retry send the same email twice?

Yes, when Resend accepted the message but the response never arrived. The agent writes that trade-off into a comment above the loop: for verification and reset emails a duplicate is harmless and a lost one blocks the person, so retrying is the safer side.

### Why not retry on every non-2xx answer?

A 400, 401, 403 or 422 from Resend means the request itself is wrong, such as a bad API key or a rejected `from` address, and repeating it only delays the error the caller needs to show. Only 429, 5xx and a thrown `fetch` can succeed on a later attempt.

### Does development mode change?

No. With `MOCKS` set the mock server in `tests/mocks/index.ts` answers the Resend URL and writes the email to a fixture, and without `RESEND_API_KEY` the existing branch logs the email and returns a mocked success. The loop only runs around a real `fetch`.

### How do the tests wait through the backoff?

The attempt count and delays are module constants that the test overrides to the smallest values, so the three cases finish in well under Vitest's default timeout. The agent quotes the durations from the Vitest output.

## More Resend jobs

- [Draft a Product Update Email in Resend From a Changelog](https://getrush.ai/run/draft-product-update-broadcast/resend/)
- [Check Email Deliverability in Resend](https://getrush.ai/run/email-deliverability-report/resend/)
- [Send a Personal Welcome Email for Each Signup Through an API](https://getrush.ai/run/welcome-email-per-signup/resend/)

## More jobs like this: Hand off a long task

- [Add Email Verification to an AdonisJS App](https://getrush.ai/run/add-email-verification/adonisjs/)
- [Add Email Verification to a Django REST Framework Project](https://getrush.ai/run/add-email-verification/django-rest-framework/)
- [Add Email Verification to a FastAPI App on SQLModel](https://getrush.ai/run/add-email-verification/sqlmodel/)

## Keep reading

- [What an agent can do in Resend itself, once you connect it](https://getrush.ai/integrations/resend/)
- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
