Skip to Content

Adapters

Learn about database adapters in Duron

Duron uses adapters to interact with different database backends. Adapters abstract away the database-specific implementation details, allowing you to use Duron with any supported database.

Available Adapters

PostgreSQL Adapter

The PostgreSQL adapter uses Drizzle ORM to interact with PostgreSQL databases.

import { postgresAdapter } from 'duron/adapters/postgres'

const adapter = postgresAdapter({
  connection: process.env.DATABASE_URL || 'postgres://user:pass@localhost:5432/db',
  schema: 'duron', // Optional, defaults to 'duron'
  migrateOnStart: true, // Optional, defaults to true
})

Options:

  • connection - PostgreSQL connection string, or a postgres.js options object (for example { host, port, database, username, password, max }). Not a postgres() instance: the adapter creates its own clients.
  • schema - Database schema name (default: 'duron'). The built-in migrations create the duron schema only: for another schema, include Duron's tables in your own Drizzle schema and set migrateOnStart: false (see Integrating Duron Schema). With another schema and the built-in migrations, start() fails before it changes the database.
  • migrateOnStart - Whether to run migrations on startup (default: true). The Client option of the same name also applies: migrations run only when neither is false.
  • migrationsFolder - A folder of Drizzle migrations to apply on startup instead of the built-in ones, for example migrations generated from createSchema() for your schema. Its SQL runs unchanged and must create every table the adapter uses. The applied migrations are recorded in duron.migrations, whatever the schema: with another schema, this creates a duron schema that holds only the migrations table.
  • pruneArchive - Optional scheduled pruning of archived jobs (see Archive retention)

PGLite Adapter

The PGLite adapter extends the PostgreSQL adapter to work with PGLite (in-memory PostgreSQL). Perfect for development and testing.

import { pgliteAdapter } from 'duron/adapters/pglite'

const adapter = pgliteAdapter({
  connection: ':memory:', // or a file path for persistence
  schema: 'duron', // Optional, defaults to 'duron'
  migrateOnStart: true, // Optional, defaults to true
})

Options:

  • connection - ':memory:' for in-memory database, or a file path for persistence
  • schema - Database schema name (default: 'duron'; see the PostgreSQL adapter for other schemas)
  • migrateOnStart - Whether to run migrations on startup (default: true; see the PostgreSQL adapter)
  • migrationsFolder - Migrations to apply instead of the built-in ones (see the PostgreSQL adapter)
  • pruneArchive - Optional scheduled pruning of archived jobs (see Archive retention)

Using Adapters

Pass the adapter to the Duron client:

import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'

const client = duron({
  database: postgresAdapter({
    connection: process.env.DATABASE_URL!,
  }),
  actions: {
    sendEmail,
  },
})

Archive retention

Retention is opt-in for both adapters. Without pruneArchive, the adapter creates no prune timer or PostgreSQL lock client.

const adapter = postgresAdapter({
  connection: process.env.DATABASE_URL!,
  pruneArchive: {
    olderThan: '30d', // Keep the last 30 days
    intervalMs: 3_600_000, // Check once an hour
    batchSize: 1000, // Default
    maxBatches: 100, // Default per pass
  },
})

Each pass deletes the archived jobs (completed, failed or cancelled) whose finished_at is before the cutoff, together with their steps; waiting and running jobs are never touched. olderThan is a duration before now (a whole number followed by ms, s, m, h or d, for example '30d'), a Date, or a timestamp in milliseconds. A pass deletes at most batchSize × maxBatches jobs; the rest goes in the next pass.

The scheduler runs at a fixed interval, not at a time of day. To prune only in a window, for example at night, leave pruneArchive out and call client.pruneArchive() from your own scheduler:

// For example from a cron job that runs at 3:00
await client.pruneArchive({ olderThan: '30d' })

The scheduler attempts a pass immediately during startup, then at the configured interval; adapters of one schema coordinate with an advisory lock, so one of them prunes at a time. adapter.pruneArchive() prunes directly, outside that coordination. See How it works: archive retention for the lock session, its key, failure handling and manual pruning.

Database Schema

Duron creates the following tables in its schema (duron by default). Jobs and steps live in active tables while they wait or run, and move to archive tables when they finish (completed, failed or cancelled). Queries such as getJobs read both.

jobs_active and jobs_archive Tables

Store job information. Both tables have the same columns.

  • id - UUID primary key
  • action_name - Name of the action
  • group_key - Group key for concurrency control
  • description - Job description (nullable)
  • checksum - Checksum of the action definition
  • input - JSONB input data
  • output - JSONB output data (nullable)
  • error - JSONB error data (nullable)
  • status - Job status (created, active, completed, failed, cancelled)
  • timeout_ms - Timeout in milliseconds
  • expires_at - Expiration timestamp (nullable)
  • concurrency_limit - Concurrency limit for the group
  • concurrency_step_limit - Step concurrency limit for this job
  • action_concurrency_limit - Action concurrency limit (nullable: no action limit)
  • client_id - ID of the Duron instance that owns the job (nullable)
  • created_at - Timestamp
  • started_at - Timestamp (nullable)
  • finished_at - Timestamp (nullable)
  • updated_at - Timestamp

job_steps_active and job_steps_archive Tables

Store step information. The archive table also has job_finished_at, the time its job was archived.

  • id - UUID primary key
  • job_id - The step's job
  • parent_step_id - Parent step ID for nested steps (nullable)
  • parallel - Whether this step runs in parallel with siblings
  • name - Step name
  • output - JSONB output data (nullable)
  • error - JSONB error data (nullable)
  • status - Step status (active, completed, failed, cancelled)
  • timeout_ms - Timeout in milliseconds
  • expires_at - Expiration timestamp (nullable)
  • retries_limit - Maximum number of retries
  • retries_count - Current retry count
  • delayed_ms - Delay before next retry in milliseconds (nullable)
  • history_failed_attempts - JSONB record of previous failed attempts
  • created_at - Timestamp
  • started_at - Timestamp
  • finished_at - Timestamp (nullable)
  • updated_at - Timestamp

clients Table

One liveness row per running Client: client_id and last_seen_at, written by the heartbeat. Recovery uses it to find dead workers (see Job Recovery).

claim_lock Table

An empty table without columns. Each claim transaction locks it (LOCK TABLE ... IN EXCLUSIVE MODE) so that the claims of all workers on the schema run one at a time; it never holds rows. See Claim Admission and Group Capacity.

Migrations

The adapter runs Duron's migrations on startup unless its migrateOnStart option or the Client's migrateOnStart option is false (both default to true). The migrations ship in the package's migrations/postgres directory. They create the duron schema and its tables, and record what was applied in the duron.migrations table. They are only for the default duron schema: for another schema, manage the tables with your own migrations (see Integrating Duron Schema). If migrations would run at start with the built-in migrations and another schema, start() fails before it changes the database. New versions can add migrations; Upgrading lists the ones that need attention.

Instances that start at the same time migrate one at a time: each runs its migrations in one transaction that first takes a transaction-level advisory lock for the migrations schema (key hashtextextended('duron:migrate:duron', 0)). A later instance waits for the first one to commit, then finds the migrations applied and applies nothing, instead of failing on the concurrent creation of the same schema or tables. The lock is released when that transaction ends. The transaction is READ COMMITTED whatever default_transaction_isolation is, so the later instance sees the migrations that the first one committed while it waited. On PGLite the same transaction and lock run on its single session.

Contributors generate new migrations from packages/duron with:

bun run generate:postgres

Upgrading to the job listing indexes

The migration 20261130153037_silly_layla_miller adds six btree indexes that serve the job listing sorts by createdAt, startedAt and status, on both jobs_active and jobs_archive. It is the first migration that existing installations apply to populated tables.

Duron applies all pending migrations in one transaction. Each CREATE INDEX holds a lock on its table until that transaction commits, so writes to both jobs_active and jobs_archive are blocked until the whole migration finishes: creating jobs, claiming, completing, moving jobs to the archive and pruning wait; reads continue. In a rolling deploy, instances still running the previous version stall on every write for that time. The time grows with the size of the tables: about 0.3 seconds for 200,000 archived jobs in our tests, growing roughly linearly, so expect a minute or more for tens of millions.

For small tables nothing needs to be done. For large tables, either:

  • run the upgrade in a maintenance window, or start a single instance with migrateOnStart while the other instances are stopped; or
  • build the indexes beforehand without blocking writes. The migration creates them with CREATE INDEX IF NOT EXISTS under the same names, so with the indexes already in place it builds nothing and only takes the table locks briefly.

To build them beforehand, run these statements against the database while the current version keeps running. CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so run each statement on its own (for example with psql, which runs each -c statement in autocommit mode). The names, columns and collation must be exactly these:

CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_created_at_id" ON "duron"."jobs_active" ("created_at", "id");
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_started_at_id" ON "duron"."jobs_active" ("started_at", "id");
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_status_c_id" ON "duron"."jobs_active" ("status" COLLATE "C", "id");
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_created_at_id" ON "duron"."jobs_archive" ("created_at", "id");
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_started_at_id" ON "duron"."jobs_archive" ("started_at", "id");
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_status_c_id" ON "duron"."jobs_archive" ("status" COLLATE "C", "id");

A concurrent build that fails or is cancelled leaves an invalid index with that name, and IF NOT EXISTS would then skip it. Before upgrading, check that all six indexes are valid:

SELECT c.relname, i.indisvalid
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'duron' AND c.relname IN (
  'idx_jobs_active_created_at_id', 'idx_jobs_active_started_at_id', 'idx_jobs_active_status_c_id',
  'idx_jobs_archive_created_at_id', 'idx_jobs_archive_started_at_id', 'idx_jobs_archive_status_c_id'
);

For any row with indisvalid = false, run DROP INDEX CONCURRENTLY "duron"."<name>"; and run its CREATE INDEX CONCURRENTLY statement again.

If you manage Duron's tables with your own Drizzle migrations (see below), the generated migration contains plain CREATE INDEX statements in your schema: the same locking applies, and you can pre-build the indexes the same way in your schema and add IF NOT EXISTS to your migration.

Upgrading to the claim lock

The migration 20261202120334_silent_thunderbolt creates the empty claim_lock table. It touches no existing table and takes no lock on the job tables, so it applies at once on any table size and needs no preparation or maintenance window (no concurrent pre-build). Upgraded instances lock this table in every claim; instances of the previous version do not, so during a rolling upgrade their claims are protected only by SERIALIZABLE (claims of both versions can abort each other with 40001 and are retried) until every instance is upgraded. Running both versions is safe: group limits hold and every job is claimed once. Claims can be slower until the rollout ends: a claim of the previous version row-locks every eligible job until it commits, upgraded claims skip those jobs, and upgraded workers do not follow up a short claim at once, so they can wait for a job settlement or the next pullInterval to claim the rest.

LOCK TABLE ... IN EXCLUSIVE MODE requires the UPDATE, DELETE or TRUNCATE privilege on claim_lock (or MAINTAIN on PostgreSQL 17 and later), or ownership of the table. If your workers connect with a different role than the one that runs the migrations, and you grant privileges per table (for example a one-time GRANT ... ON ALL TABLES IN SCHEMA duron, without default privileges), grant the new table to the worker role after the migration, before you start upgraded workers. Otherwise every claim fails with SQLSTATE 42501 (insufficient privilege), and no job is claimed:

GRANT UPDATE ON "duron"."claim_lock" TO <worker_role>;

If you manage Duron's tables with your own Drizzle migrations, export claimLockTable from createSchema() too (see below) and generate a migration: the adapter locks the claim_lock table of its schema in every claim, so claims fail until that table exists.

Integrating Duron Schema into Your Own Drizzle Schema

If you're already using Drizzle ORM in your project and want to manage all migrations together, you can include Duron's schema in your own Drizzle schema instead of using Duron's automatic migrations. This is also the way to use a schema other than duron: the built-in migrations create only the duron schema.

Step 1: Import and Include Duron's Schema

In your Drizzle schema file (e.g., schema.ts), import createSchema from Duron and include the tables:

import { pgTable } from 'drizzle-orm/pg-core'
import createSchema from 'duron/adapters/postgres/schema'

// Create Duron's schema with your desired schema name
const {
  schema: jobsSchema,
  jobsActiveTable,
  jobsArchiveTable,
  jobStepsActiveTable,
  jobStepsArchiveTable,
  clientsTable,
  claimLockTable,
} = createSchema('jobs')

// Export all of them so Drizzle Kit creates the schema and every table the adapter uses
export {
  jobsSchema,
  jobsActiveTable,
  jobsArchiveTable,
  jobStepsActiveTable,
  jobStepsArchiveTable,
  clientsTable,
  claimLockTable,
}

// Also export your other tables
export const users = pgTable('users', {
  // ... your table definition
})

Note: The schema name you pass to createSchema() (e.g., 'jobs') must match the schema option you provide to the adapter. createSchema() uses a Drizzle pgSchema(), so the name cannot be 'public'.

Step 2: Configure the Adapter

When creating the adapter, set migrateOnStart: false to disable Duron's automatic migrations:

import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'

const client = duron({
  database: postgresAdapter({
    connection: process.env.DATABASE_URL!,
    schema: 'jobs', // Match the schema name used in createSchema
    migrateOnStart: false, // Disable automatic migrations
  }),
  actions: {
    sendEmail,
  },
})

With a schema other than duron and migrateOnStart left on, start() fails before it changes the database, with an error that points to this section.

Step 3: Generate and Run Migrations

Since you've disabled Duron's automatic migrations, you'll need to generate and run migrations using your own Drizzle Kit configuration:

  1. Configure Drizzle Kit to include your schema file:
// drizzle.config.ts
import { defineConfig } from 'drizzle-kit'

export default defineConfig({
  schema: './schema.ts', // Your schema file that includes Duron's tables
  out: './drizzle',
  dialect: 'postgresql',
})
  1. Generate migrations using Drizzle Kit:
drizzle-kit generate
  1. Run migrations using your preferred method (e.g., Drizzle Kit, a migration tool, or manually):
drizzle-kit migrate

When you upgrade Duron, generate a migration again: new versions can change Duron's tables (see Upgrading).

Benefits

  • Unified migrations: All your database migrations (including Duron's) are managed in one place
  • Better control: You have full control over when and how migrations are run
  • Schema consistency: Duron's tables are part of your main schema, making it easier to manage relationships and queries

Important Notes

  • Make sure the schema option in the adapter matches the schema name you pass to createSchema()
  • Always set migrateOnStart: false when using this approach
  • Export the schema object and all six tables (jobsActiveTable, jobsArchiveTable, jobStepsActiveTable, jobStepsArchiveTable, clientsTable and claimLockTable) from your schema file, so that Drizzle Kit creates the schema and every table the adapter uses

Custom Adapters

You can create custom adapters by extending the Adapter class:

import { Adapter } from 'duron/adapter'
import type {
  CreateJobOptions,
  FetchOptions,
  Job,
  ReleaseJobOptions,
  // ... other types
} from 'duron/adapter'

export class MyCustomAdapter extends Adapter {
  protected async _start() {
    // Initialize your database connection
  }

  protected async _stop() {
    // Database cleanup while SQL is still usable (for example delete the liveness row)
  }

  protected async _createJob(options: CreateJobOptions): Promise<string | null> {
    // Implement job creation
  }

  protected async _fetch(options: FetchOptions): Promise<Job[]> {
    // Claim up to options.batch jobs
  }

  protected async _releaseJob(options: ReleaseJobOptions): Promise<boolean> {
    // Optional: return an active job of this adapter's id to the queue (see below)
  }

  // ... implement the other abstract methods
}

Adapter methods

The public methods validate their options and results, start the adapter on first use, refuse work after stop(), log errors and send notifications. Each calls the protected method of the same name with a leading underscore, which a custom adapter implements.

GroupPublic method (calls _<name>)
Lifecyclestart(), stop(), heartbeat()
JobscreateJob, completeJob, failJob, cancelJob, releaseJob, retryJob, timeTravelJob, deleteJob, deleteJobs, fetch, recoverJobs
StepscreateOrRecoverJobStep, completeJobStep, failJobStep, delayJobStep, cancelJobStep
QueriesgetJobById, getJobSteps, getJobs, getJobStepById, getJobStatus, getJobStepStatus, getActions
ArchivepruneArchive, truncateArchive, getArchiveStats

All these _<name> methods are abstract except _releaseJob, and so is _notify(event, data), which sends a notification. Optional protected hooks:

  • _releaseJob(options) - default releases nothing and returns false (see below)
  • _finishesStepsWithJob - getter, default false (see below)
  • _heldJobIds(options) - helper for a custom _recoverJobs (see below)
  • _close() - releases owned resources (connections) after database cleanup, also when cleanup fails
  • _canCleanup() - whether _stop() can still run SQL

The adapter also has setId(id), setLogger(logger), setMigrateOnStart(migrateOnStart), the id and logger getters, and emits job-available and job-status-changed events. The Client calls setId, setLogger and setMigrateOnStart; do not call them on an adapter that a Client uses.

The Client passes its migrateOnStart option with setMigrateOnStart(), and the adapter reads it in the protected getter clientMigrateOnStart (true when no Client set it). An adapter that runs migrations in _start() must run them only when clientMigrateOnStart is true and its own option allows them, so that false on either one turns them off. The PostgreSQL and PGLite adapters do this; a custom adapter that ignores clientMigrateOnStart ignores the Client option.

Claims, locking and recovery

Adapter.fetch() dispatches to your _fetch override, and so does Client.fetch() when the Client has actions configured. A custom _fetch is responsible for its own cross-worker capacity safety; it only receives the built-in claim lock and SERIALIZABLE protection when it delegates to the built-in PostgreSQL/PGLite _fetch (see Multi-Worker Setup).

Likewise, the built-in cancellation storage locking covers only _cancelJob, _completeJob, _failJob and _createOrRecoverJobStep as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see Cancellation and Stored Steps). A custom _recoverJobs likewise does not take part in recovery's per-phase locking (see Recovery and concurrent steps). For its own recoveries, the Client tells the built-in _recoverJobs which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom _recoverJobs keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A custom _recoverJobs that does not delegate can apply the same exclusion with the protected _heldJobIds(options), passing the options object it received: an array means "include the adapter's own id, except these held jobs" ([] for a direct call on an adapter without a Client), and null means "skip the adapter's own id". A direct recoverJobs() call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs.

A subclass of the PostgreSQL or PGLite adapter that opens its own transactions must use the protected this._transaction(work, config?), as every built-in transaction does. It checks the adapter's stop gates before BEGIN, at the start of work and after work, so a transaction whose callback completes after stop() drained the adapter rolls back instead of committing. A direct this.db.transaction() does not get these checks. Nested tx.transaction() savepoints run inside the outer callback and are not checked separately.

Shutdown: releases and final step statuses

A graceful Client.stop() returns the jobs it did not finish to the queue through releaseJob(), which calls _releaseJob({ jobId }). The built-in adapters set the job back to created (start, expiry and owner cleared) when it is still active, owned by this adapter's id and not expired, and keep its steps. The default _releaseJob of the Adapter class releases nothing and returns false, and the Client logs a warning for each job it could not release. This changes the behavior of a custom adapter that does not override it: before releases existed, stop() cancelled the running jobs (_cancelJob), and only claimed jobs that had not started stayed active. Now neither kind is cancelled: both stay active with this adapter's id until recovery requeues them (another worker's recovery once this adapter's liveness row is deleted or stale, or a startup recovery with the same id). Override _releaseJob to return them to the queue at once.

When a stopped job's handler still resolves (or its output fails validation), the steps that the abort ended are written with the job: completeJob and failJob take an optional steps list ({ stepId, status: 'cancelled' | 'failed', error? }). The built-in adapters return true from the protected getter _finishesStepsWithJob, and their _completeJob and _failJob write those steps in the transaction that ends the job, after the job row lock, so a job that does not end keeps its steps unchanged. The default of the Adapter class returns false, and then nothing changes for a custom adapter: completeJob and failJob first write each step with _cancelJobStep or _failJobStep, then call _completeJob or _failJob without steps. That is not atomic: if the job write then fails, the stop returns the job to the queue with those steps already cancelled or failed, and its next run fails on such a step (Cannot recover a cancelled step) unless the handler catches that. To make it atomic, apply options.steps in your _completeJob and _failJob (only to steps that are still active) and override _finishesStepsWithJob to return true. A subclass of the PostgreSQL or PGLite adapter inherits _finishesStepsWithJob = true: if it overrides _completeJob or _failJob without delegating to the built-in method, it must apply options.steps itself or override the getter to return false. Otherwise those steps are not written and stay active in the archived job.

Best Practices

Use PGLite for Development

PGLite is perfect for development and testing:

const adapter = pgliteAdapter({
  connection: ':memory:',
})

Use PostgreSQL for Production

PostgreSQL is recommended for production:

const adapter = postgresAdapter({
  connection: process.env.DATABASE_URL!,
  schema: 'duron',
})

Connection Pooling

The PostgreSQL adapter creates a postgres.js connection pool from its connection option. Pass postgres.js options to size it:

const adapter = postgresAdapter({
  connection: {
    host: 'localhost',
    port: 5432,
    database: 'app',
    username: 'app',
    password: process.env.PGPASSWORD,
    max: 10, // Connection pool size
  },
})

The adapter also opens one connection for notifications and, with pruneArchive, one for the prune lock.

Environment Isolation

Use a separate database for each environment (development, staging, production). A schema other than duron needs your own migrations (see Integrating Duron Schema): the built-in migrations create only the duron schema.

const adapter = postgresAdapter({
  connection: process.env.DATABASE_URL!, // a different database per environment
})

On this page