Use lifecycle hooks
Deliver terminal callbacks and wrap attempt boundaries with middleware.
Use lifecycle hooks for notifications and external cleanup after a run ends. Task and runtime hooks follow the same rules:
| Run status | Outcome callback | Final callback |
|---|---|---|
succeeded | onSuccess | onComplete |
failed or expired | onFailure | onComplete |
cancelled | onCancel | onComplete |
onFailure does not run for cancelled runs. To record every end state, such as a payment outcome, use onComplete, or handle onSuccess, onFailure, and onCancel.
Only configured functions run. A run cancelled or expired before its first attempt still fires its hooks, with run.counters.attempts === 0. Retryable attempt failures and releases do not fire terminal hooks.
import { task } from '@runlane/core'
import * as z from 'zod'
const sendReport = task({
id: 'reports.send',
schema: z.object({ reportId: z.string() }),
run: ({ reportId }) => ({ reportId, sent: true }),
onSuccess: async ({ run }, { deliveryId, signal }) => {
const response = await fetch('https://example.com/report-events', {
method: 'POST',
headers: { 'content-type': 'application/json', 'idempotency-key': deliveryId },
body: JSON.stringify({ runId: run.id, status: run.status }),
signal,
})
if (!response.ok) throw new Error('Report notification failed.')
},
})Hooks receive the saved normalized payload. Success hooks also receive output; task-level hooks apply the current output schema, while runtime hooks receive raw JSON. Failure hooks receive a bounded public failure. Expiry supplies a synthetic timeout failure without changing the saved run outcome. Cancel hooks receive no failure. Complete receives the matching terminal input.
You can set the same callbacks on createRunlane() to observe every task, including tasks without task-level callbacks. No callback order is promised. Selected callbacks run independently, at most four at once. A failed outcome callback cannot prevent complete from running.
Delivery and retries
The terminal transaction saves a small state on the run only when callbacks exist or need discovery. The finishing worker invokes callbacks after that transaction commits. Cancellation, expiry, and recovery use the same state. Transport lanes publish a run_hooks_wakeup; polling workers claim indexed work directly. On eager transport runtimes, when runs.cancel() saves a terminal cancellation, it attempts to publish the first hook wakeup before returning. A failed publish leaves cancellation saved and returns deliveryError; maintenance retries delivery. A worker must have the task registered to invoke callbacks.
Callbacks have their own short lease. They never hold the task's run lease or queue capacity. Stored results and completion waits are available before hooks finish. runNow() and executeNext() await eager hook delivery before returning, so their latency includes callback work, up to hooks.timeout per callback. Hook errors never change the terminal outcome.
A storage failure during eager hook delivery returns the saved run with deliveryError. See saved changes and delivery errors. Callback failures remain in the run's independent hook state and retry under the hook policy.
With retries enabled, a callback may run more than once. A crash after an external effect but before settlement can repeat the callback. deliveryId stays fixed for that callback; hookAttempt increases on each claim. Use the delivery ID to deduplicate external effects, the same way a task uses a step token. Respect the abort signal. JavaScript cannot stop a callback that ignores it, so timed-out effects may overlap a later retry.
Set hooks.timeout, hooks.leaseDuration, and hooks.discoveryTimeout to tune delivery deadlines. Their defaults come from contractDefaults.hooks. The callback timeout must be shorter than its lease.
Workers resolve callbacks from their current task registration. Code is not pinned to the run's version. Keep the task registered while hooks remain pending. Missing callbacks after discovery are skipped visibly.
Retry a failed callback
Only the failed callback retries. The task never runs again because a hook failed. Its result is saved before hooks start and never changes. Each callback, such as onSuccess or onComplete, keeps its own attempt count. A callback that succeeds is not repeated when another callback fails.
The default policy comes from contractDefaults.hooks.retry. It allows nine retries after the first attempt. Its exponential backoff starts at 1 second and caps each wait at 5 minutes. The waits are 1s, 2s, 4s, 8s, 16s, 32s, 64s, 128s, and 256s. Together they add up to 511 seconds, about 8.5 minutes, plus callback time. These waits are minimums. On transport lanes, the next delivery-recovery pass requests a wakeup for a due retry. A full runMaintenanceOnce() publishes that wakeup in the same pass, within its outbox limit. Separate recovery and outbox services follow their own intervals. Callback start also depends on transport delivery and worker capacity. Polling workers check for due callbacks once per contractDefaults.maintenance.services.interval.
hooks.retry accepts the same RetryPolicy as task retries. Both use the same parser, validation rules, and delay calculation. A plain thrown error is retryable. A RunlaneError uses its own retryable flag, which defaults to false. Only retryable failures with attempts left are retried. Non-retryable failures mark that callback failed at once.
Runlane also stops callbacks when saved output fails the task's current output schema (task_output_invalid). Invalid log entries stop with configuration_invalid. An oversized individual log body stops with log_limit_exceeded. Run-wide entry and byte quotas save one truncation marker without failing the callback. A deploy that tightens an output schema can stop a pending success hook for a run saved by the old code.
To turn retries off, set maxRetries: 0:
import { createRunlane } from '@runlane/core'
// Use your application's lane, queues, and task catalog.
const runlane = createRunlane({
lane,
queues,
tasks,
hooks: { retry: { maxRetries: 0 } },
})Each callback then runs at most once. A callback that throws is marked failed. If the worker crashes during its claim, recovery marks that callback failed after the lease expires. A crash before the effect can lose it; a crash after the effect cannot repeat it.
To change the schedule, use a fixed duration:
const runlane = createRunlane({
lane,
queues,
tasks,
hooks: { retry: { maxRetries: 2, backoff: '10s' } },
})This allows three attempts, with 10 seconds between attempts. If you supply retry without backoff, it uses the fixed 30-second delay from contractDefaults.retry.backoff, just like a task. Changing only the budget does not keep the exponential curve. To keep the default exponential curve while changing the budget, copy the full default policy:
import { contractDefaults } from '@runlane/core'
const hooks = { retry: { ...contractDefaults.hooks.retry, maxRetries: 4 } }An object backoff accepts type, delay, and optional maxDelay. The cap must be at least the base delay. Invalid settings fail with configuration_invalid when you construct the runtime; the error identifies hooks.retry.
Runlane logs a callback failure and counts it only after storage saves the result. If the result cannot be saved, for example because the claim's lease ran out first, that attempt emits no failure log and no retry or exhausted count. Attempt and timing metrics still record it, and its error is still recorded on the runlane.task.hook span. The next claim either runs the callback again or logs exhausted.
hook_delivery_failed logs include run_id, task_id, and hook attempt. Retried failures log at warn with reason: retry_scheduled; the final retryable failure or expired final claim logs at error with reason: exhausted. A non-retryable failure logs at error with reason: not_retryable. Monitor runlane.hook.exhausted.count for every callback that ends failed, including non-retryable failures and discovery timeouts. Once all callbacks settle, any failed callback makes runs.get() and CLI runs get show hooks: failed with bounded failure details. Other callbacks still finish. Done and failed hooks do not delay retention.
Use the shared public tools to check a retry budget:
import { contractDefaults, getRetryDelayMilliseconds, retryPolicySchema } from '@runlane/core'
import { strict as assert } from 'node:assert'
const policy = retryPolicySchema.parse(contractDefaults.hooks.retry)
const retryWindow = Array.from({ length: policy.maxRetries }, (_, index) =>
getRetryDelayMilliseconds(policy, index + 1),
).reduce((total, delay) => total + delay, 0)
assert(retryWindow >= 5 * 60 * 1000, 'The retry schedule must cover 5 minutes.')Delivery budgets
On SQS, hook delivery keeps the receipt open during callback work and log drain. Set receive visibility to cover hooks.timeout, storage settlement, and log drain. On Lambda, eager hooks run inside the same invocation as the task outcome. Include that work in the function's remaining time budget. Reduce hooks.timeout when needed and keep it shorter than hooks.leaseDuration. A timed-out callback remains eligible for recovery under its retry policy.
Polling workers drain available hook work in bounded pages. Callback deliveries run concurrently, up to the workers' combined concurrency. Long-lived idle workers scan at most once per maintenance service interval. After its run slots finish, drain() delivers callbacks due at storage time without idle pacing and waits for their settlement. Hook deliveries do not spend maxRuns or change DrainResult. A retryable failure with attempts left schedules the callback for a future time. That drain does not invoke it again. See test hook retries.
Closing a polling worker or runtime stops new polling hook claims immediately, including scans and claims waiting on storage. Aborting a drain's signal also stops hook acquisition. Unclaimed hooks remain available to later workers and maintenance recovery. Callbacks already started keep their worker's shutdown grace and hook deadline; stopping acquisition does not abort them early.
If a storage scan, claim, or settlement fails during the final hook pass, drain() logs hook_delivery_failed and stops that pass. It still returns the run count already completed. Maintenance or a later drain can recover the pending hooks. Discovery timeout logs reason: discovery_timeout; claim exhaustion logs only callbacks newly failed by that claim.
Remove a task with pending hooks
Keep at least one worker with the task registered until pending hooks finish. A worker without that task acknowledges hook wakeups and records delivery_ignored with reason hook_handler_missing. Delivery recovery republishes wakeups so a registered worker in a mixed fleet can handle them. Ordinary run-execution wakeups still retry when their task is missing.
If no worker can resolve discovery or invoke pending hooks, hooks.discoveryTimeout limits how long they wait unclaimed since becoming due. Its default is 24 hours. A later worker scan or delivery-recovery pass marks unresolved work failed with a visible hooks.lastFailure reason. Done and failed hook state permits retention cleanup. Until that pass, pending work stays retained and transport recovery may republish wakeups. This policy can abandon callbacks; restore the registration before the timeout when their effects are required.
Wrap attempt boundaries
Middleware runs once per attempt, including attempts that park. Runtime middleware wraps task middleware in registration order. Cleanup unwinds in reverse.
import { task } from '@runlane/core'
import * as z from 'zod'
const calculate = task({
id: 'calculate',
schema: z.number(),
middleware: [
async (_input, next) => {
const result = await next()
console.log({ outcome: result.outcome })
},
],
run: (value) => value * 2,
})Middleware receives { payload, context } as its first argument. payload is the saved normalized input; context is the task context for this attempt.
Each middleware must call and await next() exactly once. Missing, duplicate, and detached calls fail the attempt with a structured error. next() resolves to returned, failed, suspended, or abandoned after admitted task operations drain. This includes output validation for completed children in a batch join. If a pause is already selected when an admitted child wait delivers its rejection, next() reports failed. Middleware observes raw handler output and cannot replace it.
When a wait suspends, middleware cleanup runs while the handler's wait stays parked. Application catch, finally, and code after that wait do not resume. Suspension stays primary if cleanup throws. Existing task failures also stay primary; secondary cleanup errors are logged. Setup failure or cleanup after success fails an owned attempt. If the execution signal aborted first, for example during worker shutdown or at a platform time limit, Runlane treats the attempt as interrupted instead and requeues it, subject to the interruption allowance. Crashes can skip cleanup, so use durable steps or terminal hooks for business effects that must survive a crash.
The discovery wait starts at the earliest pending callback’s availableAt, or hooks.createdAt when none is pending. A lapsed claim restarts the wait at hooks.claimExpiresAt if that is later. These times come from storage; writer clock skew cannot extend the wait. Retry backoff does not consume this budget.