Client API
Complete reference for the Duron Client API
The Duron Client is the main interface for interacting with Duron. It manages job execution, action handling, and database operations.
Creating a Client
Create a client using the duron() function:
import { duron } from 'duron'
import { pgliteAdapter } from 'duron/adapters/pglite'
const client = duron({
database: pgliteAdapter({
connection: ':memory:',
}),
actions: {
sendEmail,
processOrder,
},
})Client Options
database
Required. The database adapter to use. Use one adapter instance per Client: the Client sets the adapter's client ID and owns its lifecycle (stopping the Client stops the adapter). Creating a second Client with an adapter that a Client already uses throws a TypeError. This includes an adapter whose Client was stopped: a stopped adapter cannot start again, so create a new adapter instance for a new Client.
{
database: pgliteAdapter({ connection: ':memory:' }),
}actions
Optional. A record of action definitions.
{
actions: {
sendEmail,
processOrder,
},
}variables
Optional. Variables available to all actions via ctx.var.
{
variables: {
apiKey: process.env.API_KEY,
db: myDatabase,
},
}id
Optional. Unique identifier for this Duron instance. Defaults to a random UUID.
The id must be unique per running process. Recovery requeues the jobs of this Client's own id that it does not hold, so two running Clients with the same id requeue each other's running jobs. Do not derive it from process.pid alone: in containers every worker is usually PID 1. See Worker IDs.
{
id: 'worker-1',
}syncPattern
Optional. Synchronization pattern for fetching jobs. Defaults to 'hybrid'.
'pull'- Periodic discovery atpullInterval'push'- Database availability notifications as a fast path, plus the same periodic discovery'hybrid'- Same as'push'(recommended)false- Disable automatic fetching. Explicitfetch()still works, andrecoverJobsOnStartstill applies
In every enabled mode, a Client with actions starts one background discovery pass as soon as it is running (start() does not wait for it) and then checks for work every pullInterval, so jobs whose notification was lost, jobs requeued by recovery and jobs that became claimable when a group slot freed up are still found. Without actions, a Client never claims or recovers jobs; fetch() returns []. actions: {} keeps worker behavior, so a claimed job of an unknown action is failed.
{
syncPattern: 'hybrid',
}waitReadTimeout
Optional. Time budget in milliseconds for each read of a job's result by waitForJob() and runActionAndWait() (status and detail, active and archive). Defaults to 5000. Values must be integers from 1 through 2,147,483,647; other values are rejected. A wait whose first read does not finish in time resolves null (waitForJob) or rejects with WaitReadTimeoutError (runActionAndWait). See How it works: wait results.
{
waitReadTimeout: 3_000,
}pullInterval
Optional. Defaults to 5000. Used for two independent schedules:
- Worker discovery (Clients with actions and an enabled
syncPattern): the interval between periodic discovery checks, and the cooldown after a failed discovery or recovery attempt. - Pending-wait reconciliation (every sync mode, with or without actions): its cadence and error cooldown. It never fetches or executes jobs.
{
pullInterval: 10_000, // 10 seconds
}See How it works: worker discovery for clamping, cooldowns and missed ticks.
batchSize
Optional. Defaults to 10. The most jobs that this Client claims automatically at once, and keeps outstanding (claimed, queued, running or finishing); automatic claiming pauses while it has that many. It is also the batch of a fetch() without batchSize. It is not the number of handlers that run at once (actionConcurrencyLimit per action) and not the SQL group limit (groupConcurrencyLimit or groups.concurrency), which applies across all workers. See How it works: claim ceiling.
{
batchSize: 20,
}actionConcurrencyLimit
Optional. Maximum number of jobs that can run concurrently per action. Defaults to 100.
{
actionConcurrencyLimit: 50,
}groupConcurrencyLimit
Optional. Maximum number of jobs that can run concurrently per action name and group key. Defaults to 10.
{
groupConcurrencyLimit: 5,
}migrateOnStart
Optional. Defaults to true. Whether the adapter applies Duron's pending migrations when it starts. The adapter has an option of the same name (migrateOnStart): migrations run at start only when neither option is false. Set false on the Client or on the adapter to turn them off, for example when you run the migrations yourself or connect with a role that cannot change the schema.
{
migrateOnStart: false,
}recoverJobsOnStart
Optional. Whether to recover stuck jobs on startup: jobs of dead workers, and jobs that a previous process with the same id left active. Defaults to true. See How it works: recovery.
{
recoverJobsOnStart: true,
}recoverJobsInterval
Optional. Interval in milliseconds between periodic recovery runs. Defaults to 60000 (1 minute). Set to 0 to disable periodic recovery (only runs on startup). Recovery archives expired jobs as failed and requeues the jobs of unresponsive workers; it runs inside worker discovery and never touches a job this Client holds. See How it works: recovery.
{
recoverJobsInterval: 30_000, // Run recovery every 30 seconds
}heartbeatInterval
Optional. Interval in milliseconds between heartbeat updates. Each instance periodically upserts a liveness record in the clients table. Defaults to 5000 (5 seconds).
{
heartbeatInterval: 5_000, // 5 seconds
}heartbeatTimeout
Optional. Milliseconds after which a client without a heartbeat is considered dead. A dead client's active jobs are recovered (requeued or failed if expired). Should be at least 3x heartbeatInterval. Defaults to 15000 (15 seconds).
{
heartbeatTimeout: 15_000, // 15 seconds
}shutdownTimeout
Optional. Budget in milliseconds of each phase of stop(): settling a startup that is still running, draining admitted work (running handlers and steps, their final writes, and the release of the jobs that did not finish), database cleanup, and closing the adapter's connections. A phase that exceeds it makes stop() reject. It applies to this Client's adapter. An integer from 1 to 2147483647; other values make the constructor throw. Defaults to 5000 (5 seconds).
{
shutdownTimeout: 30_000, // give running jobs up to 30 seconds to finish or be released
}logger
Optional. Logger instance or log level. Defaults to 'error'.
{
logger: 'info', // or a Pino logger instance
}telemetry
Optional. Telemetry configuration for OpenTelemetry tracing. See Telemetry for details.
import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
const tracerProvider = new TracerProvider({
spanProcessors: [new BatchSpanProcessor({ exporter: new OTLPTraceExporter() })],
})
{
telemetry: { tracerProvider },
}Options:
tracerProvider- Required intelemetry. An OpenTelemetryTracerProvider(interface from@opentelemetry/api) created by your application. Duron gets its tracer withtracerProvider.getTracer('duron'). The provider's Resource (for exampleservice.name), span processors and exporters apply to Duron's spans. Duron does not register, flush or shut down the provider.
Without telemetry, tracing is disabled: Duron uses a no-op tracer and does not read the global tracer provider. If telemetry is set without a valid tracerProvider, or with a removed option, the constructor throws a TypeError.
Breaking change: traceExporter, serviceName and batchDelayMs are removed. See Migration
from traceExporter.
Lifecycle Methods
start()
Start the Duron instance. Initializes the database, recovers stuck jobs, and sets up sync patterns.
await client.start()Returns: Promise resolving to true when the Client is running, false when it cannot start (for example after stop()). Other methods also start the Client on their first call. A Client that failed to start or was stopped cannot start again: create a new adapter and a new Client.
stop()
Stop the Duron instance. Stops worker discovery, aborts all running jobs, returns the jobs that did not finish to the queue, waits for that work to drain, and stops the database.
await client.stop()Returns: Promise resolving to true. It rejects when a phase does not finish within shutdownTimeout or a cleanup step fails (one error, or an AggregateError). Concurrent and repeated calls share one stop. After stop() began, every other method rejects with Lifecycle is not accepting work and start() resolves false.
Unfinished jobs are returned to the queue, not cancelled: a handler that still resolves after the abort completes its job; other jobs, and claimed jobs that did not start, become created again for any worker. An explicit cancelJob() still cancels. stop() can also be awaited inside a handler or step; that job is then cancelled. See How it works: shutdown.
Breaking change: before, stop() cancelled every running job, and its queued jobs stayed claimed
until recovery. Now they return to the queue and run again on a worker. Make handlers idempotent
across a restart, or call cancelJob() before stop() for jobs that must not run again.
Job Methods
runAction(actionName, input?)
Run an action by creating a new job.
const jobId = await client.runAction('sendEmail', {
to: 'user@example.com',
subject: 'Hello',
body: 'Test',
})Parameters:
actionName- Name of the action to runinput- Input data for the action (validated against action's input schema)
Returns: Promise resolving to the created job ID
fetch(options?)
Manually fetch and process jobs from the database.
Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see recoverJobsInterval) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when stop() begins reject; a call whose claim was already issued returns its jobs, but no handler starts after stop(): those jobs are returned to the queue. If the Client did not start (start() resolved false, for example because a custom adapter's start() declined), the call rejects instead of waiting. Direct client.database.fetch() calls are outside this coordination.
const jobs = await client.fetch({
batchSize: 20,
})Parameters:
options.batchSize- Number of jobs to fetch (optional)
Returns: Promise resolving to array of fetched jobs
cancelJob(jobId)
Cancel a job by its ID.
await client.cancelJob(jobId)Parameters:
jobId- The ID of the job to cancel
Returns: Promise resolving to true if the job is running on this Client and was aborted, false otherwise
What happens depends on where the job is:
- Running on this Client (its handler has started, including while it finishes up after an abort): the handler is aborted in memory and the call returns
true. The job writes its own cancellation when it settles. - Anything else: the call issues its own
Adapter.cancelJoband returnsfalse, even when the database cancellation succeeds. If that write rejects, the rejection reaches this caller only. Concurrent calls each issue their own write and get their own result. - Claimed by this Client but not started: the claim reply is still pending, or the job is queued behind
actionConcurrencyLimit. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active is rescued by this Client's next startup or periodic recovery (seerecoverJobsInterval): requeued (and run again) if it has not expired, or archived asfailedif it has. WithrecoverJobsInterval: 0it stays active until a later startup recovery with this Client'sid, or until this Client stops and another worker's recovery rescues it. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. - Running on another Client: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere: its handler can still start and then fail when step creation returns
null.
This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or recovery. After stop(), new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain.
retryJob(jobId)
Retry a failed job by creating a copy of it.
const newJobId = await client.retryJob(jobId)Parameters:
jobId- The ID of the job to retry
Returns: Promise resolving to the new job ID, or null if retry failed
runActionAndWait(actionName, input?, options?)
Run an action and wait for its completion. This is a convenience method that combines runAction and waitForJob.
const result = await client.runActionAndWait('sendEmail', {
to: 'user@example.com',
subject: 'Hello',
body: 'Test',
})
console.log(result.status) // 'completed' | 'failed' | 'cancelled'
console.log(result.output) // Typed based on action's output schemaParameters:
actionName- Name of the action to runinput- Input data for the action (validated against action's input schema)options.signal- Optional AbortSignal to cancel the operation. If aborted, the job will be cancelled and the promise will reject.options.timeout- Optional timeout in milliseconds. If the job doesn't complete within this time, the job will be cancelled and the promise will reject.
On abort or timeout the promise rejects immediately and cancelJob(jobId) runs in the background (its errors are logged), with the behavior described under cancelJob. waitForJob is different: its timeout or abort settles only that waiter and never cancels the job.
If the first read of the job's status does not finish within waitReadTimeout, the promise rejects with WaitReadTimeoutError; if that read fails, it rejects with WaitReadFailedError (the read error is its cause). Both are exported from duron. The job may exist and keep running: only the read gave up, and the job is not cancelled. If the Client stops while the call waits, it rejects with Lifecycle is not accepting work (or Client is not accepting work when the stop begins right after the job was created, before the wait starts); the job is not cancelled. A job that has no readable detail rejects with Job not found.
Returns: Promise resolving to the job result with typed input and output
Example:
// With timeout
const result = await client.runActionAndWait(
'processOrder',
{ orderId: '123' },
{
timeout: 30000, // 30 seconds
},
)
// With abort signal
const controller = new AbortController()
const result = await client.runActionAndWait(
'processOrder',
{ orderId: '123' },
{
signal: controller.signal,
},
)
// Cancel the operation
controller.abort()timeTravelJob(jobId, stepId)
Time travel a job to restart from a specific step. The job must be in completed, failed, or cancelled status. This resets the job and ancestor steps to active status, deletes subsequent steps, and preserves completed parallel siblings.
const success = await client.timeTravelJob(jobId, stepId)Parameters:
jobId- The ID of the job to time travelstepId- The ID of the step to restart from
Returns: Promise resolving to true if time travel succeeded, false otherwise
A false result (the job is not terminal, or the step does not belong to it) changes nothing: the job and its steps stay where they were, so an archived job can still be retried, time-traveled to an existing step or pruned.
Which steps are kept:
- The target step and its ancestor steps are reset to active and run again.
- A completed step is kept if it was created strictly before the target step (by its
createdAttimestamp). Kept steps return their stored output when the job runs again. - Completed
parallelsiblings of the target and of its ancestors are kept with their child steps, whenever they were created. - All other steps are deleted, and run again when the job reaches them.
With PGLite, step timestamps have millisecond resolution. A completed step created in the same
millisecond as the target step is not "before" it, so time travel deletes it and the step runs
again. PostgreSQL timestamps have microsecond resolution. Mark steps that do not depend on each
other as parallel: true to keep them regardless of their timestamps.
deleteJob(jobId)
Delete a job by its ID. Active jobs cannot be deleted.
const deleted = await client.deleteJob(jobId)Parameters:
jobId- The ID of the job to delete
Returns: Promise resolving to true if deleted, false otherwise
deleteJobs(options?)
Delete multiple jobs using the same filters as getJobs. Active jobs cannot be deleted and will be excluded from deletion.
const deletedCount = await client.deleteJobs({
filters: {
status: ['completed', 'failed'],
actionName: ['sendEmail'],
},
})Parameters:
options- Query options including filters (same asgetJobs)
Returns: Promise resolving to the number of jobs deleted
Archive Methods
Finished jobs (completed, failed or cancelled) move to archive storage. These methods inspect and clean it up. To prune on a schedule instead, use the adapters' pruneArchive option.
getArchiveStats()
Get statistics about the archive.
const stats = await client.getArchiveStats()
// { jobsCount, stepsCount, oldestJobDate, totalSizeBytes, lastPrunedAt }Returns: Promise resolving to:
jobsCount- Number of archived jobsstepsCount- Number of archived stepsoldestJobDate- The oldest archived job's date, ornullwhen the archive is emptytotalSizeBytes- Size of the archive tables in bytes, ornullwhen unknownlastPrunedAt- When a scheduled prune pass last completed, ornull
pruneArchive(options)
Delete archived jobs that finished before a cutoff, together with their steps. Jobs that are waiting or running are never touched.
// Keep the last 30 days
const deleted = await client.pruneArchive({ olderThan: '30d' })Parameters:
options.olderThan- The cutoff. One of:- a duration before now: a whole number followed by
ms,s,m,hord(for example'30d','12h','500ms') - a
Date - a timestamp in milliseconds
- a duration before now: a whole number followed by
options.batchSize- Optional. Jobs deleted per statement. Defaults to1000.options.maxBatches- Optional. Statements per call. Defaults to100, so one call deletes at mostbatchSize × maxBatchesjobs (100,000 by default). Call again to delete the rest.
Returns: Promise resolving to the number of deleted jobs
A job is deleted when its finished_at is before the cutoff. The cutoff of a duration is computed from the application's clock, while finished_at comes from the database clock. Each batch commits on its own: if a later batch fails, the earlier ones stay deleted. A manual call does not take the scheduled pruning lock, so it can run at the same time as a scheduled pass (see How it works: archive retention).
truncateArchive()
Delete every archived job and step at once. This cannot be undone.
await client.truncateArchive()Returns: Promise resolving when the archive is empty
Query Methods
getJobById(jobId)
Get a job by its ID. Does not include step information.
const job = await client.getJobById(jobId)Parameters:
jobId- The ID of the job to retrieve
Returns: Promise resolving to the job, or null if not found
getJobs(options?)
Get matching jobs from active and archive storage with global sorting and pagination. Job records include input, output, and error, but not steps. A terminal job that an older version left in active storage after a failed time travel remains visible under its status filter.
SQL adapters apply every requested sort key in order, then break ties by job ID in the
direction of the last sort key (ID descending when that key is descending). The order
is total, so while the jobs do not change, every job appears on exactly one page. The
default, also for an empty sort array, is startedAt descending. Nulls
sort last ascending and first descending. Text (status, actionName, description)
uses byte order (Unicode code point order in a UTF-8 database): it does not depend on
the database locale and, unlike JavaScript UTF-16 order, sorts characters above U+FFFF
after U+E000–U+FFFF. Dates sort by their stored microsecond precision, finer than the
millisecond Date values returned. duration sorts numeric durationMs (including
fractional or negative values). Unfiltered sorts by createdAt, startedAt and
status use indexes in both storages; with filters (for example a status filter), the
database may scan and sort the matching jobs instead.
total counts all matching jobs even for an empty or out-of-range page. Count and
page queries do not share a method-wide snapshot, and separate page requests do
not promise a stable snapshot during concurrent changes. At most pageSize job
payloads return from the database; this does not bound payload size, database
filtering/sorting work, or latency.
const result = await client.getJobs({
page: 1,
pageSize: 20,
filters: {
status: ['active', 'completed'],
actionName: ['sendEmail'],
groupKey: ['user-123'],
clientId: ['worker-1'],
description: 'order', // Fuzzy match on description
createdAt: [new Date('2024-01-01'), new Date('2024-12-31')],
startedAt: [new Date('2024-01-01'), new Date('2024-12-31')],
finishedAt: [new Date('2024-01-01'), new Date('2024-12-31')],
updatedAfter: new Date('2024-01-01'),
search: 'email',
inputFilter: { userId: '123' },
outputFilter: { success: true },
},
sort: [
{ field: 'createdAt', order: 'desc' },
{ field: 'status', order: 'asc' },
],
})Parameters:
options.page- Page number (default: 1)options.pageSize- Number of items per page (default: 10)options.filters- Filter options (see below)options.sort- Sort options (see below)
Filter Options:
status- A job status or an array of statusesactionName- An action name or an array of action namesgroupKey- An array of group keys (exact match), or one string (case-insensitive substring match)clientId- A client ID or an array of client IDsdescription- Case-insensitive substring match on the job descriptioncreatedAt- A date (on or after it) or a range[start, end](inclusive), compared at second precisionstartedAt- Same ascreatedAtfinishedAt- Same ascreatedAtupdatedAfter- Jobs updated strictly after this date (millisecond precision)search- Case-insensitive match on action name, group key, description, client ID or job ID, or English full-text search in input and outputinputFilter- JSONB filter on input dataoutputFilter- JSONB filter on output data
Sort Options:
field- Field to sort by:'createdAt','startedAt','finishedAt','status','actionName','expiresAt','duration','description'order- Sort order:'asc'or'desc'
Returns: Promise resolving to { jobs, total, page, pageSize }. Job timestamps are
Date values; durationMs is a number or null.
getJobSteps(options)
Get all matching steps for a job from active and archive storage, ordered by createdAt ascending.
There are no page or pageSize options.
const result = await client.getJobSteps({
jobId,
search: 'fetch',
updatedAfter: new Date('2024-01-01'),
})
// result: { steps, total }Parameters:
options.jobId- The ID of the joboptions.search- Optional search in step names or output. SQL adapters use case-insensitive name matching (including SQL%and_wildcards) or English full-text output search.options.updatedAfter- Optional strict boundary: only steps whoseupdatedAt, truncated to milliseconds, is greater than this date. Applies to both name and output matches.
Returns: Promise resolving to { steps, total }, where total equals steps.length after filtering.
Step output is searchable but omitted from list results. Use getJobStepById to retrieve output.
getJobStepById(stepId)
Get a step by its ID with all information.
const step = await client.getJobStepById(stepId)Parameters:
stepId- The ID of the step to retrieve
Returns: Promise resolving to the step, or null if not found
getJobStatus(jobId)
Get job status and updatedAt timestamp.
const status = await client.getJobStatus(jobId)Parameters:
jobId- The ID of the job
Returns: Promise resolving to job status result, or null if not found
getJobStepStatus(stepId)
Get job step status and updatedAt timestamp.
const status = await client.getJobStepStatus(stepId)Parameters:
stepId- The ID of the step
Returns: Promise resolving to step status result, or null if not found
waitForJob(jobId, options?)
Wait for a readable completed, failed, or cancelled job result. Shared notification hints provide a fast path; while waits remain registered, an independent Client loop also checks retained results at pullInterval. Lost hints and recovery-produced terminal failures do not require a worker fetch or a fresh notification.
Initial and periodic checks read lightweight status before terminal detail. Hints request detail directly. Returned detail must itself be terminal: a stale hint or earlier terminal status is not sufficient after time travel.
const job = await client.waitForJob(jobId)Parameters:
jobId- The ID of the job to wait foroptions.timeout- Optional caller waiting timeout in milliseconds. Expiry resolves this waiter tonull; omission means no caller timeout. This is separate from the Client'swaitReadTimeout.options.signal- Optional AbortSignal to cancel waiting. If aborted, the promise resolves tonull.
Returns: A terminal result containing id, actionName, status, groupKey, description, input, output, and error. Returns null on caller timeout/abort, initial-check failure/expiry, missing detail after a terminal status/hint, or when stop() begins while the wait is pending. A call made after stop() began rejects with Lifecycle is not accepting work instead. null does not mean the job failed.
Example:
// Wait for a job to complete (no timeout)
const job = await client.waitForJob(jobId)
// Wait with a timeout
const job = await client.waitForJob(jobId, { timeout: 5000 })
// Wait with an abort signal
const controller = new AbortController()
const job = await client.waitForJob(jobId, { signal: controller.signal })
// Cancel waiting
controller.abort()Notes:
- Already-terminal jobs still require a successful admitted read. Missing/nonterminal status keeps the wait pending. Established waiters survive later read failures and retry after a
pullIntervalcooldown; expired reads start their cooldown only after actual settlement. - Waiters share a listener and bounded FIFO read scheduling, not cancellation. Cancelling one waiter leaves siblings registered. A waiter arriving after a read starts cannot receive that read's result.
- Each periodic pass considers at most ten IDs in round-robin order. Initial/hint checks share a four-actual-chain limit and one chain per ID. No waits means no periodic wait timer. These are work bounds, not completion or query-rate guarantees.
- Expired results are discarded. Caller cancellation and read-observer expiry do not cancel SQL or release actual capacity. Four unresolved chains can block all further checks, including queued initial reads.
- Retained results must remain readable long enough to be observed. Pruned output cannot be reconstructed; there is no stronger SQL snapshot or execution-generation guarantee.
- Stop settles pending waits locally and drains actual reads/transaction cleanup under the shared drain budget (
shutdownTimeout, 5 seconds by default).waitReadTimeoutdoes not extend or reset any lifecycle phase.
getActions()
Get action statistics including counts and last job created date.
const actions = await client.getActions()Returns: Promise resolving to action statistics
getActionsMetadata()
Get action metadata including input schemas and mock data.
const metadata = await client.getActionsMetadata()Returns: Promise resolving to action metadata array
Utility Methods
getConfig()
Get the current configuration of this Duron instance.
const config = client.getConfig()Returns: Configuration object including options, actions, and variables
logger
Access the Pino logger instance.
client.logger.info('Client started')tracer
Access the OpenTelemetry tracer for creating custom spans. Always returns a tracer — it's a no-op tracer when no telemetry.tracerProvider is configured.
const span = client.tracer.startSpan('custom-operation')database
Access the database adapter instance.
const adapter = client.database