All jobs

Add Activity Heartbeats to a Temporal Workflow

Yes. An agent adds heartbeats and a heartbeat timeout to your long-running Temporal activities, honours cancellation, tests both with the SDK tools and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the activity options first, because a heartbeat without a heartbeat timeout does nothing. In temporalio/money-transfer-project-template-ts, package.json pins the TypeScript SDK packages (@temporalio/activity, client, common, envconfig, worker, workflow, testing) at ~1.14.1 on Node 18 (.nvmrc and @tsconfig/node18) with TypeScript 4.9 and Mocha. src/workflows.ts defines moneyTransfer, which proxies withdraw, deposit and refund with a retry policy of initialInterval 1 second, maximumInterval 1 minute, backoffCoefficient 2, maximumAttempts 500 and nonRetryableErrorTypes of InvalidAccountError and InsufficientFundsError, and a startToCloseTimeout of 1 minute; there is no heartbeatTimeout, so a worker that dies mid-activity is only noticed when that minute runs out and the retry count climbs toward 500. src/activities.ts calls BankingService from src/banking-client.ts, an in-memory bank with two accounts, 85-150 holding 2000 and 43-812 holding 0, whose withdraw and deposit take a referenceId the comments describe as being for idempotent transaction tracking. src/worker.ts registers everything on the money-transfer task queue, src/client.ts starts workflow id pay-invoice-801 moving 400. Tests in src/mocha: activities.test.ts runs each activity in a MockActivityEnvironment, and workflows.test.ts uses TestWorkflowEnvironment.createLocal() with a worker whose activities are stubbed in one case and real in three failure cases. .eslintrc.js makes @typescript-eslint/no-floating-promises an error and forbids Node built-ins inside workflow files.

The agent changes the activities to report progress and listen for cancellation. Each one imports heartbeat and Context from @temporalio/activity, calls heartbeat({ step: 'calling-bank' }) before the bank call and heartbeat({ step: 'recorded', transactionId }) after it, and passes Context.current().cancellationSignal into the banking call so a cancelled workflow aborts a call still in flight rather than letting it finish. BankingService.withdraw and deposit gain an optional AbortSignal parameter, which the mock honours by rejecting when the signal is already aborted. On retry, an activity reads Context.current().info.heartbeatDetails: when the last heartbeat said recorded, it returns the recorded transaction id instead of charging the account twice, which is what the bank's referenceId was there for. In workflows.ts the proxy gets a heartbeatTimeout well under the one-minute startToCloseTimeout, chosen and explained in the pull request, so a stalled worker is detected in seconds and the activity is retried on a healthy one.

Tests cover the two new behaviours with the SDK's own tools. In activities.test.ts, MockActivityEnvironment emits a heartbeat event for each call, so the test collects the details and asserts the calling-bank then recorded sequence; a second case constructs the environment with heartbeatDetails set to a recorded step and asserts the activity returns that id without calling the bank; a third calls env.cancel() and asserts the activity fails with CancelledFailure. In workflows.test.ts, a new case switches to TestWorkflowEnvironment.createTimeSkipping() and registers a deposit stub that never heartbeats and never returns, so the workflow sees a heartbeat timeout and a retry, and the test asserts the second attempt completes the transfer. The existing four workflow cases keep running against the local test server as before.

The agent runs npm run lint, where no-floating-promises will flag a forgotten await on a heartbeat-aware call, npm run build for the TypeScript, and npm test, which downloads the test server on first use, so the sandbox needs network for that step. The worker itself needs no change: the SDK throttles heartbeats to a fraction of the heartbeat timeout, so calling heartbeat on every step is cheap and the pull request says so.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add activity heartbeats to this Temporal TypeScript project. Read src/workflows.ts, src/activities.ts, src/banking-client.ts, src/worker.ts, the Mocha tests, package.json and .eslintrc.js first, and note the retry policy and timeouts in force. In each activity call heartbeat with a step detail before and after the bank call, pass the activity's cancellation signal into the banking client and make the mock honour it, and on retry read heartbeatDetails so a step already recorded returns its transaction id instead of charging again. Add a heartbeatTimeout to the activity options that is well under the start-to-close timeout and explain the value. Extend the activity tests with MockActivityEnvironment to assert the heartbeat sequence, the resume-from-details path and cancellation, and add a time-skipping workflow test where a deposit stub that never heartbeats is retried after a heartbeat timeout. Run lint, build and the test suite and open a pull request that explains the timeout chosen and what each test proves.",
  "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 edits src/activities.ts, src/banking-client.ts, src/workflows.ts, src/mocha/activities.test.ts and src/mocha/workflows.test.ts. Its description names the heartbeat timeout and why it sits where it does relative to the one-minute start-to-close timeout, lists the heartbeat details each activity sends, and explains the resume path that avoids a double charge.

The run's record keeps the ESLint output, the TypeScript build and the Mocha run with the new cases, so a reviewer can see the heartbeat sequence assertion and the time-skipping retry pass before reading the diff.

Before merging, a reviewer checks the resume path against how the real bank API behaves, since the mock accepts any referenceId and a production bank may not, and runs npm run worker with npm run client locally to watch the activity's heartbeat details appear on the workflow in the Temporal web UI.

Run it on every Linear issue labelled temporal

A team that tracks reliability work in Linear adds an automation with a linear trigger on linear.issue.labeled for the label temporal, the Project that holds this repository, and this prompt. Labelling the issue that describes a stuck transfer starts one run; the issue's text is added after the prompt, so the on-call engineer's notes on which activity stalled reach the agent as written.

The trigger fills in nothing in the prompt, so the same automation serves the next reliability issue, a child workflow for refunds or a search attribute on the transfer, as long as the issue says what should change.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Heartbeats are easy to add and easy to get wrong in the ways that only show up in production: a timeout longer than the activity, details that are sent but never read on retry, a cancellation that is observed but not propagated into the call. The agent writes the tests that pin each of those down with the SDK's mock environment and time-skipping server, in its own sandbox, and keeps the output in the run's record.

The pull request explains the one value a human should weigh, the heartbeat timeout, and shows the test that proves a stalled worker is retried, so the review is about the number rather than about whether the mechanism works.

Frequently asked questions

Why do heartbeats need a heartbeatTimeout to matter?

Without a heartbeatTimeout in the activity options the server never expects a heartbeat, so an activity on a dead worker is only noticed when startToCloseTimeout expires, one minute in this project. With the timeout set, a missing heartbeat fails the attempt after that interval and the retry policy schedules it on a live worker.

How does the resume path avoid charging twice?

Each activity heartbeats a recorded step with the transaction id right after the bank call succeeds. If the worker dies before the activity returns, the retry reads that step from heartbeatDetails and returns the id without calling the bank again. The test for it constructs MockActivityEnvironment with those details and asserts the bank is not called.

Will heartbeating on every step flood the server?

No. The SDK throttles heartbeats so that at most a fraction of the heartbeat timeout passes between the ones it actually sends, keeping the latest details. Calling heartbeat often is the recommended pattern, and the pull request notes the throttle so a reviewer does not try to hand-tune call frequency.

Does the test suite need a Temporal server?

The workflow tests use TestWorkflowEnvironment, which downloads and runs a local test server the first time, and the new retry case uses its time-skipping mode so the heartbeat timeout elapses without waiting in real time. The activity tests use MockActivityEnvironment and need no server at all.

More Temporal jobs

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

Keep reading