Skip to main content

Polling with Long-Running Step Heartbeat

View as Markdown

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 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.

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.

Rules

  • Keep each round inside the heartbeat window; 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.
  • 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. The polling Step can use either durability.
  • 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. 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.
  • 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.
  • 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.
  • 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.
  • 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.

polling_flow.pyPython
# 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,

Example: examples/python/dex_examples/patterns/polling/polling_flow.py

Compare the polling patterns

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

Polling with WaitFor Timer 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.

BehaviorWaitFor TimerLong-running Step heartbeat
Each roundA new Step execution in the Flow's historyA heartbeat or Stream message inside one attempt
Between roundsNo Worker task slot is heldThe attempt holds a Worker task slot
Dex Server failoverA Timer wait continues and uses no retry; a WaitFor or Execute attempt a Worker had received fails and uses a retryThe running attempt fails and uses a retry
IntervalWhole secondsAny interval

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.

Next