Polling with WaitFor Timer
View as MarkdownPolling 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:
WaitForreturns a Timer for the polling interval.- When the Timer fires,
Executecalls the external API once, with its own short timeout. - On a transient error,
Executereturns the error. The retry policy runs the round again. - On a terminal status,
Executereturns the next decision: success or a business failure. - While the work is not finished,
ExecutereturnsGoToto 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
GoToto the same Step when the work is not ready. EachGoTostarts 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 fromWaitFor. In this pattern,WaitForonly declares the Timer. - Give
ExecuteRetrya few attempts with backoff for transient errors. Route exhausted retries with theExecuteFailureoption 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
SkipTimerinstead 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.
# 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
// maxPollRounds bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
const (
pollInterval = 10 * time.Second
PollIntervalTimerID = "poll-interval"
maxPollRounds = 60
jobCallTimeout = 10 * time.Second
)
type JobPollRound struct {
JobID string `json:"jobId"`
RoundNumber int `json:"roundNumber"`
}
type CheckJobStatus struct {
dex.StepDefaults
jobs *polling.FakeJobService
}
func (CheckJobStatus) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{
ExecuteRetry: &dex.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2,
MaximumAttempts: 3,
},
ExecuteFailure: dex.ProceedToOnExecuteFailure(RecordJobWaitFailure{}, nil),
}
}
func (CheckJobStatus) WaitFor(ctx dex.Context, _ JobPollRound) (*dex.Wait, error) {
Example: examples/go/patterns/polling-with-timer/workflow.go
// MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
private static final Duration POLL_INTERVAL = Duration.ofSeconds(10);
public static final String POLL_INTERVAL_TIMER_ID = "poll-interval";
private static final int MAX_POLL_ROUNDS = 60;
private static final Duration JOB_CALL_TIMEOUT = Duration.ofSeconds(10);
final class CheckJobStatus implements Step<JobPollRound> {
@Override
public Class<JobPollRound> getInputType() {
return JobPollRound.class;
}
@Override
public StepOptions getStepOptions() {
return StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.backoffCoefficient(2.0)
.maximumAttempts(3)
.build())
.onExecuteFailureProceedTo(RecordJobWaitFailure.class)
.build();
}
@Override
public Wait waitFor(final Context context, final JobPollRound pollRound) {
return Wait.until(Timer.byDuration(POLL_INTERVAL, POLL_INTERVAL_TIMER_ID));
}
@Override
public StepDecision execute(final Context context, final JobPollRound pollRound) {
final JobStatus status = jobs.getJobStatus(pollRound.jobId(), JOB_CALL_TIMEOUT);
if (status.state() == JobState.SUCCEEDED) {
return StepDecision.gracefulComplete(status.result());
}
if (status.state() == JobState.FAILED) {
return StepDecision.forceFail("job " + pollRound.jobId() + " failed");
}
if (pollRound.roundNumber() >= MAX_POLL_ROUNDS) {
return StepDecision.forceFail("job " + pollRound.jobId()
+ " did not finish in " + MAX_POLL_ROUNDS + " rounds");
}
final JobPollRound nextRound =
new JobPollRound(pollRound.jobId(), pollRound.roundNumber() + 1);
return StepDecision.goTo(CheckJobStatus.class, nextRound);
}
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/pollingwithtimer/PollingWithTimerFlow.java
// MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
const POLL_INTERVAL_MS = 10_000;
export const POLL_INTERVAL_TIMER_ID = "poll-interval";
const MAX_POLL_ROUNDS = 60;
const JOB_CALL_TIMEOUT_MS = 10_000;
class CheckJobStatus implements Step<JobPollRound> {
public readonly inputCodec = jobPollRoundCodec;
public constructor(private readonly jobs: FakeJobService) {}
public getStepType(): string {
return "CheckJobStatus";
}
public getStepOptions(): StepOptions {
return {
executeRetry: {
initialIntervalMs: 1_000,
backoffCoefficient: 2,
maximumAttempts: 3,
},
executeFailure: ExecuteFailure.proceedTo(RecordJobWaitFailure),
};
}
public waitFor(_context: Context, _pollRound: JobPollRound): Wait {
return Wait.until(Timer.byDuration(POLL_INTERVAL_MS, POLL_INTERVAL_TIMER_ID));
}
public async execute(context: AsyncContext, pollRound: JobPollRound): Promise<StepDecision> {
const status = await this.jobs.getJobStatus(
pollRound.jobId,
AbortSignal.any([context.cancellationSignal, AbortSignal.timeout(JOB_CALL_TIMEOUT_MS)]),
);
switch (status.state) {
case "SUCCEEDED":
return gracefulComplete(status.result);
case "FAILED":
return forceFail(`job ${pollRound.jobId} failed`);
}
if (pollRound.roundNumber >= MAX_POLL_ROUNDS) {
return forceFail(`job ${pollRound.jobId} did not finish in ${MAX_POLL_ROUNDS} rounds`);
}
const nextRound = { jobId: pollRound.jobId, roundNumber: pollRound.roundNumber + 1 };
return goTo(CheckJobStatus, nextRound);
}
}
Example: examples/typescript/src/patterns/polling-with-timer/polling-with-timer-flow.ts
// MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
const POLL_INTERVAL: Duration = Duration::from_secs(10);
pub const POLL_INTERVAL_TIMER_ID: &str = "poll-interval";
const MAX_POLL_ROUNDS: u32 = 60;
const JOB_CALL_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JobPollRound {
pub job_id: String,
pub round_number: u32,
}
impl Step for CheckJobStatus {
type Input = JobPollRound;
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new()
.execute_retry(
RetryPolicy::new()
.initial_interval(Duration::from_secs(1))
.backoff_coefficient(2.0)
.maximum_attempts(3),
)
.on_execute_failure_proceed_to(&RecordJobWaitFailure)
}
fn wait_for(&self, _context: &mut Context, _poll_round: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::until(
Timer::by_duration(POLL_INTERVAL).with_id(POLL_INTERVAL_TIMER_ID),
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.
| 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 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.