by odessa

A high-performance job queue for PostgreSQL on Node.js that runs background tasks (emails, PDFs, calculations) without blocking your application. Integrates with BullMQ, GCP Cloud Tasks, and Faktory.
graphile-worker is a PostgreSQL-backed job queue for Node.js that executes background tasks (email sending, PDF generation, data processing) without blocking application code. It is suited for any team running a Node.js backend with an existing PostgreSQL database who needs reliable, persistent background processing with minimal infrastructure overhead.
generated/ - Auto-generated SQL type bindings used internallyplugins/ - Built-in task loader plugins (JS files, executable files)sql/ - Raw SQL query modules for job lifecycle operations (complete, fail, get, return)cleanup.ts - Utilities for releasing resources and cleaning up worker statecli.ts - Command-line interface entry point for running workers via terminalconfig.ts - Configuration resolution and validation logiccron.ts - Cron scheduling engine that drives recurring job executioncronConstants.ts - Time unit constants used in cron calculationscronMatcher.ts - Pattern matching logic for cron expressionscrontab.ts - Crontab file parser; exports parseCronItem, parseCronItems, parseCrontabdeferred.ts - Promise-based deferred utility used internallyfs.ts - Filesystem helpers for task discoverygetCronItems.ts - Loads and resolves cron item definitionsgetTasks.ts - Discovers and loads task functions from the filesystemhelpers.ts - withPgClient factory helpers wrapping pg Pool/PoolClientindex.ts - Primary public API re-export barrelinterfaces.ts - All TypeScript types and interfaces (Task, Job, WorkerPool, etc.)lib.ts - Internal shared utilities: processSharedOptions, CompiledSharedOptions, retry logiclocalQueue.ts - Batched in-process job queue that reduces database polling loadlogger.ts - Logger abstraction; exports Logger, consoleLogFactory, LogFunctionFactorymain.ts - Core worker pool runner: , Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 82979e2f66ff21ac…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
runTaskListrunTaskListOncemigrate.ts - Applies graphile-worker database migrationspreset.ts - Default WorkerPreset graphile-config presetrunner.ts - High-level entry points: run, runOnce, runMigrationssignals.ts - OS signal handling for graceful shutdowntaskIdentifiers.ts - Utilities for normalizing task identifier stringsversion.ts - Package version constantworker.ts - Individual worker unit that checks out and executes a single jobworkerUtils.ts - Standalone utilities: makeWorkerUtils, quickAddJob, addJobAdhocnpm install pg graphile-config @graphile/logger tslib user@example.com
npm install --save-dev @types/pg typescript
No native modules, pod installs, or Android linking steps are required. This is a pure Node.js package.
Drop the source into your project at src/worker-source/ (or any path you prefer).
Database migration - graphile-worker needs its schema in Postgres before any worker runs:
import { runMigrations } from "./worker-source";
await runMigrations({ connectionString: process.env.DATABASE_URL });
Create a tasks/ directory at your project root (or configure taskDirectory). Each file exports a default Task function.
tsconfig - ensure resolveJsonModule and esModuleInterop are enabled:
{
"compilerOptions": {
"esModuleInterop": true,
"resolveJsonModule": true,
"module": "CommonJS",
"target": "ES2019"
}
}
Environment variables:
DATABASE_URL - PostgreSQL connection string (e.g. postgres://user:pass@localhost/mydb)NO_LOG_SUCCESS - set to 1 to suppress success log linesGRAPHILE_ENABLE_DANGEROUS_LOGS - set to 1 to enable verbose internal logsRun via the high-level run export or the CLI (graphile-worker -c "$DATABASE_URL").
import { run } from "./worker-source";
const runner = await run({
connectionString: string;
taskDirectory?: string;
concurrency?: number;
// ...additional SharedOptions
});
// runner.promise resolves when the runner stops
await runner.promise;
Starts the full worker pool: connects to Postgres, loads tasks from taskDirectory, and begins polling. Use this as your main long-running process entry point. Call runner.stop() for graceful shutdown.
import { makeWorkerUtils } from "./worker-source";
const utils = await makeWorkerUtils({ connectionString: string });
await utils.addJob("send-email", { to: "user@example.com" });
await utils.release();
Creates a standalone utility object for adding jobs outside of a worker context - ideal for web servers or scripts that only enqueue work. Always call release() when finished.
import { runTaskList } from "./worker-source";
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const workerPool = await runTaskList(compiledOptions, taskList, pool);
Lower-level API that accepts an already-compiled options object and an explicit TaskList map. Use when you need fine-grained control over task loading or when integrating with an existing pg Pool.
import { parseCrontab } from "./worker-source";
const items = parseCrontab(`
0 * * * * send-digest ?fill=1h
`);
Parses a crontab-format string into ParsedCronItem[]. Use to validate or programmatically generate cron schedules before passing them to run.
Start a worker that processes tasks from the tasks/ directory. Each task file exports a default async function.
import { run } from "./worker-source";
async function main() {
const runner = await run({
connectionString: process.env.DATABASE_URL!,
concurrency: 5,
taskDirectory: `${__dirname}/tasks`,
});
process.once("SIGTERM", () => runner.stop());
await runner.promise;
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
// tasks/send-email.ts
import { Task } from "./worker-source";
const task: Task = async (payload, helpers) => {
const { to } = payload as { to: string };
helpers.logger.info(`Sending email to ${to}`);
// ... call your email service
};
export default task;
Add jobs from HTTP request handlers without starting a worker pool in the same process.
import express from "express";
import { makeWorkerUtils } from "./worker-source";
const app = express();
app.use(express.json());
let workerUtils: Awaited<ReturnType<typeof makeWorkerUtils>>;
async function bootstrap() {
workerUtils = await makeWorkerUtils({
connectionString: process.env.DATABASE_URL!,
});
app.post("/send-email", async (req, res) => {
await workerUtils.addJob("send-email", { to: req.body.to });
res.json({ queued: true });
});
app.listen(3000);
}
bootstrap().catch(console.error);
process.on("SIGTERM", async () => {
await workerUtils.release();
process.exit(0);
});
Declare task payload types via declaration merging and schedule recurring work.
// types/graphile-worker.d.ts
declare global {
namespace GraphileWorker {
interface Tasks {
"daily-digest": { userId: string };
"send-email": { to: string; subject: string };
}
}
}
// worker.ts
import { run, parseCrontab } from "./worker-source";
import type { Task } from "./worker-source";
const dailyDigest: Task = async (payload, helpers) => {
const { userId } = payload as GraphileWorker.Tasks["daily-digest"];
helpers.logger.info(`Generating digest for ${userId}`);
};
async function main() {
const runner = await run({
connectionString: process.env.DATABASE_URL!,
taskList: { "daily-digest": dailyDigest },
crontab: `0 9 * * * daily-digest`,
});
await runner.promise;
}
main().catch(console.error);
index.ts - Barrel re-export of all public symbols; the only import path consumers should use.interfaces.ts - Canonical TypeScript definitions for Task, Job, WorkerPool, AddJobFunction, WorkerEvents, and all other shared types.runner.ts - Implements run, runOnce, runMigrations - the three high-level entry points most applications use.main.ts - Implements runTaskList and runTaskListOnce; manages the worker pool lifecycle, LISTEN/NOTIFY, and retry logic.worker.ts - Single-worker unit; checks out one job from the queue, calls the matching task function, reports success or failure.workerUtils.ts - Provides makeWorkerUtils and quickAddJob for job enqueueing without a full worker context.localQueue.ts - Batches database job fetches to reduce round-trips; manages STARTING/POLLING/WAITING/TTL_EXPIRED/RELEASED state machine.cron.ts - Drives the cron scheduling loop; compares known crontabs against parsed items and triggers backfill or new job creation.crontab.ts - Parses crontab text format into structured ParsedCronItem objects.lib.ts - Internal shared logic: option compilation, retry delay calculation, error coercion, sleep, safeEmit.logger.ts - Thin logging abstraction over @graphile/logger; re-exports Logger and consoleLogFactory.migrate.ts - Runs SQL migrations to install or upgrade the graphile_worker schema in Postgres.helpers.ts - Factory functions for creating withPgClient wrappers from a Pool or PoolClient.preset.ts - Exports WorkerPreset, the default graphile-config preset wiring everything together.signals.ts - Registers OS signal handlers (SIGTERM, SIGINT) and triggers graceful pool shutdown.sql/ - Individual SQL query modules (completeJobs, failJobs, getJobs, returnJobs, resetLockedAt) called by the worker internals.plugins/ - LoadTaskFromJsPlugin and LoadTaskFromExecutableFilePlugin for task discovery strategies.generated/sql.ts - Auto-generated query type bindings; do not edit manually.runMigrations or running graphile-worker --migrate before starting any worker.DATABASE_URL not set: processSharedOptions will throw at startup - always provide connectionString explicitly or set DATABASE_URL in your environment."type": "module", import graphile-worker via the npm package name, not relative source paths, or set "module": "CommonJS" in tsconfig.run silently finds no tasks if taskDirectory points to a compiled dist/ path that doesn't exist yet - ensure you build before running or use ts-node/tsx.concurrency no higher than your pg pool max minus headroom for migrations and cron.runner.promise or call runner.stop(), the process may exit before in-flight jobs complete - always wire SIGTERM to runner.stop().I have purchased the graphile-worker source block. The source files are in `src/worker-source/` and the integration guide is in `USAGE.md`.
The upstream npm package is `user@example.com`.
Please help me integrate this into my existing Node.js/TypeScript/Express project step by step:
1. Read `USAGE.md` and `src/worker-source/index.ts` to understand all available exports.
2. Run the database migration so the graphile_worker schema exists in my Postgres instance (connection string is in DATABASE_URL env var).
3. Create a `src/tasks/` directory and add a sample task called `send-email` that logs the payload.
4. Add a worker process entry point at `src/workerProcess.ts` that calls `run` with concurrency 5, pointing at `src/tasks/`.
5. Add a helper module at `src/jobQueue.ts` that exports an initialized `makeWorkerUtils` instance so Express routes can call `addJob`.
6. Wire a POST `/queue/send-email` route in my Express app to enqueue a `send-email` job.
7. Add TypeScript declaration merging for my task payload types in `src/types/graphile-worker.d.ts`.
8. Show me how to handle graceful shutdown on SIGTERM for both the worker process and the utils instance.
Use only the exports visible in `src/worker-source/index.ts` and described in `USAGE.md`. Do not invent APIs.
graphile-worker is released under the MIT License. See the upstream repository at https://www.npmjs.com/package/graphile-worker and https://github.com/graphile/worker for full license text, changelog, and official documentation at worker.graphile.org.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
SaaS, AI & Subscription Products
Free