Skip to main content

Polling with WaitFor Timer

View as Markdown

Polling with a WaitFor Timer checks an external system once per round, and each round is a new Step execution. Use it when a Flow waits for a cloud build, a provisioning job, or a third-party status, and you want to see every round in the Flow's history.

The polling Step waits for a Timer in WaitFor. Its Execute calls the external system once. While the work is not finished, the Step moves to itself for the next round.

Shape

Each round of the polling Step runs these steps:

  1. WaitFor returns a Timer for the polling interval.
  2. When the Timer fires, Execute calls the external API once, with its own short timeout.
  3. On a transient error, Execute returns the error. The retry policy runs the round again.
  4. On a terminal status, Execute returns the next decision: success or a business failure.
  5. While the work is not finished, Execute returns GoTo to the same Step with the next round's input.

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

Rules

  • Return GoTo to the same Step when the work is not ready. Each GoTo starts a new Step execution, which waits for a new Timer.
  • Bound the loop. Carry a round number in the Step input and stop at a maximum. The round limit bounds the number of checks. It does not bound the elapsed time: each round also spends time on the external call, retries, and queueing. For a hard deadline, use the Flow timeout or a deadline watchdog.
  • Keep the Step input small and fixed in size, such as the job ID and the round number. Keep accumulated state, such as collected results, in Attributes, never in a growing Step input.
  • Check the job status in Execute. Never poll the external system from WaitFor. In this pattern, WaitFor only declares the Timer.
  • Give ExecuteRetry a few attempts with backoff for transient errors. Route exhausted retries with the ExecuteFailure option to a short Step that records the failure; see Execute Failure Recovery.
  • Timers count whole seconds. For an interval below a few seconds, use Polling with Long-Running Step Heartbeat.
  • Give the Timer a condition ID. In tests, skip it with SkipTimer instead of shortening the interval; see Skip a Timer.

Example

PollingWithTimerFlow waits for the same simulated job as the heartbeat example. StartJob starts the job with the Flow ID as an idempotent job ID. CheckJobStatus waits for a 10-second Timer, then reads the job status once. While the job runs, it moves to itself with the next round number. It stops after 60 rounds. When its retries run out, it moves to RecordJobWaitFailure, which fails the Flow with the recovery error.

The simulated job succeeds six seconds after it starts, so the first round finds it finished. Call the complete-job endpoint to finish it early.

polling_with_timer_flow.pyPython
# MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
POLL_INTERVAL = timedelta(seconds=10)
POLL_INTERVAL_TIMER_ID = "poll-interval"
MAX_POLL_ROUNDS = 60
JOB_CALL_TIMEOUT = timedelta(seconds=10)


@dataclass(frozen=True)
class JobPollRound:
job_id: str
round_number: int


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

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

def wait_for(self, context: Context, poll_round: JobPollRound) -> Wait:
return Wait.until(
Timer.by_duration(POLL_INTERVAL, condition_id=POLL_INTERVAL_TIMER_ID)
)

async def execute(
self, context: AsyncContext, poll_round: JobPollRound
) -> StepDecision:
status = await asyncio.wait_for(
self.jobs.get_job_status(poll_round.job_id),
JOB_CALL_TIMEOUT.total_seconds(),
)
if status.state is JobState.SUCCEEDED:
return graceful_complete(status.result)
if status.state is JobState.FAILED:
return force_fail(f"job {poll_round.job_id} failed")
if poll_round.round_number >= MAX_POLL_ROUNDS:
return force_fail(
f"job {poll_round.job_id} did not finish in {MAX_POLL_ROUNDS} rounds"
)
next_round = JobPollRound(poll_round.job_id, poll_round.round_number + 1)
return go_to(CheckJobStatus, next_round)

Example: examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py

Compare the polling patterns

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.

Polling with Long-Running Step Heartbeat is lighter. One Step execution holds the whole wait.

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 long intervals, to see each round, or to Time Travel to a round. Choose the heartbeat pattern for short intervals or the lightest loop. Time Travel reaches a round only inside the run's recent history window; see Recover a Flow with Time Travel.

Next