# Add Activity Retry Policies to a Temporal TypeScript Workflow

Yes. An agent reads your Temporal workflows, gives each activity an explicit retry policy, marks bad-input errors non-retryable, tests both and opens a PR.

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

## What the agent does

The agent clones the project into its own cloud sandbox and reads how activities are declared before touching a policy. In a project like the `expense` sample in temporalio/samples-typescript, `src/workflows.ts` calls `proxyActivities` with a single option, `startToCloseTimeout: '5 minutes'`, and no `retry` block, so `createExpense` and `payment` run under the SDK's default policy, which keeps retrying with backoff and no attempt limit until the timeout ends the attempt. `src/activities.ts` makes each activity one `axios.post` to `http://localhost:3000`, `/create` with the expense id and `/action` with `action: 'payment'`. The server in `src/server/index.ts` throws `Invalid action` for an unknown action and refuses a state transition that is not `CREATED` to `COMPLETED`, so the same `POST` can fail because the server is down, which is worth retrying, or because the request is wrong, which never is. `package.json` pins `@temporalio/*` at `^1.25.0`, `axios` at `^0.28.0`, `express` at `~4.20.0`, has no `test` script and no `@temporalio/testing`, while the neighbouring `hello-world` sample has both and a `src/mocha` folder.

It separates the two kinds of failure in the activities first. Each `axios.post` is wrapped so that a response with a 4xx status becomes `ApplicationFailure.create({ nonRetryable: true, type: 'InvalidExpenseRequest', message, details: [status, body] })`, while a connection error or a 5xx is rethrown as it is and stays retryable. The base URL moves from the string literal to an environment variable with the same default, so a test can point the activity at a server it controls. The activity logs the attempt number from `Context.current().info.attempt` on each failure, so a worker's log shows a retry storm as it happens.

Then it writes the policy where the workflow declares its activities. `proxyActivities` in `src/workflows.ts` gets a `retry` block with `initialInterval`, `backoffCoefficient`, `maximumInterval` and `maximumAttempts` chosen for a payment call that talks to one HTTP service, plus `nonRetryableErrorTypes: ['InvalidExpenseRequest']` so the typed failure above stops the workflow at once. A `scheduleToCloseTimeout` bounds the whole retry sequence so a server that stays down fails the workflow in a known time instead of running until the task is abandoned. Each value has a one-line comment saying what it protects against, because a retry policy with no reasons is the first thing the next engineer deletes.

It proves the policy with tests modelled on the `hello-world` sample. It adds `@temporalio/testing` and `mocha` as dev dependencies, a `test` script, and `src/mocha/activities.test.ts`, which starts a throwaway Express server on a free port that answers 500 twice and then 200, runs `createExpense` through `MockActivityEnvironment`, and asserts that a 400 produces a non-retryable `ApplicationFailure` of the right type. `src/mocha/workflows.test.ts` uses `TestWorkflowEnvironment.createTimeSkipping` with a mocked `createExpense` that fails on its first calls and succeeds after, asserting the workflow completes and that a mocked `InvalidExpenseRequest` ends it without further attempts. It runs `pnpm install` for the workspace, `pnpm --filter temporal-expense test`, `tsc --build` and `eslint .`, and puts the output in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add explicit retry policies to the activities in this Temporal TypeScript project. Read src/workflows.ts, src/activities.ts, the server the activities call and package.json first, and say which failures should retry and which never should. In the activities, turn responses that mean a bad request into a non-retryable ApplicationFailure with a named type and leave connection errors and server errors retryable; make the server base URL configurable with the same default. In proxyActivities add a retry block with initialInterval, backoffCoefficient, maximumInterval, maximumAttempts and nonRetryableErrorTypes, and a scheduleToCloseTimeout, with a comment per value. Add @temporalio/testing and mocha, a test script, an activity test against a local server that fails then succeeds, and a workflow test with the time-skipping test environment showing retries and the non-retryable stop. Run the tests, the build and lint, and open a pull request with the output.",
  "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 changing `src/workflows.ts` and `src/activities.ts`, adding `src/mocha/activities.test.ts` and `src/mocha/workflows.test.ts`, and extending `package.json` with the test script and the two dev dependencies. The description has a table of failure modes, each with the HTTP status or error it maps to and whether it retries, followed by the policy values and the reason for each.

The run's record keeps the `pnpm --filter temporal-expense test` run from the sandbox, including the time-skipping test environment starting and the attempts the mocked activity went through, and the `tsc --build` and `eslint .` output, so a reviewer sees the policy exercised rather than described.

Before merging, a reviewer checks the `maximumAttempts` and `scheduleToCloseTimeout` against what the payment service's own timeouts allow, decides whether a 409 from the server should count as a bad request or a transient conflict, and confirms the worker's log line per failed attempt is what on-call wants to see.

## Run it on every Temporal project with default retries

A team with several workers hands this off from the terminal once per project: one `POST /o/{org}/sessions` with this body and the repository in `resources`, and a `request_id` that is a UUID v5 of the repository name so a retried call returns the run it already started. The key's `webhook_url` reports each finished run with its pull request.

A monorepo of samples or services gets one run per package instead, each prompt naming the package directory, so each pull request stays small enough to review the policy values one by one. Each run reads that package's own activities and decides afresh which errors are permanent.

## Why run it on Rush?

A retry policy is a set of numbers nobody wants to argue about without seeing them run. The agent reads the real activities and the real server, decides which errors are permanent, and then proves the policy with the SDK's own test environment in its sandbox: a server that fails and recovers, a bad request that stops the workflow, and the attempt count asserted, all before the pull request exists.

The same body runs across every Temporal project a team owns, and each pull request keeps its own failure table and its own test output. That is how a platform team replaces unlimited default retries with bounded, explained ones across workers written at different times by different people.

## Frequently asked questions

### Why change anything if Temporal retries by default?

Because the default policy has no attempt limit and no idea which errors are permanent. A payment call that returns 400 is retried with growing backoff until the `startToCloseTimeout` ends the attempt, and then retried again. An explicit policy with `nonRetryableErrorTypes` fails fast on bad input and bounds the total time with `scheduleToCloseTimeout`.

### How does the agent decide which errors are non-retryable?

From the server the activities call. In the expense sample, `src/server/index.ts` rejects unknown actions and invalid transitions, which are bugs in the request, not outages, so they become a typed `ApplicationFailure` with `nonRetryable: true`. Connection refused and 5xx responses stay retryable. The pull request lists each mapping so you can move a status from one column to the other.

### Will the tests need a running Temporal server?

No. `TestWorkflowEnvironment.createTimeSkipping` from `@temporalio/testing` downloads a test server on first use and skips time between retries, so a policy with minutes of backoff runs in seconds. The activity test uses `MockActivityEnvironment` and a local Express server on an ephemeral port, so nothing external is needed.

### Does it also add heartbeats or cancellation handling?

Not in this change. The activities are single short HTTP calls, so a heartbeat would add noise rather than safety. The pull request says so and points at the `activities-cancellation-heartbeating` pattern for the day an activity becomes long-running.

### Can I apply the same policy to several activity groups?

Yes. `proxyActivities` is called once per set of options, so the agent writes one shared `retry` object and reuses it where the activities share a backend, and splits a second group when one activity calls a different service with different limits. The comments next to each value carry over.

## More Temporal jobs

- [Add a Temporal Schedule to a TypeScript Workflow](https://getrush.ai/run/add-schedules/temporal/)
- [Add Custom Search Attributes to Temporal Workflows](https://getrush.ai/run/add-search-attributes/temporal/)
- [Add Signals and Queries to a Temporal Workflow](https://getrush.ai/run/add-signals-and-queries/temporal/)

## The same job on other stacks

- [Add Retry Policies With Exponential Backoff to Airflow DAGs](https://getrush.ai/run/add-retry-policies/airflow/)
- [Add Retry Policies to the Flaky Assets in a Dagster Project](https://getrush.ai/run/add-retry-policies/dagster/)
- [Turn On Safe Retries for Event-Driven Firebase Cloud Functions](https://getrush.ai/run/add-retry-policies/firebase-functions/)

## Keep reading

- [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/)
