PlatformoctaflowCore

View as Markdown

Retry & timeout

Attempt budgets, backoff, wall-clock timeouts — and how a failure is classified as transient.

const flaky = defineStep({
  type: 'call-api', workflowInputSchema, outputSchema,
  retry: { maxAttempts: 4, backoff: 'exponential', initialDelayMs: 500, maxDelayMs: 30_000 },
  timeoutMs: 10_000, // aborts + retries on expiry
  handler: async (ctx) => { /* throw a retryable error to retry within budget */ },
});

A failure is retried (with backoff via the dispatcher’s startAfterSeconds) up to maxAttempts; after that the step fails terminally. → examples/03-retry-timeout.ts

Field Default Meaning
maxAttempts 1 Total attempts including the first
backoff 'fixed' 'fixed' or 'exponential' (initialDelayMs × 2^(n-1))
initialDelayMs 1000 Delay before the 2nd attempt
maxDelayMs 60000 Cap on the computed delay

Backoff is delivered as the dispatcher’s startAfterSeconds, so it is rounded up to whole seconds — an initialDelayMs under 1000 still waits a second, and a dispatcher that ignores the option retries immediately.

timeoutMs is a wall-clock bound on one attempt. On expiry the engine fires ctx.signal and produces a retryable failure, so the step retries within its budget; a handler that ignores the signal keeps running in the background, so pass ctx.signal to anything that accepts one.

Which failures count as retryable is decided in this order:

  1. An explicit marker on the error — always wins.
    import { retryableError, nonRetryableError, markRetryable } from 'octaflow';
    
    throw retryableError('encoder busy');              // retry, whatever the message says
    throw nonRetryableError('timeout must be > 0');    // never retry — a bug, not a blip
    throw markRetryable(await client.readError(), true); // tag an error you didn't construct
    A marker is found through cause, so wrapping doesn’t lose it: new Error('upstream failed', { cause: retryableError('busy') }) still retries.
  2. The step’s own predicate, for classifying a whole family of errors at once:
    isRetryable: (e) => e instanceof HttpError && e.status >= 500,
    (defineMapStep takes itemIsRetryable for its per-item children.)
  3. isRetryableError — the zero-config default. It reads structured fields first: code (ECONNRESET, ECONNREFUSED, ETIMEDOUT, EAI_AGAIN, …) and HTTP status from status / statusCode / response.status (408, 425, 429 and 5xx except 501/505). Only then does it fall back to matching the message against a small vocabulary (rate limit, timeout, fetch failed, service unavailable, …).

That last fallback is a convenience, not a classifier — it can only judge wording. A genuine bug reading 'timeout must be > 0' looks transient to it. When the answer matters, mark the error rather than phrasing it to suit the heuristic.

To stop guessing entirely, give the engine a defaultRetryable:

createWorkflowEngine({ …, config: { defaultRetryable: false } }); // strict: never guess

It replaces the classifier’s answer only where the classifier guessed. Explicitly marked errors, steps with their own isRetryable, and engine-generated failures like a step timeout are unaffected.

Carrying on without the step: onFailure

By default a step whose budget is spent fails terminally: its dependents are skipped and the workflow fails. That is the right outcome when every step is load-bearing. It is the wrong one for a pipeline whose result is a report — fetch, analyse, cross-check, summarise — where one analysis that could not run should cost a section of the report, not the report.

onFailure: { output } gives such a step a stand-in: once its attempt budget is spent, the step completes with that output instead of failing, and the DAG carries on as if it had succeeded.

const comments = defineStep({
  type: 'analyse-comments', workflowInputSchema, dependencies: { fetch },
  outputSchema: z.object({ comments: z.array(commentSchema), analysed: z.boolean() }),
  retry: { maxAttempts: 2 },
  onFailure: { output: { comments: [], analysed: false } },
  handler: async (ctx) => { /* may throw — the provider is down, the model refused */ },
});

What the stand-in changes, and what it does not:

  • Dependents run and read the stand-in from ctx.deps.comments, so give it a shape they can act on (analysed: false, an empty list) rather than a value that looks like a real result. The stand-in is checked against outputSchema when the step is defined, and kept as the schema parses it (defaults applied), so a mismatch is a thrown error at module load, not a broken run later.
  • The failure is kept. The step’s error holds the message, on a step whose status is completed — that combination is exactly “this is a stand-in”, on the record and in toPublicWorkflow. The observer gets step.defaulted in place of step.completed, with the error, the attempt and the duration; no step.failed is emitted. A real completion always clears error.
  • The budget is spent first. Retries happen exactly as without the policy; the stand-in only replaces the terminal failure. The same goes for the other ways a step can end without running: the stuck-step sweeper failing a crashed step past its budget, the DLQ worker’s handleStepExhausted, a sub-workflow that failed or was cancelled (onFailure on defineSubWorkflowStep), and a map item (itemOnFailure, whose stand-in takes that item’s slot while the map goes on).
  • Not compensated. If the run later fails, saga compensation skips a step that completed with its stand-in: it did no work, so there is nothing to undo. onAfterStep does not run for it either.
  • Not retried by retryWorkflow. A run whose failures were all absorbed completes, so there is nothing to retry; if it failed for another reason, the retry leaves stand-in steps as they are and re-runs only what failed.

A wait step is settled by onTimeout, not onFailure — a wait has no attempts to spend.

The other retry layer

The step’s retry policy is not the only thing that re-runs work. With pg-boss there are two independent mechanisms, and they trigger on different things:

Step retry (RetryPolicy) Queue retry (StepQueueConfig)
Owned by the engine pg-boss
Fires when the handler fails and the failure is retryable executeStep throws out of the worker
Budget maxAttempts, default 1 retryLimit, default 2
Delay backoff / initialDelayMs retryDelay, default 30 s
Exhaustion step marked failed, workflow cascades job → dead-letter queue → your DLQ worker calls handleStepExhausted

A handler that throws is caught by defineStep and turned into a step failure, so it goes down the first column — the queue never sees it. The second column is for failures around the handler: the store is unreachable, the process is killed, the worker itself throws. That’s why production wiring needs a DLQ worker: without one, a job that exhausts its queue retries leaves its step stuck in running until the stuck-step sweeper picks it up.

Being deferred by the step gate is neither: a throttled step is re-enqueued without consuming an attempt from either budget.

From octaflow@0.44.0 in the platform repository, MIT-licensed.npm