Wait without failing
Pause for time or an external event without recording a failure.
Await a wait when the task needs time or an external result. This pauses the task without recording a failure or spending retry budget. On resume, the handler starts from the top and reuses completed keyed waits.
Pause once at a stable key
Use context.step.sleep() between workflow stages:
await context.step.run('send-welcome', { output: z.string() }, sendWelcome)
await context.step.sleep('welcome-delay', '1d')
await context.step.run('send-reminder', { output: z.string() }, sendReminder)Here sendWelcome and sendReminder are application callbacks that return message IDs. The stable keys save each completed stage. The delay gets a checkpoint when the run resumes, so replay continues after it.
Every context.step.* call shares one counter per key per attempt. The first use keeps the plain key; later uses become key#2, key#3, and so on. This applies to callback results, child bindings, batch items in item order, sleeps, and signals. Handler-written keys cannot contain : or #.
- Runlane tells repeated keys apart by the order the handler reaches them. Keep that order the same on every attempt.
- Load a list inside
step.runif it comes from an API or a database. Lists from the payload are already stable. - If a check decides which steps run and its answer can change between attempts, save the check with
step.run, or put the item id in the key (pause-${stage}).
See save step results for callback results and manual retries.
Wait until a date
Use context.wait.until() for an absolute time from the payload or a saved application record:
await context.wait.until(new Date(payload.sendAt), { reason: 'scheduled_send' })Pass a valid Date. This call needs no key or saved step. On replay, dates that have passed resolve at once, including when the worker clock is behind storage time. A loop can await several dates without assigning keys.
Poll again after a delay
Put the timed wait in the task handler. This example belongs in src/tasks/collect-report.ts:
import { task } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ REPORTS_API_URL: z.url() }).parse(process.env)
const reportSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('processing') }),
z.object({ downloadUrl: z.url(), status: z.literal('ready') }),
])
export const collectReport = task({
id: 'report.collect',
output: z.object({ downloadUrl: z.url() }),
schema: z.object({ reportId: z.string() }),
async run({ reportId }, context) {
const response = await fetch(new URL(`/reports/${encodeURIComponent(reportId)}`, env.REPORTS_API_URL), {
signal: context.signal,
})
if (!response.ok) throw new Error(`Reports API returned ${response.status}`)
const report = reportSchema.parse(await response.json())
if (report.status === 'ready') return { downloadUrl: report.downloadUrl }
return context.release('30s', { reason: 'provider_still_processing' })
},
})Write return context.release(...) when a handler with an output schema ends by pausing. TypeScript does not treat an awaited Promise<never> as the end of a function.
The next attempt starts this handler from the beginning. Keep maintenance running so transport-backed lanes publish a new wakeup when the delay is due.
Wait for a signal
A signal wakes runs that are already waiting on the same key. It does not store the approval itself. This example assumes your application has an approval API that stores the decision and returns { approved: boolean } from its read endpoint.
Save each decision check in a step, then wait only while it is pending. On replay, the handler follows the same checks and waits before it asks the API for a new decision:
import { task } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ APPROVAL_API_URL: z.url() }).parse(process.env)
const approvalSchema = z.object({ approved: z.boolean() })
export const waitForApproval = task({
id: 'approval.wait',
schema: z.object({ accountId: z.string() }),
async run({ accountId }, context) {
async function readApproval() {
const response = await fetch(
new URL(`/accounts/${encodeURIComponent(accountId)}/approval`, env.APPROVAL_API_URL),
{
signal: context.signal,
},
)
if (!response.ok) throw new Error(`Approval API returned ${response.status}`)
return approvalSchema.parse(await response.json())
}
while (!(await context.step.run('read-approval', { output: approvalSchema }, readApproval)).approved) {
await context.step.waitForSignal('approval', `approval.${accountId}`, {
reason: 'approval_required',
timeout: '1h',
})
}
},
})Each pass saves a decision check, waits for the signal, and checks again. The timeout makes the task check once an hour in case a signal was missed. The loop reuses one key. Runlane numbers every use (approval, then approval#2), so every pass waits once, and replay skips the passes that already finished.
Each pass saves a decision step and a wait step. For frequent, open-ended polling, read the current state outside a saved step and use context.release() to start the next check. A release saves no wait checkpoint.
Save the approval before sending its signal. Call this service from an authenticated route that checks the caller's access to the account. The approval API must make repeated writes safe:
import { type RunlaneRuntime } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ APPROVAL_API_URL: z.url() }).parse(process.env)
export async function approveAccount(runlane: RunlaneRuntime, accountId: string) {
const response = await fetch(new URL(`/accounts/${encodeURIComponent(accountId)}/approval`, env.APPROVAL_API_URL), {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ approved: true }),
})
if (!response.ok) throw new Error(`Approval API returned ${response.status}`)
return runlane.signals.send(`approval.${accountId}`)
}The resumed handler starts at the top, replays completed checks and waits, then reads the current approval. The keyed signal wait replays { ok: true } for a signal or { ok: false, error } for a timeout. This loop rechecks approval after either result. Use .unwrap() when a timeout should fail the task. Read the application state again after the wait; a wakeup alone does not prove approval. If approval remains pending, the loop waits again.
A signal sent before the waiter exists is not saved for later. A signal can also arrive between the approval read and the wait being stored. The one-hour timeout makes the run check again if it misses that signal. This timeout is a next-check time, not an approval deadline. Workers and maintenance must be running to make that check happen.
The send result contains only runs that this call successfully resumed. For a human decision with a durable result and a fixed deadline, use a wait token.
Use limit to bound a high-fanout send. Call it again when more matching waiters may remain.
Wait for another run
Use const result = await context.join(childRunId) to follow an existing run. It resolves to { ok: true, output, run } or { ok: false, error, run }. Check result.ok before reading output. Use .unwrap() to fail the parent when the joined run does not succeed. Named child references and known run IDs use the same completion recovery. See trigger child tasks.
Wait for a stored result
Use a wait token when the external event must carry one durable result, such as an approval. Tokens remain readable before and after a run resumes.
| Need | Use |
|---|---|
| Retry a failure | Task retry policy |
| Pause once in a workflow | step.sleep() |
| Poll again later | release() |
| Wait until a calendar time | wait.until() |
| Wake current matching waiters | Signal |
| Store one external decision | Wait token |
| Follow one known run | join() |
Verify the wait
- Execute the first attempt.
- Confirm the run is
releasedwith the expected wait condition. - Advance a controlled clock, send the signal, complete the token, or finish the child.
- Run maintenance when the lane requires it.
- Execute the next attempt and check the final state.
If a run does not resume, check the key or due time, maintenance, environment, queue, and delivery path. Do not throw an error to wake it sooner; that changes failure history and retry accounting.
Code before the release can run again. Save repeat-sensitive work as a durable step.
Await waits directly and use their timeout option instead of Promise.race. Follow the wait safety rules when managing resources or combining waits with other work.