Why long-running Temporal activities need heartbeats
A team running a multi-gigabyte file transfer, a media transcode or a long batch submission to an external provider may have activities that run for minutes or hours. If the worker process dies or hangs partway through, the activity is not automatically known to be stuck. Without heartbeats, Temporal has no visibility into what the activity is doing between its start and its completion. The activity's start-to-close timeout is the only clock, so a worker that silently stops can leave the activity appearing to run until that long timeout expires. Setting that timeout to hours means a failed run may sit undetected for hours, and a retry then restarts the transfer or job from byte zero or from the first record.
A heartbeat is a periodic call from the activity to the Temporal service that says the activity is still alive. The activity sends it through the heartbeat function in its SDK, and it can attach a details payload, such as the last processed offset or the last completed batch. The service uses the HeartbeatTimeout setting to decide when a missing heartbeat means the worker is gone, then fails the attempt so a retry can run. Because the last recorded details are delivered to the next attempt, heartbeats also act as a checkpoint: the retried activity can resume from the saved position instead of repeating finished work. The heartbeat interval must be shorter than the heartbeat timeout, and the team should confirm the exact behavior of their SDK version before relying on it.
Teams need heartbeats when an activity runs long enough that a silent failure is costly, and when the work can be resumed from a recorded position. If an activity finishes in seconds or a few minutes and is safe to repeat in full, a plain activity with a retry policy is usually simpler. If the work is a fan-out over many independent items, a child workflow or a batch design often fits better, because each child keeps its own history and progress. Before committing, confirm with the engineering team that the activity can be made idempotent at each checkpoint, and that the heartbeat details stay small enough for the service's payload limits.
How heartbeats flow between the worker, the Temporal Service and a retried attempt
The flow starts when a workflow schedules an activity on a task queue and a worker in the client's network picks it up. The activity sends heartbeats carrying progress details to the Temporal Service, which is hosted inside the trust boundary. If heartbeats stop, the heartbeat timeout expires and the retry policy schedules a new attempt on a healthy worker, which reads the last recorded details from the heartbeat. Check that heartbeat timeouts are shorter than the activity timeout, and that the details recorded are enough to resume safely.
Heartbeat details move from a worker to the Temporal Service, then to a retried attempt on another worker.
Heartbeat timeout, retry and progress settings compared
This table compares the settings a team sets for a long-running Temporal activity, what each one detects, what it misses and when it fits. Read each row as a separate control, then combine them: heartbeats catch a silent worker, timeouts bound total time, and retries decide what happens after a failure. Confirm exact defaults and units in the SDK you use.
| Setting | What it detects | What it does not detect | When it fits |
|---|---|---|---|
| Heartbeat timeout | A worker that stopped sending heartbeats, such as a crashed process, a lost worker or a hung activity thread | A slow activity that keeps heartbeating, or an activity that heartbeats without making progress | Any activity that runs for minutes or hours and must be reassigned quickly when its worker disappears |
| Start-to-close timeout | An single attempt that runs longer than the allowed time for one execution | Total elapsed time across retries, and a worker that is lost before the attempt times out | A ceiling on how long one attempt may run, set above the expected duration of the longest normal attempt |
| Schedule-to-close timeout | Total time from scheduling to completion across all attempts and retries | Which attempt failed, or whether the worker is alive during the run | A hard business deadline for the whole activity, such as a batch that must finish by a set time |
| Retry policy and maximum attempts | Failed attempts, which are retried with backoff until the maximum attempts or a non-retryable error | Silent hangs, since a hang produces no failure for the retry policy to act on | Transient failures such as network errors, paired with a non-retryable error type for business failures |
| Heartbeat details (progress) | The last recorded progress point, which the next attempt can read to resume | Whether the saved progress is still correct, so the activity must be safe to repeat from that point | Work that processes items in sequence, such as a file or record set, where restarting from zero wastes time |
How recording progress in heartbeats lets an activity resume after a restart
When a worker dies mid-activity, the next attempt starts with only one piece of state from the failed run: the heartbeat details the activity last recorded. Anything held in memory, in a local file or in a variable is gone. That makes the checkpoint the activity's memory. Choose a value that marks a safe place to restart, such as a byte offset into a file, a page cursor returned by the source API, or the index of the last completed batch. Record it through the heartbeat call in Heartbeat or the equivalent SDK method, and read it back on the retry through the heartbeat details accessor before doing any work.
Checkpoints are not free of correctness risk. The activity repeats everything after the last recorded checkpoint, so the work between checkpoints must be idempotent. Writes need a stable key or a deduplication check, uploads need a deterministic object name, and calls to external systems need an idempotency key where the provider supports one. Confirm with each downstream system whether repeated requests are safe, because a heartbeat only tells Temporal the worker is alive, not that the side effects were applied once. Keep checkpoints small, since heartbeat details are sent to the Temporal Service on every call and large payloads slow each heartbeat down. Store bulky state in your own database or object store and record only a pointer in the heartbeat.
Heartbeat frequency is a trade-off the team must test, not a default to accept. Throttling heartbeats reduces load on the service, but a heartbeat timeout only fires when no heartbeat arrives within the configured window, so a long gap between calls can be mistaken for a stuck worker. Measure the longest realistic interval between heartbeats under production load, including slow external calls and garbage collection pauses, and set the heartbeat timeout with margin above that figure. Run a restart test on a staging worker that kills the process mid-batch, then confirm the retry resumes from the checkpoint, produces no duplicate side effects and finishes within the expected window.
Setting up a long-running activity with heartbeats
This sequence takes a long-running activity from design to a tested setup in which a stuck or killed worker is detected, and a retried attempt resumes from the last recorded checkpoint instead of starting over. It is written for the team building the workflow and the engineers who will operate the workers.
Define the activity boundary and checkpoint data
Split the long job into activities that each do one unit of external work, such as one file, one API page or one batch of records, and decide what progress marker must survive a restart. The workflow owner and the activity author agree on this together. Write down the checkpoint fields (for example a cursor, a last completed item ID or a byte offset) and confirm that each unit can be safely repeated. Done when every checkpoint field has a named owner and a documented way to resume from it.
Choose the heartbeat timeout and retry policy
Set the heartbeat timeout in the workflow's activity options, not in the activity code, so operators can change it without redeploying the worker. Pick a value that is longer than the worst normal gap between heartbeats, including garbage collection pauses and slow calls to downstream systems, and shorter than the time you are willing to wait before a dead worker is replaced. Set the retry policy next to it, and mark errors that will never succeed on retry as non-retryable. Confirm the values with the SDK documentation for your language, since option names differ. Done when the timeout and retry settings are written in a reviewed workflow change with the reasoning recorded.
Code the heartbeat call and the checkpoint
Inside the activity, call the SDK's heartbeat function at a regular point in each unit of work, and pass the checkpoint as the heartbeat details so Temporal stores the latest value. Keep the heartbeat call on the activity's own loop, not in a separate background thread that can keep reporting after the real work has stalled. Heartbeat calls are how the server learns the activity is still alive, so calling it too rarely causes false timeouts, and calling it too often adds load. Use the SDK's cancellation signal from heartbeats to stop cleanly when the workflow cancels. Done when a local run shows the checkpoint being recorded at each heartbeat.
Read the last checkpoint on resume
At the start of the activity, read the heartbeat details from the previous attempt through the SDK's accessor for last heartbeat details. If the value exists, continue from that position. If it is empty, start from the beginning of the unit. Keep the resume logic in one function so it can be unit tested without a running cluster. Done when a test that seeds a checkpoint shows the activity skipping work already completed and starting at the recorded position.
Make the external side effects idempotent
Repeating a unit of work after a timeout means the external system may receive the same request twice. For each side effect, use an idempotency key derived from the workflow ID and the unit identifier, or check the target system for an existing result before writing. Record which calls the target system deduplicates and which ones your code must guard. Engineers from the team that owns the external system should confirm the behavior, since it is not something the workflow can enforce. Done when a repeated run against a test target produces the same final state as a single run.
Test the timeout with a paused worker
In a non-production namespace, start the workflow, then pause the worker process without stopping it, for example by suspending it with a debugger or freezing its container. Wait for the heartbeat timeout to pass and confirm in the Web UI or event history that the attempt is marked as timed out and a new attempt is scheduled. Confirm that the paused process does not keep writing results after the timeout, because a late write is a sign the idempotency check is missing. Done when the event history shows the timeout and the retry, and the final output matches a clean run.
Kill the worker mid-run and confirm the resume
Start a run with enough units to stop partway, then terminate the worker process hard, without a graceful shutdown. Start a replacement worker on the same task queue and let the retry pick up the activity. Check that the new attempt begins at the last recorded checkpoint, that no unit is processed twice on the target system beyond what idempotency allows, and that the workflow completes with the expected result. Keep the event history and worker logs from the run as the evidence for the change review. Done when the test passes three times in a row against the same inputs and the logs show resume from checkpoint, not restart from zero.
Confirm alerts and operator runbook
Before release, decide which signals the operations team will watch, such as activity timeouts and retry counts for this activity type, and set alerts on them in the monitoring stack your organization uses. Write a short runbook covering what a timeout looks like in the Web UI, how to confirm that a replacement worker has picked up the task, and when to cancel the run. Ask the platform team to confirm that the alert routing reaches an on-call rota. Done when a deliberately triggered timeout raises the alert and the runbook steps lead an operator to the correct event history.
Choosing heartbeat settings by activity type
A file or data transfer is the clearest case for heartbeats that carry progress. The activity reads or writes a stream of bytes, so the heartbeat can record how far the transfer has got, and a retry can resume from that point instead of starting over. The heartbeat timeout should be short enough to notice a stalled connection or a dead worker, but long enough that a slow read on a busy disk does not look like a failure.
- Byte-offset checkpoints: Record the byte offset of the last fully written chunk, plus a checksum or version identifier for the source object, so a resumed attempt can confirm the source has not changed.
- Heartbeat frequency: Send heartbeats after each chunk or on a fixed time interval, whichever gives a sensible balance between detection speed and heartbeat volume.
- Timeout drivers: Derive the heartbeat timeout from the slowest chunk you measure on production storage, not from the average throughput.
- Storage and network tests: Test resume against your own object store, NFS or SFTP endpoint, including interrupted uploads and partial files left behind.
- Idempotent writes: Make the write step safe to repeat, for example by writing to a temporary key and renaming on completion.
Before relying on offsets, check that the target system supports the resume behavior you assume and measure heartbeat intervals on the network path your workers actually use.
A batch of external API calls usually walks through pages of results with a cursor. The heartbeat can store the cursor returned by the last successful page, so a restarted worker continues from that page. The timeout matters most when a single call can hang, because one stuck request can hold the whole activity until the heartbeat timeout expires.
- Cursor checkpoints: Store the opaque cursor or next-page token together with the count of records processed, not the full result set.
- Per-call timeouts: Set a timeout on each HTTP request so that a hung call fails before the heartbeat timeout does.
- Duplicate handling: Confirm whether the API can return the same records after a resume, and make downstream writes idempotent by record key.
- Cursor expiry: Ask the provider how long a cursor stays valid, since an expired cursor forces a restart from an earlier point.
- Rate limit behavior: Test how the API responds to throttling during a long batch, because waiting for a rate limit window can look like a stalled activity.
Review the provider's documented cursor lifetime and rate limits, then run a resume test against the sandbox or staging environment you will use in production.
Some compute work cannot report partial progress. A model scoring run, a cryptographic operation or a single transform over a dataset may produce no useful intermediate state. In this case the heartbeat's main job is liveness: it proves the worker is still running the activity, and the activity can then be retried from the beginning if the worker disappears. Checkpoints are optional and, if used, should be coarse.
- Liveness only: Send heartbeats from a separate goroutine or thread so that a long computation does not block them.
- Coarse checkpoints: If the job can be split into stages, record the stage name and its output location rather than in-memory state.
- Retry cost: Measure how long a full restart takes, since that cost decides whether the heartbeat timeout should be generous.
- Resource pressure: Test heartbeats under CPU or memory pressure on the worker host, because a starved heartbeat thread produces false timeouts.
- Worker shutdown: Verify that a graceful shutdown lets the activity finish or stop cleanly before the timeout fires.
Confirm the SDK version and the worker settings in a load test that matches your largest job, because heartbeat behavior under pressure is where most surprises appear.
An activity that waits for a third-party system, such as a partner's batch job finishing or a provisioning request completing, spends most of its time idle. The heartbeat here shows the worker is alive and the wait is still active. The checkpoint usually holds a job identifier and the last observed status, which lets a restarted attempt resume the wait rather than submit the job again.
- Job identifier checkpoints: Store the external job ID and the last status seen, and never resubmit a job when an identifier already exists.
- Poll cadence: Keep the poll interval well below the heartbeat timeout, and separate it from the heartbeat interval so polls do not delay heartbeats.
- External timeouts: Compare the wait's expected maximum duration with the provider's own job retention window, because the external job may expire before the wait ends.
- Network path tests: Test from the worker network, including firewalls, proxies and DNS changes, since these often break a long-lived wait without an error.
- Stuck detection: Decide what happens when the external status never changes, and set an overall limit separate from heartbeats.
Ask the partner for their job retention and status-change behavior, then test a restart mid-wait in your own environment before setting final values.
Security and data exposure risks in heartbeat details
Heartbeat details look like harmless progress markers, but they are stored in workflow history and travel over the same API as everything else. The cards below cover the places where a long-running activity can leak data, accept unauthorized requests or replay a side effect, and the control each one calls for.
Sensitive data in stored heartbeat details
Heartbeat details are recorded in workflow history, so a cursor, file path or record fragment written there is stored with the workflow. Without a custom payload codec, that data is readable by anyone who can read history through the API or database. Check what each heartbeat writes, keep it to offsets and counters, and confirm that payload encryption through a codec applies to heartbeat details as well as activity inputs and results.
Self-hosted security docsUnauthenticated frontend access by default
If no Authorizer is configured, self-hosted Temporal uses the noopAuthorizer, which allows every API request. Any client that can reach the frontend can start, signal, read or terminate workflows, including the ones that hold long-running activities. Configure an Authorizer plugin and a ClaimMapper so that namespace roles decide who may read history and who may act on it.
Security settingsWorker placement on trusted networks
Workers that run long activities hold credentials for the systems they call and report progress back to the frontend. The Temporal deployment docs say services should run on hosts that are not reachable from the public internet, with access restricted to trusted internal networks. Place workers and the frontend in private subnets, restrict ingress to known sources and confirm that no heartbeat-capable endpoint is exposed to the internet.
Deployment guideMutual TLS between services and workers
Heartbeat traffic and the activity results around it cross the network between workers and the frontend, and between internal Temporal services. Self-hosted Temporal supports mTLS with separate settings for internode and frontend traffic. Enable both paths, issue certificates with a defined rotation process and confirm that workers reject connections that present no valid client certificate.
mTLS settingsCredentials and tokens in checkpoints
A checkpoint is written to history and may be read back on a retry or after a restart. Storing an API token, a presigned URL or a database password in heartbeat details copies that secret into durable storage and makes rotation harder. Keep credentials in the worker's secret store, fetch them at attempt start and record only a position or an opaque resume marker in the heartbeat.
Side effects replayed on retry
When a worker dies, the activity is retried from the last heartbeat or from the start, so work after the checkpoint can run again. A payment, a provisioning call or an email sent twice is a real exposure. Pass an idempotency key derived from the workflow and the business object into each external call, make the downstream system reject duplicates and confirm that the checkpoint and the side effect are never out of step in a way the key cannot cover.
Operating long activities after go-live
Once long activities run for hours, the work shifts from building them to watching them. The first thing to watch is retries caused by heartbeat timeouts: an activity that stops heartbeating looks stuck to the server, so it is retried, and a retry that starts from the same checkpoint repeats work the previous attempt already finished. Build a dashboard that counts activity attempts beyond the first, grouped by activity type and task queue, and alert when that count rises across a window you agree with the owning team. Pair it with a check on whether each activity's heartbeat details advance between attempts. If attempts keep returning to the same progress value, the checkpoint logic is wrong, not the infrastructure. Confirm how your Temporal version reports attempt counts and heartbeat details in its visibility and Web UI before you write alert rules against them.
Build a second set of signals around workers and history. Track worker shutdowns, restarts and pod evictions against the task queues that were running activities at the time, because a shutdown during a long activity is the usual trigger for a timeout-driven retry. For history growth, watch the size of workflows that contain activities with frequent heartbeats, since each recorded heartbeat adds to the workflow's event history. Heartbeat less often than the work requires, or throttle heartbeats in code, and treat the heartbeat interval as a setting you tune with load testing rather than a fixed value. Set alert thresholds only after you have a baseline from your own environment, and document who receives each alert.
The runbook for a stuck activity should start by identifying the workflow ID, activity type, current attempt number and last heartbeat time, then checking whether the worker is alive and still polling the task queue. If the worker is healthy but the activity has no progress, decide whether to let the retry policy continue, cancel the activity, or reset the workflow to an earlier point, and record that decision with its reason. Deployments need a stated rule for in-flight activities: either the worker waits for running activities to finish within a grace period before it exits, or the activity is cancelled and resumes from its last heartbeat. Agree that rule with the application owners, test it in a non-production namespace, and confirm the graceful shutdown and cancellation behavior in the SDK documentation for the language you use.
Limits to confirm for long-running activities in your environment
Long-running activities depend on limits that vary by SDK, server version and storage backend, so the values in the Temporal docs and your own tests decide the design. Confirm each item below before writing heartbeat logic, and record the answers next to the workflow code so reviewers can trace them.
Maximum activity duration
Find out how long a single activity attempt may run before the server times it out, and which timeout you set controls that limit: start-to-close, schedule-to-close or both. Activities that run for hours usually need a start-to-close timeout sized to the longest expected attempt, plus a plan for what happens when that timeout fires. Confirm the behavior with your SDK's timeout documentation and a test that runs past the limit.
Heartbeat payload size and frequency
Heartbeats carry progress details back to the server, and the docs and your SDK define how large a details payload may be and how often you may send one. Sending a heartbeat on every record in a million-item loop can flood the service, so batch progress updates to a sensible interval. Measure payload size and call rate in a staging run before you set the interval.
Heartbeat details and history size
Heartbeat details are recorded in workflow history in some configurations, so frequent or large details can grow history and push a workflow toward history limits. Confirm whether your SDK and server version persist heartbeat details in history, and what that means for a workflow that runs for days. Keep details small, such as a cursor or a last-processed key, and store bulk progress in your own system.
Cancellation through heartbeat responses
Confirm whether a cancellation request reaches a running activity through the heartbeat response in your SDK, and how the activity learns it should stop. Activities that never heartbeat will not see a cancel request in time, so the activity code must check for cancellation at each heartbeat and clean up before returning. Test a cancel request against a running activity to confirm the timing you observe.
Activity behavior during worker shutdown
Find out what the SDK does with in-flight activities when a worker receives a stop signal, including whether it waits for them to finish, cancels them or lets the server time them out. The graceful shutdown window and the heartbeat timeout together decide how quickly a replacement worker picks the activity up after a deployment. Rehearse a rolling restart during a long activity and record what the history shows.
Server version, schema and chart compatibility
The self-hosted service must run a server version that your SDK supports, on a persistence backend and deployment chart that match it, and the Temporal docs list the supported combinations. Helm chart versions below 0.73.1 do not work with server images 1.30 and later, and schema upgrades must run before server upgrades when release notes call for them. Check the supported versions in the Temporal docs before you build, and pin the same versions in your test and production environments.
Deployment docsQuestions buyers ask about long-running Temporal activities
What drives the effort to add heartbeats to an existing Temporal activity?
The main drivers are how long the activity runs, how many distinct stages it has, and how much of its progress is already stored outside the activity. A short activity that calls one API may need only a timeout setting and a few lines of heartbeat code. A multi-hour job that reads files, calls several services and writes results needs each unit of work identified, a checkpoint format chosen, and resume logic written and tested. Other cost factors include whether the activity is idempotent, whether side effects can be repeated safely, and how many workers and task queues run it. Ask for a written inventory of activities, their current timeouts and retry policies before requesting a quote.
How long does a first long-running activity take to build and test?
The duration depends on the activity's complexity, the number of failure cases to test, and the test environment available to the team. Building the heartbeat, choosing timeouts, and writing checkpoint logic is usually the smaller part. Most of the time goes to forcing failures: killing workers mid-run, simulating network loss, and confirming that a restarted worker resumes from the last checkpoint without duplicating side effects. DeployOpen does not publish durations, so the timeline comes from the written scope. Ask for the planned test scenarios and the environments they run in, since those set the schedule more than the code does.
Can our own team add heartbeats and resume logic without outside help?
Yes, many teams do this in-house once they understand the Temporal activity model, and the Temporal documentation covers heartbeat timeouts, heartbeat details and retry behavior. The points that most often need experienced review are the choice of heartbeat interval, the checkpoint granularity, and whether each step is safe to repeat. A common split is for internal engineers to own the business logic and checkpoint format while an outside team reviews the design and runs the failure tests. Your team should decide early which of these tasks it can staff with people who will still be there after the engagement ends.
What does the work need from our team?
Plan for three inputs. First, sample workloads that match production in size and duration, including the slowest realistic input. Second, a failure test environment where workers can be stopped, restarted and isolated from their dependencies without affecting real systems. Third, a named owner for checkpoint design who can decide what counts as a completed step and approve changes to the stored progress format. Also provide access to current worker deployment settings, shutdown behavior and alerting, because heartbeat timeouts interact with them. Ask the implementation partner to list these inputs in the written scope so gaps show up before work starts.
How could Temporal Cloud pricing affect the cost of long-running activities?
Temporal Cloud pay-as-you-go pricing starts at 50 US dollars per million actions, and storage is billed separately as active and retained GB-hours. Long-running activities can change the mix. Heartbeats send additional traffic to the service, and any extra retries or resumed attempts may add billed work. Larger payloads kept in workflow history also affect storage. Before modeling costs, confirm on the Temporal pricing page whether heartbeats count toward billed actions, and how retries and activity attempts are metered. Then estimate heartbeat frequency and expected restarts for your workload, and compare the result with a self-hosted cost model that includes your own infrastructure and staff time.
What goes wrong when heartbeat timeouts are set too short or too long?
A timeout that is too short causes Temporal to treat a healthy but busy worker as stuck, which triggers retries and duplicate work. A timeout that is too long delays detection of a crashed worker, so the activity sits idle until the timeout expires. Both problems are easier to find in a test environment that simulates slow dependencies and worker crashes than in production. Set the heartbeat interval based on observed pauses in the activity, not on the total run time. Check that the activity's start-to-close timeout still matches its longest expected run, and document why each value was chosen.
Does a heartbeat guarantee that an activity never repeats work?
No. A heartbeat only tells Temporal that the activity is still running, and it lets a restarted attempt read the last recorded details. Work performed after the last heartbeat can still be repeated, and external side effects such as payments or emails are not rolled back. Design each step so it can run twice safely, using idempotency keys, conditional writes or external status checks. Confirm the exact resume behavior with the Temporal SDK version your team uses, because details differ by language.
How DeployOpen scopes and delivers long-running activity work
DeployOpen approaches long-running Temporal activities as a scoped engineering task, covering heartbeat timeouts, progress recording and resume behavior after worker restarts. Work is agreed in writing before the build starts, and the result is tested, documented and handed over inside infrastructure you control.
How we scope
- Inventory which activities run for minutes or hours and what each one must survive.
- Agree heartbeat timeout values, retry settings and progress fields for each activity in writing.
- Define which worker restarts, deployments and failure modes the resume design must handle.
How we build
- Implement heartbeats that record progress and resume from the last checkpoint without repeating side effects.
- Make activities idempotent so retries after a lost worker do not duplicate external changes.
- Test stuck-worker detection by killing workers mid-activity and confirming timeouts and resumption.
How we hand over
- Document heartbeat intervals, timeout rationale and checkpoint format for each long-running activity.
- Provide a runbook covering stuck activities, manual retries and worker shutdown behavior.
- Walk your engineers through the code and tests so they can change activities safely later.
How we support
- Offer ongoing support, upgrades and continuous testing as a retainer after handover.
- Retest activity resume behavior when Temporal server or SDK versions change.
- Confirm with your team how alerts on heartbeat timeouts reach the people who respond to them.

