Skip to content

About

Fast and flexible PostgreSQL integration for TaskIQ - supporting asyncpg, psycopg3, psqlpy, and pg8000 (soon) drivers

Resources

Contributing

Security policy

Stars

31 stars

Watchers

0 watching

Forks

Repository files navigation

taskiq-postgresql

PostgreSQL integration for taskiq: a broker that keeps pending messages in a table and delivers them with LISTEN/NOTIFY and a periodic sweep, a result backend, and a persistent schedule source, all in one PostgreSQL database. It works with three drivers, asyncpg, psycopg 3 and psqlpy, each installed as an extra.

Installation

Install the package with the extra for the driver you use. The drivers are optional dependencies, so without an extra no driver is available.

pip install "taskiq-postgresql[asyncpg]"
pip install "taskiq-postgresql[psycopg]"
pip install "taskiq-postgresql[psqlpy]"

With uv: uv add "taskiq-postgresql[asyncpg]". The integrations with SQLAlchemy, SQLModel and Alembic are extras too (see Integrations).

Quickstart

The connection string comes from an environment variable. There is no default DSN: omitting dsn, or passing None (what os.environ.get returns for an unset variable), raises TypeError, and an empty string is rejected at construction.

export POSTGRESQL_URL="postgresql://<user>@<host>:5432/<database>"

Put the broker, the result backend and the scheduler source in one module, so the worker and the scheduler import the same objects:

# app.py
import os

from taskiq import TaskiqScheduler

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend
from taskiq_postgresql.drivers import AsyncpgDriver
from taskiq_postgresql.scheduler_source import PostgresqlSchedulerSource

dsn = os.environ["POSTGRESQL_URL"]

# Each component takes its own driver instance; the drivers live in
# taskiq_postgresql.drivers, one class per extra.
result_backend = PostgresqlResultBackend(
    dsn=dsn,
    driver=AsyncpgDriver(),
    run_migrations=True,
)
broker = PostgresqlBroker(
    dsn=dsn,
    driver=AsyncpgDriver(),
    run_migrations=True,
).with_result_backend(result_backend)
scheduler_source = PostgresqlSchedulerSource(
    dsn=dsn,
    driver=AsyncpgDriver(),
    run_migrations=True,
)
scheduler = TaskiqScheduler(broker=broker, sources=[scheduler_source])


@broker.task
async def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

driver takes an instance of one of the three classes of taskiq_postgresql.drivers, AsyncpgDriver, PsycopgDriver and PsqlpyDriver, or the driver's name. The default "asyncpg" is the by-name form of AsyncpgDriver(), and "psycopg" and "psqlpy" are the by-name forms of the other two; the instance is where the driver's own options go (Driver options).

run_migrations=True creates the tables and indexes on startup (CREATE ... IF NOT EXISTS) and adds the broker's channel and not_before columns to its table (ALTER TABLE ... ADD COLUMN IF NOT EXISTS), which also upgrades a table created by 0.4.x. Processes that start at the same time, such as the two that taskiq worker starts by default, take a PostgreSQL advisory lock first, so they create the tables one after the other. Once the tables, indexes and columns exist, startup only checks for them, so the application's role needs no CREATE privilege from then on (Privileges). run_migrations is off by default; you can leave it off and create the tables yourself, with taskiq postgresql migrate or the SQL that taskiq postgresql generate or taskiq postgresql plan prints (see Migrations). A component that does not migrate still checks its table when it starts, and refuses to start without it (Check at startup).

Start a worker. It claims a message as soon as the message's NOTIFY arrives, and it also sweeps the table for due messages when it starts and every poll_interval seconds, so a message sent while no worker was listening is delivered once one is (Delivery).

taskiq worker app:broker

Send a task and wait for its result:

# kick.py
import asyncio

from app import add, broker


async def main() -> None:
    await broker.startup()
    task = await add.kiq(1, 2)
    result = await task.wait_result(timeout=10)
    print(result.return_value)  # 3
    await broker.shutdown()


if __name__ == "__main__":
    asyncio.run(main())

Store a schedule and run the scheduler, which sends the task whenever the schedule is due:

# schedule.py
import asyncio

from taskiq import ScheduledTask

from app import scheduler_source


async def main() -> None:
    await scheduler_source.startup()
    await scheduler_source.add_schedule(
        ScheduledTask(
            task_name="app:add",
            labels={},
            args=[1, 2],
            kwargs={},
            cron="* * * * *",
        ),
    )
    await scheduler_source.shutdown()


if __name__ == "__main__":
    asyncio.run(main())
taskiq scheduler app:scheduler

PostgresqlSchedulerSource is imported from taskiq_postgresql.scheduler_source; the package root exports the broker, the result backend and register_cleanup.

Configuration

Every constructor takes dsn as its first argument. It is a connection string or a callable that takes no arguments and returns one. A callable is resolved once, at startup, for all three components and all drivers; if it returns None or an empty string, startup fails with an error that says so.

PostgresqlBroker

Argument Type Default Meaning
dsn str or Callable[[], str] required Connection string.
result_backend AsyncResultBackend or None None Result backend; .with_result_backend(...) does the same.
task_id_generator Callable[[], str] or None None Custom task id factory.
field_for_task_id "VarChar", "Text" or "Uuid" "Uuid" SQL type of the task_id column.
channel_name str "taskiq" LISTEN/NOTIFY channel, also stored with each message: a worker's sweep takes only the messages of its own channel. Use a different one per queue that shares a database.
table_name str "taskiq_messages" Table that holds pending messages.
driver str or Driver "asyncpg" Database driver.
max_retry_attempts int 5 Accepted for compatibility, currently unused.
connection_kwargs dict or None None Keyword arguments for the pool and for the LISTEN connection of a driver chosen by name, so each option must be valid for both. With a driver instance, leave it unset and give the options to the instance.
pool_kwargs dict or None None Accepted for compatibility, currently unused. Use connection_kwargs.
run_migrations bool False Create the table and index on startup, and add the channel and not_before columns with their index. Off, startup only checks them; see Check at startup.
poll_interval float 1.0 Seconds between two sweeps of the table for due messages; see Delivery. A value that is not a finite number above zero raises ValueError.
health_check_interval float 30.0 Seconds the LISTEN connection may stay silent before the worker checks it; see Lost connections. A value that is not a finite number above zero raises ValueError.
query_timeout float 30.0 Seconds the worker waits for that check, for a claim (not with psqlpy) and for a close before it gives the connection up; see Lost connections. A value that is not a finite number above zero raises ValueError.

PostgresqlResultBackend

Argument Type Default Meaning
dsn str or Callable[[], str] required Connection string.
keep_results bool True When False, a result row is deleted after it is read.
table_name str "taskiq_results" Table that holds results.
field_for_task_id "VarChar", "Text" or "Uuid" "Uuid" SQL type of the task_id column.
serializer TaskiqSerializer or None None Result serializer; None means PickleSerializer(); see the note below before changing it.
driver str or Driver "asyncpg" Database driver.
run_migrations bool False Create the table and index on startup, add the progress column, make result accept NULL, and add the updated_at column with its index. Off, startup only checks them; see Check at startup.
store_progress bool True When False, set_progress writes nothing; reading progress and the table do not change. See Task progress.
result_ttl float, timedelta or None None Delete results not written for this long, in seconds or as a timedelta; None deletes nothing. See Cleaning up old results.
cleanup_interval float, timedelta or None 3600.0 Time between two cleanups of the timer startup() starts when result_ttl is set, in seconds or as a timedelta; None starts no timer; pass None with register_cleanup.
cleanup_batch_size int 1000 The most rows one cleanup statement deletes, from 1 to 2147483647.
**connect_kwargs Any none Keyword arguments for the connection pool of a driver chosen by name. With a driver instance, pass none and give the options to the instance.

Results are stored with pickle, and unpickling can run code. Treat the results table as trusted data that only your own workers write: anyone who can write to it can run code in the process that reads a result. Restrict database access accordingly, for example with a role that only the workers use to write the results table.

Leave serializer unset. A result is a TaskiqResult object, and taskiq's JSONSerializer and MSGPackSerializer raise TypeError when asked to store one, so they cannot replace pickle here.

Task progress

The result backend stores the progress that taskiq's ProgressTracker reports, in the progress column of the task's result row, so a client can read how far a task is while it runs:

import os

from taskiq import TaskiqDepends
from taskiq.depends.progress_tracker import ProgressTracker, TaskState

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend

dsn = os.environ["POSTGRESQL_URL"]
broker = PostgresqlBroker(dsn=dsn).with_result_backend(
    PostgresqlResultBackend(dsn=dsn),
)


# A task asks for the tracker as a dependency; decorate it with @broker.task.
async def import_rows(tracker: ProgressTracker[dict] = TaskiqDepends()) -> None:
    await tracker.set_progress(TaskState.STARTED, {"done": 0})
    await tracker.set_progress(TaskState.STARTED, {"done": 50})


async def watch(task_id: str) -> None:
    progress = await broker.result_backend.get_progress(task_id)
    if progress is not None:
        print(progress.state, progress.meta)
  • Progress is JSON, whatever serializer is set, and meta must be JSON serializable: set_progress raises ValueError, and writes nothing, when it is not. A database never holds a pickle that a reader unpickles for it here.
  • get_progress returns None for a task with no row or no progress. A later report replaces the earlier one.
  • A row may hold progress, a result or both, each written on its own: a result never erases the progress, and the progress never erases a result. Only a row with a result is a ready result. is_result_ready is False and get_result raises ResultIsMissingError for a row that holds only progress, and with keep_results=False the read leaves that row alone. Reading a real result with keep_results=False deletes the row, progress included.
  • store_progress=False makes set_progress do nothing. Reading, and the table with its progress column, do not depend on it.

Storing progress changes the results table (see Database schema), and a reader that does not know about progress takes a row that holds only progress for a ready result and fails. Upgrade every process that reads results (wait_result, get_result, is_result_ready) before any worker stores progress: first the SQL or one start with run_migrations=True, then the readers, then the workers, with store_progress=False on the workers' backend until every reader is upgraded. The changelog's "Upgrading from 0.4.x" has the whole list.

Cleaning up old results

Results stay in the table until something deletes them. Set result_ttl, then pick what runs the cleanup:

Path You set It runs Pick it when
taskiq scheduler (recommended) result_ttl and cleanup_interval=None, and call register_cleanup(broker, cron=...) As one task that taskiq scheduler kicks, on one worker you run, or can run, taskiq scheduler
built-in timer result_ttl only (cleanup_interval keeps its default) In every process that calls broker.startup(): workers, taskiq scheduler and any client that starts the broker; a lock lets one delete at a time you run no scheduler
your own call result_ttl and cleanup_interval=None, and await result_backend.cleanup() after startup() Where and when you call it another scheduler already drives your jobs
CLI (optional) result_ttl (or --older-than), and cleanup_interval=None when you schedule it Once per taskiq postgresql cleanup app:broker, from a shell, the operating system's cron or a Kubernetes CronJob you schedule jobs outside Python, or want one cleanup now
pg_cron (optional) cleanup_interval=None, the pg_cron extension on the server, and the SQL that taskiq postgresql cleanup app:broker --pg-cron SCHEDULE prints Inside PostgreSQL, one batch per run, as the role that scheduled it your server already runs pg_cron

What every path shares.

  • result_ttl measures the time since the row was last written, not since it was created. Storing a result and storing progress both renew the clock (the updated_at column), so a task that reports progress for an hour is not deleted while it does. It applies to every row of the table, so give the backend a table of its own. The broker's table is never touched.
  • A run deletes the oldest rows first, cleanup_batch_size at a time, and goes on while a batch is full. Only one process runs a batch at a time (a transaction-scoped advisory try-lock, released when the batch's transaction ends); a process that finds another batch running deletes nothing that time. Between two batches of one run another process can take the lock, so the batches of two runs interleave: every row is still deleted once. A row another transaction has locked is left for the next run. A run that deleted rows logs how many at INFO, never a task id. taskiq postgresql cleanup prints the count on stderr instead; a pg_cron job writes none of its own, and what pg_cron records of a run is in cron.job_run_details.
  • result_ttl needs the DELETE privilege (Privileges).
  • A failed run is reported by the type of the error, the type of its cause when it has one (psycopg and psqlpy wrap every error in their own), and a SQLSTATE when the error or its cause carries one, such as 42501 for a missing privilege. Never its message, which can hold a connection string or a row. The timer logs it as a warning; the scheduled task raises it; taskiq postgresql cleanup prints it and exits with 1.

Adding the updated_at column is step 3 of the results table. Rows written before it count from the moment the step ran, so nothing is deleted the day the release is installed: the oldest of them goes result_ttl after the step. They all carry the same time, so the first run after result_ttl has passed deletes the whole backlog at once, batch after batch with no pause between them: on a large table that is a burst of WAL, replication lag and vacuum work. A smaller cleanup_batch_size keeps each statement short but adds no pause. To choose when it happens, use register_cleanup with a cron in a quiet hour, or call cleanup() yourself then, with cleanup_interval=None in both cases. A process still on 0.5.0 does not renew updated_at when it writes: upgrade every process that writes results before relying on result_ttl.

With taskiq scheduler (recommended). register_cleanup registers the cleanup as a task with a schedule label, which LabelScheduleSource reads:

import os
from datetime import timedelta

from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource

from taskiq_postgresql import (
    PostgresqlBroker,
    PostgresqlResultBackend,
    register_cleanup,
)

result_backend = PostgresqlResultBackend(
    dsn=os.environ["POSTGRESQL_URL"],
    run_migrations=True,
    result_ttl=timedelta(days=7),
    cleanup_interval=None,
)
broker = PostgresqlBroker(dsn=os.environ["POSTGRESQL_URL"]).with_result_backend(
    result_backend,
)
register_cleanup(broker, cron="0 3 * * *")
scheduler = TaskiqScheduler(broker, sources=[LabelScheduleSource(broker)])

With this in app.py, run a worker and a scheduler:

taskiq worker app:broker
taskiq scheduler app:scheduler
  • Call register_cleanup in the module that both taskiq worker and taskiq scheduler import, the one that builds the broker: the scheduler reads the label to know when to kick the task, and the worker needs the task to run it.
  • register_cleanup needs a PostgresqlResultBackend with result_ttl set and cleanup_interval=None, and raises otherwise. The scheduled task replaces the built-in timer, which starts in every process that calls broker.startup() and would run beside the task in all of them.
  • cron is read in UTC and is checked when register_cleanup is called. Write five fields separated by single spaces, numbers only, and Sunday as 0: * as a whole field, */n, a range such as 1-5 (ascending), a-b/n, or a comma list of those. Anything else (day names, 7 for Sunday, a number out of range, */0, a range such as 5-1, * inside a list) raises ValueError. A day of month that none of the listed months has, such as 31 in February, is not refused and never runs.
  • cron_offset takes a time zone name ("Europe/Lisbon") or a timedelta added to the clock. The name is checked with Python's zoneinfo when register_cleanup runs, so that process needs a tz database: the system's, or the tzdata package where there is none, such as Windows or Alpine. A duration string such as "PT1H" is refused: pass a timedelta.
  • Run one taskiq scheduler: it kicks one message per tick and one worker runs it. If two schedulers run, each tick kicks two cleanups; the lock lets one statement run at a time, so no row is deleted twice.
  • The task's count is stored as a result like any other, and result_ttl deletes it in time.
  • A scheduler takes several sources. With the Quickstart's PostgresqlSchedulerSource, add the label source beside it, sources=[scheduler_source, LabelScheduleSource(broker)], rather than replacing it.

With the built-in timer. With result_ttl and no scheduler, the backend deletes the rows that have not been written for that long:

import os
from datetime import timedelta

from taskiq_postgresql import PostgresqlResultBackend

result_backend = PostgresqlResultBackend(
    dsn=os.environ["POSTGRESQL_URL"],
    result_ttl=timedelta(days=7),
    run_migrations=True,
)
  • startup() starts a timer when both result_ttl and cleanup_interval are set, in every process that calls broker.startup(): workers, taskiq scheduler and any client that starts the broker. Its first run waits a random time of up to cleanup_interval, so workers started together do not all clean at once; after that it runs every cleanup_interval, and shutdown() stops it. A failed run is logged as a warning and the next run is tried.

With your own call. For a process that wants its own schedule (another scheduler that already runs your jobs):

  • await result_backend.cleanup() runs one cleanup and returns how many rows it deleted: call it after startup(), with cleanup_interval=None so no timer runs too. It raises ValueError when result_ttl is None.

With the CLI (optional). taskiq postgresql cleanup runs one cleanup from outside the application, with no code, on every PostgresqlResultBackend that its TARGETs bring. TARGET is read as for taskiq postgresql migrate (module:object of a broker, a TaskiqScheduler or a component, and --app-dir); a target with no result backend is an error.

taskiq postgresql cleanup app:broker
taskiq postgresql cleanup app:broker --dry-run
taskiq postgresql cleanup app:broker --older-than 86400 --batch-size 500
  • Run without a mode flag, it deletes the rows not written for result_ttl, cleanup_batch_size at a time and while a batch is full, as cleanup() does, and prints on stderr how many it deleted. --older-than SECONDS and --batch-size N replace the backend's values for that run. On a backend without result_ttl, --older-than alone sets the age; with neither, the command exits with 1.
  • --older-than below the backend's result_ttl deletes results that clients may not have read yet. The command prints a warning on stderr and goes on.
  • --dry-run counts the results that are older than the age, prints that count and the number of batches it would take on stderr, takes no lock and deletes nothing.
  • The lock is the one every path shares. When another session holds it, the command deletes nothing more, prints a line on stderr that says so and still exits with 0, so a CronJob does not alert: run it again for the rest.
  • Exit status: 0 success; 1 an error (a target without a result backend, a backend without result_ttl and no --older-than, a connection or server error); 2 a usage error.
  • The command does not start the backend, so it starts no timer and runs no DDL: the table needs step 3 below (taskiq postgresql migrate creates it), and without it the command fails with 1.
  • Whoever runs it needs SELECT, UPDATE and DELETE on the results table (Privileges).
  • To run it on a schedule, from the operating system's cron or a Kubernetes CronJob, build the backend with cleanup_interval=None in the application's processes, so that their built-in timers do not run beside it.

With pg_cron (optional). If your server already runs pg_cron, it can run the cleanup inside PostgreSQL. The library never requires, creates or checks it: --pg-cron connects to nothing and prints the SQL. What follows is the setup its README describes at v1.6.8; read that README for your version.

  1. Install the pg_cron package for your server's major version (for example postgresql-18-cron on Debian and Ubuntu, pg_cron_18 on Red Hat and Fedora), at version 1.5 or later. The pg_cron changelog puts named jobs in 1.3, cron.schedule_in_database in 1.4 and cron.timezone in 1.5.

  2. Add shared_preload_libraries = 'pg_cron' to postgresql.conf and restart PostgreSQL. A reload is not enough: the cron.* settings other than cron.log_min_messages and cron.launch_active_jobs also need a restart.

  3. Set cron.database_name (default postgres) to the database that holds the results table. pg_cron can be installed in one database of a cluster; for a results table in another, use --database (below).

  4. In that database, as a superuser, run CREATE EXTENSION pg_cron;, and give the role that schedules the job USAGE on the cron schema:

    CREATE EXTENSION pg_cron;
    GRANT USAGE ON SCHEMA cron TO taskiq;
  5. Let the job connect. By default pg_cron opens a libpq connection to cron.host (default localhost) as the job's role, which pg_hba.conf has to allow: its README suggests trust for that role from localhost, a password in a .pgpass file that libpq reads, or a Unix socket directory as cron.host with trust for local connections. Limit any trust rule to the job's role and to local connections. The alternative is cron.use_background_workers = on, which runs jobs in background workers instead of connections, limited by max_worker_processes. If the job cannot connect it cannot run: look at cron.job_run_details and the server log.

  6. Give the role a search_path that finds the table. The command names the table as you configured it, without a schema, and a new session takes the search_path of its role and database, not the one in your application's connection string. With the table outside the default path, set it for the role (names here are examples; taskiq is the schema that holds the table):

    ALTER ROLE taskiq IN DATABASE app SET search_path = taskiq;

    The example leaves public out on purpose: the job resolves the table, and any function a trigger on it calls without a schema, through this path, and the first match wins. pg_catalog is searched first unless the path names it. A schema that other roles can create objects in has no place on the path: in a database upgraded from PostgreSQL 14 or earlier, everyone can create objects in public unless REVOKE CREATE ON SCHEMA public FROM PUBLIC was run. See the PostgreSQL documentation on schemas.

Build the backend with cleanup_interval=None in every process, as for the taskiq scheduler: the command exits with 2 for a backend whose built-in timer would run, which is one with both result_ttl and cleanup_interval set. Then print the SQL, and apply it as the role that should own the job, in the pg_cron database:

taskiq postgresql cleanup app:broker --pg-cron '*/5 * * * *' > taskiq_cleanup_cron.sql
psql "$POSTGRESQL_URL" -v ON_ERROR_STOP=1 -f taskiq_cleanup_cron.sql

For a backend built as in the taskiq scheduler example above (a week of result_ttl, the default table and batch size), the file holds one statement:

SELECT cron.schedule('taskiq_postgresql.cleanup.taskiq_results', '*/5 * * * *', 'WITH gate AS (SELECT pg_try_advisory_xact_lock(hashtext(''taskiq_postgresql.cleanup''::text), hashtext(''taskiq_results''::text)) AS taken), doomed AS (SELECT task_id FROM taskiq_results WHERE (SELECT taken FROM gate) AND updated_at < NOW() - make_interval(secs => ''604800.0''::double precision) ORDER BY updated_at LIMIT ''1000''::bigint FOR UPDATE SKIP LOCKED), deleted AS (DELETE FROM taskiq_results WHERE task_id IN (SELECT task_id FROM doomed) RETURNING 1) SELECT (SELECT taken FROM gate) AS taken, (SELECT count(*) FROM deleted) AS deleted');
  • It runs one batch per run: at most cleanup_batch_size rows (1000 by default), with no loop. That is a trade-off: pick a schedule and a batch size that delete faster than results are written, and use --dry-run to measure a backlog. pg_cron starts one instance of a job at a time and queues a second until the first ends. The lock above still applies: a run that finds it held deletes nothing.
  • A session that keeps the lock for good stops every cleanup, whichever way it runs, and none of them reports it as a failure: the CLI exits with 0 and cron.job_run_details records the run as a success. An advisory lock needs no privilege to take. "A held lock" below shows how to find it.
  • --older-than and --batch-size set the age and the batch size written into the SQL, and the warning for an --older-than below result_ttl is the same.
  • The schedule takes the five numeric fields register_cleanup takes. The command accepts only the characters 0-9, *, ,, /, - and the space, at most 100 of them, which is a subset of what pg_cron accepts (it also reads day names, 7 for Sunday, $ and N seconds; this command refuses them). pg_cron reads the schedule in GMT unless cron.timezone says otherwise.
  • The job is named taskiq_postgresql.cleanup. and the table's name, folded to lower case. --job-name NAME sets another name, with one result backend: 1 to 100 characters from letters, digits, _, ., $ and -, not starting with ., $ or -. Check in the pg_cron documentation what scheduling a name that already exists does before you rely on a second run to replace the job.
  • The job runs in the database where cron.schedule is called, with the permissions of the role that called it, and a role sees only its own jobs. Schedule it with the role that writes the results, which needs SELECT, UPDATE and DELETE on the table (Privileges), not with a superuser. The reason is more than the privilege checks a superuser skips: each run's DELETE fires the triggers on the results table, and a trigger function runs as the role that runs the DELETE unless it is declared SECURITY DEFINER. The table's name, and any function a trigger calls without a schema, resolve through that role's search_path. So a job that belongs to a role more privileged than the table's owner lets the owner, or anyone who can create a relation of the same name earlier on that path, run SQL as that role every time the job fires. Keep the job's owner no more privileged than the table's owner, and keep schemas that other roles can write to off its search_path (step 6). The command lives in the cron.job table, so anyone who can write that table can change it.
  • pg_cron records each run in cron.job_run_details: the job, the status, a return message and the start and end times. It does not clean that table, and cron.log_run = off turns it off. Look there first when a job does not do what you expect, and use --dry-run for the number of results that are due.

A held lock. This query shows the sessions that hold, or wait for, the cleanup lock of the default table. For another table, put its name, in lower case, in the last hashtext:

SELECT l.pid, l.granted, a.usename, a.application_name, a.state, a.xact_start, a.query
FROM pg_locks AS l
JOIN pg_stat_activity AS a ON a.pid = l.pid
WHERE l.locktype = 'advisory'
  AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
  AND l.objsubid = 2
  AND l.classid = hashtext('taskiq_postgresql.cleanup')::oid
  AND l.objid = hashtext('taskiq_results')::oid;

pg_locks shows the two keys of an advisory lock as oid, which is unsigned, and hashtext returns a signed integer, hence the casts. A cleanup that is running holds the lock until its batch's transaction ends, so a row that stays for minutes is the one to look at: xact_start says since when, and pg_terminate_backend(pid) ends that session. The details of another role's session need a superuser or a member of pg_read_all_stats. Watch the table as well: its size (pg_total_relation_size('taskiq_results')) and the age of its oldest row, SELECT now() - min(updated_at) FROM taskiq_results, which should stay near result_ttl plus the time between runs.

Stopping the job. Remove it by name, in the pg_cron database. The name below is the default for the example's table; with --job-name, use that one:

SELECT cron.unschedule('taskiq_postgresql.cleanup.taskiq_results');

Two databases. A job that cron.schedule creates runs in the database where it is called, the one pg_cron is installed in. For a results table in another database of the same server, --database NAME prints cron.schedule_in_database(..., 'NAME') instead (version 1.4 of pg_cron or later, which step 1 above already asks for). NAME is 1 to 63 bytes with no control character, line break or invisible format character (such as a zero-width space or a right-to-left override). Like --job-name, it takes one result backend: with several, the command exits with 2, so run it once for each database. Both jobs are created in the pg_cron database and the default name has no database in it, so give each its own name with --job-name. With cron.database_name = 'orders', and a second application whose results are in the billing database:

taskiq postgresql cleanup orders.worker:broker --pg-cron '*/5 * * * *' --job-name taskiq_cleanup_orders
taskiq postgresql cleanup billing.worker:broker --pg-cron '*/5 * * * *' --job-name taskiq_cleanup_billing --database billing

Apply both outputs with psql in the orders database. The role that owns the billing job needs the same three privileges on that table, in billing. The command does not check that the database exists: a wrong name is a job that fails on every run. Check in the pg_cron documentation which privilege cron.schedule_in_database needs and whether cron.unschedule removes a job by the name you gave it; this README does not say.

Step 3 of the results table. Every write now also updates updated_at, so it is no longer a HOT update: expect more index writes and a little more bloat on a table with many rewrites of the same row.

Step 3 is not lock-free on a large table. Every path that runs it (run_migrations=True, taskiq postgresql migrate, the SQL that generate and plan print, the Alembic revision, the Django migration) runs it in one transaction, so the table is locked against reads and writes from the ALTER TABLE until the commit, and the index is built meanwhile: every set_result, set_progress, is_result_ready and get_result waits for as long as the build takes, which grows with the number of rows. On a large table, before you deploy, add the column and build the index yourself. First the column:

ALTER TABLE taskiq_results
  ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW();

Then the index, outside a transaction (a psql run with --single-transaction is one):

CREATE INDEX CONCURRENTLY IF NOT EXISTS taskiq_results_updated_at_idx
  ON taskiq_results (updated_at);

With another table name, use it in both statements and in the index name. After that, run_migrations=True and taskiq postgresql migrate plan first and find nothing pending, so they run no DDL. The Django migration 0004, the script generate prints and the other migration formats run the step's statements whatever the database holds: both are IF NOT EXISTS no-ops that take only a brief ACCESS EXCLUSIVE lock and build nothing. If CREATE INDEX CONCURRENTLY fails, it leaves an invalid index. That does not make the step pending, and plan and check report it as advisory: run DROP INDEX CONCURRENTLY IF EXISTS taskiq_results_updated_at_idx; and build it again.

PostgresqlSchedulerSource

Argument Type Default Meaning
dsn str or Callable[[], str] required Connection string.
table_name str "taskiq_schedulers" Table that holds schedules.
driver str or Driver "asyncpg" Database driver.
startup_schedule dict[str, list[dict]] or None None Schedules to insert on startup, keyed by task name. Each entry needs cron or time and may have args, kwargs and cron_offset. A task that already has a stored schedule is skipped, and so is a task the broker does not know.
broker AsyncBroker or None None Needed only with startup_schedule, to look the tasks up.
run_migrations bool False Create the table and indexes on startup. Off, startup only checks them; see Check at startup.
**connect_kwargs Any none Keyword arguments for the connection pool of a driver chosen by name. With a driver instance, pass none and give the options to the instance.

The source implements taskiq's ScheduleSource (get_schedules, add_schedule, delete_schedule, post_send). A schedule with a time is deleted after it is sent. schedule_id is stored in a UUID column, so keep the generated value or pass a UUID string.

Table names, in all three components, and the broker's channel_name are checked when the component is built and then written into SQL unquoted. A name is accepted when it is made of ASCII letters, digits, _ and $, does not start with a digit or $, is at most 63 bytes, is not a reserved word and is not schema-qualified (put the schema on the role's search_path instead); anything else raises ValueError. A table name must also leave room for the names derived from it (the primary key, the sequence and the indexes): at most 61 bytes for every component. A name with upper case letters works, as PostgreSQL folds it, and warns with a DeprecationWarning: configure it in lower case. Python hides that warning by default outside __main__; it shows under pytest or with python -W default. Switching has a cost. The broker's channel column keeps the spelling that was configured when a row was stored, so after switching a channel name, a worker does not claim rows stored under the old spelling: stop producers and workers, then drain the queue or run UPDATE <table> SET channel = '<new>' WHERE channel = '<old>'. A table name is hashed as configured into the migration lock key, so switch a table name with no migration pending or with the workers stopped. Use identifiers you control, never user input.

Driver options

With a driver chosen by name, the keyword arguments (connection_kwargs of the broker, **connect_kwargs of the other two) go to that driver. With an instance they go to its constructor, AsyncpgDriver(listen_options=..., **pool_options), and the component takes no connection_kwargs or **connect_kwargs of its own: passing one raises TypeError. The other options of the component, such as table_name, are still accepted. The options are the ones of the library the driver wraps:

Driver Pool LISTEN connection
asyncpg asyncpg.create_pool asyncpg.connect
psycopg psycopg_pool.AsyncConnectionPool psycopg.AsyncConnection.connect
psqlpy psqlpy.ConnectionPool psqlpy.ConnectionPool

The LISTEN connection of a driver instance takes the connection options of its pool, so a TLS or credential option given once reaches both. The options that exist for the pool alone stay out: for asyncpg those that size it or hook its connections (init_size, min_size, max_size, max_queries, max_inactive_connection_lifetime, connect, setup, init, reset and loop); for psqlpy max_db_pool_size and conn_recycling_method; for psycopg everything but the pool's kwargs, which holds the options of its connections. Give listen_options to use another set: it replaces them, and is not merged with them.

import os

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend

dsn = os.environ["POSTGRESQL_URL"]

# A pool option goes to the result backend directly; the broker shares its
# kwargs with the LISTEN connection, so give it only options both accept.
result_backend = PostgresqlResultBackend(dsn=dsn, min_size=1, max_size=10)
broker = PostgresqlBroker(
    dsn=dsn,
    connection_kwargs={"command_timeout": 30},
).with_result_backend(result_backend)

A driver instance has its own first-LISTEN deadline. psqlpy and psycopg give up the first LISTEN of a listener after the listen_probe_timeout of the instance, 30 s by default, or wait with no deadline for None; asyncpg has no such option. Chosen by name, the broker passes its own query_timeout as that deadline, so with an instance the broker's query_timeout does not set it.

Delivery

kick() stores each message in the broker's table in one INSERT, together with the broker's channel and the time the message becomes due. The PostgreSQL server computes that time from its own clock: NOW(), plus the delay label in seconds when the message has one, as @broker.task(delay=...) and SmartRetryMiddleware set. A message due at once is also announced with NOTIFY, and a listening worker claims it right away. A delayed message gets no NOTIFY, and nothing waits for it in the process that sent it, so it is delivered even if that process exits before the delay ends. If the NOTIFY fails once the message is stored, kick() logs a warning and returns, and the next sweep delivers the message; an error while storing it is raised to the caller.

Every worker sweeps the table for the due messages of its channel, earliest due first, when it starts listening and then every poll_interval seconds, however many notifications arrive in between. The sweep also delivers a message whose NOTIFY reached no worker, because none was listening or the LISTEN connection was down. No message is claimed before it is due. Once it is due, a running worker of its channel that keeps up with its messages claims it within about poll_interval seconds.

A worker claims a message by deleting its row (DELETE ... RETURNING), so each message reaches one worker only. Delivery is at most once: a claimed message is gone from the table, and a worker that stops before finishing the task does not give it back.

Lost connections

If the LISTEN connection closes or fails, the worker logs one warning, keeps delivering through the sweep and opens the connection again. It waits about 0.5 s before the first attempt and twice as long after each failed one, up to 30 s, logging a warning for each failure and an INFO line once LISTEN works again.

A connection can also go silent without closing: a NAT or a load balancer that drops an idle flow sends no FIN or RST, so the client still sees an open socket that never gets an answer. When the LISTEN connection has been quiet for health_check_interval seconds, the worker sends the same LISTEN again, which changes nothing on the server, and reopens the connection if no answer comes within query_timeout seconds. With psycopg the check runs every health_check_interval seconds, even while notifications arrive. These checks also keep the flow alive in a NAT, and pg_stat_activity keeps showing the LISTEN. The server keeps the abandoned session, still listening, until its own TCP keepalive notices the dead client (tcp_keepalives_idle, which defaults to the operating system's two hours on Linux); set it, and tcp_user_timeout, on the server to free such sessions sooner.

With asyncpg and psycopg, a claim that gets no answer within query_timeout seconds is given up and logged as an error, a connection that does not answer is dropped from the pool, and the sweep tries again. The connection is then aborted, which gets one more second at most to end the wait, so a claim is given up within query_timeout plus that second. A pool gets over silent connections one claim at a time, so with several of them the sweep delivers again after each has timed out once. A claim given up after its DELETE was done loses that message, as any lost answer to a claim does under at-most-once delivery.

shutdown() gives a connection that does not answer query_timeout seconds to close and then closes it by force, so with silent connections it may take up to about twice query_timeout.

query_timeout does not bound psqlpy's claims. psqlpy can neither cancel a query on the server nor drop one pooled connection, so a claim it gave up would leave its DELETE queued, to run later and take a row nobody receives. A claim on a silent psqlpy connection, and listen() with it, waits until the operating system gives up on the socket, which by default takes about 15 minutes on Linux. To shorten that, set psqlpy's tcp_user_timeout_sec and its keepalives_* settings in connection_kwargs.

TLS

The broker, the result backend and the scheduler source each open their own connections, so give all three the same TLS settings. To verify the server certificate and its host name, each driver takes its own options:

  • asyncpg: the ssl keyword argument, here an ssl.SSLContext that trusts your CA and checks the host name (the default of create_default_context).
  • psycopg: sslmode=verify-full and sslrootcert in the DSN. They are libpq parameters, so the same DSN serves all three components.
  • psqlpy: the ssl_mode and ca_file keyword arguments.

The blocks below give each component its own driver instance, with the options in its constructor. The broker's LISTEN connection takes the same options as its pool, so it verifies the server too.

import os
import ssl

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend
from taskiq_postgresql.drivers import AsyncpgDriver
from taskiq_postgresql.scheduler_source import PostgresqlSchedulerSource

dsn = os.environ["POSTGRESQL_URL"]
tls = {"ssl": ssl.create_default_context(cafile="/path/to/ca.pem")}

broker = PostgresqlBroker(dsn=dsn, driver=AsyncpgDriver(**tls))
result_backend = PostgresqlResultBackend(dsn=dsn, driver=AsyncpgDriver(**tls))
scheduler_source = PostgresqlSchedulerSource(dsn=dsn, driver=AsyncpgDriver(**tls))

For psycopg the options live in the DSN, so nothing else changes:

postgresql://<user>@<host>:5432/<database>?sslmode=verify-full&sslrootcert=/path/to/ca.pem
import os

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend
from taskiq_postgresql.drivers import PsycopgDriver
from taskiq_postgresql.scheduler_source import PostgresqlSchedulerSource

dsn = os.environ["POSTGRESQL_URL"]  # the DSN above

broker = PostgresqlBroker(dsn=dsn, driver=PsycopgDriver())
result_backend = PostgresqlResultBackend(dsn=dsn, driver=PsycopgDriver())
scheduler_source = PostgresqlSchedulerSource(dsn=dsn, driver=PsycopgDriver())

For psqlpy:

import os

from psqlpy import SslMode

from taskiq_postgresql import PostgresqlBroker, PostgresqlResultBackend
from taskiq_postgresql.drivers import PsqlpyDriver
from taskiq_postgresql.scheduler_source import PostgresqlSchedulerSource

dsn = os.environ["POSTGRESQL_URL"]
tls = {"ssl_mode": SslMode.VerifyFull, "ca_file": "/path/to/ca.pem"}

broker = PostgresqlBroker(dsn=dsn, driver=PsqlpyDriver(**tls))
result_backend = PostgresqlResultBackend(dsn=dsn, driver=PsqlpyDriver(**tls))
scheduler_source = PostgresqlSchedulerSource(dsn=dsn, driver=PsqlpyDriver(**tls))

Keep the password out of the source and out of version control: read the DSN from the environment or a secret store, or pass a callable as dsn.

Database schema

With run_migrations=True the package runs this SQL, shown with the default table names and field_for_task_id="Uuid". A test builds the same statements from the code and compares them with these blocks. taskiq postgresql generate prints them for your own names (see Migrations).

The broker (taskiq_messages):

CREATE TABLE IF NOT EXISTS taskiq_messages (
    id SERIAL NOT NULL PRIMARY KEY,
    task_id Uuid NOT NULL,
    task_name VARCHAR NOT NULL,
    message BYTEA NOT NULL,
    labels JSONB NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS taskiq_messages_id_idx ON taskiq_messages USING HASH (id);
ALTER TABLE taskiq_messages
  ADD COLUMN IF NOT EXISTS channel VARCHAR,
  ADD COLUMN IF NOT EXISTS not_before TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS taskiq_messages_not_before_idx
  ON taskiq_messages (channel, not_before, id);

channel holds the broker's channel_name and not_before the time the message becomes due. They are added by ALTER TABLE rather than in CREATE TABLE, so a new table and one created by 0.4.x end up with the same columns.

The result backend (taskiq_results):

CREATE TABLE IF NOT EXISTS taskiq_results (
    task_id Uuid NOT NULL PRIMARY KEY,
    result BYTEA NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS taskiq_results_task_id_idx ON taskiq_results USING HASH (task_id);
ALTER TABLE taskiq_results
  ADD COLUMN IF NOT EXISTS progress BYTEA;
ALTER TABLE taskiq_results ALTER COLUMN result DROP NOT NULL;
ALTER TABLE taskiq_results
  ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS taskiq_results_updated_at_idx ON taskiq_results (updated_at);

progress holds the task's progress as JSON (Task progress), and result accepts NULL because a row can hold progress before it holds the result; a row with result IS NULL is not a ready result. Like the broker's columns, progress is added by ALTER TABLE, so a new table and one created by 0.4.x end up the same. DROP NOT NULL is the one statement of the package that changes a column instead of adding one, and it takes an ACCESS EXCLUSIVE lock on the table for a moment. updated_at is the clock result_ttl reads (Cleaning up old results); every upsert renews it, and the btree index on it serves the cleanup.

The scheduler source (taskiq_schedulers):

CREATE TABLE IF NOT EXISTS taskiq_schedulers (
    id UUID NOT NULL PRIMARY KEY,
    task_name VARCHAR(100) NOT NULL,
    schedule JSONB NOT NULL,
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS taskiq_schedulers_id_idx ON taskiq_schedulers USING HASH (id);
CREATE INDEX IF NOT EXISTS taskiq_schedulers_task_name_idx ON taskiq_schedulers USING HASH (task_name);

task_id has the type set by field_for_task_id (VarChar, Text or Uuid). A broker message is deleted when a worker claims it (DELETE ... RETURNING), which is why only one worker gets each message.

Privileges

Once the tables, indexes and columns above exist, no role needs a DDL privilege. Besides USAGE on the schema, a role that sends tasks needs INSERT and SELECT on the broker's table (the INSERT returns the new id) and USAGE on its taskiq_messages_id_seq sequence. A worker needs SELECT, UPDATE and DELETE on the broker's table: UPDATE because the sweep locks the row it claims with FOR UPDATE SKIP LOCKED. A worker that also sends tasks, for example through SmartRetryMiddleware, needs both sets.

A role that uses the result backend needs SELECT, INSERT and UPDATE on its table, and DELETE with keep_results=False or with result_ttl. Storing progress needs nothing more than storing a result: both are one upsert, on different columns.

Whoever runs taskiq postgresql cleanup, or owns the pg_cron job that does, needs SELECT, UPDATE and DELETE on the results table: the cleanup locks the rows it deletes with FOR UPDATE SKIP LOCKED, which needs UPDATE.

Migrations

There are three ways to create the tables and their indexes:

  • run_migrations=True, as in the quickstart: each process creates what is missing when it starts.
  • taskiq postgresql migrate, once per deploy before the workers start, for example in a release job. The workers then run with run_migrations=False.
  • taskiq postgresql generate, which prints the SQL so that you run it yourself or hand it to your migration tool, or taskiq postgresql plan, which prints only the SQL one database still lacks.

taskiq postgresql check tells whether a database has every table, column and index, so that a deploy can stop before the workers start; a component that does not migrate runs the same check when it starts (Check at startup).

SQLAlchemy, SQLModel, Alembic and Django can also hold the tables (see Integrations).

The commands take the module:object paths that taskiq worker and taskiq scheduler take, and --app-dir like them. A broker brings its result backend when that is a PostgresqlResultBackend, and a TaskiqScheduler brings its broker and its PostgresqlSchedulerSource sources; a table named twice is created once. The commands import your module but start nothing: generate never connects, migrate connects only to create the tables, and plan and check only to read the catalog, with each component's own DSN and driver. The exit status is 0 on success, 1 on an error or when a path holds no component of this package, and 2 on a usage error; plan and check also exit with 3 or 4 (Plan and check).

Generate the SQL

taskiq postgresql generate app:scheduler > taskiq_tables.sql
psql "$POSTGRESQL_URL" -v ON_ERROR_STOP=1 -f taskiq_tables.sql

Only the script goes to standard output; messages go to standard error. The script starts with a comment that names the package version and the tables, then runs in one transaction: it sets a lock timeout for that transaction, takes, per table, the advisory lock run_migrations=True takes, then creates each table and index with IF NOT EXISTS, adds the broker's channel and not_before columns and their index the same way, which also upgrades a broker table created by 0.4.x, adds the results table's progress column and lets its result accept NULL, and adds its updated_at column and the index on it. The statements are the ones in Database schema, with your table names and field_for_task_id.

The script is idempotent: a second run changes nothing, and the advisory lock lets it run while workers with run_migrations=True are starting. It is not lock-free. On a live database it locks the tables even when nothing is missing: CREATE INDEX waits for every open transaction that wrote to the table, and ALTER TABLE for every open transaction that used it, before they find that the index or the column exists, and every later query on the table, the producers' INSERT included, waits behind the ALTER TABLE. So the script starts with SET LOCAL lock_timeout = '10s': a statement that waits that long for a lock, the advisory lock included, fails, and the whole script rolls back instead of stalling the broker. Run it again once the long transaction has ended. --lock-timeout SECONDS sets another limit; --lock-timeout 0 leaves the statement out, so the session's own lock_timeout applies (PostgreSQL's default, 0, waits for ever). taskiq postgresql migrate checks first and runs no DDL when every table, column and index exists, so it takes no table lock on a database that is already up to date, and taskiq postgresql plan prints only the steps a database still lacks (Plan and check).

To generate without importing the application, for example where its settings are not available, name one component per call. --table-name and --field-for-task-id default to the component's own defaults:

taskiq postgresql generate --component broker --table-name taskiq_messages --field-for-task-id Uuid

--no-transaction leaves out BEGIN and COMMIT, and --no-lock the lock. Without BEGIN, SET LOCAL lock_timeout is the first statement and lasts until the transaction that runs the script ends; outside a transaction PostgreSQL ignores it with a warning. --format picks another output format, when a package has installed one (see Writing a migration format), and --option KEY=VALUE passes options to it.

Apply it with migrate

taskiq postgresql migrate app:scheduler

migrate runs the code run_migrations=True runs at startup, whatever the components set, then closes its connections. It does not start the broker, so nothing listens, and it inserts no startup_schedule. To create what is missing, the role it connects with needs CREATE on the schema, and must own a table to add a missing index to it.

From then on the workers can run with run_migrations=False and a role that only reads and writes rows. With the default table names:

GRANT USAGE ON SCHEMA public TO taskiq_worker;
GRANT SELECT, INSERT, UPDATE, DELETE ON taskiq_messages, taskiq_results, taskiq_schedulers TO taskiq_worker;
GRANT USAGE ON SEQUENCE taskiq_messages_id_seq TO taskiq_worker;

Such a role can also keep run_migrations=True: once every table and index exists, startup only checks for them.

Plan and check

plan reads the catalog of one database, in one read-only query, and prints the SQL of the migration steps that database still lacks, and only that: on a database that has every step it prints nothing. On a broker table that 0.4.x created, that is the step that adds channel and not_before:

taskiq postgresql plan app:scheduler > taskiq_pending.sql
psql "$POSTGRESQL_URL" -v ON_ERROR_STOP=1 -f taskiq_pending.sql

The script is the one generate writes, with the same lock timeout and advisory lock and the same options (--lock-timeout, --no-transaction, --no-lock, --format), for the pending steps only. A comment after the version line names the database and search_path the plan was computed for: it is right for that database at that moment, and each statement still only adds what is missing, or relaxes a NOT NULL that is still there. The locks each step takes (note: lines) and what no step fixes (problem: lines), such as an invalid index or an index name that another table took, go to standard error, each with what to do. --format alembic writes a revision file with only the pending steps, and --format django a Django migration, whose first line is the same comment. A plan is for one database: when the components use different connection strings, pass --dsn, or plan one table at a time with --component.

check reads the same catalog and changes nothing. It reports each pending step and each problem on standard error, and --json also prints the report on standard output, as one object with the keys current, pending (each with table, kind, step, severity, what is missing: table, columns, indexes, and the not_null_columns the step still has to make nullable), problems (each with table, code, severity and detail) and advisory_only:

taskiq postgresql check app:scheduler --json

Both commands take --dsn to read another database than the components' own, and, like generate, --component with --table-name and --field-for-task-id to describe one table without importing the application; --component needs --dsn, and reads with the first driver installed of asyncpg, psycopg and psqlpy. Their query reads only pg_catalog, which every role can read by default, so a role without DDL privileges can run them.

Other users of the machine can read a command line (ps), and it stays in the shell history and in a CI job's definition: give --dsn a connection string without the password, and the password through a password file (~/.pgpass, or the file PGPASSFILE names) or PGPASSWORD. asyncpg and psycopg use them when the string has no password, PGPASSWORD first; psqlpy reads neither. When a driver cannot read the connection string, the error of plan, check and migrate leaves out the driver's message, which can quote part of the password, and says what to check; their other errors leave out the connection string and its password.

PGPASSFILE=/run/secrets/pgpass taskiq postgresql check --component broker --dsn postgresql://taskiq@db.internal/app

The exit status says what to do:

Exit status plan check
0 The plan is printed, or no step is pending. Up to date; a missing index alone only warns.
1 An error: the connection, the import of the application, a path without a component. The same.
2 A usage error. The same.
3 Not used. A table or a column is missing, or a column is still NOT NULL: a step is pending.
4 A problem no step fixes needs a person; the plan, if any, is still printed. The same; it wins over 3.

So a deploy can check the database before it starts the workers, with the workers' own configuration, and stop when a migration was forgotten: exit status 3 or 4 fails the step.

# In the deploy job, before the workers start.
taskiq postgresql check app:scheduler

Check at startup

A component with run_migrations=False, the default, reads the catalog once when it starts, with the query check runs, through its own connection pool, and compares its table with what this release needs. It runs no DDL. When the table, or a column that a step adds, is missing, startup() raises SchemaNotReadyError (from taskiq_postgresql.exceptions) before anything else starts, naming what is missing and how to create it. On a broker table that 0.4.x created:

taskiq_messages is not ready and run_migrations is off: step 2 has not run (missing columns: channel, not_before; missing indexes: taskiq_messages_not_before_idx). Create what is missing with `taskiq postgresql migrate <module>:<object>`, with the SQL `taskiq postgresql plan <module>:<object>` prints, or with an Alembic revision (`alembic revision --autogenerate`); or start once with run_migrations=True.

The same holds for a results table created before progress: its step 2 adds progress and relaxes result, so with run_migrations=False the backend refuses to start on it, whatever store_progress says, until the step has run. Step 3 (updated_at and its index) is checked the same way, whether or not result_ttl is set.

A missing index, or an index no step can fix (an invalid one, or one whose name another table took), logs a warning instead: the component works, if more slowly. With run_migrations=True startup reads the catalog the same way, takes the migration lock and runs the DDL only when a step is pending, and logs the same warning for an index no step can fix.

The check needs the database at startup: on one it cannot reach, startup() fails with DatabaseConnectionError before the worker starts, as it does with run_migrations=True. With psycopg that happens once the connection pool has waited for a connection for its timeout, 30 seconds by default.

Alembic, Django and Flyway

Flyway runs each migration in a transaction of its own, so give it the script without BEGIN and COMMIT. The lock and the lock timeout stay, and last until its transaction ends. Write the script as a versioned migration, with the next free version number:

taskiq postgresql generate app:scheduler --no-transaction > db/migration/V2__taskiq_tables.sql

A Flyway file holds the SQL of the release that generated it, and the script only adds what is missing or relaxes a NOT NULL that is still there, so when an upgrade changes the tables (the changelog says so), add a new migration with the new script.

For Alembic and Django, install their extra instead of copying the script. Alembic shows how autogenerate writes the steps a database lacks, each with a lock timeout that ends with the step, a helper for a revision of your own, and a format that writes the revision file. Django shows an app whose migrations run the steps, and a format that writes a migration file for an app of your own.

Writing a migration format

--format NAME loads the callable registered as NAME in the taskiq_postgresql.migration_formats entry-point group. This package registers sql; another package adds a format in its own pyproject.toml:

[project.entry-points."taskiq_postgresql.migration_formats"]
tables = "my_package.formats:render"

The callable takes the tables and the options, and returns the text that generate prints. This one lists the tables in Markdown:

from collections.abc import Sequence

from taskiq_postgresql.migrations import (
    FormatOptions,
    MigrationFormatOptionError,
    TableSchema,
)


def render(schemas: Sequence[TableSchema], options: FormatOptions) -> str:
    """List each table's columns and indexes in Markdown."""
    unknown = sorted(set(options.extra) - {"title"})
    if unknown:
        raise MigrationFormatOptionError(f"unknown options: {', '.join(unknown)}")
    lines = [f"# {options.extra.get('title', 'taskiq tables')}"]
    for table in schemas:
        lines.append(f"## {table.name} ({table.kind})")
        for column in table.columns:
            null = "null" if column.nullable else "not null"
            lines.append(f"- `{column.name}`: {column.type_name}, {null}")
        for index in table.indexes:
            columns = ", ".join(index.columns)
            lines.append(f"- index `{index.name}`: {index.method} on {columns}")
    return "\n".join(lines) + "\n"

The contract:

  • schemas is a sequence of TableSchema, one per table: kind, name, columns (ColumnSchema: name, sql_type, type_name, length, nullable, default, primary_key), indexes (IndexSchema: name, columns, method) and steps (MigrationStep: number, the SQL statements in the order they run, each idempotent, and objects, a StepObjects with creates_table and the columns and indexes the step creates). The columns and indexes are the table's shape after every step, except that indexes leaves out the primary key's own index, which CREATE TABLE creates and PostgreSQL names (taskiq_messages_pkey for taskiq_messages). Read the structure instead of parsing SQL; to emit SQL, reuse render_sql or the steps' statements as they are.
  • options is a FormatOptions: transaction and lock (False with --no-transaction and --no-lock), lock_timeout (the seconds of --lock-timeout, 10 by default, 0 for none), and extra, the --option KEY=VALUE pairs. Raise MigrationFormatOptionError for an option the format does not accept; generate then exits with 2.
  • A format may also take a keyword-only comments parameter, a sequence of lines: plan then passes the line that names the database the plan is for, to write as a comment at the top of the file. For a file another migration tool runs, render_steps(schemas, options, ...) refuses a comment, an option or a table name the file cannot hold, and returns each step with its comment lines and its statements, the lock and the lock timeout included.
  • When the format needs an optional dependency, import it at module level and put it in an extra named after the format. If the import fails, generate tells the user to run pip install '<your-package>[<format>]'. Listing the formats loads none of them.
  • Pick a name no other package uses. When several installed packages register one name, generate refuses it, exits with 2 and names the packages. A name this package registers, such as sql, always loads this package's own format, so no other package can replace it.

All these names are importable from taskiq_postgresql.migrations.

Integrations

SQLAlchemy, SQLModel, Alembic and Django can hold the tables too. Each integration is an extra, installed with the extra of your driver:

pip install "taskiq-postgresql[asyncpg,sqlalchemy]"
pip install "taskiq-postgresql[asyncpg,sqlmodel]"
pip install "taskiq-postgresql[asyncpg,alembic]"
pip install "taskiq-postgresql[psycopg,django]"

sqlmodel and alembic bring SQLAlchemy with them, and django brings Django. The integrations build the tables from the description that generate renders as SQL, so the columns, types, defaults, indexes and their names are the ones run_migrations=True creates. Like the commands, the SQLAlchemy, SQLModel and Alembic integrations take module:object paths (with app_dir= for --app-dir), components, brokers and schedulers. They also take table_schema(...) descriptions, which need neither your application nor a DSN; the Django app reads paths and such descriptions from its settings.

SQLAlchemy and SQLModel

add_taskiq_tables adds the tables to a MetaData as SQLAlchemy Table objects and returns them:

# models.py
from sqlalchemy.orm import DeclarativeBase

from taskiq_postgresql.contrib.sqlalchemy import add_taskiq_tables


class Base(DeclarativeBase):
    """The base class of your models."""


# The quickstart's app:scheduler brings its broker, the broker's result
# backend and the scheduler source.
taskiq_tables = add_taskiq_tables(Base.metadata, "app:scheduler")

Base.metadata.create_all(engine) then creates them along with your models. A table that the metadata already holds under the same name is reused if it is the same table; otherwise ValueError is raised. taskiq_metadata(...) returns a new MetaData that holds only these tables. The tables are not models: read and write them through the components.

With SQLModel, the tables go to SQLModel.metadata, or to the metadata= you pass:

from taskiq_postgresql.contrib.sqlmodel import add_taskiq_tables

add_taskiq_tables("app:scheduler")

Alembic

Import taskiq_postgresql.contrib.alembic in env.py and put the tables in target_metadata:

# alembic/env.py
from myapp.models import Base

from taskiq_postgresql.contrib.alembic import taskiq_metadata

target_metadata = [Base.metadata, taskiq_metadata("app:scheduler")]

Importing the module registers an autogenerate hook. alembic revision --autogenerate then reads which migration steps the database lacks and writes each one into the revision as op.execute(...) calls that hold the step's SQL: the statements run_migrations=True and generate run, the advisory lock first. On an empty database that is every step; on a database 0.4.x set up, only the step that adds the broker's channel and not_before; on an up-to-date one, nothing. The SQL is written out, so the revision never imports this package and keeps doing the same thing after you upgrade it. Its downgrade() leaves the steps in place: they only add columns and indexes, which an earlier release ignores. The hook takes the place of the create_table, add_column and create_index Alembic would write for these tables and keeps everything else, so a column whose type differs from the description still shows up.

If your models' metadata already holds the tables, as after add_taskiq_tables above, import the module for its hook and keep your metadata:

# alembic/env.py
import taskiq_postgresql.contrib.alembic  # noqa: F401  (the autogenerate hook)
from myapp.models import Base

target_metadata = Base.metadata

alembic check runs autogenerate without writing a revision, and fails while the database lacks a step that no revision adds, with New upgrade operations detected: [('taskiq_postgresql_step', 'taskiq_messages', 1), ...]. Run it in CI against an empty database that only Alembic migrates, so that a step a release adds fails the build until a revision brings it:

alembic upgrade head
alembic check

Autogenerate compares the revisions with the database it connects to. If workers with run_migrations=True already ran a step there, as on a shared development database, the step exists and the revision leaves it out; a production database that only Alembic migrates then never gets it. Generate revisions against a database that only Alembic migrates, or run the workers with run_migrations=False wherever Alembic owns the schema; alembic check in CI catches what slips through.

The lock each step takes holds until Alembic commits, and workers that start meanwhile wait for it. With the default transaction_per_migration=False that is the end of alembic upgrade; pass context.configure(..., transaction_per_migration=True) to commit after each revision instead.

Each step also bounds its own lock waits, as the script of generate does. It starts with SET LOCAL lock_timeout = '10s', so a statement that waits longer for a lock (the advisory lock, or ALTER TABLE on a table that a worker's open transaction has read) fails and Alembic rolls the revision back, instead of making every query on the table wait behind it. Its last statement gives the transaction back the lock_timeout it had, so your own migrations in the same revision wait for locks as before. Set the number of seconds with context.configure(..., taskiq_postgresql_lock_timeout=5) in env.py, which autogenerate writes into each step of the revision; 0 leaves both statements out, and the transaction's own lock_timeout applies. The lock and the bound only work inside the revision's transaction: upgrade_taskiq_tables raises RuntimeError on an autocommit connection (autocommit_block(), or an AUTOCOMMIT isolation level) instead of running the steps unbounded.

If the workers keep run_migrations=True and Alembic should leave the tables alone, keep them out of target_metadata and filter them out instead; otherwise autogenerate proposes op.drop_table for each of them:

# alembic/env.py
from taskiq_postgresql.contrib.alembic import exclude_taskiq_tables

include_object = exclude_taskiq_tables("app:scheduler")

Pass it as context.configure(..., include_object=include_object). It hides the tables, their columns and their indexes, from Alembic and from the hook. Alembic does not compare sequences, so the broker's sequence needs no filter. If you already have an include_object, include an object only when both do.

An autogenerated revision names the tables as they were where it was generated. When the names come from settings that differ between environments, write the revision by hand with upgrade_taskiq_tables. It runs the steps of each table up to the step through names, one statement at a time and in the revision's transaction. A released step never changes, so the revision runs the same SQL whatever release is installed; when a release adds a step, add a revision with the new through. Every table in a call must have that step, so tables with different numbers of steps take separate calls ([step.number for step in table_schema("broker").steps] lists them):

# alembic/versions/taskiq_tables.py
from alembic import op

from myapp.settings import QUEUE
from taskiq_postgresql.contrib.alembic import upgrade_taskiq_tables
from taskiq_postgresql.migrations import table_schema

revision = "taskiq_tables"
down_revision = None


def upgrade() -> None:
    upgrade_taskiq_tables(
        op,
        table_schema("broker", table_name=f"{QUEUE}_messages"),
        through=2,
    )
    upgrade_taskiq_tables(
        op,
        table_schema("result_backend", table_name=f"{QUEUE}_results"),
        table_schema("scheduler_source", table_name=f"{QUEUE}_schedulers"),
        through=1,
    )


def downgrade() -> None:
    pass

Pass field_for_task_id too if you changed it, and lock_timeout= to change the 10 seconds each call bounds its lock waits by (0 for no bound of its own). alembic upgrade --sql prints the statements instead of running them.

Without autogenerate, generate --format alembic writes a revision file with every step of each table, as autogenerate writes it for an empty database:

taskiq postgresql generate app:scheduler --format alembic --option revision=taskiq_tables > alembic/versions/taskiq_tables.py

The format takes these options:

  • revision: the revision id, made of letters, digits and _. By default, the first 12 hex digits of the SHA-256 of the statements, so the same tables give the same id.
  • down_revision: the revision it follows, usually your current head. By default there is none: it is a first revision.
  • downgrade: none (the default) leaves the tables in place; drop makes downgrade() drop them with DROP TABLE IF EXISTS, bounded by the same lock timeout as the steps. The table names must be plain SQL identifiers (letters, digits, _ and $, not starting with a digit): the format refuses others.

The file has no BEGIN or COMMIT, because Alembic runs each revision in its own transaction, so --no-transaction changes nothing; --no-lock leaves out the locks, and --lock-timeout sets each step's bound on lock waits as above. Any other option, or a value the format does not accept, exits with 2. plan --format alembic takes the same options and writes the same file with only the steps that the database it reads still lacks (Plan and check), under a first comment line that names that database and its search_path. It checks them before it connects, and refuses downgrade=drop, with exit status 2, when a table it would drop already exists, such as a broker table 0.4.x created that only needs step 2: the revision does not create that table, so its downgrade must not drop it.

Django

The django extra adds a Django app whose migrations create the tables with the SQL run_migrations=True runs. It allows Django 5.2 LTS (5.2.19 or later) and, on Python 3.12 and later, Django 6.0 and 6.1. Add the app to INSTALLED_APPS and name in TASKIQ_POSTGRESQL_TARGETS the components whose tables it creates, as the module:object paths the commands take:

# settings.py
INSTALLED_APPS = [
    # ... your apps
    "taskiq_postgresql.contrib.django",
]

# The quickstart's app:scheduler brings its broker, the broker's result
# backend and the scheduler source.
TASKIQ_POSTGRESQL_TARGETS = ["app:scheduler"]

Then migrate it with your other apps, or on its own:

python manage.py migrate taskiq_postgresql

The app, labelled taskiq_postgresql, has no models, only migrations: one per migration step. 0001 runs step 1 of every table (the table and its indexes) 0002 step 2 of the broker table (its channel and not_before, which also completes a broker table 0.4.x created), 0003 step 2 of the results table (progress, and result accepting NULL) and 0004 its step 3 (updated_at and its index); a release that adds a step adds a migration. Each migration runs its statements one at a time, in the migration's transaction. It first keeps the transaction's own lock_timeout, then sets SET LOCAL lock_timeout = '10s', so that a statement that waits longer for a lock fails and rolls the migration back instead of stalling the broker. It then takes the advisory lock run_migrations=True takes, so workers that start meanwhile wait for the migration, and runs statements that only add what is missing or relax a NOT NULL that is still there; its last statement gives the transaction back the lock_timeout it kept, so the other migrations of the same transaction wait for locks as before. python manage.py sqlmigrate taskiq_postgresql 0001 shows the SQL. Once the tables exist, the workers can run with run_migrations=False.

An entry can also be a dict that describes a table by kind, which needs no import of your application: kind is broker, result_backend or scheduler_source, and table_name and field_for_task_id default to the component's own. TASKIQ_POSTGRESQL_LOCK_TIMEOUT sets the seconds of the lock timeout; 0 leaves the bound out:

# settings.py
TASKIQ_POSTGRESQL_TARGETS = [
    {"kind": "broker", "table_name": "jobs", "field_for_task_id": "Text"},
    {"kind": "result_backend", "table_name": "job_results"},
]
TASKIQ_POSTGRESQL_LOCK_TIMEOUT = 5

The migrations read the settings when they run, not when they were written. With TASKIQ_POSTGRESQL_TARGETS missing or empty, or with a table name that is not a plain SQL identifier (letters, digits, _ and $, not starting with a digit), migrate raises ImproperlyConfigured before any statement runs, instead of recording migrations that created nothing, and manage.py check reports taskiq_postgresql.E001, or taskiq_postgresql.E002 for a lock timeout that is not a whole number of seconds. The check only reads the settings; the paths, and so the table names of their components, are imported when migrate or sqlmigrate runs. Unlike the taskiq postgresql commands, the app imports them with the project's own sys.path, the one manage.py starts with its own directory first, and never from the directory the command runs in.

Django never applies a migration twice, so a table you add to the settings, or rename, after the app was migrated is not created by the next migrate. Create it with taskiq postgresql migrate (Apply it with migrate) or with the SQL taskiq postgresql plan prints for that database (Plan and check), or keep it in a migration of your own, written by the format below.

The app's migrations reverse to nothing, the same default as the Alembic downgrade(): the tables and their rows stay, because the steps only add tables, columns and indexes that an earlier release ignores. Drop the tables yourself if you mean to. To unapply them:

python manage.py migrate taskiq_postgresql zero

That also unapplies every migration of your other apps that depends on one of this app's, such as a migration that grants a role access to the tables or adds a trigger to them, and each of those runs its own reverse: a reversed CreateModel drops its table, with its rows. migrate taskiq_postgresql zero --plan lists them without running anything.

The migrations run on the database migrate migrates (--database), and a database router's allow_migrate decides for the label taskiq_postgresql as for any app. On a database that is not PostgreSQL they raise NotSupportedError: keep the app off it with a router.

To keep the tables in an app of your own instead of installing this one, generate --format django writes a migration file with every step, its SQL written out, so that the file never imports this package. Writing the file needs no Django, so the format works without the django extra:

taskiq postgresql generate app:scheduler --format django --option dependencies=shop.0004_orders > shop/migrations/0005_taskiq_tables.py

The option dependencies names the migrations it follows, as app_label.migration_name separated by commas, usually the latest migration of that app; by default there are none. Each step becomes a migrations.RunSQL with the advisory lock (--no-lock leaves it out) and the lock timeout (--lock-timeout), whose reverse runs nothing; keep the migration atomic, since both only last inside its transaction. --no-transaction changes nothing: Django runs each migration in a transaction of its own. Table names must be plain SQL identifiers, and any other option exits with 2. plan --format django writes the same file with only the steps the database it reads still lacks, under a first comment line that names that database. A released step never changes, so when a release adds one, add a migration with the new step.

Plugins

A package can add what this one loads by name, through two entry-point groups in its own pyproject.toml: taskiq_postgresql.drivers adds a driver, which driver="name" selects, and taskiq_postgresql.migration_formats adds a migration format (Writing a migration format). A driver implements the protocols of taskiq_postgresql.core.port and never builds SQL; the contributing guide says how to write and prove one. The component calls the registered factory with the connection options it received (and listen_options for the broker), or you pass an instance of the driver as driver= and skip the name.

The registry loads by exact name and on demand, and only the entry point with that name is imported. The names this package registers (asyncpg, psqlpy and psycopg for drivers, sql, alembic and django for formats) resolve inside this package before any entry point is read, so no installed package can replace them. Any other name that two or more installed packages register is an error that names them: uninstall all but one. An unknown driver name raises UnknownDriverError and an unknown format name raises UnknownMigrationFormatError; each lists the names available. A name that differs from a bundled one only by case, such as Asyncpg, is unknown too, and the error names the bundled spelling; no entry point is loaded for it. A value that looks like a connection string, given as driver= by mistake, is refused with an error that says so and quotes none of it.

A plugin is dangerous functionality. It runs in your process with your rights, and a driver sees every connection string and every payload. The registry narrows which code a name loads; it does not isolate that code. Install plugins only from packages you trust, from the index you expect, and pin their versions.

Compatibility

  • Python and dependencies: the supported Python versions are the requires-python field of pyproject.toml; its dependencies and extras hold the supported ranges of taskiq, pydantic, the drivers, SQLAlchemy, SQLModel and Alembic.
  • PostgreSQL: the test suite runs on PostgreSQL 17 and 18.
  • Drivers: asyncpg, psycopg 3 and psqlpy, selected with the driver argument, by name or as an instance of AsyncpgDriver, PsycopgDriver or PsqlpyDriver. The test suite runs against all three.

Upgrading

Coming from 0.4.x? Follow "Upgrading from 0.4.x" in the changelog. It is the only upgrade guide.

Troubleshooting

  • TypeError: PostgresqlBroker.__init__() missing 1 required positional argument: 'dsn' (or the same for PostgresqlResultBackend or PostgresqlSchedulerSource): pass a connection string.
  • TypeError: PostgresqlBroker needs a non-empty PostgreSQL connection string for 'dsn', but got None.: the value you passed is None or empty, usually an environment variable that is not set. For an empty string the message says got ''.
  • SchemaNotReadyError: ... is not ready and run_migrations is off on startup: the table, or a column this release adds, is missing in the database the component connects to. The message names them. Create them with taskiq postgresql migrate, with the SQL taskiq postgresql plan prints or with an Alembic revision, or start once with run_migrations=True; taskiq postgresql check shows what is missing (Plan and check).
  • relation "..." does not exist: the tables are missing. Start once with run_migrations=True, or create them as described in Migrations.
  • ImportError: ... is not installed: install the extra for the driver you selected, for example pip install "taskiq-postgresql[psycopg]".
  • UnknownDriverError: unknown driver '...': the name is not a bundled driver or a plugin that is installed; the message lists the names available.
  • TypeError: ... was given a driver instance and connection options: you gave an instance and connection_kwargs or **connect_kwargs too. Give the options to the instance (Driver options).
  • DatabaseConnectionError on startup: the DSN, the network path or TLS settings are wrong; the message carries the driver's own error.
  • A task is sent but no worker runs it: use the same channel_name and table_name on both sides. A delayed task waits for its delay, then for the next sweep.
  • column "channel" of relation "taskiq_messages" does not exist from kick(), or a worker logging Error claiming a due message on channel ... with column "channel" does not exist every poll_interval, or Error claiming message <id> on channel ... with column "not_before" does not exist for each NOTIFY: the table was created by 0.4.x and lacks the new columns. Start once with run_migrations=True, or run the SQL in "Upgrading from 0.4.x" of the changelog.
  • ResultGetError from wait_result or get_result for a task that reports progress: a process that reads results still runs a release without progress, which takes a row that holds only progress for a ready result. Update every reader, and pass store_progress=False to the workers' backend until then (Task progress).
  • Fatal Python error: PyGILState_Release when a process that used psqlpy exits: psqlpy occasionally aborts the interpreter at exit, after the work is done, which turns the exit code into an abort. It happens with psqlpy alone, and it was seen with psqlpy 0.13.1 on Python 3.10, not on 3.13. Where the exit code matters on 3.10, use another driver.
  • No Listening started. line from taskiq worker on Python 3.14 or newer: taskiq 0.13.0 sets up logging in its worker processes only when they start with spawn, and Python 3.14 starts them with forkserver on Linux. The worker runs; only its log lines are missing.

Contributing and security

Setup, tests, the dependency policy and the release process are in CONTRIBUTING.md. Changes are listed in CHANGELOG.md. Report vulnerabilities as described in SECURITY.md, not in a public issue.

License

MIT. See LICENSE.

About

Fast and flexible PostgreSQL integration for TaskIQ - supporting asyncpg, psycopg3, psqlpy, and pg8000 (soon) drivers

Resources

Contributing

Security policy

Stars

31 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages