SQL (database)
A broker-less, DBOS-style transport — dispatched steps are rows in the database you already run. Workers claim tasks with SELECT … FOR UPDATE SKIP LOCKED. The table + claim contract is documented so Node and Python workers share it.
The SQL transport needs no broker. A dispatched step is a row in the same database your durable
store already uses: ctx.step inserts a task row, a worker claims it with
SELECT … FOR UPDATE SKIP LOCKED, runs the handler, writes a result row, and the engine polls that
row to resume the run. The database you already operate is the queue.
pnpm add @dudousxd/nestjs-durable-transport-dbHow it compares to the other transports, and what the SQL transport doesn't support: see Choosing a transport.
new DbTransport({ executor: mikroOrmExecutor(em) }); // rides your app's connectionconst transport = new DbTransport({ executor: typeOrmExecutor(ds), group: 'pipeline.extract' });
transport.handle('pipeline.extract', async (input) => extract(input));group is the queue token this instance polls — set it to the exact (optionally
@<partition>-suffixed) step name it serves; each DbTransport instance polls one queue.
Trade-off vs a real broker: throughput is bounded by polling + row contention — great for
workflow/pipeline scale (modest rate, long steps), not for high-fanout firehoses. Requires
FOR UPDATE SKIP LOCKED: Postgres 9.5+ or MySQL 8+ (not SQLite).
Worker health
DbTransport doesn't implement groupHealth/listWorkerGroups — the engine's workerHealth()
query, and the dashboard/Telescope worker-health panels built on it, return empty for this
transport's groups; only a groupHealth-capable transport (BullMQ) returns non-empty results.
Liveness here is the lease itself, not a separate heartbeat: a claimed row whose claimed_at is
older than leaseMs is treated as abandoned and reclaimed by the next poll (see
Claim protocol).
Options
| Option | Description |
|---|---|
executor | How to run SQL, built from the app's own connection. mikroOrmExecutor(em), typeOrmExecutor(dataSource), drizzlePgExecutor(db) (from @dudousxd/nestjs-durable-store-drizzle/pg), or a custom SqlExecutor. |
group | The queue token this instance serves — required to register handle()s. |
prefix | Table-name prefix. Default durable. |
schema | The Postgres schema (MySQL: the database) the tables live in, written into every statement: "<schema>"."durable_transport_tasks". Created on first use when autoCreate is on. Default: the connection's current schema. See Database schema. |
pollMs | Poll interval in ms when a queue is empty. Default 500. |
batchSize | Max task rows claimed per poll. Default 10. The task loop claims only as many rows as it has free concurrency slots (capped by this). The results loop claims rounds of up to 256 rows, or this if larger. |
concurrency | How many tasks this instance runs at once. Default 1. |
leaseMs | How long a claimed row is owned before it's reclaimable (crash recovery), in ms. Default 30_000. Every claim the instance holds is renewed every leaseMs / 3, so a step may run longer than this. |
onError | Where a failing poll, a throwing result handler or a lost claim is reported. Default console.error. |
autoCreate | Create the tables on first use if missing. Default true — the CREATE TABLE statements in The contract are for reference/manual provisioning, not a required setup step. |
instanceId | Prefix of the claim token this instance stamps in claimed_by. Defaults to a random UUID. |
Database schema
To keep the transport tables out of your app's schema, set schema:
new DbTransport({ executor: typeOrmExecutor(ds), group: 'api', schema: 'durable' });Every statement then names it ("durable"."durable_transport_tasks", on MySQL the durable
database), and autoCreate creates it when it is missing (the role needs CREATE on the database
for that). Give every engine and worker that shares the tables the same schema and prefix,
including Python workers (run_db_worker(..., schema="durable")). The
name must be a plain identifier of at most 63 characters.
Don't move the tables with search_path. Behind PgBouncer in transaction mode a
SET search_path leaks to other clients' connections. The schema option writes the schema into
every statement instead.
The contract
This is the single source of truth for the table shape and the claim protocol. The TypeScript
DbTransport and the Python db_runner both implement against this
spec — so a Node engine and a Python worker share the same two step tables without drift. Table
names are <prefix>_transport_tasks and <prefix>_transport_results (default prefix durable),
qualified as <schema>.<table> when a schema is set, plus <prefix>_transport_runs, the engines' own run queue, which workers never touch.
Tables
CREATE TABLE durable_transport_tasks (
step_id varchar(191) PRIMARY KEY, -- "<runId>:<seq>", the step identity
run_id varchar(191) NOT NULL,
seq integer NOT NULL,
name varchar(191) NOT NULL, -- step name → handler key
grp varchar(191) NOT NULL, -- worker group → which workers poll it
input text, -- JSON (longtext on MySQL)
attempt integer NOT NULL,
status varchar(32) NOT NULL, -- 'pending'
claimed_by varchar(191), -- lease owner (debug)
claimed_at bigint, -- lease stamp (epoch ms)
created_at bigint NOT NULL
);
CREATE TABLE durable_transport_results (
step_id varchar(191) PRIMARY KEY,
run_id varchar(191) NOT NULL,
seq integer NOT NULL,
status varchar(32) NOT NULL, -- 'completed' | 'failed'
output text, -- JSON
error text, -- JSON
started_at bigint, -- worker pickup (epoch ms) → queue-wait
claimed_by varchar(191),
claimed_at bigint,
created_at bigint NOT NULL
);
CREATE TABLE durable_transport_runs (
run_id varchar(191) PRIMARY KEY, -- one row per queued run
ns varchar(191) NOT NULL, -- the engine namespace ('' for one that drives all)
priority integer NOT NULL, -- higher first
wake integer NOT NULL, -- 1 for a wake, 0 for a start
claimed_by varchar(191),
claim_token varchar(191), -- this claim; the row is deleted by it
claimed_at bigint, -- lease stamp, renewed while the run is in flight
created_at bigint NOT NULL
);started_at is what makes queue-wait work over this transport: the
worker stamps when it picked the task up, the engine subtracts its dispatch time.
Claim protocol
A worker claims only what it can run, keeps every claim it holds alive, and settles a task only while it still owns it:
- Claim — in one transaction, lease up to as many un-leased rows as the worker has free slots,
stamped with a token unique to this claim round (
<instanceId>:<uuid>):SELECT * FROM durable_transport_tasks WHERE grp = ? AND (claimed_at IS NULL OR claimed_at < ?) -- ? = now − leaseMs ORDER BY created_at ASC LIMIT ? FOR UPDATE SKIP LOCKED; UPDATE durable_transport_tasks SET claimed_by = ?, claimed_at = ? WHERE step_id IN (…);SKIP LOCKEDis the heart of it: concurrent workers step over each other's locked rows instead of blocking, so a row is never claimed twice. Theclaimed_at < now − leaseMsclause reclaims a row whose worker crashed mid-flight (crash recovery, in place of heartbeats). - Renew — while a row is claimed, its worker re-stamps
claimed_at(everyleaseMs / 3), so only a dead worker's rows age into a reclaim. - Run — re-check the row is still claimed under the token, then execute the handler for
namewith the parsedinput. - Settle — in one transaction, and only if
claimed_byis still the token:DELETEthe task row and write the result row. A worker whose claim was taken over writes nothing. A result row already waiting for the samestep_id(an earlier attempt's) is replaced and its claim cleared (ON CONFLICT … DO UPDATE/ON DUPLICATE KEY UPDATE), so a retry's result is never dropped.
A step fan's tasks are inserted 200 rows per statement.
The engine side mirrors it on the results table: claim a round of up to 256 rows (with a token) →
hand them all to the engine at once → DELETE … WHERE claimed_by = <token> AND step_id IN (…) for the
ones it settled. The next round is claimed while one runs, up to 512 results in flight per instance,
so a wide fan's results are settled in batches rather than one by one. A result handler that throws
is reported through onError and the row is re-delivered after the lease. Delivery is at-least-once (a
worker that crashes mid-handler, or blocks its event loop past leaseMs, can have its task re-run
elsewhere), so handlers should be idempotent, keyed on step_id.
Run queue
Engines queue the runs they start in <prefix>_transport_runs, and every driving instance polls it:
it claims up to 50 rows at a time for its namespace with the same FOR UPDATE SKIP LOCKED
transaction (highest priority, then oldest), at most 256 runs in flight per instance, renews the
lease of the rows it holds and deletes a row by its claim_token once the run's turn settles.
Queueing a run whose row exists is an upsert that clears the claim and keeps wake if either side
is a wake (ON CONFLICT DO UPDATE / ON DUPLICATE KEY UPDATE): a run waiting is not queued twice,
and one queued again while an instance holds its row is taken once more instead of being deleted
with it.
Dialect notes
Only two things differ between Postgres and MySQL, and both libraries handle them the same way:
| Postgres | MySQL | |
|---|---|---|
| Placeholders | $1, $2, … | ? / %s |
| Identifier quoting | "col" | `col` |
| Idempotent task insert | ON CONFLICT (step_id) DO NOTHING | INSERT IGNORE |
| Result upsert | ON CONFLICT (step_id) DO UPDATE | ON DUPLICATE KEY UPDATE |
| JSON column | text | longtext |
AWS SQS
The queue-backed transport on AWS SQS. Same RemoteTask/StepResult contract as BullMQ — tasks go to a per-group queue, results return on a shared queue — so Node and Python workers interoperate.
Overview
Where durable state lives. A StateStore interface with MikroORM, TypeORM, Prisma and Drizzle adapters that run on Postgres, MySQL, SQLite or libSQL, an in-memory store for tests, and auto-schema on boot (opt-out, with a migration helper).