From 10b35a05b995ad56b380d27b5134eb67996b07ec Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:29:06 +0100 Subject: [PATCH 1/4] docs: describe delivery guarantees, failures and schema changes New 'Delivery and Failures' page: how NOTIFY and polling deliver messages, reconnection and keepalive, at-most-once vs at-least-once with processing_timeout, the new parameters, automatic schema changes and how to prepare them in advance, the psqlpy rolling-upgrade caveat and known driver limitations. The broker schema in Common Issues was outdated (taskiq_queue, UUID, BYTEA); it now matches the real table, with the new columns and indexes and the privileges a non-owner role needs. --- docs/tutorial/common_issues.md | 20 ++++-- docs/tutorial/delivery.md | 126 +++++++++++++++++++++++++++++++++ zensical.toml | 1 + 3 files changed, 141 insertions(+), 6 deletions(-) create mode 100644 docs/tutorial/delivery.md diff --git a/docs/tutorial/common_issues.md b/docs/tutorial/common_issues.md index 313de93..3af82a7 100644 --- a/docs/tutorial/common_issues.md +++ b/docs/tutorial/common_issues.md @@ -23,18 +23,26 @@ Check PostgreSQL is running and accessible: ## Table Creation Issues -Ensure user has `CREATE TABLE` permissions or manually create tables using provided schemas: +Ensure user has `CREATE TABLE` permissions or manually create tables using provided schemas. +A broker that does not own its table needs only `SELECT`, `INSERT`, `UPDATE` and `DELETE` on it and `USAGE` on its +id sequence, as long as the table and its indexes below exist: ```sql -- for broker -CREATE TABLE taskiq_queue ( +CREATE TABLE taskiq_messages ( id SERIAL PRIMARY KEY, - task_id UUID NOT NULL, + task_id VARCHAR NOT NULL, task_name VARCHAR NOT NULL, - message BYTEA NOT NULL, - labels JSONB, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() + message TEXT NOT NULL, + labels JSONB NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + claimed_at TIMESTAMP WITH TIME ZONE, + attempts INTEGER NOT NULL DEFAULT 0 ); +CREATE INDEX taskiq_messages_pending_idx ON taskiq_messages (id) WHERE status = 'pending'; +-- only if the broker uses processing_timeout +CREATE INDEX taskiq_messages_processing_idx ON taskiq_messages (claimed_at) WHERE status = 'processing'; -- for result backend CREATE TABLE taskiq_results ( diff --git a/docs/tutorial/delivery.md b/docs/tutorial/delivery.md new file mode 100644 index 0000000..2fd3ffb --- /dev/null +++ b/docs/tutorial/delivery.md @@ -0,0 +1,126 @@ +--- +title: Delivery and Failures +--- + +This page explains how a message travels from `kick()` to a worker, what happens when a connection or a +worker fails, and which broker parameters control that. + +## How a message is delivered + +1. `kick()` inserts the message into the messages table (`taskiq_messages` by default) with the status `pending` + and sends `NOTIFY , ''`. +2. A listening worker receives the notification and claims the message: it changes the status to `processing` + only if it is still `pending`, so exactly one worker gets it. +3. When the task is done, the worker acknowledges the message, and the row is deleted. + +A message with a `delay` label is inserted right away, but becomes available only after its delay. + +`NOTIFY` is fast but not reliable: PostgreSQL drops a notification nobody is listening to. To make sure no message +is left behind, every listening worker also **polls** the table: + +- right after it starts listening, which picks up messages kicked while no worker was running (e.g. during a deploy); +- right after its LISTEN connection is restored, which picks up messages kicked while it was reconnecting; +- every `poll_interval` seconds (5 by default), which also picks up delayed messages whose producer exited before + sending the delayed notification. + +Polling claims the oldest ready message with `FOR UPDATE SKIP LOCKED`, so workers never claim the same row, and a +backlog is drained without waiting between messages. + +!!! note "After upgrading" + Workers poll messages that are already in the table, too. If earlier versions left messages stuck in + `pending`, they are executed right after the upgrade. With `processing_timeout` (see below), messages stuck in + `processing` are delivered again as well. Delete them first if they should not run. + +## Connection failures + +Each broker keeps one connection for `LISTEN` and a pool for everything else. When the LISTEN connection is +lost (PostgreSQL restart, `pg_terminate_backend`, a network problem), the broker reconnects with randomized +delays of up to 30 seconds and polls the table right after reconnecting. + +Some failures do not close the connection: + +- a proxy (pgbouncer, HAProxy, a cloud load balancer) or `idle_session_timeout` closes connections that send no + queries, and a LISTEN connection only receives data; +- a connection can hang without being closed, for example after a network partition. + +So the broker also runs a small keepalive query, `SELECT 1 /* taskiq-pg LISTEN keepalive */`, on its LISTEN +connection every `listen_keepalive_interval` seconds (30 by default). If the query does not answer within +`listen_keepalive_timeout` seconds (5 by default), the connection is treated as lost. Set +`listen_keepalive_interval` below the idle timeout of your proxy, or to `None` to disable the check. + +!!! note + A `read_connection` passed by you is not reconnected and not checked with keepalive queries: + its lifecycle is your responsibility. The asyncpg and aiopg brokers log a warning when it is closed, and the + psycopg broker raises from `listen()`. + +## Worker failures and at-least-once delivery + +If a worker dies after claiming a message but before acknowledging it (for example, `kill -9`), or the +acknowledgement does not reach the database, the message stays in `processing`. + +By default, such a message is **not** delivered again (at-most-once delivery). To deliver it again (at-least-once +delivery), set `processing_timeout`: + +```python +broker = AsyncpgBroker( + dsn, + processing_timeout=600, # seconds; longer than your longest task + max_retry_attempts=5, +) +``` + +A message claimed longer than `processing_timeout` seconds ago is returned to the queue and delivered again, +up to `max_retry_attempts` claims in total. After that, its status becomes `failed`, a warning is logged, and the +row stays in the table for you to inspect. + +!!! warning + With `processing_timeout`, a task can run more than once: + + - make tasks idempotent; + - make the timeout longer than your longest task, otherwise a task that is still running is delivered again. + +## Parameters + +| Parameter | Default | Meaning | +|---|---|---| +| `poll_interval` | `5.0` | Seconds between polls for pending messages whose notification was missed. | +| `listen_keepalive_interval` | `30.0` | Seconds between keepalive queries on the broker's own LISTEN connection; `None` disables them. | +| `listen_keepalive_timeout` | `5.0` | Seconds to wait for a keepalive query before reconnecting. | +| `processing_timeout` | `None` | Seconds after which an unacknowledged message is delivered again; `None` keeps at-most-once delivery. | +| `max_retry_attempts` | `5` | With `processing_timeout`, how many times a message may be claimed before it is marked as `failed`. | + +## Schema changes + +On startup, the broker creates the messages table if it does not exist and brings an existing table up to date: + +- it adds the `claimed_at` and `attempts` columns, which is instant even for a large table; +- it creates a partial index on pending messages (`_pending_idx`) and, with `processing_timeout`, on + processing messages (`
_processing_idx`). + +Building an index on a large existing table blocks writes to it until the index is ready. To avoid that, create +the indexes yourself before upgrading: + +```sql +CREATE INDEX CONCURRENTLY IF NOT EXISTS taskiq_messages_pending_idx + ON taskiq_messages (id) WHERE status = 'pending'; +-- only if you use processing_timeout +CREATE INDEX CONCURRENTLY IF NOT EXISTS taskiq_messages_processing_idx + ON taskiq_messages (claimed_at) WHERE status = 'processing'; +``` + +Schema setup is serialized with an advisory lock, so many workers can start at the same time. The broker +only runs the statements for the parts that are missing, so an application role with only `SELECT`, `INSERT`, +`UPDATE` and `DELETE` privileges (and `USAGE` on the id sequence) works with a table that was prepared in advance, +see [Common Issues](common_issues.md#table-creation-issues). + +!!! warning "Rolling upgrade with psqlpy" + Once a new version adds the columns, workers of older versions that use `PSQLPyBroker` fail to read claimed + messages, and those messages stay in `processing`. Stop the old psqlpy workers before starting the new ones. + +## Known limitations + +- **aiopg pool.** aiopg opens new pool connections while holding a pool-wide lock. If opening a connection hangs + (for example, right after a PostgreSQL restart behind some proxies), every operation on the pool waits for it, + up to the pool `timeout` (60 seconds by default). Lower it with `write_kwargs={"timeout": ...}` if needed. +- **psycopg.** The psycopg broker reads notifications only while `listen()` is iterated. A worker with no free + slots notices a lost connection when the next slot frees up; polling still picks up the messages. diff --git a/zensical.toml b/zensical.toml index 7b6ab8c..cedf9e6 100644 --- a/zensical.toml +++ b/zensical.toml @@ -10,6 +10,7 @@ nav = [ "tutorial/result_backend.md", "tutorial/schedule_source.md", "tutorial/sharing_pool.md", + "tutorial/delivery.md", "tutorial/common_issues.md", ] }, { "API" = ["reference.md"] }, From 841a570e261ff63c3743db8cb6c42324d6b3bac5 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:24:12 +0100 Subject: [PATCH 2/4] docs: an acknowledgement of an expired claim is ignored --- docs/tutorial/delivery.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/tutorial/delivery.md b/docs/tutorial/delivery.md index 2fd3ffb..e8123c1 100644 --- a/docs/tutorial/delivery.md +++ b/docs/tutorial/delivery.md @@ -13,7 +13,7 @@ worker fails, and which broker parameters control that. only if it is still `pending`, so exactly one worker gets it. 3. When the task is done, the worker acknowledges the message, and the row is deleted. -A message with a `delay` label is inserted right away, but becomes available only after its delay. +A message with a `delay` label (in seconds) is inserted right away, but becomes available only after its delay. `NOTIFY` is fast but not reliable: PostgreSQL drops a notification nobody is listening to. To make sure no message is left behind, every listening worker also **polls** the table: @@ -79,6 +79,9 @@ row stays in the table for you to inspect. - make tasks idempotent; - make the timeout longer than your longest task, otherwise a task that is still running is delivered again. + When a worker acknowledges a message after it was delivered again, the acknowledgement is ignored: the row is + deleted only by the worker that claimed it last. + ## Parameters | Parameter | Default | Meaning | From 0b2739eb7823a0d56a4b32e74fe695fede57cdb4 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:42:19 +0100 Subject: [PATCH 3/4] docs: move the psqlpy rolling-upgrade warning to the release notes --- docs/tutorial/delivery.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/tutorial/delivery.md b/docs/tutorial/delivery.md index e8123c1..211aa4e 100644 --- a/docs/tutorial/delivery.md +++ b/docs/tutorial/delivery.md @@ -116,10 +116,6 @@ only runs the statements for the parts that are missing, so an application role `UPDATE` and `DELETE` privileges (and `USAGE` on the id sequence) works with a table that was prepared in advance, see [Common Issues](common_issues.md#table-creation-issues). -!!! warning "Rolling upgrade with psqlpy" - Once a new version adds the columns, workers of older versions that use `PSQLPyBroker` fail to read claimed - messages, and those messages stay in `processing`. Stop the old psqlpy workers before starting the new ones. - ## Known limitations - **aiopg pool.** aiopg opens new pool connections while holding a pool-wide lock. If opening a connection hangs From 5d4d6ca48c16163d5423030c0bfaebec76d059f3 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:43:57 +0100 Subject: [PATCH 4/4] docs: keep upgrade steps out of the docs; they go to the release notes --- docs/tutorial/delivery.md | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/docs/tutorial/delivery.md b/docs/tutorial/delivery.md index 211aa4e..26050fa 100644 --- a/docs/tutorial/delivery.md +++ b/docs/tutorial/delivery.md @@ -26,11 +26,6 @@ is left behind, every listening worker also **polls** the table: Polling claims the oldest ready message with `FOR UPDATE SKIP LOCKED`, so workers never claim the same row, and a backlog is drained without waiting between messages. -!!! note "After upgrading" - Workers poll messages that are already in the table, too. If earlier versions left messages stuck in - `pending`, they are executed right after the upgrade. With `processing_timeout` (see below), messages stuck in - `processing` are delivered again as well. Delete them first if they should not run. - ## Connection failures Each broker keeps one connection for `LISTEN` and a pool for everything else. When the LISTEN connection is @@ -92,24 +87,11 @@ row stays in the table for you to inspect. | `processing_timeout` | `None` | Seconds after which an unacknowledged message is delivered again; `None` keeps at-most-once delivery. | | `max_retry_attempts` | `5` | With `processing_timeout`, how many times a message may be claimed before it is marked as `failed`. | -## Schema changes - -On startup, the broker creates the messages table if it does not exist and brings an existing table up to date: - -- it adds the `claimed_at` and `attempts` columns, which is instant even for a large table; -- it creates a partial index on pending messages (`
_pending_idx`) and, with `processing_timeout`, on - processing messages (`
_processing_idx`). +## Schema setup -Building an index on a large existing table blocks writes to it until the index is ready. To avoid that, create -the indexes yourself before upgrading: - -```sql -CREATE INDEX CONCURRENTLY IF NOT EXISTS taskiq_messages_pending_idx - ON taskiq_messages (id) WHERE status = 'pending'; --- only if you use processing_timeout -CREATE INDEX CONCURRENTLY IF NOT EXISTS taskiq_messages_processing_idx - ON taskiq_messages (claimed_at) WHERE status = 'processing'; -``` +On startup, the broker creates the parts of its schema that are missing: the messages table and its columns, +a partial index on pending messages (`
_pending_idx`) and, with `processing_timeout`, a partial index on +processing messages (`
_processing_idx`). Schema setup is serialized with an advisory lock, so many workers can start at the same time. The broker only runs the statements for the parts that are missing, so an application role with only `SELECT`, `INSERT`,