Save step results
Save a completed step so retries can reuse its validated result.
Use a durable step when a task may restart after a retry or release but one completed side effect should not be submitted again.
import { task } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ REPORTS_API_URL: z.url() }).parse(process.env)
const jobSchema = z.object({ jobId: z.string() })
const jobStatusSchema = z.object({ pending: z.boolean() })
export const processReport = task({
id: 'report.process',
output: z.object({ jobId: z.string() }),
schema: z.object({ reportId: z.string() }),
async run({ reportId }, context) {
const submission = await context.step.run('submit-provider-job', { output: jobSchema }, async ({ token }) => {
const response = await fetch(new URL('/jobs', env.REPORTS_API_URL), {
body: JSON.stringify({ reportId }),
headers: { 'content-type': 'application/json', 'idempotency-key': token },
method: 'POST',
signal: context.signal,
})
if (!response.ok) throw new Error(`Reports API returned ${response.status}`)
return jobSchema.parse(await response.json())
})
const response = await fetch(new URL(`/jobs/${encodeURIComponent(submission.jobId)}`, env.REPORTS_API_URL), {
signal: context.signal,
})
if (!response.ok) throw new Error(`Reports API returned ${response.status}`)
const status = jobStatusSchema.parse(await response.json())
if (status.pending) return context.release('30s', { reason: 'provider_job_pending' })
return { jobId: submission.jobId }
},
})Wrap the side effect
Give the step a stable key and validate the output that Runlane will store.
For a callback that returns nothing, omit the options: await context.step.run('send-email', async ({ token }) => { await sendEmail(user, token) }). This overload returns Promise<void>. Runlane saves completion with null in storage and returns undefined on replay without repeating the callback. Steps with an output schema still validate and replay the saved schema output; existing checkpoints keep their format.
In a loop, put the item ID in the key so each saved result follows its item:
for (const user of users) {
await context.step.run(`send-email-${user.id}`, { output: z.string() }, ({ token }) => sendEmail(user, token))
}Here users is your application's user list, and sendEmail returns a message ID and passes token to the provider for idempotency. Use stable, unique IDs that contain neither : nor #; Runlane reserves those characters in step keys.
Repeated keys as a shortcut
When the item order stays the same on every attempt, a loop can reuse 'send-email' instead. Runlane distinguishes those calls by their order, not by item identity.
Every context.step.* call shares one counter for each key in an attempt. This includes run, trigger, triggerAndWait, each triggerBatch or triggerBatchAndWait item in item order, sleep, and waitForSignal. Trigger-and-wait counts a key once. The first call saves under the plain key. Later calls save under key#2, key#3, and so on. Calls are counted as soon as you make them, before any await.
- Keep repeated-key calls in the same order on every attempt.
- Keyless
context.wait.createToken()calls are also counted in call order. Keep their 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}).
A call that fails before saving a result gives its number back if it still holds the highest number for that key. A caught failure followed by a manual retry can then use the same stored key. A saved result keeps its number even if later delivery or observation fails.
On the first success, Runlane validates and transforms the callback output once, stores the schema output, and returns it. A later attempt with the same run and step key returns that saved output without calling the callback or applying the schema again. Other runs have their own checkpoints, even when they use the same step key.
Keep a step key's saved output shape compatible across deployments. Original callback outputs are not retained separately; changing the schema does not transform existing checkpoints. Storage still validates the persisted record format on reads.
The task can now release and poll again without intentionally submitting a second provider job.
Use the step token as the provider's idempotency key when possible. A remote call can succeed before its checkpoint is stored. See make side effects safe to repeat for database and API patterns.
The token lets a repeated submission resolve to the same remote operation. A durable step cannot make a non-idempotent API exactly once.
A callback that throws is not checkpointed. Output that fails the step schema is also not checkpointed and fails the attempt with a structured task-output error. Fix the callback or schema mismatch before retrying.
Test a failure or release after the step. Execute another attempt and confirm the callback ran once while both attempts saw the same output.
Durable steps are part of the storage contract, so every conforming lane keeps these checkpoint rules.
For human review, direct keyless context.wait.createToken() calls already reuse their token by call order. Save only the notification side effect in a step. See build a human-in-the-loop flow.
Save a wait outcome
Use await context.step.sleep('pause', '1m') for a pause that happens once in this run. Use await context.step.waitForSignal('approval', 'account_123', { timeout: '1h' }) to save a signal or timeout outcome. The signal result is { ok: true } or { ok: false, error } with wait_timed_out. .unwrap() returns nothing or throws a non-retryable error. Replay resolves from the saved checkpoint.
Waits use the same counter as callback and child steps. For example, step.run('pause', ...) followed by step.sleep('pause', '1m') saves the callback under pause and the wait under pause#2. Keep that order on every attempt. A wait loop uses pause, pause#2, then pause#3; each pass waits once and later attempts replay completed passes.
Finish work that holds a connection, lock, or open span inside step.run before awaiting a wait. Follow the wait safety rules when combining waits with other work.
Use return context.release('1m') when the next attempt should recheck state from the top without a saved wait outcome.
Runlane stores the wait checkpoint in the resume or claim transaction. It adds no checkpoint transaction. See wait without failing.