Skip to Content
Runlane
Build with RunlaneBuild tasks

Retry failed work

Retry temporary failures with a bounded retry budget and backoff.

Use automatic retries for transient failures where running the same task again is safe. Use a release instead when the task is waiting for an expected business condition. In tests, use createTestLane({ clock: () => clock.now() }) with a controlled runtime clock, advance time, and execute due retries. In a local app, createLocalLane() needs runlane dev; a missing dev session fails the trigger before any task retry policy applies.

Set the retry policy on the task

Put retry policy on the task definition, for example in src/tasks/sync-account.ts:

src/tasks/sync-account.ts
import { ErrorCode, RetryBackoffType, RunlaneError, task } from '@runlane/core'
import * as z from 'zod'

const env = z.object({ ACCOUNTS_API_URL: z.url() }).parse(process.env)

export const syncAccount = task({
  id: 'account.sync',
  schema: z.object({ accountId: z.string() }),
  retry: {
    maxRetries: 3,
    backoff: {
      type: RetryBackoffType.Exponential,
      delay: '30s',
      maxDelay: '5m',
    },
  },
  async run({ accountId }, context) {
    const response = await fetch(new URL(`/accounts/${encodeURIComponent(accountId)}/sync`, env.ACCOUNTS_API_URL), {
      method: 'POST',
      signal: context.signal,
    })
    if (response.status === 404) {
      throw new RunlaneError({
        code: ErrorCode.TaskFailed,
        message: 'The account no longer exists.',
        retryable: false,
      })
    }
    if (!response.ok) throw new Error(`Accounts API returned ${response.status}`)
  },
})

maxRetries counts automatic retries after failures, not the initial attempt. This task allows three retries. Releases, waits, and expired-lease recovery do not spend or reset the allowance, or increase backoff. See Stop crash loops for the separate interruption allowance. Attempt timeouts count as failures.

If you omit retry, a failed task does not retry automatically. When you set retry, you must supply maxRetries; 0 also disables automatic retries. See the task reference for backoff options, defaults, and migration from maxAttempts.

New runs save this policy at acceptance. Editing the task later does not change those runs. Before deploying, follow the stored-policy upgrade requirements. Runs without a snapshot fail to decode.

With a retry policy, an ordinary thrown error becomes a retryable task failure. If retries remain, Runlane stores the run as retrying with its next due time. The fourth failure in this example exhausts the budget and stores a terminal failed run, even if releases occurred between failures.

Keep the handler safe to repeat. An external effect can succeed before Runlane stores the attempt result. See make side effects safe to repeat.

Use provider idempotency or a durable step around work that must not be submitted twice.

Stop crash loops

Runlane limits how often an attempt can stop without saving progress. An attempt earns a checkpoint when it saves a step result, binds a named child, or saves the result of a keyed wait during that attempt. A wait that resumes between attempts does not count as progress for the next attempt. Replaying saved work, updating metadata or tags, writing logs, and streaming output do not count either.

maxInterruptions accepts a non-negative safe integer or 'unlimited'. Set it on task() or createRunlane(): the task value wins, then the runtime value, then contractDefaults.run.maxInterruptions. Accepted runs keep that resolved value. Set 0 to fail on the first counted interruption. 'unlimited' disables the interruption budget. It cannot be overridden per trigger or execution.

  • A platform time limit or an expired started lease adds one to counters.interruptions if the attempt saved no new checkpoint. If it saved one, Runlane resets the count to zero.
  • If a transport deadline stops acquisition before Runlane stages the lease, the provider retries the delivery. No attempt starts and the interruption count stays the same.
  • A polling drain skips that increment if a run has less than the full budget at claim time. This can happen after another run in the same concurrency slot, even if that run lost its lease, after the slot waited for a scheduled fire, or when the claim crosses the handoff time. Time spent in observers after the claim does not change this decision. The run keeps its queue position so a later invocation can give it the full budget. Pass context.signal to long calls. If the host kills the attempt, lease recovery uses the expired-lease rule even after a late start.
  • A graceful shutdown, deploy, caller abort, or lost transport receipt leaves the count unchanged. Normal outcomes reset it, including an invocation handoff.

The run fails when the count exceeds its saved allowance. The failure uses task_interrupted and retryable: false. It includes the cause, count, and limit in failure.meta. Split the work into durable steps, use a long-running worker, or choose maxInterruptions: 'unlimited'. This protection is separate from failure retries and does not spend maxRetries.

Fix the cause, then create a fresh run with the current task settings:

pnpm exec runlane rerun <run-id>

The new run starts with zero counters. The failed run remains available for inspection.

Stop retrying a permanent failure

Use RunlaneError with retryable: false when another attempt cannot help. In the example, a missing account ends the run as failed even if retries remain. Other HTTP failures use an ordinary Error, so the task's retry policy applies.

Both ordinary errors and RunlaneError keep their real name, message, and bounded stack in storage. Use RunlaneError to control the error code and retry decision. This example saves "The account no longer exists." with its code and retryable flag. Keep secrets out of every thrown message and meta. Users with realtime Output permission can read failure messages, but never stacks. See stored failure messages for message limits and handling of other thrown values.

Choose which responses are permanent based on the API you call. A validation error, revoked access, or deleted record may need an application change before the work can succeed.

Catch public API errors with error instanceof RunlaneError, then inspect error.code and error.retryable. Use the error reference for the full constructor, stored failure fields, and error codes.

Make sure due retries can run

Polling workers can acquire due retrying runs from storage. Transport-delivery deployments also need maintenance to append and publish a fresh delivery request when a retry becomes due. Keep that code in the deployment's maintenance entry point; do not put it in the task module.

To verify the policy, make the dependency fail in a controlled test, execute one attempt, and inspect runlane.runs.attempts(runId). The run should be retrying before the budget is exhausted and failed afterward.

If a run fails without retrying, check:

  • the run's saved executionPolicy.retry.maxRetries is greater than run.counters.retries;
  • the error is retryable;
  • a structured error was not marked non-retryable.

If a retry is past due, inspect workers, maintenance, and delivery. Raising the retry count will not move stuck work.

Use wait without failing when the provider is healthy but has not finished the requested work.

Inspect failed attempts

runlane dev and runlane work print one line per attempt event, followed by the error and stack on failure. Retry lines show the delay. Maintenance lines show only nonzero counters when work happened. NO_COLOR and redirected output disable styling; --json prints complete structured events.

Use runlane runs get <run-id> --events for the latest failure and stack plus attempt history. runlane runs timeline <run-id> shows each attempt's failure message. runlane runs logs <run-id> shows timestamped application logs and attributes. Add --json to read complete stored fields.

On this page