Multi-Worker Setup
Learn how to run Duron with multiple worker processes for scalability and fault tolerance
Duron supports running multiple worker processes that share the same database, allowing you to scale job processing horizontally and improve fault tolerance.
Overview
In a multi-worker setup, you can:
- Scale horizontally: Add more worker processes to handle increased load
- Separate concerns: Run dashboard/server processes separately from worker processes
- Improve fault tolerance: If one worker crashes, others continue processing jobs
- Optimize resource usage: Scale dashboard and workers independently
Architecture
A typical multi-worker setup consists of:
-
Dashboard/Server Process: Handles API requests and serves the dashboard UI
- Configured with
syncPattern: falseto prevent job processing - Only manages the API and dashboard
- Configured with
-
Worker Processes: Handle job processing
- Each worker has a unique
id - Configured with
syncPattern: 'hybrid'for efficient job processing - Heartbeat-based liveness detection for crashed-instance recovery
- Each worker has a unique
All processes share the same database, so jobs created through any process are available to all workers.
Configuration
Worker Configuration
Each worker process needs:
- Unique ID: Each worker process must have its own identifier (see Worker IDs)
- Sync pattern: Use
syncPattern: 'hybrid'for efficient processing
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'
// Unique per running process. Not `worker-${process.pid}`: in containers every PID is 1.
const workerId = process.env.WORKER_ID || `worker-${crypto.randomUUID()}`
const client = duron({
id: workerId, // Unique ID for this worker
syncPattern: 'hybrid', // Efficient job processing
database: postgresAdapter({
connection: process.env.DATABASE_URL!,
}),
actions: {
sendEmail,
processOrder,
},
heartbeatInterval: 5_000, // Liveness heartbeat every 5s (default)
heartbeatTimeout: 15_000, // Consider dead after 15s (default)
recoverJobsOnStart: true, // Recover stuck jobs on startup
})
await client.start()Dashboard/Server Configuration
The dashboard/server process should:
- Disable job processing: Use
syncPattern: false - Share the same database: Use the same database connection
- Define actions: Actions must be defined for the API to work
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'
import { createServer } from 'duron/server'
const client = duron({
id: 'dashboard-server',
syncPattern: false, // Disable automatic job fetching
database: postgresAdapter({
connection: process.env.DATABASE_URL!,
}),
actions: {
sendEmail, // Actions must be defined for the API
processOrder,
},
})
await client.start()
// Create the API server
const app = createServer({ client })Complete Example
Here's a complete example showing how to set up a multi-worker architecture:
Parent Process (Dashboard Server)
import { serve } from 'bun'
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'
import { createServer } from 'duron/server'
import { getHTML } from 'duron-dashboard/get-html'
// Dashboard server: Only serves the API
const client = duron({
id: 'dashboard-server',
syncPattern: false, // Workers handle job processing
database: postgresAdapter({
connection: process.env.DATABASE_URL!,
}),
actions: {
sendEmail,
processOrder,
},
})
await client.start()
// Create the API server
const app = createServer({ client })
// Spawn worker processes
const workerCount = parseInt(process.env.WORKER_COUNT || '2', 10)
const workers: Bun.Subprocess[] = []
for (let i = 1; i <= workerCount; i++) {
const worker = Bun.spawn(['bun', 'worker.ts'], {
cwd: import.meta.dir,
env: {
...process.env,
WORKER_ID: `worker-${i}`,
},
stdout: 'inherit',
stderr: 'inherit',
})
workers.push(worker)
client.logger.info(`Started worker ${i} (PID: ${worker.pid})`)
}
// Handle graceful shutdown (Ctrl+C, or SIGTERM from a process manager)
const shutdown = async () => {
client.logger.info('Shutting down...')
// Stop all workers (SIGTERM: each worker stops gracefully)
for (const worker of workers) {
worker.kill()
}
// Wait for workers to exit
await Promise.all(workers.map((worker) => worker.exited))
// Stop the client. stop() rejects when cleanup does not finish.
try {
await client.stop()
} catch (error) {
client.logger.error({ error }, 'Dashboard server did not stop cleanly')
}
process.exit(0)
}
process.once('SIGINT', shutdown)
process.once('SIGTERM', shutdown)
// Start the server
const port = parseInt(process.env.PORT || '3000', 10)
serve({
port,
routes: {
'/': async () => {
const html = await getHTML({
url: `http://localhost:${port}/api`,
enableLogin: false,
showLogo: false,
})
return new Response(html, {
headers: { 'Content-Type': 'text/html' },
})
},
'/api/*': app.fetch,
},
})
client.logger.info(`🚀 Dashboard server running at http://localhost:${port}`)Worker Process
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'
// Unique per running process. Not `worker-${process.pid}`: in containers every PID is 1.
const workerId = process.env.WORKER_ID || `worker-${crypto.randomUUID()}`
const client = duron({
id: workerId,
syncPattern: 'hybrid',
database: postgresAdapter({
connection: process.env.DATABASE_URL!,
}),
actions: {
sendEmail,
processOrder,
},
logger: 'debug',
recoverJobsOnStart: true,
heartbeatInterval: 5_000, // Liveness heartbeat every 5s (default)
heartbeatTimeout: 15_000, // Consider dead after 15s (default)
})
await client.start()
client.logger.info(`✅ Worker ${workerId} started and ready to process jobs`)
// Stop gracefully on Ctrl+C and on SIGTERM (sent by `worker.kill()`, process managers and
// orchestrators): unfinished jobs return to the queue for the other workers.
const shutdown = async () => {
client.logger.info(`Shutting down worker ${workerId}...`)
try {
await client.stop()
} catch (error) {
client.logger.error({ error }, 'Worker did not stop cleanly')
}
process.exit(0)
}
process.once('SIGINT', shutdown)
process.once('SIGTERM', shutdown)Claim Admission and Group Capacity
The built-in PostgreSQL and PGLite adapters claim jobs with one SERIALIZABLE transaction per fetch. The latest unexpired job for each action name and group key supplies the concurrency limit. The latest unexpired job of each action supplies the action limit (the action's concurrency option; none when it is not set). The claim first selects, without row locks, the oldest created jobs of each group that fit in its free slots (its limit minus its active jobs), and of those, the oldest of each action that fit in the action's free slots (its limit minus its active jobs in all groups). The older jobs of a full group or of an action at its limit therefore never keep younger jobs of other groups or actions from being claimed. It then row-locks those candidates, oldest first, with SKIP LOCKED until the batch is full. A claim therefore locks only the jobs it claims, not the whole backlog. A candidate that another transaction holds (for example a concurrent cancel) is skipped and still uses its group's slot in that claim. Claimed jobs are returned, and their handlers can start, only after the transaction commits.
Before its claim statement, each claim transaction locks the schema's claim_lock table, an empty table that only serves this purpose (LOCK TABLE ... IN EXCLUSIVE MODE). The claims of all workers on a schema therefore run one at a time, in the order they asked for the lock. A claim holds the lock for a few milliseconds (about 60 ms with a backlog of 50,000 jobs). Taking the lock does not start the transaction's snapshot, so each claim sees the jobs that the previous claims took: concurrent workers do not claim the same jobs, do not claim more than a group's or an action's limit, and do not abort each other's claims. A claim waits at most 1 second for the lock (SET LOCAL lock_timeout; the timeout also bounds any other lock wait of the claim transaction, for example while DDL locks a job table). This leaves room for more than 15 claims queued ahead of it even with a large backlog. When the wait times out (SQLSTATE 55P03), the transaction rolls back and the fetch returns no jobs. This is logged at debug level, is not retried, and is not a failure: automatic discovery treats it as an empty claim, without a cooldown.
A worker can stop between taking the lock and committing, for example when its process is paused, its VM is suspended or its network is lost. While it holds the lock, every claim on the schema waits 1 second and returns no jobs. To bound this, the PostgreSQL adapter's claim transaction also sets SET LOCAL idle_in_transaction_session_timeout = '5s': when the claim session waits more than 5 seconds for its client's next statement, PostgreSQL ends that session (SQLSTATE 25P03), the claim rolls back with nothing claimed, and the lock is free again. So a stalled worker stops all claims on the schema for about 5 seconds, not until TCP keepalive ends its session (about 2 hours by default). A normal claim waits for its client only for a few round trips, far below 5 seconds; the timer does not run while a statement runs or waits for a lock. A worker whose own event loop is blocked for more than 5 seconds during a claim loses that claim: its fetch fails with a connection error, the jobs stay claimable, and automatic discovery logs the error and waits one pullInterval. Both settings are LOCAL to the claim transaction and do not change the session. A lower lock_timeout or idle_in_transaction_session_timeout that you configured (for the server, database or role, or in the connection options) is kept: the adapter reads both settings once at startup and uses the lower of each and Duron's bound (1 and 5 seconds). The PGLite adapter has one in-process session, so it does not set the idle timeout.
Because the claims on a schema run one at a time, the claim lock limits the claim rate of all workers on that schema together to about one claim per claim duration. A claim takes a few milliseconds on a small backlog, so hundreds of claims per second, and about 17 to 57 ms with a backlog of 50,000 created jobs, so about 17 to 60 claims per second (measured on PostgreSQL 16 and 19 for one claim of 10 jobs). Each claim takes up to its batch size of jobs, so the job start rate of the fleet is at most about that rate times the batch size. Larger batches raise this ceiling. When more claims queue than finish within 1 second, the claims at the end of the queue return empty after the lock timeout and are made again later.
The SERIALIZABLE isolation remains a safety net for claims that do not take the claim lock, such as a worker running an older Duron version. When such a claim and a built-in claim would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE 40001), either during the claim statement or at COMMIT. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible.
The fetch retries a claim rejected with 40001 up to 5 times. Each retry is a new transaction, so it sees the claims that committed in the meantime. It starts after a random delay that grows with each retry (exponential backoff with full jitter): up to 10, 20, 40, 80 and then 160 ms, so the waits add at most 310 ms to a claim, plus the time of the retried transactions themselves. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual client.fetch() or adapter.fetch() call rejects, and automatic discovery logs the failure once, waits one pullInterval, and then makes a new claim; notifications and queued client.fetch() calls also wait for that cooldown. Once stop() has begun, no new retry starts and a pending wait ends at once: the claim rejects with its conflict, and that shutdown failure is logged at debug level instead of error. Other claim errors are not retried. Handle the rejection of a fetch() you start without awaiting.
Limits of this protection:
-
Only built-in claims participate. A worker running an older Duron version (which does not take the claim lock), a custom
_fetchoverride or direct SQL that claims underREAD COMMITTEDcan still exceed a limit when it runs concurrently. During a rolling upgrade, claims of older workers can also conflict (40001) with claims of upgraded workers, as before. Mixing versions is safe: theSERIALIZABLEisolation still keeps every claim within its group limits and claims every job once. It can be slower until all workers are upgraded: an older worker's claim row-locks every eligible job until it commits, and upgraded claims skip those jobs (see Upgrading to the claim lock). -
SQL
now()in a claim is the claim transaction's start time, before any wait for the claim lock, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs'startedAtandexpiresAt. -
The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior.
-
If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed.
-
Driver version: Duron is tested with postgres.js 4.2.0 and supports 4.1.1 or later. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers; those reproductions were not repeated on 4.2.0, where the native test suite passes. Applications that pin postgres.js 3.x keep both:
- If the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned.
- After
stop(), work still waiting for a pooled connection can open a new connection that the stopped adapter does not close. That idle session stays open until the driver'smax_lifetimecloses it (a random 30 to 60 minutes by default) or the process exits.
With 4.1.1 and 4.2.0, work queued while the adapter closes after a lost connection has not been verified.
-
PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation.
Worker Discovery
Each Client with actions runs one discovery at a time (startup pass, periodic checks every pullInterval, notifications and client.fetch() calls share one queue) and claims at most batchSize jobs outstanding. Notifications only make discovery faster: periodic checks find work whose notification was lost. See How it works: worker discovery.
Cancellation and Stored Steps
Cancelling a job in the database archives the job as cancelled and archives every one of its steps as cancelled, including steps that had already completed or failed. On PostgreSQL, a cancellation that commits keeps every step committed before it took the job, and no step for that job can be created while it runs. A step creation that arrives while the cancellation holds the job waits for it and then returns null (the existing "job is not active" result) instead of failing with a foreign-key error. A step creation that took the job first makes the cancellation wait, and its step is archived as cancelled. A step status write that reaches its step first succeeds and is then overwritten to cancelled; one that arrives later waits and returns false.
The same row lock orders cancelJob, completeJob and failJob on one job: the first to lock it wins and the others return false. Recovery skips a job that one of them holds. A claim also skips a created job that a cancellation holds, and a claim whose snapshot predates a committed cancellation of its candidate fails with 40001 and is retried as described above.
A call that waited rechecks its existing conditions against the latest version of the job. This changes two outcomes when recovery requeues a job whose owner looks dead:
- A late step creation from the previous execution returns
null. - A late
completeJoborfailJobfrom the previous execution returnsfalse, and the requeued job stays requeued and can run again.
If the late call locks the job first, it wins and recovery skips the job. These are rechecks of the existing conditions, not ownership or execution fencing: after time travel or a new claim, a stale handler can still create steps and update reset steps with their old IDs.
Limits:
- The guarantees hold when the effective transaction isolation is
READ COMMITTED(the PostgreSQL default) and only for the built-in writers. Duron does not set the isolation level. Under a differentdefault_transaction_isolation, these locks can raise serialization errors earlier, and behavior has not been analyzed. Workers on an older Duron version, custom adapter overrides and direct SQL do not participate. - They describe the stored result as of the cancellation's commit, until a later time travel, prune or reset changes the job. A time travel that returns
false(for example for an unknown step) rolls back completely: the job and its steps stay archived as they were, so the job can still be retried, time-traveled to an existing step or pruned. - A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived
finishedAtandupdatedAtare the database time at the transaction's start (now()), before any wait. - Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select).
completeJobandfailJobcan wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them.client.stop()observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. - Recovery's own step handling, including steps created while recovery runs, is described in Recovery and concurrent steps.
- This is storage behavior only.
client.cancelJob()aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere: it continues until a step write returns "not active". A job this Client has claimed but not yet started (claim reply pending or queued locally) never starts its handler once acancelJob()call is admitted on this same Client; seecancelJob. Cancellations made through another Client or directly on the adapter do not suppress this Client's claimed or queued jobs: such a handler can still start and then fail when step creation returnsnull. - PGLite runs one statement at a time; it shows the same sequential results, not concurrent locking behavior.
Job Recovery
Duron uses heartbeat-based liveness detection for crashed-instance recovery:
- Heartbeat: Each instance periodically upserts a liveness record in the
clientstable (everyheartbeatInterval). PostgreSQL and PGLite use SQLnow()for both the first write and subsequent updates. - Periodic recovery: A worker with configured actions runs recovery during a discovery turn once more than
recoverJobsIntervalhas elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Without startup recovery, the first discovery turn recovers. A failed recovery skips that turn's claim and applies thepullIntervalcooldown; later turns claim as usual. There is no separate recovery timer: automatic workers check at everypullInterval, and withsyncPattern: falseonlyclient.fetch()calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see Worker Discovery). SettingrecoverJobsIntervalto0disables periodic recovery. - On startup: When
recoverJobsOnStartis enabled, a worker recovers eligible jobs for its configured actions during startup. - Dead detection: A foreign owner is fresh only when
last_seen_at > now() - heartbeatTimeout. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners.- Own jobs: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed
cancelJobbefore the handler started, a failed finalcompleteJob/failJobwrite, or a failed cancellation write of a running job that was aborted (that job is requeued and runs again). A job this worker holds is never requeued; a job claimed by a directclient.database.fetch()is not held, so it can be. Use one adapter instance per Client; a second Client constructor on an adapter that a Client already uses throws aTypeError, also when that Client was stopped (a stopped adapter cannot start again). - Direct calls: A direct
client.database.recoverJobs()call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. The jobs a Client holds are not arecoverJobsoption. On an adapter that no Client uses, a direct call includes the adapter's own ID entirely, so it also requeues jobs that this adapter claimed and is still running. WithrecoverJobsOnStart: falseandrecoverJobsInterval: 0, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them.
- Own jobs: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed
- Recovery behavior:
- Expired jobs (exceeded timeout): Archived as failed with error information
- Stuck jobs (not expired): Reset to
createdstatus and can be picked up by any worker
Trade-off: a job of this client that is lost locally while the process keeps running (for example, its handler promise never settles) is not rescued by periodic recovery. Its own timeout and expiry handling still applies, and another process that later starts with the same ID rescues it once at startup.
Recovery and concurrent steps
On PostgreSQL, each recovery phase (expired archival, then requeue) runs in its own transaction. It first locks the eligible jobs, skipping jobs another transaction holds, and then archives or requeues only those jobs in a second statement. That statement sees every step committed before the job was locked:
- A requeue that discards steps (job checksum not retained) deletes them all, so the next run cannot recover a step from the discarded execution.
- Expired archival archives every such step before the job's active rows are deleted. A step ID that a step creation returned is in active or archive storage.
- A step creation that holds the job when recovery locks it makes recovery skip that job until a later pass. A step creation that arrives after the lock waits and then returns
null.
Limits:
- The guarantees hold only under effective
READ COMMITTEDisolation (the PostgreSQL default) and only for the built-in writers. Duron does not set the isolation level. Other isolation levels have not been verified. Custom_recoverJobsoverrides, workers on older Duron versions and direct SQL do not take part. - This covers which steps are archived or deleted, not their versions. A step status write can still commit while recovery copies its steps, and the copy can then have the earlier version. It is not ownership or execution fencing.
- Each phase uses its own transaction start time for expiry checks and written timestamps. A job that expires after archival starts and before requeue starts is handled by a later pass. A failure or shutdown between the two statements rolls that phase back and rejects
recoverJobs. A phase that already committed stays committed. - Recovery holds its job locks until the phase commits, with no deadline. It needs a few more database round trips than a single statement.
After a successful drain, shutdown deletes the instance's liveness row before closing its database resources. Other instances can then discover eligible jobs on their next recovery pass without waiting for heartbeat staleness. If admitted work does not drain, Duron withholds that deletion and reports incomplete shutdown. A failed deletion is not reported as a successful release; existing staleness recovery still applies to a retained row.
Heartbeat clock and failure limits
The initial heartbeat must succeed before Client startup can succeed. Startup failure triggers automatic cleanup. A periodic heartbeat failure is logged through the configured logger, is nonfatal, and is retried at the normal heartbeat cadence only while running. During stop(), the heartbeat continues at the same cadence until every job of the Client is completed, failed, cancelled or released, then stops before the liveness row is deleted. A drain longer than heartbeatTimeout therefore does not let other workers recover a job that still runs. No beat is sent after the admitted-work drain ends, also when it exceeds shutdownTimeout.
SQL now() is transaction-start time, not continuously advancing wall time or commit time. Using it removes the application-clock offset from new heartbeat writes, but does not provide an execution lease or prevent duplicate effects. Delayed or failed writes, event-loop stalls and SQL clock movement can still affect recovery. Native SQL precision and the strict freshness comparison are preserved. Existing rows are not migrated; an ordinary heartbeat can replace a legacy future timestamp with an earlier SQL timestamp.
Job complete/fail/cancel timestamps (finishedAt) also use SQL now(), like claim, step and recovery timestamps. The cutoff of a relative prune duration (olderThan: '30d') is computed from the application clock. Recorded timestamps need not be monotonically ordered under clock offset or movement.
Notification Hints
Notifications are advisory hints, not durable events: a lost hint is found by periodic discovery or pending-wait reconciliation. See How it works: notification hints.
Lifecycle and Shutdown
client.stop() closes admission at once, aborts running handlers and returns the jobs that do not finish to the queue for the other workers. Each of its four phases (startup settlement, admitted-work drain, database cleanup, owned close) has the shutdownTimeout budget. See How it works: shutdown.
Best Practices
Worker IDs
Every running process must use its own Client id. Recovery treats the jobs of its own id that this Client does not hold as leftovers of an earlier process, and requeues them. If two running workers share an id, each recovery (on start and every recoverJobsInterval) requeues the jobs the other worker is running, so those jobs run twice.
// Good: unique per process (the default when `id` is omitted is also a random UUID)
id: `worker-${crypto.randomUUID()}`
// Good: host name, PID and a random part
id: `worker-${os.hostname()}-${process.pid}-${crypto.randomUUID()}`
// Good only if no two running processes ever get the same value (for example a StatefulSet pod name)
id: process.env.WORKER_ID
// Avoid: not unique. Containers usually run the worker as PID 1, so every replica is `worker-1`
id: `worker-${process.pid}`A stable id that is reused only after the previous process ended (such as a StatefulSet pod name) lets startup recovery rescue that process's leftover jobs at once. With a random id, other workers rescue them once the old process's heartbeat goes stale (heartbeatTimeout).
Heartbeat Settings
Configure heartbeat timing based on your deployment:
heartbeatInterval: How often to send a heartbeat (default: 5s)heartbeatTimeout: When to consider a client dead (default: 15s)
heartbeatInterval: 5_000, // Send heartbeat every 5s
heartbeatTimeout: 15_000, // Consider dead after 15sKeep heartbeatTimeout at least 3x heartbeatInterval to tolerate occasional missed beats.
Resource Management
- Separate dashboard and workers: Run dashboard/server in a separate process to avoid resource competition
- Monitor worker health: Use process managers (PM2, systemd, etc.) to restart failed workers
- Graceful shutdown: Handle
SIGINT/SIGTERM, awaitclient.stop(), and report cleanup failures. Unfinished jobs return to the queue for the other workers; make steps honor theirsignalso that handlers end withinshutdownTimeout, and keep the orchestrator's grace period (for example Kubernetes'terminationGracePeriodSeconds) above the stop's phases (up to fourshutdownTimeoutbudgets). The stopping worker keeps its heartbeat while it drains, soshutdownTimeoutcan exceedheartbeatTimeout. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence.
Scaling
- Horizontal scaling: Add more worker processes to handle increased load
- Vertical scaling: Increase resources for individual workers if needed
- Load balancing: Jobs are automatically distributed across available workers
Troubleshooting
Jobs Not Being Processed
If jobs aren't being processed:
- Check worker status: Verify workers are running and connected to the database
- Check sync pattern: Ensure workers have
syncPattern'hybrid','push'or'pull'(notfalse), and thatpullIntervalis not larger than the delay you can accept for work whose notification was lost - Check outstanding work: Automatic claims pause while
batchSizeclaimed jobs are still outstanding; a stuck handler keeps its slot until it settles - Check database connection: Verify all processes can connect to the database
- Check logs: Look for errors in worker logs
Jobs Stuck in Active Status
If jobs remain in active status:
- Check heartbeat settings: Ensure
heartbeatTimeoutis appropriate (default: 15s) - Manual recovery: Use
client.database.recoverJobs({ checksums })to recover stuck jobs of other workers manually (it skips this worker's own ID; see Job Recovery)
Duplicate Job Processing
If jobs are processed multiple times:
- Check worker IDs: Ensure each running worker has its own ID (shared IDs make recovery requeue a peer's running jobs)
- Check database isolation: Verify database connection isolation
- Check concurrency limits: Review group concurrency limits
Environment Variables
Common environment variables for multi-worker setups:
# Database connection
DATABASE_URL=postgres://user:password@localhost:5432/duron
# Server configuration
PORT=3000
# Worker configuration
WORKER_COUNT=2
WORKER_ID=worker-1 # Set automatically for each worker
See Also
- Client API - Complete client configuration reference
- Examples - More code examples
- Adapters - Database adapter configuration