Skip to content

Releases

v0.5.0 - Watch task progress and fail fast on values PostgreSQL rejects

Choose a tag to compare

@Kludex Kludex released this 02 Dec 14:25
f3b567d

🐘 Watch task progress and fail fast on values PostgreSQL rejects

pgtask is a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension.

This release lets a client follow a task's state and checkpoints without polling. It also stops a task from repeating a step or a spawn whose value PostgreSQL will never store, and replaces the unmaintained Chrono dependency with time and Croner.

pip install pgtask==0.5.0

👀 Follow a task without polling

  • Watch a task's state and checkpoints from Python (#81). TaskHandle.watch() yields a typed TaskUpdate each time the task's state or checkpoints change, and ends after the update in which the task finishes. It is a plain async iterator, so a timeout around anext() does not end it.
  • Wake observers when a worker records a checkpoint (#81). Workers batch checkpoint wakeups and send them in a separate transaction on 64 pgtask_checkpoint_* shards, which keeps NOTIFY off the checkpoint write path. Rust callers get Store::task_changes() and Store::task_checkpoints().
  • Let a producer read one task's checkpoints (#81). Migration 0016 adds pgtask.task_checkpoints(uuid) and grants it wherever pgtask.task_result(uuid) is granted, so a client with the producer role can watch a task without the observer role.

🧱 Fail once when a value can never be stored

  • Stop repeating a step whose value is too large (#82). A step value over 1 MiB was rejected after the step had run, and the failure was retried, so every attempt ran the step again. The task now fails once with checkpoint_too_large, naming the step, the size, and the limit. A value PostgreSQL rejects for another reason, such as one holding \u0000, fails once with checkpoint_rejected.
  • Stop retrying a spawn PostgreSQL rejects (#87). A child whose payload or headers are over their limit fails the spawning task once with child_spawn_rejected. A full queue is still retried.
  • Deliver a result or signal at the 1 MiB limit (#86). PostgreSQL wraps a child result or a signal before it checkpoints it, and that wrapper pushed values in the last bytes below their own limit over the checkpoint limit. A valid child result then failed with result_rejected or exhausted its parent's attempts, and a valid signal could not reach its waiter. Migration 0017 gives checkpoints 1 KiB of room for the wrapper.

🕰️ Replace Chrono with time and Croner

  • Remove the unmaintained Chrono dependency (#80). Timestamps use time::OffsetDateTime with SQLx's native time support, and cron schedules are evaluated by Croner. The cargo-deny exception for Chrono is gone.
  • Read an infinity timestamp without panicking (#80). time's large-dates feature covers the whole PostgreSQL range, so reading a task whose run_at is infinity or past the year 9999 works.
  • Update dependencies with security advisories (#79). The lock moves rustls, rustls-webpki, tokio, url, and ctutils past their advisories, and off the yanked chacha20 release.

⬆️ Upgrading

This release adds migrations 0016 and 0017. Run migrations with the new CLI before replacing workers:

PGTASK_DATABASE_URL="$DATABASE_URL" pgtask migrate

The storage protocol remains unchanged: the database supports 1..=2, and workers require protocol 2. The migrations preserve existing SQL function signatures, so 0.4.0 and 0.5.0 workers can share the migrated database during a rolling upgrade. TaskHandle.watch() needs migration 0016.

Cron expressions: three spellings that the old parser accepted are now refused. A stored schedule that uses one stops creating tasks: each time it is due, the worker logs a warning and moves it one minute forward. No other schedule runs at a different time.

Spelling Example Write instead
A full day or month name, tues, or thurs 0 0 9 * * monday 0 0 9 * * mon
A wildcard inside a list 0 0 1,* * * * 0 0 * * * *
A space inside a field 1, 0 0 * * * 1,0 0 * * * *

Check stored cron expressions has a query that finds the affected schedules before you upgrade.

Rust API: public types that carried chrono::DateTime<Utc> now carry time::OffsetDateTime. A few timestamp spellings that Chrono parsed, such as an offset without a colon (+0000), are rejected.

Python exception handling: task.step() raises NonRetryableError when its value is over 1 MiB or PostgreSQL rejects it, and task.spawn() does when PostgreSQL rejects the child's values. Both used to raise a retryable RuntimeError.

Error readers: a task's error can now have the types checkpoint_too_large, checkpoint_rejected, and child_spawn_rejected. A Python task records them as a handler_error with "retryable": false.

Checkpoint size: a step value is still limited to 1 MiB, which pgtask.commit_checkpoint now enforces itself. A stored checkpoint can be up to 1 KiB larger when PostgreSQL wraps a result or a signal.


📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.5.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 16, 17, and 18 are tested.

The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Thanks to @Trollgeir for the checkpoint notifications behind watch(), the Chrono replacement, and the dependency updates.


Documentation: https://kludex.github.io/pgtask/

Full changelog: v0.4.0...v0.5.0

v0.4.0 - Keep workers moving and control Python retries

Choose a tag to compare

@Kludex Kludex released this 05 Oct 19:00
ee2c450

🐘 Keep workers moving and control Python retries

pgtask is a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension.

This release batches worker outcomes, stops idle database polling, and keeps oversized results, broken schedules, listener reconnects, and routine shutdowns from disrupting unrelated work. Python handlers can now choose terminal failures and catch a step's original exception.

pip install pgtask==0.4.0

🚀 Move work with fewer database operations

  • Batch task completions and failures (#16). Workers flush transitions with size and deadline bounds while preserving ordered responses and lease fencing. In the pull request's benchmark of 10,000 no-op tasks at concurrency 100, drain throughput increased from 4,803 to 6,550 tasks per second and database transactions fell by about 80%.
  • Let idle workers sleep (#48). Empty task, schedule, and wait queues now return no deadline instead of an immediate deadline, so workers stop repeatedly querying an idle database.
  • Drain retention backlogs without whole-table scans (#57). Each retention tick processes up to 16 batches per queue for terminal tasks and idempotency keys. New indexes speed up history cleanup, and worker rows and capabilities are removed after the worker has been expired for 24 hours by default. Python exposes retention_enabled, retention_batch_size, and retention_interval.
  • Browse large queue lists in bounded pages (#71). The observer dashboard lists 100 queues at a time with a name-based cursor. The database aggregates only the queues needed for the page, rather than every queue ever created.

🧱 Keep disruptive work from blocking progress

  • Isolate outcomes PostgreSQL cannot store (#55). A result over 1 MiB fails its own task terminally with result_too_large. Errors over 256 KiB are truncated, and NUL characters are escaped. If a batch is still rejected, workers write its transitions individually so unrelated tasks do not wait for lease expiry and run again.
  • Keep healthy schedules moving past a broken definition (#56). A deterministic materialization failure is isolated and deferred for one minute instead of rolling back the entire batch. Failed schedule and wait sweeps also back off rather than spinning.
  • Re-arm durable waits after an administrator retry (#56). Finishing a task resolves its outstanding signal waits, and signal and child-result waits reuse stale registrations instead of failing on a duplicate key.
  • Return unfinished tasks promptly during shutdown (#58). After the grace period, workers cancel remaining handlers and release their fenced leases without consuming retry budget. Python exposes shutdown_grace; cancelling worker.run() now follows the same graceful shutdown path before re-raising CancelledError.
  • Catch up after a silent listener reconnect (#58). Workers wake their task and schedule loops when the notification connection reconnects. Result waits re-read task state, so a missed notification does not force a wait until the next poll.

🐍 Make Python failure handling explicit

  • Choose terminal failures by exception type (#72, #73). Raising pgtask.NonRetryableError, a subclass, or an exception explicitly caused by one fails the task without further retries. Nested exception groups are terminal when any member meets that rule, including groups from the exceptiongroup backport on Python 3.10.
  • Catch a step's original exception (#73). A failing task.step() raises the operation's own ordinary exception object, preserving its attributes, cause, and traceback. Handler failures also record a retryable boolean; readers must still accept older and database-generated errors without that field.
  • Distinguish retry budget from durable resumptions (#67). Task.failed_attempts exposes the failures and lease losses counted by max_attempts, while Task.attempt also counts resumptions. pgtask.TaskSuspended is now public so broad exception handlers can re-raise durable suspensions.

🧪 Keep stress tests focused on real failures

Schedule property tests now clean up their stored schedules instead of leaving a backlog that stalls later worker tests (#61). Linearizability checks deterministically cover committed writes whose replies are lost, without depending on whether a timeout beats a database round trip (#62). Administrator tests inspect their own schedule row instead of depending on the first page of shared data (#65).

The SQL mutation sweep matches the current attempt-budget expressions and tests forged lease tokens across completion, failure, sleep, waits, and spawn. Mutations that are equivalent under the existing invariants are documented and excluded from the score rather than reported as missed bugs (#70). The task-lifecycle model also covers fenced shutdown releases and separates failed attempts from claims (#58).


⬆️ Upgrading

This release adds migrations 0010, 0011, 0013, 0014, and 0015. Run migrations with the new CLI before replacing workers:

PGTASK_DATABASE_URL="$DATABASE_URL" pgtask migrate

The storage protocol remains unchanged: the database supports 1..=2, and workers require protocol 2. The migrations preserve existing SQL function signatures, so 0.3.0 and 0.4.0 workers can share the migrated database during a rolling upgrade. The Helm chart runs the migration hook before replacing worker Deployments.

Large tables: migration 0014 builds two indexes that can block writes while they are created. To avoid that build-time write lock, create them concurrently before running migrations, outside a transaction:

CREATE INDEX CONCURRENTLY IF NOT EXISTS tasks_terminal_retention_idx
    ON pgtask.tasks (queue_name, completed_at, id)
    WHERE state IN ('succeeded', 'failed', 'cancelled');

CREATE INDEX CONCURRENTLY IF NOT EXISTS result_waits_result_task_idx
    ON pgtask.result_waits (result_task_id);

Python exception handling: a step's ordinary exception is no longer wrapped in RuntimeError. Runtime-detected terminal errors, such as an invalid JSON step result or a corrupt signal checkpoint, now raise NonRetryableError instead. Update handlers that relied on catching the old wrapper. TaskSuspended remains an Exception; re-raise it before a broad except Exception around durable calls.

History readers: attempt history can now contain state = 'released', and signal-wait history can contain outcome = 'cancelled'. Rust code constructing a complete WorkerConfig literal must supply the new expired_worker_retention field.

Shutdown timing: lease release is best effort and waits at most five seconds after the grace period. Keep the pod termination grace period longer than shutdown_grace so release can run. Any lease that cannot be released still expires and consumes a failed attempt during recovery.


📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.4.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 16, 17, and 18 are tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: v0.3.0...v0.4.0

v0.3.0 - Scale queues and harden durable workflows

Choose a tag to compare

@Kludex Kludex released this 11 Sep 10:25
aeabbf9

🐘 Scale queues and harden durable workflows

pgtask is a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension.

This release improves the hot paths for busy queues, closes two durable-workflow correctness gaps, adds ordered batch enqueueing to every SDK, and expands support to PostgreSQL 16.

pip install pgtask==0.3.0

🚀 Move more work with fewer database operations

  • Enqueue batches through Python, TypeScript, and Go (#17). The new APIs preserve request order and commit each batch atomically. The repository benchmark increased from 2,131 to 7,353 enqueued tasks per second.
  • Keep lease recovery out of the claim path (#15). Workers recover expired leases on a dedicated interval instead of scanning before every claim.
  • Remove redundant writes and notifications (#19). Completion throughput increased from 1,349 to 2,660 tasks per second in the repository benchmark, while deterministic sharded wakeups remain unchanged.
  • Scale worker demand sampling by queue, not replica count (#18). One worker samples queue-wide demand per heartbeat interval, avoiding the same scan from every replica.
  • Fill Python worker capacity in one claim (#20). Claim batches now follow configured concurrency instead of fetching one task at a time.

🧱 Preserve durable workflow progress

  • Close the result-wait lost-wakeup race (#29). Result-wait registration now serializes against child completion, so a child cannot finish while its parent's uncommitted wait is invisible. Lease renewal also locks workflow ancestry in a consistent order to avoid deadlocks.
  • Keep durable resumptions outside the retry budget (#35). Sleeps, signal waits, and child-result waits can resume after the final execution attempt because only failures consume retry budget. Worker backoff now follows failed attempts rather than the number of resumptions.
  • Reject unsupported interval precision cleanly (#34). Fractional-millisecond schedules now return ScheduleError::UnsupportedIntervalPrecision instead of panicking or changing during a PostgreSQL round trip.

🔭 Operate larger and broader installations

  • Run on PostgreSQL 16, 17, or 18 (#22). Every Rust and SDK test matrix now covers PostgreSQL 16, and the documented minimum has been lowered accordingly.
  • Browse every schedule and worker (#46). Observer pages use indexed keyset pagination instead of rendering everything or silently stopping at 100 records. Dashboard totals remain exact.
  • Choose pgtask with direct comparisons (#36). The documentation now compares pgtask with Absurd, Celery, Dramatiq, and ARQ, with migration guidance alongside each comparison.

🧪 Test the guarantees, not only the examples

The PostgreSQL kernel now has state-machine and mutation tests for lease fencing, attempt budgets, priority, and cancellation (#26); property tests for schedule and retry arithmetic (#31); TLA+ models for task lifecycle and wait registration (#27); and fault-injected linearizability checks for leases, checkpoints, idempotency, capacity, and waits (#32).

Nightly stress runs increase the property and model case counts, model-check the TLA+ specifications, and preserve failure evidence. Weekly SQL mutation runs verify that the tests reject deliberately broken guarantees (#43). Workflow security analysis (#37), deterministic timing fixes (#38, #44), and handler-version routing coverage (#45) keep those signals trustworthy.


⬆️ Upgrading

This release adds migrations 0003 through 0008 and introduces storage protocol 2. Run migrations before replacing workers:

PGTASK_DATABASE_URL="$DATABASE_URL" pgtask migrate

Migration 0004 expands the database range to 1..=2. Existing protocol 1 workers and producers remain compatible during a rolling upgrade, while 0.3.0 workers require protocol 2. The Helm chart runs the migration hook before replacing worker Deployments.

pgtask.queue.ready.tasks is now queue-wide demand supported by any live, non-draining worker. Do not use it to scale separate Deployments with disjoint handlers on one shared queue. Use separate queues or a capability-aware external metric in that topology.


📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.3.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: v0.2.0...v0.3.0

v0.2.0 - Reach the running task from anywhere

Choose a tag to compare

@Kludex Kludex released this 17 Aug 13:12
8a1c97b

🐘 Reach the running task from anywhere

pgtask is a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension.

This release makes the current task reachable from code that never received it, so a framework calling back into your handler can still checkpoint through pgtask.

pip install pgtask==0.2.0

🚀 Ambient task context in the Python SDK

A handler receives its Task as an argument, which is enough only while you control every frame beneath it. A framework that calls back into your code does not forward it: nothing between agent.run() and the hook it invokes knows the task exists.

from pgtask import get_current_task

task = get_current_task()
if task is not None:
    result = await task.step("call-model", call_model)

It returns the task inside a handler and None outside, so library code can fall back instead of failing.

The worker sets a ContextVar around each invocation, next to the OpenTelemetry context it already attaches. Two handlers running under concurrency > 1 each see their own task, and a step operation sees the task that started it - the worker gives every invocation its own copied context, and step copies that context at call time.

This removes the reason for a @durable_task decorator that users have to remember to apply. See Reach the task from anywhere below the handler for the details.


📖 Readable package pages

Every published crate now has a README. crates.io and docs.rs showed one line of description before this, and the Python wheel opened with a title and a code block.

The pgtask crate README is also its crate documentation, so both of its examples are compiled as doctests and cannot drift from the API they describe.

The repository README leads with the published artifacts rather than asking you to clone and run Tilt.


📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.2.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 17 and 18 are both tested.


⬆️ Upgrading

No schema migration, and the storage protocol is unchanged, so a 0.1.3 worker and a 0.2.0 worker can claim from the same queue during a rolling upgrade.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: v0.1.3...v0.2.0

v0.1.3 - Durable tasks and workflows with just PostgreSQL

Choose a tag to compare

@Kludex Kludex released this 17 Aug 12:21

🐘 Durable tasks and workflows with just PostgreSQL

The first release of pgtask: a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension. The engine is Rust; the SDKs are thin clients of one versioned set of database functions.

0.1.0, 0.1.1, and 0.1.2 were release-pipeline casualties and shipped almost nothing. 0.1.3 is the first complete release; use it rather than any of them.

pip install pgtask==0.1.3
import asyncio
import os

from pgtask import Client, Task, TaskRegistry, Worker

tasks = TaskRegistry(queue_name="reports")


@tasks.task("reports.render")
async def render(task: Task, request: dict) -> dict:
    return {"report_id": request["report_id"], "attempt": task.attempt}


async def main() -> None:
    database_url = os.environ["PGTASK_DATABASE_URL"]
    client = await Client.connect(database_url)
    await client.migrate()
    await Worker(database_url, tasks).run()


asyncio.run(main())

🚀 Highlights

  • Enqueue inside your own transaction - pass your connection to Client.enqueue_on and the task commits with your data or not at all. If the transaction rolls back the task never existed, which is the outbox pattern's whole purpose, without the outbox.
  • Leases instead of acknowledgements - a claim stamps the row with a fencing token, and every transition requires it. A worker that stalls, loses its lease, and comes back finds its write matched zero rows, so it cannot overwrite the worker that took over.
  • Durable workflows are database transitions - steps store checkpoints, and a sleep, signal wait, or child-result wait releases the lease entirely. A workflow sleeping six hours costs one row, not a worker slot, and resumes after any restart.
  • Scheduling has no leader - every worker may claim due schedules, and a unique (schedule_id, scheduled_for) key makes duplicate occurrences impossible rather than merely unlikely. Interval and six-field UTC cron, with skip, latest, and bounded catch_up misfire policies.
  • Unknown work is left alone - a worker only receives task names and handler versions it declared, so you can deploy a producer before its consumer and the work waits instead of failing.
  • Least privilege is enforced by the database - producers, workers, observers, and administrators get SECURITY DEFINER functions and security-barrier views, with no direct table grants. A producer physically cannot claim a task or read another payload.
  • Rolling upgrades are a database contract - the schema and every client declare an inclusive storage protocol range, and a worker whose range does not overlap refuses to start with both ranges in the error.
  • OpenTelemetry is part of the engine - trace context travels in task headers, so a worker span is a child of the producer's request, alongside queue, worker, schedule, and admission metrics.
  • One protocol, five languages - Rust, Python, TypeScript, Go, and plain SQL.

📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.1.3, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 17 and 18 are both tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: https://github.com/Kludex/pgtask/commits/v0.1.3

v0.1.2 - Durable tasks and workflows with just PostgreSQL

Choose a tag to compare

@Kludex Kludex released this 17 Aug 12:08

🐘 Durable tasks and workflows with just PostgreSQL

The first release of pgtask: a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension. The engine is Rust; the SDKs are thin clients of one versioned set of database functions.

0.1.0 and 0.1.1 were release-pipeline casualties and shipped almost nothing. 0.1.2 is the first complete release; use it rather than either.

pip install pgtask==0.1.2
import asyncio
import os

from pgtask import Client, Task, TaskRegistry, Worker

tasks = TaskRegistry(queue_name="reports")


@tasks.task("reports.render")
async def render(task: Task, request: dict) -> dict:
    return {"report_id": request["report_id"], "attempt": task.attempt}


async def main() -> None:
    database_url = os.environ["PGTASK_DATABASE_URL"]
    client = await Client.connect(database_url)
    await client.migrate()
    await Worker(database_url, tasks).run()


asyncio.run(main())

🚀 Highlights

  • Enqueue inside your own transaction - pass your connection to Client.enqueue_on and the task commits with your data or not at all. If the transaction rolls back the task never existed, which is the outbox pattern's whole purpose, without the outbox.
  • Leases instead of acknowledgements - a claim stamps the row with a fencing token, and every transition requires it. A worker that stalls, loses its lease, and comes back finds its write matched zero rows, so it cannot overwrite the worker that took over.
  • Durable workflows are database transitions - steps store checkpoints, and a sleep, signal wait, or child-result wait releases the lease entirely. A workflow sleeping six hours costs one row, not a worker slot, and resumes after any restart.
  • Scheduling has no leader - every worker may claim due schedules, and a unique (schedule_id, scheduled_for) key makes duplicate occurrences impossible rather than merely unlikely. Interval and six-field UTC cron, with skip, latest, and bounded catch_up misfire policies.
  • Unknown work is left alone - a worker only receives task names and handler versions it declared, so you can deploy a producer before its consumer and the work waits instead of failing.
  • Least privilege is enforced by the database - producers, workers, observers, and administrators get SECURITY DEFINER functions and security-barrier views, with no direct table grants. A producer physically cannot claim a task or read another payload.
  • Rolling upgrades are a database contract - the schema and every client declare an inclusive storage protocol range, and a worker whose range does not overlap refuses to start with both ranges in the error.
  • OpenTelemetry is part of the engine - trace context travels in task headers, so a worker span is a child of the producer's request, alongside queue, worker, schedule, and admission metrics.
  • One protocol, five languages - Rust, Python, TypeScript, Go, and plain SQL.

📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.1.2, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 17 and 18 are both tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: https://github.com/Kludex/pgtask/commits/v0.1.2

v0.1.1 - Durable tasks and workflows with just PostgreSQL

Choose a tag to compare

@Kludex Kludex released this 17 Aug 11:20

🐘 Durable tasks and workflows with just PostgreSQL

The first release of pgtask: a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension. The engine is Rust; the SDKs are thin clients of one versioned set of database functions.

0.1.0 published five of the seven crates before crates.io rate-limited the rest, and shipped no wheels, image, or chart. 0.1.1 is the first complete release; use it rather than 0.1.0.

pip install pgtask==0.1.1
import asyncio
import os

from pgtask import Client, Task, TaskRegistry, Worker

tasks = TaskRegistry(queue_name="reports")


@tasks.task("reports.render")
async def render(task: Task, request: dict) -> dict:
    return {"report_id": request["report_id"], "attempt": task.attempt}


async def main() -> None:
    database_url = os.environ["PGTASK_DATABASE_URL"]
    client = await Client.connect(database_url)
    await client.migrate()
    await Worker(database_url, tasks).run()


asyncio.run(main())

🚀 Highlights

  • Enqueue inside your own transaction - pass your connection to Client.enqueue_on and the task commits with your data or not at all. If the transaction rolls back the task never existed, which is the outbox pattern's whole purpose, without the outbox.
  • Leases instead of acknowledgements - a claim stamps the row with a fencing token, and every transition requires it. A worker that stalls, loses its lease, and comes back finds its write matched zero rows, so it cannot overwrite the worker that took over.
  • Durable workflows are database transitions - steps store checkpoints, and a sleep, signal wait, or child-result wait releases the lease entirely. A workflow sleeping six hours costs one row, not a worker slot, and resumes after any restart.
  • Scheduling has no leader - every worker may claim due schedules, and a unique (schedule_id, scheduled_for) key makes duplicate occurrences impossible rather than merely unlikely. Interval and six-field UTC cron, with skip, latest, and bounded catch_up misfire policies.
  • Unknown work is left alone - a worker only receives task names and handler versions it declared, so you can deploy a producer before its consumer and the work waits instead of failing.
  • Least privilege is enforced by the database - producers, workers, observers, and administrators get SECURITY DEFINER functions and security-barrier views, with no direct table grants. A producer physically cannot claim a task or read another payload.
  • Rolling upgrades are a database contract - the schema and every client declare an inclusive storage protocol range, and a worker whose range does not overlap refuses to start with both ranges in the error.
  • OpenTelemetry is part of the engine - trace context travels in task headers, so a worker span is a child of the producer's request, alongside queue, worker, schedule, and admission metrics.
  • One protocol, five languages - Rust, Python, TypeScript, Go, and plain SQL.

📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.1.1, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 17 and 18 are both tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: https://github.com/Kludex/pgtask/commits/v0.1.1

v0.1.0 - Durable tasks and workflows with just PostgreSQL

Choose a tag to compare

@Kludex Kludex released this 17 Aug 11:00

🐘 Durable tasks and workflows with just PostgreSQL

The first release of pgtask: a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension. The engine is Rust; the SDKs are thin clients of one versioned set of database functions.

pip install pgtask==0.1.0
import asyncio
import os

from pgtask import Client, Task, TaskRegistry, Worker

tasks = TaskRegistry(queue_name="reports")


@tasks.task("reports.render")
async def render(task: Task, request: dict) -> dict:
    return {"report_id": request["report_id"], "attempt": task.attempt}


async def main() -> None:
    database_url = os.environ["PGTASK_DATABASE_URL"]
    client = await Client.connect(database_url)
    await client.migrate()
    await Worker(database_url, tasks).run()


asyncio.run(main())

🚀 Highlights

  • Enqueue inside your own transaction - pass your connection to Client.enqueue_on and the task commits with your data or not at all. If the transaction rolls back the task never existed, which is the outbox pattern's whole purpose, without the outbox.
  • Leases instead of acknowledgements - a claim stamps the row with a fencing token, and every transition requires it. A worker that stalls, loses its lease, and comes back finds its write matched zero rows, so it cannot overwrite the worker that took over.
  • Durable workflows are database transitions - steps store checkpoints, and a sleep, signal wait, or child-result wait releases the lease entirely. A workflow sleeping six hours costs one row, not a worker slot, and resumes after any restart.
  • Scheduling has no leader - every worker may claim due schedules, and a unique (schedule_id, scheduled_for) key makes duplicate occurrences impossible rather than merely unlikely. Interval and six-field UTC cron, with skip, latest, and bounded catch_up misfire policies.
  • Unknown work is left alone - a worker only receives task names and handler versions it declared, so you can deploy a producer before its consumer and the work waits instead of failing.
  • Least privilege is enforced by the database - producers, workers, observers, and administrators get SECURITY DEFINER functions and security-barrier views, with no direct table grants. A producer physically cannot claim a task or read another payload.
  • Rolling upgrades are a database contract - the schema and every client declare an inclusive storage protocol range, and a worker whose range does not overlap refuses to start with both ranges in the error.
  • OpenTelemetry is part of the engine - trace context travels in task headers, so a worker span is a child of the producer's request, alongside queue, worker, schedule, and admission metrics.
  • One protocol, five languages - Rust, Python, TypeScript, Go, and plain SQL.

📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.1.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 17 and 18 are both tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: https://github.com/Kludex/pgtask/commits/v0.1.0