The Payment Succeeded. The Worker Crashed. Will Temporal Charge Twice?
A practical guide to Temporal retries, idempotency keys, and the dangerous gap between a successful side effect and its acknowledgment.
Consider a checkout that fails in the worst possible place: the payment provider accepts the charge, then your Worker dies before Temporal receives the result. The customer’s bank says “paid.” Your application says “still processing.” A retry is coming. What stops it from charging again?
This is an illustrative failure scenario, not a claimed customer incident. It exposes the boundary every reliable workflow needs: durable orchestration must meet a side-effect API that can safely handle repetition.
The retry that turns recovery into a bug
A straightforward checkout might charge a card, reserve stock, and send a receipt. Put those calls in an HTTP handler and a process crash can erase your progress. Move them to a queue and you gain redelivery, but now the consumer must distinguish unfinished work from work that finished without an acknowledgment.
Adding a database flag helps only if the flag and the business effect share an atomic boundary. A local “charged” row cannot atomically commit with an unrelated payment provider. Write the row first and you might skip a charge that never happened. Write it afterward and you still have a crash window.
Temporal gives the orchestration durable progress. It does not turn an external payment request into a distributed transaction.
What actually survives a Worker restart
A Workflow describes the sequence. Activities perform external work. Workers run your code; the Temporal Service records execution history and coordinates tasks. During replay, recorded Activity results let Workflow code reconstruct progress without repeating completed Activities. An Activity whose completion was never recorded can execute again. See Temporal’s Activity Definition documentation.
| Failure point | What recovery needs |
|---|---|
| Before the provider accepts the charge | Another attempt that can make the payment. |
| After acceptance, before Temporal records completion | Another attempt that returns the original payment. |
| After completion is recorded | Replay uses the recorded result. |
The dangerous middle row is the reason an Activity must tolerate repeated execution. A timeout means the caller did not receive a result in time. It does not prove the remote operation failed.
Choose a key for the business operation
For this example, use charge:order-1042:v1. Every retry of this logical charge sends that same key and the same amount. A deliberate second payment needs a different operation identifier.
The provider must enforce the contract: accept a new key once, return the saved outcome for a repeated matching request, and reject reuse with different parameters. Its key retention period must cover your retry and reconciliation window. A header named “Idempotency-Key” provides no protection unless the receiving system implements these semantics.
Temporal documents Run ID plus Activity ID as one retry-stable key option. A business operation key can be more useful when deduplication must also span a new Workflow execution or a manual recovery. That wider scope is an application design choice, and requires careful rules for legitimate repeat operations.
A small TypeScript implementation
The following is a minimal integration example, not a complete payment service. The provider endpoint is a contract you must implement or map to your actual provider. No real payment credentials belong in the Workflow input. The snippets were checked against the linked SDK documentation but were not executed in this environment.
src/activities.ts — put network I/O and secrets here.
import { ApplicationFailure } from '@temporalio/common';
export async function charge(input: {
operationId: string;
amountMinor: number;
}): Promise<string> {
const base = process.env.PAYMENTS_URL;
if (!base) {
throw ApplicationFailure.nonRetryable(
'PAYMENTS_URL is missing', 'ConfigurationError'
);
}
const response = await fetch(new URL('/charges', base), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': input.operationId,
},
body: JSON.stringify({
amountMinor: input.amountMinor,
currency: 'INR',
}),
signal: AbortSignal.timeout(5_000),
});
// This classification belongs to this demo API contract.
// Verify the meaning of each status with your provider.
if (response.status === 402 || response.status === 409) {
throw ApplicationFailure.nonRetryable(
'Payment declined or operation parameters conflict',
'PaymentRejected'
);
}
if (!response.ok) {
throw new Error('Payment API returned ' + response.status);
}
const result = await response.json() as { paymentId?: string };
if (typeof result.paymentId !== 'string') {
throw new Error('Payment response has no paymentId');
}
return result.paymentId;
}src/workflows.ts — keep orchestration separate from the payment client.
import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities';
const { charge } = proxyActivities<typeof activities>({
startToCloseTimeout: '10 seconds',
scheduleToCloseTimeout: '2 minutes',
retry: {
initialInterval: '1 second',
backoffCoefficient: 2,
maximumInterval: '10 seconds',
},
});
export async function checkout(
orderId: string,
amountMinor: number
): Promise<string> {
return await charge({
operationId: 'charge:' + orderId + ':v1',
amountMinor,
});
}The five-second HTTP deadline bounds the network request. Start-To-Close bounds one Activity attempt. Schedule-To-Close bounds the overall Activity window, including queueing and retries. These settings have different jobs; the ActivityOptions reference defines their behavior.
src/worker.ts — the Worker and client must use the same Task Queue.
import { Worker } from '@temporalio/worker';
import * as activities from './activities';
async function main() {
const worker = await Worker.create({
workflowsPath: require.resolve('./workflows'),
activities,
taskQueue: 'checkout',
});
await worker.run();
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});src/client.ts — start one checkout.
import { Client, Connection } from '@temporalio/client';
import { checkout } from './workflows';
async function main() {
const connection = await Connection.connect();
try {
const client = new Client({ connection });
const handle = await client.workflow.start(checkout, {
workflowId: 'checkout-order-1042',
taskQueue: 'checkout',
args: ['order-1042', 49900],
});
console.log(await handle.result());
} finally {
await connection.close();
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});Wire it up locally
Use a supported Node.js version and install the Temporal CLI separately. In an empty project, run:
npm init -y
npm install @temporalio/client @temporalio/worker @temporalio/workflow @temporalio/common
npm install --save-dev typescript ts-node @types/nodeCreate tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"moduleResolution": "node",
"lib": ["ES2022", "DOM"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}Save the four files under src. Run temporal server start-dev in one terminal. In another, set PAYMENTS_URL to your local test provider and run npx ts-node src/worker.ts. In a third, run npx ts-node src/client.ts. These instructions use the local default address and namespace; Cloud requires connection configuration and credentials. Temporal’s TypeScript setup tutorial covers the application components.
The test provider must implement POST /charges, persist keys across restarts, and return JSON such as {"paymentId":"pay_1042"}. A process-local Map is insufficient for proving durability. Commit the package lockfile once you establish a working SDK version.
Test the acknowledgment gap deliberately
A happy-path demonstration proves very little. The useful experiment makes the provider commit a payment and then withhold the response.
- Have the test provider save the payment and key atomically in its database, then delay the first response beyond five seconds.
- Start checkout. The HTTP request should fail locally even though the provider has committed.
- Let Temporal retry. The provider should recognize the same key and return the original payment ID.
- Verify the database contains exactly one payment effect and that the provider received multiple requests with the same key.
- Repeat while stopping and restarting the Worker. Restart it with the same code and Task Queue before the overall Activity deadline expires.
This is an acceptance test plan, not a reported test result. Also test concurrent duplicate requests, mismatched amounts, provider restarts, and key expiration. The strongest deduplication check is at the system that owns the side effect.
When retries run out, uncertainty remains
Suppose the provider remains unreachable until the two-minute Activity window expires. The Workflow can fail while a payment still exists remotely. Do not translate that into “customer was not charged.”
Introduce a reconciliation path: query the provider by the original operation key, record the authoritative outcome, and resolve the order. If the business requires a refund, model that as a separate idempotent operation with its own key. A refund is a new action that can fail, not a rollback of history.
The sample ends at the payment ID intentionally. Adding inventory and receipts introduces additional business decisions: when to release a reservation, whether a receipt failure should block checkout, and who owns unresolved outcomes. Write those policies before writing a broad catch block.
Production lessons that matter more than a retry count
- Keep Workflow code replay-safe. Network calls and ordinary filesystem access belong in Activities. Workflow code must reproduce compatible commands during replay; consult the Workflow Definition guide before changing running workflows.
- Make duplicate starts safe too. A stable Workflow ID helps identify an order, but configure and test conflict and reuse policies explicitly. The provider’s operation key protects the charge across orchestration boundaries.
- Separate business rejection from infrastructure failure. A decline needs a customer-facing decision. A transient outage needs recovery. Do not silently classify every HTTP 4xx response the same way.
- Observe business outcomes. Track unresolved payment operations, retry volume, queue delay, and reconciliation age. A Workflow failure alone does not tell you the financial outcome.
- Minimize persisted sensitive data. Activity arguments and results are recorded in history. Use references and tokens, apply appropriate access controls and payload protection, and keep card data out of orchestration payloads.
For one short request with no recovery requirements, this machinery may be unnecessary. It becomes valuable when a business process must keep its place across outages, waits, and deployments.
The question to ask at every external boundary is simple: If this happened, but the acknowledgment vanished, what would the next attempt do? Temporal preserves the execution’s progress. Your side-effect contract makes the next attempt safe.
Sources: official Temporal documentation linked beside the relevant concepts. Example and failure scenario are original instructional material. No production incident or benchmark is claimed.