---
title: "Polling with Long-Running Step Heartbeat"
description: "Polling with a long-running Step heartbeat waits for an external system inside one Step execution. Use it when a Flow waits for a cloud build, a Kubernetes rollout, a provisioning job, or the status of a third-party API, and you want the lightest polling loop."
canonical_url: "https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat/"
source: "docs/content/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Polling with Long-Running Step Heartbeat

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.go.md) · [Java](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.rust.md)

Polling with a long-running Step heartbeat waits for an external system inside one Step execution. Use it when a Flow waits for a cloud build, a Kubernetes rollout, a provisioning job, or the status of a third-party API, and you want the lightest polling loop.

One Step owns the whole wait. Its `Execute` calls the external API, sleeps, and calls again until the work reaches a terminal state. [Polling with WaitFor Timer](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.md) waits for the same kind of system with one Step execution per round.

Business signals inside Dex, such as Channel messages and RPCs, are not polling. Wait for them with `WaitFor`. Business timers, such as a TTL, a reminder, or an inactivity deadline, also use `WaitFor`; see [Durable Timer](https://docs.superdurable.io/design-patterns/durable-timer.md).

**Flow graph: PollingFlow**

**Steps**

1. `StartJob` (start Step): Start the external job. Next: `AwaitJob`.
2. `AwaitJob`: Poll the job with heartbeats until it succeeds or fails. Next: the Flow completes, the Flow fails, or `RecordJobWaitFailure` if it keeps failing. Writes `JobProgress`.
3. `RecordJobWaitFailure`: Fail the Flow with the reason polling stopped. Next: the Flow fails.

Example: [examples/python/dex_examples/patterns/polling/polling_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling/polling_flow.py)

## Shape

The polling Step repeats these steps:

1. Call the external API with its own short timeout, such as 10 seconds.
2. On a transient error, return the error. The retry policy runs the Step again.
3. On a terminal status, return the next decision: success or a business failure.
4. Report progress. Write a Stream message when the status changes. Otherwise record a heartbeat with the checkpoint.
5. Sleep for the polling interval, then start again.

"Not ready yet" is a normal branch of the loop. Prefer it to returning an error and letting retries loop. An error mixes "not ready" with real failures and spends the retry budget.

A plain sleep is enough. Honor cancellation through the language SDK's mechanism. When the external call accepts a cancellation argument, pass it. Give a blocking call that cannot observe cancellation its own timeout, because the Worker slot is released only when the handler returns. Cancellation is cooperative: the loop exits at the next boundary that can report it. See [Make the Step stop](https://docs.superdurable.io/reference/server/runtime-data.md#cancel-honour).

<a id="rules"></a>

## Rules

- <a id="interval-and-timeouts"></a>Keep each round inside the heartbeat
  window; [Heartbeat](https://docs.superdurable.io/reference/python/step-options.md#heartbeat) gives the
  arithmetic. Use an interval of a few seconds when a user is watching, and
  tens of seconds for long jobs such as builds.
- <a id="limits"></a>Use one maximum-wait value for both `ExecuteMethodTimeout`
  and `TotalDuration`. Dex enforces both, so the Step computes no deadline of
  its own. After a failure, `TotalDuration` decides only whether to schedule
  another attempt. Queueing can start a scheduled attempt late, and a running
  attempt is never cut short, so the whole wait can end well after it. A
  business deadline for the Flow uses the watchdog below. Give `ExecuteRetry` a few attempts with backoff for transient errors
  and Worker crashes. See
  [Timeouts and total duration](https://docs.superdurable.io/reference/python/step-options.md#timeouts-and-total-duration).
  The polling Step can use either durability.
- <a id="when-the-wait-expires"></a>When the wait expires, the Step fails. Route
  that failure with the `ExecuteFailure` option to a short Step that records
  the business failure; see
  [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md).
  The failure record omits the last status; read it from the Stream or the logs.
- Check any other business condition inside the loop, such as a lease that
  another system owns and that can expire. The timeouts bound only a fixed
  duration.
- <a id="deadline-watchdog"></a>Use a watchdog for a business deadline that is
  shorter than the whole wait, or that the Step options cannot hold because the
  polling Step re-enters itself to commit each status change. The watchdog is a
  waiting Step that races its Timer. It declares the same Attribute lock as the
  Step that records the result. When its Timer fires, it reads the status under
  that lock and declares the work overdue only while the work is still
  unfinished.
- <a id="checkpoint-and-progress"></a>Resume from the last checkpoint, which
  `GetLastHeartbeatValue` returns. In the example, the checkpoint is the last
  reported job status. Resuming from the last stored checkpoint reduces
  repeated progress messages after a retry. A checkpoint can be lost, so
  consumers must tolerate duplicate and missing messages; see
  [Heartbeat](https://docs.superdurable.io/reference/python/step-options.md#heartbeat).
- Write a Stream message only when the observed status changes, and record a
  heartbeat otherwise. Stream messages are best effort, so consumers recover
  from durable state, such as Attributes, a read RPC, or the Flow result.
- <a id="locks"></a>Return the result from the polling Step, and commit
  anything that needs a lock in a short following Step. A polling Step that
  held the lock for the whole wait would make every Step that needs it, such
  as a watchdog, wait until the loop ends, and every RPC that needs it fail.

## Example

`PollingFlow` waits for a simulated external job. `StartJob` starts the job with the Flow ID as an idempotent job ID. `AwaitJob` polls the job status every two seconds. It writes a `JobProgress` Stream message when the status changes and completes with the job result. Each attempt lasts at most ten minutes. After a failure, the ten-minute retry budget decides whether another attempt starts. When Dex starts no further attempt, `AwaitJob` moves to `RecordJobWaitFailure`. That Step fails the Flow with the recovery error.

The simulated job reports QUEUED, then RUNNING, and succeeds six seconds after it starts. Call the complete-job endpoint to finish it early.

**Python**

```python
# Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= heartbeat_timeout - 10s.
# MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
POLL_INTERVAL = timedelta(seconds=2)
JOB_CALL_TIMEOUT = timedelta(seconds=10)
MAX_JOB_WAIT = timedelta(minutes=10)

JOB_PROGRESS = Stream("JobProgress", JobStatus, 1 << 20)


class RecordJobWaitFailure(Step[str]):
    def execute(self, context: Context, job_id: str) -> StepDecision:
        failure = context.recovery_error
        assert failure is not None
        return force_fail(
            f"waiting for job {job_id} failed: {failure.error_type}: {failure.detail}"
        )


class AwaitJob(Step[str]):
    def __init__(self, jobs: FakeJobService) -> None:
        self.jobs = jobs

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_method_timeout=MAX_JOB_WAIT,
            heartbeat_timeout=timedelta(minutes=1),
            execute_retry=RetryPolicy(
                initial_interval=timedelta(seconds=1),
                backoff_coefficient=2.0,
                maximum_attempts=3,
                total_duration=MAX_JOB_WAIT,
            ),
        ).on_execute_failure_proceed_to(RecordJobWaitFailure)

    async def execute(self, context: AsyncContext, job_id: str) -> StepDecision:
        reported_state = context.get_last_heartbeat_value(JobState)
        while True:
            status = await self.get_job_status(job_id)
            if status.state is JobState.SUCCEEDED:
                return graceful_complete(status.result)
            if status.state is JobState.FAILED:
                return force_fail(f"job {job_id} failed")
            if status.state != reported_state:
                JOB_PROGRESS.write(context, status)
                reported_state = status.state
            else:
                await context.heartbeat(reported_state)
            await asyncio.sleep(POLL_INTERVAL.total_seconds())

    async def get_job_status(self, job_id: str) -> JobStatus:
        return await asyncio.wait_for(
            self.jobs.get_job_status(job_id), JOB_CALL_TIMEOUT.total_seconds()
        )
```

Example: [examples/python/dex_examples/patterns/polling/polling_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling/polling_flow.py)

<a id="compare"></a>

## Compare the polling patterns

The long-running Step with heartbeat is lighter. One Step execution holds the whole wait.

[Polling with WaitFor Timer](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.md) records every round in the Flow's history. You see each round clearly, and you can Time Travel back to a round. It is somewhat heavier.

| Behavior            | WaitFor Timer                                                                                                           | Long-running Step heartbeat                      |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| Each round          | A new Step execution in the Flow's history                                                                              | A heartbeat or Stream message inside one attempt |
| Between rounds      | No Worker task slot is held                                                                                             | The attempt holds a Worker task slot             |
| Dex Server failover | A Timer wait continues and uses no retry; a `WaitFor` or `Execute` attempt a Worker had received fails and uses a retry | The running attempt fails and uses a retry       |
| Interval            | Whole seconds                                                                                                           | Any interval                                     |

[Lease](https://docs.superdurable.io/reference/server/high-availability.md#lease) gives the exact failover rules, including the ASYNC exception.

Choose this pattern for short intervals or the lightest loop. Choose the Timer pattern for long intervals, to see each round, or to Time Travel to a round. Time Travel reaches a round only inside the run's recent history window; see [Recover a Flow with Time Travel](https://docs.superdurable.io/components/operate-and-debug.md#time-travel).

## Next

- [External Interaction](https://docs.superdurable.io/design-patterns/external-interaction.md)
- [Polling with WaitFor Timer](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.md)
- [Step options](https://docs.superdurable.io/reference/python/step-options.md#timeouts-and-total-duration)
- [Stream](https://docs.superdurable.io/concepts/primitives/stream.md)
- [Failure Handling](https://docs.superdurable.io/design-patterns/failure-handling.md)
- [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md)
