Jobs and Steps
Understand how jobs and steps work in Duron
Duron organizes work into jobs and steps. Understanding these concepts is key to using Duron effectively.
Jobs
A job represents a single execution of an action. When you call client.runAction(), Duron creates a new job.
Job Lifecycle
Jobs go through the following states:
created- Job has been created but not yet startedactive- Job is currently being executedcompleted- Job finished successfullyfailed- Job failed with an errorcancelled- Job was cancelled before completion
A job can also go back from active to created: when its worker stops gracefully before the job finishes, or when recovery requeues the job of a dead worker. Its next run reuses the steps that already completed. See How it works: releasing unfinished jobs.
Creating Jobs
Jobs are created automatically when you call runAction():
const jobId = await client.runAction('sendEmail', {
to: 'user@example.com',
subject: 'Hello',
body: 'Test',
})Job Properties
Each job has the following properties:
id- Unique identifier (UUID)actionName- Name of the actiongroupKey- Group key for concurrency controldescription- Dynamic description of the job (if defined on the action)status- Current statusinput- Input data passed to the actionoutput- Output data returned by the action (if completed)error- Error information (if failed)createdAt- Timestamp when job was createdstartedAt- Timestamp when job startedfinishedAt- Timestamp when job finishedupdatedAt- Timestamp when job was last updatedclientId- ID of the Duron instance that owns the jobchecksum- Checksum of the action definitiontimeoutMs- Timeout of the job (the action'sexpire)expiresAt- When the running job expiresconcurrencyLimit- Concurrency limit of the job's groupconcurrencyStepLimit- Step concurrency limit of the jobactionConcurrencyLimit- The action'sconcurrencylimit when the job was created, ornull(no action limit)durationMs-finishedAt - startedAtin milliseconds, ornullbefore the job finished
Querying Jobs
You can query jobs using the client:
// Get a job by ID
const job = await client.getJobById(jobId)
// Get jobs with filters and pagination
const result = await client.getJobs({
page: 1,
pageSize: 20,
filters: {
status: ['active', 'completed'],
actionName: ['sendEmail'],
},
sort: [{ field: 'createdAt', order: 'desc' }],
})Cancelling Jobs
You can cancel a job:
await client.cancelJob(jobId)A cancelled job is archived with every step marked cancelled. cancelJob returns true only when the job is running on this Client and was aborted in memory; a job this Client has claimed but not started never starts its handler. See cancelJob for the local and remote guarantees. For how cancellation interacts with concurrent step writes, completion, claims and recovery on PostgreSQL, and its limits, see Cancellation and Stored Steps.
Retrying Jobs
You can retry a failed job:
const newJobId = await client.retryJob(jobId)Steps
Steps are units of work within an action. They allow you to break down complex actions into smaller, trackable pieces.
Creating Steps
Steps are created using ctx.step():
const processOrder = defineAction()({
name: 'processOrder',
handler: async (ctx) => {
// Step 1: Fetch user
const user = await ctx.step('fetchUser', async ({ signal }) => {
return await fetchUser(ctx.input.userId, { signal })
})
// Step 2: Validate order
await ctx.step('validateOrder', async ({ signal }) => {
return await validateOrder(ctx.input.orderId, { signal })
})
// Step 3: Process payment
const payment = await ctx.step('processPayment', async ({ signal }) => {
return await processPayment(ctx.input.orderId, { signal })
})
return { success: true }
},
})Step Context
The step handler receives a context object with:
signal- AbortSignal for cancellation supportstepId- Unique identifier for the current stepparentStepId- ID of the parent step (null for root steps)step- Function to create nested inline child stepsrun- Function to execute reusable step definitionstelemetry- Telemetry context for metrics and tracing (see Telemetry)
await ctx.step('fetchData', async ({ signal, stepId, parentStepId, run }) => {
console.log(`Executing step ${stepId}, parent: ${parentStepId}`)
// Use signal for cancellation
const response = await fetch(url, { signal })
// Call a step definition from within an inline step
await run(sendEmailStep, { to: 'user@example.com', body: 'Done!' })
return response.json()
})Nested Steps
Steps can create child steps using the step function available in the step handler context. This is useful for breaking down complex operations into smaller, trackable units.
const processOrder = defineAction()({
name: 'processOrder',
input: z.object({ orderId: z.string() }),
handler: async (ctx) => {
const result = await ctx.step('process', async ({ step, stepId }) => {
console.log('Processing step:', stepId)
// Create child steps - they inherit the parent's abort signal
const validation = await step('validate', async ({ parentStepId }) => {
// parentStepId links back to the 'process' step
console.log('Parent step:', parentStepId)
return { valid: true }
})
// Child steps can also be nested further
const payment = await step('charge', async ({ step: nestedStep }) => {
const auth = await nestedStep('authorize', async () => {
return { authCode: '123' }
})
return { charged: true, authCode: auth.authCode }
})
return { success: validation.valid && payment.charged }
})
return result
},
})Abort Signal Propagation
Child steps automatically inherit the abort signal chain from their parent. When a parent step is cancelled or times out, all child steps receive the abort signal.
await ctx.step('parent', async ({ step, signal }) => {
// If this step times out, all children are also aborted
const child1 = await step('child1', async ({ signal: childSignal }) => {
// childSignal is linked to the parent's signal
return await fetch(url, { signal: childSignal })
})
return child1
})Important: Await All Child Steps
All child steps must be awaited before the parent step returns. If a parent step completes with unawaited children, Duron will:
- Abort all pending child steps
- Wait for them to settle
- Throw an
UnhandledChildStepsError
// ❌ Bad: Unawaited child steps
await ctx.step('parent', async ({ step }) => {
step('child1', async () => {
/* ... */
}) // Not awaited!
step('child2', async () => {
/* ... */
}) // Not awaited!
return { done: true } // Throws UnhandledChildStepsError
})
// ✅ Good: All children awaited
await ctx.step('parent', async ({ step }) => {
await step('child1', async () => {
/* ... */
})
await step('child2', async () => {
/* ... */
})
return { done: true }
})
// ✅ Good: Parallel execution with Promise.all
await ctx.step('parent', async ({ step }) => {
const [result1, result2] = await Promise.all([
step('child1', async () => {
/* ... */
}),
step('child2', async () => {
/* ... */
}),
])
return { result1, result2 }
})Step Hierarchy in the Dashboard
Nested steps are displayed hierarchically in the Duron Dashboard. Each step shows its parent relationship, making it easy to understand the execution flow of complex workflows.
Reusable Step Definitions
For steps that are used across multiple actions or need to be called multiple times with different inputs, you can create reusable step definitions using createStep().
Creating a Reusable Step
Use createStep() to define a step with its own input schema, options, and handler. Like actions, steps accept any Standard Schema compliant validator:
import { createStep } from 'duron'
import { z } from 'zod'
const sendEmailStep = createStep<typeof variables>()({
name: 'send-email',
input: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
retry: { limit: 3 },
expire: 60000,
handler: async (ctx) => {
// ctx includes all step context plus action-level properties
const result = await ctx.var.emailService.send({
to: ctx.input.to,
subject: ctx.input.subject,
body: ctx.input.body,
})
return { success: true, messageId: result.id }
},
})Step Definition Context
The handler receives an extended context that includes:
input- The validated input data based on the step's input schemasignal- AbortSignal for cancellation supportstepId- Unique identifier for the current stepparentStepId- ID of the parent step (null for root steps)step- Function to create nested inline child stepsrun- Function to execute other reusable step definitionstelemetry- Telemetry context for metrics and tracingvar- Variables from the action contextlogger- Pino logger instancejobId- The job ID this step belongs to
Executing Step Definitions
Use ctx.run() to execute a step definition within an action handler:
const processOrder = defineAction<typeof variables>()({
name: 'processOrder',
handler: async (ctx) => {
// Execute the reusable step
const emailResult = await ctx.run(sendEmailStep, {
to: ctx.input.email,
subject: 'Order Confirmation',
body: `Your order ${ctx.input.orderId} has been placed.`,
})
return { success: emailResult.success }
},
})Overriding Step Options
You can override step options at call time:
// Override expire and retry at call time
const result = await ctx.run(
sendEmailStep,
{ to: 'user@example.com', subject: 'Hello', body: 'World' },
{ expire: 30000, retry: { limit: 5 } },
)Dynamic Step Names
Use a function for the name property to generate unique step names based on input. This is essential when calling the same step definition multiple times within a single job.
The name function receives a context object with:
input- The validated step inputvar- Variables from the action contextjobId- The job ID this step belongs toparentStepId- The ID of the parent step (null for root steps)
const sendEmailStep = createStep<typeof variables>()({
// Dynamic name based on input and context
name: (ctx) => `send-email-${ctx.input.to}`,
input: z.object({
to: z.string().email(),
body: z.string(),
}),
handler: async (ctx) => {
// ...
},
})
// Now you can call it multiple times with different inputs
const processOrder = defineAction<typeof variables>()({
name: 'processOrder',
handler: async (ctx) => {
// Each call creates a uniquely named step
await ctx.run(sendEmailStep, { to: 'customer@example.com', body: 'Confirmation' })
await ctx.run(sendEmailStep, { to: 'admin@example.com', body: 'Notification' })
return { success: true }
},
})Nested Steps in Step Definitions
Step definitions can create nested child steps using ctx.step():
const processPaymentStep = createStep<typeof variables>()({
name: 'process-payment',
input: z.object({ amount: z.number(), currency: z.string() }),
handler: async (ctx) => {
// Create nested child steps
const auth = await ctx.step('authorize', async () => {
return await ctx.var.paymentGateway.authorize(ctx.input.amount)
})
const capture = await ctx.step('capture', async () => {
return await ctx.var.paymentGateway.capture(auth.transactionId)
})
return { success: true, transactionId: capture.id }
},
})Composing Step Definitions
Step definitions can call other step definitions using ctx.run(). This enables powerful composition patterns where you can build complex workflows from reusable building blocks:
// Inner step definition
const validateOrderStep = createStep<typeof variables>()({
name: (ctx) => `validate-order-${ctx.input.orderId}`,
input: z.object({ orderId: z.string() }),
handler: async (ctx) => {
const order = await ctx.var.db.getOrder(ctx.input.orderId)
return { valid: order.items.length > 0, total: order.total }
},
})
// Outer step that calls inner step via ctx.run()
const processOrderStep = createStep<typeof variables>()({
name: (ctx) => `process-order-${ctx.input.orderId}`,
input: z.object({ orderId: z.string() }),
handler: async (ctx) => {
// Call another step definition from within this step definition
const validation = await ctx.run(validateOrderStep, {
orderId: ctx.input.orderId,
})
if (!validation.valid) {
throw new Error('Invalid order')
}
return { processed: true, total: validation.total }
},
})
// Use in an action
const orderAction = defineAction<typeof variables>()({
name: 'orderAction',
handler: async (ctx) => {
return ctx.run(processOrderStep, { orderId: ctx.input.orderId })
},
})This pattern supports arbitrary nesting depths. Each step definition call creates its own step in the database for tracking and observability.
Step Options
You can configure steps with options:
await ctx.step(
'fetchData',
async ({ signal }) => {
return await fetchData({ signal })
},
{
expire: 10 * 60 * 1000, // 10 minute timeout
retry: {
limit: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 10000,
},
},
)expire
Timeout in milliseconds for the step. Defaults to the action's steps.expire value.
{
expire: 5 * 60 * 1000, // 5 minutes
}retry
Retry configuration for the step. See Retries for details.
{
retry: {
limit: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 10000,
},
}parallel
Whether this step runs independently from its siblings. Defaults to false.
When a step is marked as parallel: true, it is treated as independent during time travel operations. If you time travel to a specific step, completed parallel siblings are preserved rather than deleted. This is useful for steps that don't depend on each other and can safely coexist.
await ctx.step(
'sendNotification',
async ({ signal }) => {
return await sendNotification({ signal })
},
{ parallel: true },
)You can also set parallel on reusable step definitions:
const notifyStep = createStep()({
name: 'notify',
parallel: true,
handler: async (ctx) => {
// This step is independent from siblings
},
})Step Lifecycle
Steps go through the following states:
active- Step is currently executingcompleted- Step finished successfullyfailed- Step failed with an errorcancelled- Step was cancelled
Step Properties
Each step has the following properties:
id- Unique identifier (UUID)jobId- ID of the parent jobparentStepId- ID of the parent step (null for root steps)name- Name of the stepstatus- Current statusoutput- Output data (if completed)error- Error information (if failed)timeoutMs- Timeout in millisecondsexpiresAt- Expiration timestampretriesLimit- Maximum retry attemptsretriesCount- Current retry countdelayedMs- Delay before next retry (if retrying)historyFailedAttempts- Record of previous failed attemptsstartedAt- Timestamp when step startedfinishedAt- Timestamp when step finishedcreatedAt- Timestamp when step was createdupdatedAt- Timestamp when step was last updated
Querying Steps
You can query steps for a job:
// Get the steps of a job (no pagination; output is omitted)
const result = await client.getJobSteps({
jobId,
search: 'fetch', // Optional: match step names or output
})
// Get a step by ID
const step = await client.getJobStepById(stepId)Step Concurrency
The steps of one job respect the action's steps.concurrency limit. By default, up to 100 steps of a job can run concurrently.
{
name: 'processOrder',
steps: {
concurrency: 5, // Allow up to 5 concurrent steps
},
}Best Practices
Use Steps for Trackable Work
Break down complex actions into steps for better observability:
handler: async (ctx) => {
// Good: Each operation is a step
const user = await ctx.step('fetchUser', async () => fetchUser())
const order = await ctx.step('createOrder', async () => createOrder())
const email = await ctx.step('sendConfirmation', async () => sendEmail())
return { success: true }
}Use AbortSignal for Cancellation
Always use the signal parameter for cancellation support:
await ctx.step('fetchData', async ({ signal }) => {
const response = await fetch(url, { signal })
return response.json()
})Handle Step Failures
Steps can fail independently. Handle failures appropriately:
try {
const result = await ctx.step('riskyOperation', async () => {
return await riskyOperation()
})
} catch (error) {
// Handle step failure
ctx.logger.error({ error }, 'Step failed')
throw error // Re-throw to fail the action
}