Polling with Long-Running Step Heartbeat
View as MarkdownPolling 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:
- Call the external API with its own short timeout, such as 10 seconds.
- On a transient error, return the error. The retry policy runs the Step again.
- On a terminal status, return the next decision: success or a business failure.
- Report progress. Write a Stream message when the status changes. Otherwise record a heartbeat with the checkpoint.
- 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
ExecuteMethodTimeoutandTotalDuration. Dex enforces both, so the Step computes no deadline of its own. After a failure,TotalDurationdecides 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. GiveExecuteRetrya 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
ExecuteFailureoption 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
GetLastHeartbeatValuereturns. 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.
# 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
// Keep pollInterval + jobCallTimeout <= HeartbeatTimeout - 10s.
// maxJobWait bounds each attempt and whether another attempt starts; Dex enforces it.
const (
pollInterval = 2 * time.Second
jobCallTimeout = 10 * time.Second
maxJobWait = 10 * time.Minute
)
var JobProgress = dex.DefineStream[JobStatus]("JobProgress", 1<<20)
type AwaitJob struct {
dex.StepDefaultsNoWaitFor[string]
jobs *FakeJobService
}
func (AwaitJob) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{
ExecuteMethodTimeout: maxJobWait,
HeartbeatTimeout: time.Minute,
ExecuteRetry: &dex.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2,
MaximumAttempts: 3,
TotalDuration: maxJobWait,
},
ExecuteFailure: dex.ProceedToOnExecuteFailure(RecordJobWaitFailure{}, nil),
}
}
func (step AwaitJob) Execute(ctx dex.Context, jobID string) (*dex.StepDecision, error) {
// Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= HeartbeatTimeout - 10s.
// MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
private static final Duration POLL_INTERVAL = Duration.ofSeconds(2);
private static final Duration JOB_CALL_TIMEOUT = Duration.ofSeconds(10);
private static final Duration MAX_JOB_WAIT = Duration.ofMinutes(10);
public static final Stream<JobStatus> jobProgress =
Stream.define("JobProgress", JobStatus.class, 1L << 20);
final class AwaitJob implements Step<String> {
@Override
public Class<String> getInputType() {
return String.class;
}
@Override
public StepOptions getStepOptions() {
return StepOptions.newBuilder()
.executeMethodTimeout(MAX_JOB_WAIT)
.heartbeatTimeout(Duration.ofMinutes(1))
.executeRetry(RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.backoffCoefficient(2.0)
.maximumAttempts(3)
.totalDuration(MAX_JOB_WAIT)
.build())
.onExecuteFailureProceedTo(RecordJobWaitFailure.class)
.build();
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/polling/PollingFlow.java
// Keep POLL_INTERVAL_MS + JOB_CALL_TIMEOUT_MS <= heartbeatTimeoutMs - 10s.
// MAX_JOB_WAIT_MS bounds each attempt and whether another attempt starts; Dex enforces it.
const POLL_INTERVAL_MS = 2_000;
const JOB_CALL_TIMEOUT_MS = 10_000;
const MAX_JOB_WAIT_MS = 10 * 60_000;
export const jobProgress = new Stream("JobProgress", jsonCodec<JobStatus>(), 1 << 20);
class RecordJobWaitFailure implements Step<string> {
public readonly inputCodec = stringCodec;
public getStepType(): string {
return "RecordJobWaitFailure";
}
public execute(context: Context, jobId: string): StepDecision {
const failure = context.recoveryError!;
return forceFail(`waiting for job ${jobId} failed: ${failure.errorType}: ${failure.detail}`);
}
}
class AwaitJob implements Step<string> {
public readonly inputCodec = stringCodec;
public constructor(private readonly jobs: FakeJobService) {}
public getStepType(): string {
return "AwaitJob";
}
Example: examples/typescript/src/patterns/polling/polling-flow.ts
// Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= heartbeat_timeout - 10s.
// MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
const POLL_INTERVAL: Duration = Duration::from_secs(2);
const JOB_CALL_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_JOB_WAIT: Duration = Duration::from_secs(10 * 60);
pub static JOB_PROGRESS: LazyLock<Stream<JobStatus>> =
LazyLock::new(|| Stream::new("JobProgress", 1 << 20));
struct AwaitJob {
jobs: Arc<FakeJobService>,
}
impl Step for AwaitJob {
type Input = String;
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new()
.execute_method_timeout(MAX_JOB_WAIT)
.heartbeat_timeout(Duration::from_secs(60))
.execute_retry(
RetryPolicy::new()
.initial_interval(Duration::from_secs(1))
.backoff_coefficient(2.0)
.maximum_attempts(3)
.total_duration(MAX_JOB_WAIT),
)
.on_execute_failure_proceed_to(&RecordJobWaitFailure)
}
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.
| 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 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.