How it works
Guarantees and internals behind the Client options, shutdown, notifications and archive retention
This page collects the detailed behaviour behind the options of the Client API and the adapters: what Duron guarantees, and what it does not. The option pages give the short version.
Worker discovery
Each Client with actions coordinates its own job discovery:
- One discovery at a time. The startup pass, periodic checks, notifications and
client.fetch()calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. - Safety in every mode. With
syncPattern'push','hybrid'or'pull', the Client discovers work immediately after startup and then everypullInterval. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a job expires or after another worker frees a group slot is found by the next periodic check. - Bursts and group-limited backlogs. Claims of all workers run one at a time, and the workers that took the rest of a burst received the same notifications, so a claim that returns some but fewer than the notified jobs is not followed up. An empty claim (for example after a claim lock timeout) while more than one notification is uncovered is followed up after a random 10–50 ms delay, at most twice in a row. While this Client's claims leave jobs uncovered (for example because their group is full), each of its jobs that settles makes it look for work again, so a backlog limited by a group that this Client's jobs fill drains about as fast as they finish instead of at the group limit per
pullInterval. A group slot freed by another worker is found by that worker or by the next periodic check. See Claim ceiling. - Automatic claim ceiling. Automatic claims stop while this Client has
batchSizeclaimed jobs outstanding (claimed, queued, running or finishing). See Claim ceiling for how this differs fromactionConcurrencyLimitand SQL group limits. - Recovery does not pause claiming. When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see Job Recovery).
- Failures. After a failed discovery or recovery attempt, all discovery waits one
pullInterval. Failed claims are never replayed.
This coordination is local to one Client. Other Clients, and direct calls such as client.database.fetch() or client.database.recoverJobs(), are not coordinated with it. A job claimed by a direct client.database.fetch() carries this Client's ID but is not held by the Client, so this Client's next startup or periodic recovery requeues it (or archives it as failed if it expired); see Job Recovery. Cross-worker group limits rely on the claim admission described above, not on this local coordination.
Claim ceiling (batchSize)
Below, B is the value of batchSize (default 10). Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. Claims of all workers run one at a time (see Claim Admission), so a claim that returned fewer jobs than it asked for found no more claimable jobs at that moment; it is not followed up. A claim that returned nothing (for example after waiting 1 second for the claim lock) while more than one notification is still uncovered is followed up after a random 10–50 ms delay, at most twice in a row (the second time after 50–250 ms): a third empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. A new notification or a claim that returns jobs allows them again. While this Client's last automatic claim left jobs uncovered (for example because their SQL group was full), every job that settles on this Client starts an open-ended automatic request, because its settlement can free a group slot; a job from a claim that did not cover its own request does so too. A backlog limited by a group that this Client's jobs fill therefore drains about as fast as those jobs finish, not at the group limit per pullInterval. A slot that another worker frees is found by that worker's own claims or by the next periodic check. A claim that covers its request, or an open-ended claim that finds nothing, ends this, so sparse traffic costs at most one extra claim, after a notification another worker won. For this ceiling, a positive finite value is floored and clamped to 1–Number.MAX_SAFE_INTEGER; other accepted values use 10.
B is not the number of handlers that run at once. That is actionConcurrencyLimit per action, so with the defaults (B = 10, actionConcurrencyLimit = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (groupConcurrencyLimit or groups.concurrency) and the action's concurrency option are separate limits across all workers. Jobs claimed by fetch() count toward B, and a fetch() batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate.
Periodic checks and cooldown (pullInterval)
pullInterval sets two independent schedules: periodic worker discovery (and its cooldown after a failure), and pending-wait reconciliation. For both schedules, a positive finite interval is floored and clamped to 1–2,147,483,647; other accepted values use 5000. getConfig() still returns the value you passed.
Periodic discovery is not reset or postponed by notifications or fetch() calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a 40001 serialization failure that persisted through the claim's 5 retries, from a concurrent claim of an older Duron version or a concurrent cancel; see Claim Admission and Group Capacity), every trigger waits one interval before the next claim, including notifications and queued fetch() calls. The failed claim is not replayed; the next claim is a new one.
Recovery
recoverJobsOnStart and recoverJobsInterval control when recovery runs. See also Job Recovery for liveness and multi-worker behaviour.
Startup recovery, like every recovery Duron runs for this Client, also rescues jobs that a previous process with the same Client id left active. When recoverJobsOnStart is false, the first periodic recovery does it instead. When recoverJobsOnStart is false and recoverJobsInterval is 0, Duron runs no recovery, so this Client never rescues these leftovers itself: a direct client.database.recoverJobs() call skips this Client's own id (see recoverJobsInterval). Other workers rescue them only once this Client stops and its heartbeat goes stale.
Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (performance.now(), whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the pullInterval cooldown applies; later turns claim as usual until the next recovery is due.
Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. It rescues other workers' abandoned jobs and this Client's own active jobs that it no longer holds locally, and it never touches a job this Client holds: claimed, queued behind actionConcurrencyLimit, running or writing its result, including a timed-out handler that still runs. So an own job that a rejected write left active is requeued and runs again, or is archived as failed if it expired, by the next recovery: a failed cancelJob before the handler started, a failed final completeJob/failJob write, or a failed cancellation write of a running job after its abort. A job claimed by a direct client.database.fetch() is not held either, so recovery requeues it too. This covers Duron's own startup and periodic recovery. A direct client.database.recoverJobs() call cannot see which jobs this Client holds, so it skips this Client's own id entirely and rescues only other owners. One recovery call can affect any number of jobs and has no time limit.
Recovery checks for:
- Expired jobs: Jobs that exceeded their timeout are archived as failed
- Stuck jobs: Jobs from unresponsive processes are reset to
createdstatus
Wait results
waitReadTimeout bounds each wait-result read chain.
The budget starts when a chain takes an actual slot, not while it waits in the Client FIFO. It covers pool acquisition, status/detail and active/archive reads, processing, and cleanup observation without resetting between stages. Initial participants settle null on expiry; established waiters remain pending. Late results are discarded, but actual capacity remains occupied until the underlying work and transaction cleanup settle.
Built-in PostgreSQL wait reads use a transaction-bound database context with READ COMMITTED isolation and a transaction-local remaining statement_timeout, preserving stricter inherited settings. Ordinary public reads and unrelated operations keep their settings. Pool waiting, initial setup, transport and rollback can outlast the observer; there is no active cancellation, reconnect, replacement client, or mutation replay. Transaction/setup round trips have overhead; no zero-cost or hard end-to-end deadline is promised.
Custom Client/Adapter read overrides remain real calls and may use an observation-only fallback. Their arbitrary internal SQL/JavaScript is not physically bounded by this option. PGLite has observer/continuation accounting, not PostgreSQL execution-timeout parity; synchronous WASM can delay timers. A blocked event loop can delay all observer/caller cancellation.
Notification hints
PostgreSQL and PGLite notifications are advisory hints, not durable events or acknowledgments of a mutation. After a successful validated create/retry/complete/fail/cancel/time-travel operation, both built-in SQL adapters await one hint attempt. A preparation or submission failure is reported through the configured adapter logger without replacing the original successful mutation result. No logger means no promised external error report. Errors include the original cause, backend/channel, stage and available job/client IDs, not the full payload.
A rejected notification reply does not prove nondelivery: listeners may already have received the hint. Duron does not automatically replay the mutation or retry the hint. Mutation, validation, startup and listener-registration failures still reject normally; custom adapter overrides and throwing custom loggers keep their own behavior. False/null mutation results do not produce a hint.
The whole ${schema}.${event} string is one exact channel, including dots, case and quotes. Built-in payloads remain {jobId} for availability and {jobId,status,clientId} for terminal status. Emission uses bound pg_notify arguments; native channel/text/payload limits still apply, with no truncation, renaming or chunking. PostgreSQL channels are limited to 63 bytes and payloads to fewer than 8,000 bytes in the tested default configurations. This transport handling does not establish full custom-schema migration support.
There is no ordinary notification deadline or background delivery queue. A stuck attempt can delay its caller even after the mutation commits. Shutdown observes it under the shared lifecycle budgets (see Shutdown); a timeout is not cancellation or proof of nondelivery. Notifications alone do not provide missed-event recovery. Periodic worker discovery and pending-wait reconciliation cover lost hints; recovery emits no notification and there are no recovery events.
Shutdown
What stop() does with running and claimed jobs, and how shutdownTimeout bounds it.
Releasing unfinished jobs
A graceful stop releases unfinished jobs instead of cancelling them:
- Each running handler is aborted: its steps'
signalaborts with anActionCancelError. Once the handler settles, a handler that still resolves completes its job normally: its output is validated (an invalid output fails the job), and the steps that the abort ended are storedcancelled(orfailed) in the same transaction as the completion. If that completion fails, none of these step statuses is stored and the job is returned to the queue, so its next run runs those steps again. A handler that rejects, for example because a step honored the abort, returns its job to the queue once its step callbacks have ended too, so the job does not run on another worker while its handler or a step callback still runs here. - A job that already ended before the stop reached it keeps its outcome: a handler that failed or timed out fails its job, a cancelled job is cancelled.
- Claimed jobs that have not started (queued behind
actionConcurrencyLimit, or claimed while the stop began) are returned to the queue too. - A returned job is
createdagain, without an owner, start or expiry, and ajob-availablenotification is sent, so any worker can claim it. A release never deletes its steps: the next run reuses completed steps (with their stored output) and runs again the steps that were running or waiting for a retry, whose retry count starts again at 0. Jobs have no attempt counter, so a release does not count as a failed attempt. - Unlike a release, recovery deletes the steps of a requeued job when the recovering worker does not know the job's action checksum (its handler code or
versionchanged). A claim does not compare checksums. So in a rolling deploy, a worker with the new code that claims a job released by an old worker reuses the outputs of the steps that the old code completed, matched by step name and parent step, and runs only the others. Keep step outputs compatible across versions, or give a step whose output changed a new name. - An explicit
cancelJob()still cancels: a job cancelled before or during the stop endscancelled, not released, also while the stop waits for its handler. - The drain waits for the handlers within
shutdownTimeout, and the Client keeps its heartbeat meanwhile. A handler or step that does not settle in time is not released: the stop rejects, the job staysactive, and recovery requeues it once this Client's liveness is gone (another worker's periodic recovery, or thisid's next startup).
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.
The stopping Client keeps its heartbeat (every heartbeatInterval) until each of its jobs is completed, failed, cancelled or released, so the drain can last longer than heartbeatTimeout: other workers do not recover a job that still runs here. A job whose handler or step does not settle within shutdownTimeout stays active: the heartbeat stops when the drain phase ends, and recovery requeues the job once this Client's liveness is gone.
stop() inside a handler or step
stop() can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for stop() itself; it still waits for everything else, including the calling job's own abort and cancellation write. The calling job is aborted and ends cancelled, not released, so it does not stop the next worker that would claim it. Code that runs in it after stop() resolves cannot issue database calls. The exclusion follows the handler's async context, not the await: a stop() started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits stop(). To stop and still wait for a handler, call stop() from outside it. The exclusion covers only the calling handler or step and the steps that enclose it. It never covers a sibling step, and it never crosses a job boundary: when job A enqueues job B and B calls stop(), the drain still waits for A's handler.
Phases and budgets
client.stop() closes admission immediately: it cancels scheduled discovery/prune timers (the heartbeat continues until the Client's jobs have ended, see Heartbeat clock and failure limits), discards pending automatic discovery, rejects queued client.fetch() calls that have not started, disables new event-driven work, settles pending waits with null, and aborts running handlers. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. Jobs that do not finish are returned to the queue (see Releasing unfinished jobs). It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler.
Client and Adapter share four shutdown phases, each with the budget set by the Client's shutdownTimeout option (5 seconds by default). Each budget applies to the whole phase, not separately to nested calls or individual resources:
| Phase | Work |
|---|---|
| Startup settlement | Observe already-issued initialization; skip remaining stages where safe |
| Admitted-work drain | Observe actual ordinary operations, callbacks and action/step work, and the job releases |
| Database cleanup | Attempt independent listener and liveness cleanup while SQL is usable |
| Owned close | Close owned query/listener clients or the PGLite engine |
Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately four budgets (twenty seconds by default) when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee.
After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls stop() itself is not waited for by the drain (see stop() inside a handler or step).
A timeout or cleanup failure rejects stop(). A sole error is preserved; multiple failures use AggregateError. Log and inspect the rejection rather than treating it as proof that resources closed or work stopped. Concurrent stop callers share cleanup. A later stop joins pending resource operations or retries only safe unfinished cleanup; it does not replay completed application work or allocate a replacement connection. Failed or withheld liveness deletion cannot be repaired after SQL has closed. A failed explicit unsubscribe remains an error for that attempt even if owned close subsequently releases its resources.
Failed startup is cleanup-only: Duron automatically attempts cleanup and does not restart that instance. Start calls after the terminal gate return false; use a fresh instance for another startup attempt. A superseded pending start cannot report success. Repeated successful stop returns true without repeating completed cleanup.
Archive retention
Configured with the adapters' pruneArchive option.
The scheduler attempts a pass immediately during startup, then at the configured interval. A tick skips if the previous acquisition, prune hook or unlock is still pending; skipped ticks are not queued. A contended lock also skips that pass. A prune error followed by a successful unlock is logged and permits the next normal tick. lastPrunedAt records successful scheduled hook completion, not successful unlock or proof of coordination.
PostgreSQL lock session and key
An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects that session; only a lost session is replaced by a new client (see below). Each pass acquires the schema's session-level advisory key (see below) and must receive a true unlock; the reservation is not returned between passes.
The key is derived from the adapter's schema: hashtextextended('duron:prune:' || schema, 0) (for the default schema, hashtextextended('duron:prune:duron', 0)). Adapters of the same schema coordinate; other Duron schemas in the same database, separate databases and application locks on other keys do not contend. Earlier versions used the constant key 42 for every schema. During a rolling upgrade, a worker of an earlier version (key 42) and an upgraded worker (the derived key) can prune the same schema at the same time; this is harmless, because a prune pass only deletes archived jobs older than its cutoff, and concurrent passes delete each row once. At worst, two passes lock the same rows in different orders and one of them fails with a deadlock error (40P01); Duron logs it, and the next tick retries. It ends when every worker is upgraded. DELETEs still run on the adapter's original query pool, including when that pool has max: 1. Custom _pruneArchive overrides remain in the dispatch path and can delegate to super._pruneArchive.
Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, idle_session_timeout, a pooler or load-balancer idle timeout, pg_terminate_backend), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so the key keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start, later ticks try again after a backoff that doubles from the interval up to five minutes. The backoff counts from the failure, and the tick nearest to the due time retries, so a tick that fires slightly early does not add an interval. The replacement never requested the lock, and a new attempt starts only after its close is confirmed, so the key keeps a single owner. The fault decides the log level:
- A connection or server startup fault (connection refused, reset or closed, a connect timeout, SQLSTATE class
08,57P01,57P02,57P03or57P05, also a session that closes between the bootstrap and the reservation) is logged as a warning, as during a failover. - Another fault, such as rejected credentials (
28P01) or a configuration error, is logged as an error on every attempt. The attempts continue, because the credentials can be restored. - A bootstrap result that does not prove the backend identity (malformed, or a reservation on another backend) retires scheduling, as on the first client.
A retirement during a stop is reported as an error, also the loss of an established session or a failed replacement: no later tick replaces the client, and the fault can be the stop's own close of the client.
A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee.
Manual pruning and failure limits
adapter.pruneArchive({ olderThan, batchSize, maxBatches }) remains outside scheduled coordination. Manual calls can overlap a scheduled pass or one another. olderThan accepts a duration string, a Date, or an absolute timestamp in milliseconds; rows with finished_at strictly before the cutoff are eligible. The returned count is the number of deleted jobs. Batches commit independently: a later failure does not roll back an earlier committed DELETE, and the library does not replay an issued DELETE. Future normal ticks can prune rows that remain eligible. Manual calls do not update the scheduled lastPrunedAt value.
Exclusion requires a healthy coordination session. After its loss, another scheduler can acquire the lock while an already-issued DELETE continues on the old owner's query pool. Observed loss gates subsequent library-controlled scheduled SQL, but it does not cancel issued SQL or arbitrary override code. There is no fencing, rollback, instantaneous loss detection, or failure-proof mutual exclusion promise, and no ordinary prune SQL/pass deadline.
Stop clears the timer immediately and uses the shared lifecycle's startup-settlement, admitted-work, database-cleanup and owned-close budgets. Healthy final cleanup returns the reservation once after settled work and confirmed unlock, then closes the isolated client. Uncertain ownership is not returned as reusable. A pending/rejected return cannot consume the independent close opportunity; a stop that joins an existing fault close does not restart its observer budget (shutdownTimeout). Observer expiry and fulfilled driver end() alone are not proof of physical release. Incomplete cleanup remains reported and tracked for later safe completion rather than being canceled or silently declared successful.