When a long Temporal Activity retries, use the last received heartbeat to find where to resume checking. If an item could have committed before its heartbeat arrived, read the item’s durable result at its destination using the same operation ID. Confirm a matching result before advancing. If you cannot establish what happened, hold dependent work and record the unresolved item.
TL;DR A heartbeat can tell a retry where to look. The destination has to tell it whether a write happened. Test a crash after the destination commits and before Temporal records the next heartbeat. The retry should confirm the committed item, avoid a second effect, finish eligible work, and report any unresolved case without claiming the batch completed.
Key decision facts
| Observation on retry | What to do |
|---|---|
| The recovered checkpoint belongs to the same ordered batch | Begin validation at its first unconfirmed position |
| The batch revision or operation intent differs | Stop applying that checkpoint and reconcile the original work |
| The destination proves the same operation already committed | Verify the payload and advance without another write |
| No effect exists and the original attempt cannot still commit | Attempt the operation under its original stable identity, within its retry contract |
| The receiver confirms a same-key retry contract that still applies | Retry only within that contract and verify the resulting state |
| The first attempt might still commit or the evidence is contradictory | Keep the affected item unresolved and stop its dependent actions |
| Results complete out of order | Keep per-item state or a verified contiguous prefix with explicit gaps |
Draw the crash window before you choose a cursor
Start with two systems. Temporal records the progress of an Activity attempt. The destination, such as a records database or a storage service with its own operation journal, records the business outcome. A successful response from the destination can arrive before the next heartbeat reaches Temporal. A worker can also stop after the destination accepts a request and before it reads the response. Either gap can lead a retry to see a checkpoint that is behind the actual work.
Temporal documents heartbeats as progress signals for Activities and explains how heartbeat timeouts detect a missing signal. In the relevant retry path, the SDK can read the last received heartbeat details. Heartbeat transmission can be throttled. A local call to record a heartbeat is therefore weaker evidence than an observation that the service recorded the expected details. For a staging failure exercise, control the crash and inspect the retry input. Choose your timeouts and heartbeat cadence with the actual SDK behavior in view. Temporal Activity failure detection · Temporal Python Activity timeouts and heartbeats
Consider an Activity that takes scanned supplier invoices, computes a classification for each invoice, and stores one authorized review record per item. Its checkpoint says the first two invoices have confirmed results. The third result may already be durable by the time the worker stops. The fourth invoice might depend on the third record if the application uses a shared running reconciliation. The cursor gives you an inspection position. The third invoice's authoritative operation record determines whether the next business action is required.
Start by writing a short trace of the normal path at the side-effect boundary. For each item, the Activity identifies its intended operation, calls the destination, verifies successful state, and advances a checkpoint for progress. The safe order puts the progress update behind the confirmation. A checkpoint that advances before a durable result creates the opposite risk. A retry might skip an unperformed operation because the next position was recorded too early. Test that ordering using independent readback and an artificial pause in the destination where a request remains uncommitted.
Ask the product owner which observation the user cares about. The absence of duplicate rows is important for a one-row-per-invoice workflow. A persisted row is insufficient if it contains the wrong classification or was applied to the wrong invoice revision. A repeated inference call may also consume quota without creating a duplicate record. Track cost or repeated work separately from business integrity. A recipient can tolerate redundant calculation in one workflow while treating repeated billing, submission, or notifications as unacceptable in another.
Distinguish the waits introduced by the service from the waits introduced by your application. A worker can keep sending heartbeats as it performs useful work. It can also stay alive while a downstream operation is indefinitely unresolved. Set a concrete deadline for resolving an individual item and identify the log or record that closes it. A live worker and an advancing attempt timer do not settle a dispute over what the receiver committed. When a disputed effect affects downstream work, the operational decision is whether the receiver can settle the dispute within the currently allowed time.
Give the checkpoint a stable meaning
Choose a checkpoint format that distinguishes what was done from where you should resume. For a sequential Activity over an immutable list, a practical checkpoint holds a checkpoint format version, a batch or input revision, the last confirmed item position, and the associated item identifier. If the list can be reconstructed by an identifier rather than stored in full, carry the reconstruction pointer and validate its identity on retry. Use a different structure when the work does not have stable ordering.
Write down whether the cursor names the last confirmed item or the next unconfirmed item. Both conventions can work. Mixing the two skips or repeats work. Include a simple first-item test that starts with no heartbeat details. Include an all-complete test where the cursor points to the final item and completion still requires the intended aggregate evidence. With a last-confirmed convention, a cursor of one in a three-item list means the retry must check item two, after validating that position one still identifies the named item.
Choose what deserves to be in the heartbeat. Keep the details small and suited to what the retry actually needs. The checkpoint should reveal where to inspect progress without carrying a document, model output, customer address, or unrelated sensitive data. When a retry needs more context, let it read from the approved record that owns that context. Data that is already subject to a retention policy should follow the same policy in test histories, exported logs, and retry diagnostics. Avoid printing full heartbeat payloads during routine troubleshooting.
Changing the source list after an attempt has started is a new input revision. A numeric index from the prior revision is unsafe if documents can move, disappear, or be inserted before the cursor. The smallest check verifies input revision and named item at the cursor against the immutable batch. If the current revision differs, recover the old revision or keep its remaining items visible for reconciliation. Schedule the changed population as a distinct business operation when application ownership and workflow policy allow it.
When several items run at once, a simple maximum completed index loses gaps. To see why, imagine items one, two, and four finish while item three remains unresolved. A checkpoint that records four as “last complete” would make item three appear complete if the retry assumes everything below four is done. A contiguous prefix would be two, even though item four committed. A per-item completion record or a prefix plus explicit exceptions preserves the difference. Use the receiver to verify the reported out-of-order result before recomputing the prefix.
A checkpoint worksheet
| Field | Example value | Reject or investigate when |
|---|---|---|
| Checkpoint format | Version one with a last-confirmed index | The reader only understands another representation |
| Batch identity | Approved invoice review batch February A | The same label refers to another input set |
| Input revision | Immutable manifest revision three | The item order or digest differs |
| Position and item | Two, invoice Birch | The ordered manifest at position two identifies a different item |
| Confirmation reference | Receiver operation record for invoice Birch | The record is missing or has the wrong result |
| Expected next item | Invoice Cedar | The item is absent from the selected revision |
| Deferred evidence | Per-item operation IDs with unresolved outcome | The checkpoint would otherwise hide the pending item |
Building a typed record or another validated shape helps with early error detection. The design also needs an explicit answer when a newer worker discovers an older saved checkpoint. A format change can be handled by a tested reader for the old form, or by a refusal that preserves the exact batch and operation IDs so a compatible worker can continue. Try both the expected old format and a malformed shape in staging. A fallback that silently interprets a parse failure as an empty batch can cause the workflow to repeat its entire work.
Preserve business identity across attempts
A retry is an additional execution attempt at the same authorized operation unless the application explicitly creates a new operation. Give each intended item effect a stable operation ID. A useful identity combines the batch revision, item identifier, and operation intent when those fields are sufficient. The attempt number, worker identity, or model tool call ID can change on retry. Include those values in logs, while keeping them separate from the business key used by the receiver.
The operation identity needs something to compare. Freeze the aspects of the payload that define the intended effect, such as destination resource, item revision, approved action, and meaningful parameters. Decide whether the resulting classification is itself fixed before the call or produced anew during retry. If it is fixed, a different result under the same operation ID is a conflict. If the retry can recompute a candidate result, define where the system first binds an accepted result to that ID. A committed prior result may already settle the operation even if a fresh model invocation would choose another output. Sincllm on reconciling uncertain tool effects
An idempotency key helps when the receiver has a documented or verified contract for the key. Check its ownership scope, lifetime, how it handles a repeated key with a changed payload, and whether concurrent submissions can race. An HTTP request header cannot create a guarantee the receiver does not implement. After the allowed retention window expires, an old key might be treated as new. In that case, recover via an authoritative journal, an application-owned durable uniqueness constraint, or a verified state read before attempting another write. Amazon Builders’ Library on safe retries and idempotent APIs
A practical database-backed design can make the operation record and the resulting document update one transaction, when both belong to the same database and that contract fits the application. The receiver then checks the stable key and the result within its own transaction. If a follow-up message or other effect goes to a second system, success in the first database says only what committed there. Record and read the second effect under its own evidence contract. A checker that returns “complete” whenever the first table contains a row can miss the second side effect entirely.
At the beginning of a resumed attempt, ask the receiver for the expected item under the stable ID. A matching committed receipt points to a read path for the real content. A definitive refusal with proof the prior attempt cannot commit may permit a retry. An unavailable destination, a pending record with uncertain ownership, a conflicting payload, or a stale cached view provides weaker evidence. Keep the interval open if the retry contract cannot settle it. The practical test is what a fresh authoritative read demonstrates, not how long the previous worker was silent.
Configure progress and attempt boundaries around the actual work
Temporal Activity options include several distinct timeouts. A Start-to-Close Timeout applies to one attempt once it begins. A Schedule-to-Close Timeout applies across the time from scheduling to closing the Activity, including retry time. A Heartbeat Timeout concerns missing progress signals for eligible long-running Activities. Consult the SDK and operational policy for the available options and their precise behavior. Set them for your workload and practice retrieving on-the-wire progress in staging. Temporal Activity failure detection · Temporal Python Activity timeouts
Think through the branch each timeout should exercise. A worker that cannot begin an attempt points toward queue capacity or routing. A worker that starts, reports progress, then loses its process can exercise heartbeat-based detection when configured. A worker that has stalled in a long blocking downstream call can look similar unless you inspect both ends. The checkpoint design guides recovery once a retry occurs. Good diagnostics identify the reason and the time budget available for the next attempt.
Pick an illustrative timing scenario to test how the window behaves. Imagine a staging test where the Activity sends a confirmed checkpoint for invoice Birch. The destination then accepts the Cedar request and creates a durable outcome after a controlled pause. The Activity process exits before proposing the next heartbeat. Arrange the environment so a retry can start under the expected Activity settings, using short bounded test times appropriate to the staging workflow. Read the retry input and verify that it still points to Birch even though the Cedar result already exists.
Then introduce a second test where the service receives no heartbeat carrying Cedar because a recent call was throttled. Control the timestamps so the condition is observable. The exact interval depends on configuration and worker behavior. A deterministic staging crash just before any Cedar heartbeat is an easier first reproduction. Once that passes, choose a separate end-to-end test that can distinguish a heartbeat call in application logs from what the retry recovers. This provides evidence that the application handles stale progress even when instrumentation reports a more recent local state.
Review whether excessive heartbeat detail, high iteration frequency, or long blocking work affects the method you chose. A batch with fast items may need periodic bounded progress with a durable ledger between checkpoints. A batch with items that take significant time may also need progress signals during an item if the SDK permits and the operation can safely report them. Keep business completion distinct from progress within an item. “OCR started” or “request submitted” is useful diagnostic state, but it should never make the completed prefix advance.
Run a crash matrix against an independently observable destination
Use a staging destination that can identify each attempted write and show which writes actually committed. The Activity's logs can help locate the crash but should not be the only source of truth. If a database backs the test, use a fresh transaction against the authoritative primary or another read path with justified consistency. If a service owns the writes, read its operation journal and resulting resource through an allowed endpoint. A cached read that returns the old value can be a deliberate control, provided the fixture explains how to identify it as stale.
An illustrative batch contains four invoices in this order: Alder, Birch, Cedar, and Delta. Each input is fixed to revision A. The business key identifies one approved classification per invoice in that named batch. The Activity has already completed Alder and Birch. Verify that the receiver shows both results and arrange for Temporal to have the checkpoint ending at Birch. This is the common prefix. Use it across case runs so the observable difference is confined to what happens for Cedar.
| Case | What the first attempt does | Expected observation on retry |
|---|---|---|
| Commit before progress | Cedar commits, then the Activity process stops before the next heartbeat | Retry receives Birch and confirms exactly one matching Cedar result |
| Definitive non-commit | Test destination stops Cedar before its transaction can commit | Retry learns that the original attempt cannot apply, completes Cedar under the same key, and reads it back |
| Unresolved request | First attempt may still be in progress and the receiver cannot say which result will win | Cedar remains unresolved, its dependent action stays blocked, and the attempt records the operation ID |
| Changed payload | Receiver has Cedar under the expected key with a different approved input or payload | Retry raises a conflict and preserves both observations |
| Wrong revision | Retry receives a checkpoint whose index belongs to revision A while manifest B is selected | Checkpoint validation fails before an index is used |
| Premature progress | A deliberately defective test implementation records Cedar as complete before the write can commit | Readback exposes Cedar as incomplete even if the next item is Delta |
For the commit-before-progress case, pause the test Activity after the real destination transaction and before it sends the progress update. Verify the receiver accepted the write through a channel separate from the Activity thread. Stop the process under the staging failure mechanism. When the next attempt begins, record both the recovered checkpoint and the receiver response. The expected retry finds the existing Cedar result and does not create a second one. Then it processes Delta if Cedar is the only remaining dependency and the result still satisfies the intent.
The definitive non-commit case demands a stronger observation than a missing row. Arrange for the test destination to abort the transaction or reject the request before writes are allowed, and prove that the original executor cannot later apply it. Only after that control can the test expect a new attempt to complete Cedar safely without relying on concurrent idempotency. If the real receiver supports submission under the same validated key even while the first attempt may be in flight, test that separately under the actual receiver semantics. The better match is the scenario your production system will face.
The unresolved case is a negative control for the release decision. In staging, make the operation lookup time out or give it a result from a read replica intentionally held behind the primary. Observe whether the Activity flags uncertainty instead of treating the lookup as proof of absence. Induce a conflict separately by placing a deliberately different result under the same business identity in test data. A correct retry preserves the discrepancy. It should avoid rewriting the fixture until the problem can be attributed to a prior authorized action, a malformed request, or a mistaken binding.
The premature-progress case tests the protocol itself. Under the defective test implementation, save a cursor that would cause the retry to skip Cedar. Then induce failure before Cedar's receiver commit. An invariant that checks every expected durable result catches this defect, even if the final row for Delta is present. Keep the defective code isolated and designated as a test case. A run that merely reports the highest observed index will miss the very condition this control demonstrates.
Use the same batch manifest and namespace or isolated test partition semantics for comparisons across cases. Assign fresh business operation identities per independent fixture run so an earlier test does not create the next test's starting state accidentally. Preserve the intended identity across attempts within a case. Tie each observation to the case, destination, attempt, batch revision, and clock source. When the timing evidence is unclear, the receiver's transaction and operation records can distinguish a genuine after-commit crash from a prepared write that never became durable.
Check the four outcomes, not only the last cursor
For the successful crash fixture, independently read Alder, Birch, Cedar, and Delta. Count matching completed operations by exact item and revision. The expected outcome is four matching results for four intended items. Under the unresolved fixture, Alder and Birch can be confirmed while Cedar remains unresolved. If Delta depends on Cedar by the application's contract, Delta cannot be confirmed merely because its code was reached. If Delta is independent and already committed, retain that fact and the unresolved Cedar separately. Either way, the whole batch remains partially verified until all required items settle.
Check absence of unintended effects at the instrumented destinations. A database may have one row per key while the receiving service had two attempted requests or an extra downstream event. Which observations are relevant depends on what the operation was meant to guarantee. If the receiver contract prevents duplicate committed effects, record the difference between multiple attempts and multiple durable effects. If the cost of redundant inference is relevant, measure model invocation count from the authorized service record separately. The staging test can return healthy integrity with an unwanted cost regression.
Keep the test low-impact. Use synthetic documents and a destination your team can safely reset between fixtures. A planned crash in a staging Activity does not require terminating an unrelated worker pool. If an event needs to happen precisely before the heartbeat, expose a test-only pause at the intended point instead of timing a process kill by guesswork. Verify that the pause or fault control is unavailable in normal production paths. Keep evidence that the crash really crossed the window you intended.
Decide how recovery interacts with partial results
A workflow may need to report what has finished while still reconciling the rest. Make the output distinguish a confirmed item, a pending item with an active attempt, and an unresolved item that requires a durable read or operator decision. A single value such as “processed three of four” can mask a batch where confirmation is missing for an earlier prerequisite. Use the actual set of confirmed item IDs and list which dependencies prevent further work or a complete result.
If unordered items can proceed independently, a failure for Cedar might allow Delta to finish. Preserve that decision in the contract. A retry should read confirmed state for Delta if it processes positions from a prefix before Cedar. Starting Delta anew because the prefix is behind can repeat work or effects. A receiver journal and per-item resolution state let the workflow preserve the progress it has observed and make the smallest new attempt needed to finish the batch. Sincllm on returning partial workflow results
Agree where handoff happens when recovery times out. One option is to return an application-level unresolved result the parent Workflow can route for review, when its contract supports that state. Another is to raise a failure with durable evidence accessible to the coordinator. Choose the behavior consistent with the existing application and retry policy. Avoid marking unresolved items as successfully applied just to terminate a retry loop. If an automatic workflow retries a blocked item, bound the retry condition to an observed change in a dependency, such as the destination becoming readable again.
Record original authority when a person takes over. The fact that a retry could not establish the status of an earlier write does not authorize a new payload. The handoff should tell the reviewer what originally qualified the action, which result was expected, which attempt is unresolved, where the receiver can be read, and when the current retry contract expires. If legitimate new instructions alter the intended effect, create a separately authorized operation after the earlier effect is reconciled. An old key reused for new intent defeats the comparison the retry depends on.
Choose records an on-call operator can verify
A good on-call display joins, rather than collapses, the Temporal attempt and the receiver outcome. Include the logical Activity identity, attempt number if available, batch input revision, recovered cursor, intended operation ID, matching destination record and current state. Display when the observations were taken. Make the target resource navigable under authorized access. People need a way to check evidence that is stale without manually searching a directory of loosely labeled logs.
Use consistent states. For example, “checkpoint loaded” documents a parsed retry input. “Destination confirmed” records the committed business result. “Safe to retry” refers to in-scope receiver evidence about the prior effect or the active same-key contract. “Unresolved” means no verified historical outcome has been established. If practical, keep “conflict” as a special case that prompts an owner review of the competing identities or payloads. A fresh read can transition a record without changing what was actually observed in the earlier attempt.
Inspect timing on comparable clocks when diagnosing a crash window. A wall-time entry from the worker and one from a receiver may differ because the hosts do not agree closely enough or write logs after their actions. A controlled staging pause and explicit transaction receipt can give stronger ordering evidence. In production, record whether you observed commit-before-heartbeat directly or inferred it from separate facts. The inference may be sufficient to avoid a duplicate write when the current destination result is authoritative, even if the root cause is still open.
Build a view that detects both under-reporting and prematurely claiming success. Suppose a dashboard counts “attempts completed” from Temporal and a separate monitor counts known durable effects from your application database. A discrepancy can be useful but needs interpretation. Some attempts may never have been expected to write, while a batch may perform several effects before closing. Join at the item or operation level before extrapolating from totals. Use denominators drawn from the frozen input manifest and flag unknown items explicitly.
Recovery checklist
- Confirm the intended item, input revision, approved parameters, and stable operation ID against the frozen batch.
- Read the actual checkpoint and determine its index convention before using an offset.
- Ask the authoritative destination for the business operation and the resulting resource.
- Verify matching payload and scope when an effect already exists.
- Retry only with evidence that the original cannot apply, or under a verified same-key contract within its limits.
- Keep the cursor behind every unresolved prerequisite, or retain explicit per-item state that prevents a hidden gap.
- Check every item and every required downstream effect before marking the batch complete.
- Retain the attempt and receiver evidence needed for a later operator to understand the work.
In a minimal staging launch, run the successful duplicate-avoidance case and the adverse ambiguous-read case before changing timeout or worker settings. Then extend the same logic to fresh cases that differ in one relevant way, such as an out-of-order result or an incompatible input revision. Compare expected and observed business results. A method that worked only when the list was ordered or when the receiver had unlimited key retention needs those conditions documented. Test again when the conditions change.
When a heartbeat is the wrong place for a completion ledger
Heartbeats work well as bounded hints for retry progress. If a single Activity covers an enormous mutable population, a large number of incremental effects, or side effects across several organizations, carrying sufficient recovery detail in one checkpoint may be a poor fit. Consider putting durable item state in the owning application, turning batches into an explicitly managed set, or making smaller Activities whose inputs and results are easier to verify. The result should be a local, testable record of work, rather than a status message that needs progressive reinterpretation.
Consider a workflow that classifies documents into an application database and also sends a notification for certain classifications. The completion definition might require both a stored classification and a sent notification. A reader can check the database row while still having no evidence that the notification receiver applied the action. Make the classification and notification separately recoverable logical effects when they have different observation and retry rules. If the notification provider has no authoritative lookup and no verified same-key behavior, holding for explicit reconciliation may be preferable to repeated automatic execution.
A change in checkpoint frequency affects how much recent progress a retry might need to inspect. It does not make ambiguous commits decidable. If it becomes expensive to inspect many item records after every retry, tune batches or design a durable indexing strategy, then measure how much work the retry actually revisits. Preserve the original operation identity through the change and rerun the primary crash fixture. An optimization that checks fewer records while allowing an unreconciled gap to disappear fails the purpose of the recovery protocol.
Rehearse the operator decision after the receipt window expires
Schedule one staging fixture that represents delayed recovery. Suppose the first Activity attempt has been identified, but its destination response is no longer visible through the provider’s standard request lookup. The normal same-key receipt window has also expired. Your system still has the input revision, the original business key, and a record of the approved effect. Consult the durable destination resource and any authoritative operation journal the team retains. Make the fixture explicit about which observations can actually bind the resource to that old operation.
Prepare two outcomes that look similar in a summary view. In one, the current invoice record carries the same batch revision and operation ID as the expected Cedar result. In the other, a human corrected the same invoice through an independent operation after the original Activity stalled. The record's current status can be identical across both fixtures. The decisive evidence is the application’s operation identity, provenance, and resulting revision. Do not infer that your worker applied the old action just because the desired visible value is now present.
Document the expected handoff in the second fixture. Preserve the operator’s correction, report the earlier attempt unresolved if its effect is still unknown, and ask the application owner to decide whether any approved action remains. A new same-key attempt cannot settle an expired contract. The exercise also tells you how long to retain the evidence needed to recover the underlying work. If your business needs a longer reconciliation window than the destination supplies, keep an authoritative record you control or reduce the time the workflow can be left unresolved.
After resolving an ambiguous item, rerun the same batch fixture with the original operation ID and input revision. Compare the first destination record with the final result and require one matching effect. Keep the first unresolved observation in the incident log so the restored path does not obscure the earlier evidence.
FAQ
Does a more frequent heartbeat prevent duplicate writes?
More reliable recent progress may reduce revisit work, but an acceptance or commit can still precede the next recorded heartbeat. Test that window directly. You need a stable business identity and destination evidence, or the receiver's verified equivalent retry contract, to decide whether another write is safe.
What if the retry has no heartbeat details?
Use a defined initial state. Look up prior item effects under their stable identities before creating any new effects if the Activity could have begun. Confirm why there are no details when the distinction matters, for example a first attempt, an earlier transmission that did not arrive, or a rejected format. A published retry protocol should distinguish “no checkpoint exists” from “an existing checkpoint could not be interpreted.”
Can I use the Temporal attempt number as the idempotency key?
Attempt numbers belong to execution diagnostics. A second attempt at the same authorized business action must be able to discover the first result. Use a business key stable across those attempts. Include the attempt number elsewhere so a reviewer can reconstruct the order of events.
What if the receiving API has no read endpoint?
Find out whether it provides another authoritative observation, such as a durable transaction journal, a reconciliation export, or a documented same-key result. If the earlier effect is possible and every permitted observation remains inconclusive, report the item unresolved. Avoid a new effect just because the first request no longer appears in a local queue.
Should the workflow advance past an independent item that finished out of order?
Preserve a confirmed independent result even if an earlier item remains unresolved. Decide whether to schedule more independent work from the business contract. Avoid representing the highest observed position as a contiguous completed prefix unless every required item below it is confirmed.
Which result makes the crash drill pass?
The retry reads the expected checkpoint, reconciles the item that may have committed, and leaves consistent durable results for every verified item. The adverse case remains visibly unresolved when its facts are ambiguous. A pass requires these observations at the actual business destinations, even when both Temporal and the application report that the worker attempt ended normally.
sinc-LLM