# Prevent Duplicate Workflow Starts in a Temporal TypeScript App

Yes. An agent derives each Workflow Id from the payment's reference id, sets the reuse and conflict policies, handles the already-started error and tests it.

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

## What the agent does

The agent starts from how the client names a Workflow, because that is the only thing Temporal dedupes on. In an app laid out like temporalio/money-transfer-project-template-ts, `src/client.ts` builds a `Client` from `loadClientConnectConfig()` and calls `client.workflow.start(moneyTransfer, { args: [details], taskQueue: taskQueueName, workflowId: 'pay-invoice-801' })`: a hard-coded id for a `PaymentDetails` whose `referenceId` is `'12345'`. `src/banking-client.ts` says in its comments that `referenceId` is passed to `withdraw` and `deposit` for idempotent transaction tracking, but nothing ties it to the Workflow Id, so a caller that retries after a network error, or a second process handling the same payment, is free to start a second transfer with a different id. `src/shared.ts` holds the type and the `money-transfer` task queue; `src/workflows.ts` already compensates with `refund` when `deposit` fails.

Then it reads the installed SDK rather than the docs: `package.json` pins `@temporalio/client`, `@temporalio/common` and the rest at `~1.14.1`, and the agent opens the type definitions under `node_modules/@temporalio/common` for the exact members of `WorkflowIdReusePolicy` and `WorkflowIdConflictPolicy` and the name of the `WorkflowExecutionAlreadyStartedError` the client throws. The default reuse policy lets a new execution start under an id whose previous execution completed, which is exactly the double payment to prevent; the conflict policy decides what happens when an execution with that id is still running.

The change is in the client. `workflowId` becomes a prefix plus `details.referenceId`, so the same payment always maps to the same id; `workflowIdReusePolicy` is set to the reject-duplicate member, so a completed or failed transfer cannot be started again under that id, and `workflowIdConflictPolicy` to the use-existing member, so a start that races a running transfer returns a handle to the one in flight instead of throwing. The start is wrapped so that a `WorkflowExecutionAlreadyStartedError`, which still arrives when the reuse policy rejects a finished execution, is reported as a duplicate payment with the existing run's id rather than as a crash, and the test-only ids in `src/mocha/workflows.test.ts` stay as they are. The agent adds two tests to that file beside the existing `TestWorkflowEnvironment.createLocal()` suite: starting the same `details` twice yields one execution with one `firstExecutionRunId`, and starting it again after `handle.result()` resolves throws the already-started error.

To prove it, the agent runs `npm install`, `npm run build`, `npm run lint` and `npm test` in its sandbox; `createLocal()` downloads the Temporal CLI's dev server on first use, and the agent pastes the mocha output. It also starts `npm run worker` and runs `npm run client` twice, pasting the second run's output, which names the existing Workflow instead of starting a new one. The README's sample output, which shows a generated `workflow-…` id, is updated to the new form.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Make Workflow starts idempotent in this Temporal TypeScript app. Read package.json, src/client.ts, src/workflows.ts, src/activities.ts, src/banking-client.ts, src/shared.ts, src/mocha/workflows.test.ts and the README first, then read the type definitions under node_modules/@temporalio/common for the exact members of WorkflowIdReusePolicy and WorkflowIdConflictPolicy and the already-started error class. In src/client.ts derive workflowId from a fixed prefix and details.referenceId, set the reuse policy that rejects a duplicate of a finished execution and the conflict policy that uses the running one, and handle WorkflowExecutionAlreadyStartedError by reporting the existing Workflow Id instead of crashing. Add two mocha tests in src/mocha/workflows.test.ts: the same details started twice give one execution with one firstExecutionRunId, and a start after the result resolves throws the already-started error. Run npm install, npm run build, npm run lint and npm test and paste the output. Start the worker, run the client twice and paste the second run's output. Update the README's sample output. Change no Activity and no Workflow code.",
  "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

The pull request changes `src/client.ts`, `src/mocha/workflows.test.ts` and the README. Its description quotes the two policy members and the error class from the installed SDK's type definitions with their file paths, shows the mocha output with the two new tests, and shows the client's second run reporting the Workflow already started for that reference id.

`src/workflows.ts` and `src/activities.ts` are unchanged: the Workflow still withdraws, deposits and refunds on a failed deposit, and the worker registers the same code. The task queue, namespace and connection setup are as before. The only behavioural change is at the start: one reference id now means at most one transfer.

Before merging, a reviewer decides whether a retry that finds a finished transfer should surface as an error or read the existing result and return it, confirms the id prefix will not collide with other Workflow types sharing the namespace, and checks that whatever produces `referenceId` upstream is unique per payment, since the guarantee now rests on it.

## Run it on every Monday morning

Add an automation to the Project with a prompt that asks for a report rather than a change: list every `client.workflow.start`, `execute` and `signalWithStart` call, say which derive their `workflowId` from a business key and which use a generated or hard-coded one, and name the reuse and conflict policy each sets. Give it a `schedule` trigger with `cron` set to Monday morning in your `timezone`, and switch it to read-only so the run comments and never pushes.

Each slot starts one run in the Project's repository; turning the automation back on moves the schedule to its next slot rather than firing the ones it missed. The report is the run's artifact, so a new start call that slipped in with a random id shows up within a week. From your own server, the fixing run starts with this request and a `request_id` that is a UUID v5 of the report's artifact id, so a retried start returns the run already begun.

## Why run it on Rush?

Idempotent starts are a few lines, but the lines depend on enum names that changed across SDK releases and on a server behaviour that is easy to misremember. The agent reads the installed SDK's own type definitions in its sandbox rather than a version of the docs, and proves the behaviour against a real Temporal dev server through the SDK's test environment, so the pull request shows the duplicate being refused rather than asserting it.

The transcript keeps the build, lint, test and client runs with their output, so a reviewer checks the policy members and the test results from one page without checking the branch out. Several services that start Workflows can be audited and fixed at once, each run in its own sandbox with its own dev server, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why derive the id from referenceId instead of generating a UUID?

Temporal dedupes on the Workflow Id and nothing else. A UUID made at call time is different on every retry, so two starts for one payment are two transfers. `referenceId` already travels with the payment into `withdraw` and `deposit` as the bank's own dedupe key, so building the Workflow Id from it gives the whole transfer the same key.

### What does the conflict policy change?

It decides what a start does when an execution with that id is still running. With the use-existing member the start returns a handle to the running execution, so two processes handling the same payment at once both wait on the one transfer. The reuse policy covers the other case, an execution that already finished, by rejecting the start.

### Will the existing tests still pass?

Yes. They start Workflows under their own ids through `client.workflow.execute` on the test environment and never go through `src/client.ts`, so the change does not reach them. The two new tests sit in the same file and use the same `TestWorkflowEnvironment` and `Worker.create` setup.

### Does this need a Temporal server in CI?

The existing suite already does: `TestWorkflowEnvironment.createLocal()` downloads and starts the Temporal CLI's dev server, which is why `npm test` passes `--exit` to mocha. The new tests add no further requirement. The repository has no workflow file today, so adding one is a separate change.

## More Temporal jobs

- [Review Pull Requests to Temporal Go Workflows for Determinism](https://getrush.ai/run/review-pull-requests/temporal/)
- [Upgrade npm Dependencies in a Temporal TypeScript Project](https://getrush.ai/run/upgrade-npm-dependencies/temporal/)
- [Write Tests for Temporal TypeScript Workflows That Have None](https://getrush.ai/run/write-workflow-tests/temporal/)

## More jobs like this: Turn a Linear label into a PR

- [Reduce Host Permissions in a Chrome Extension from a Linear Issue](https://getrush.ai/run/reduce-host-permissions/chrome-extension/)
- [Remember Window Size and Position in an Electron App](https://getrush.ai/run/remember-window-state/electron/)
- [Reproduce a Bug from a Linear Issue in a Next.js App](https://getrush.ai/run/reproduce-linear-bug/nextjs/)

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