Introducing a new way to review your PRs.

Read the announcement

zipstack / unstract

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

View on GitHub

28 documents · Updated Nov 23, 2026

docs / worker-queue-orchestration

Queue-backed worker orchestration

Queue-backed worker orchestration moves selected asynchronous work from Celery to a durable PostgreSQL queue. It gives workers a shared work stream with at-least-once delivery, scheduled task firing, batch coordination, result replies, and recovery paths for work that stops part way through. The reaper also exposes the queue's health and progress so operators can see when delivery or recovery is stalled. See the parent page, Workflow execution system, for the wider execution lifecycle. See Worker operations and execution plugins for task behavior inside a worker and Backend workflow management for the backend state that the queue coordinates.

System boundary

The queue system sits between task producers and worker processes. Producers write a task description to a named queue. Consumers claim that description, run the registered task, and confirm completion. Workflow execution uses the same boundary for orchestration tasks, file batches, and the final callback.

Transport selection

Transport selection controls where a task travels. Celery remains the safe default. Operators can opt individual task names into PostgreSQL, while a workflow execution can carry one transport choice for its full coupled path. This prevents a single execution from splitting its orchestration, batch work, and callback across queues that do not share the same coordination state.

The queue route does not silently fall back to Celery when PostgreSQL enqueue fails. A missing PostgreSQL consumer also leaves the message durable but unprocessed, so queue consumers are part of the deployment contract for every opted-in task.

flowchart LR
    P[Task producer] --> R{Transport choice}
    R -->|default or not opted in| C[Celery]
    R -->|PG task or execution override| Q[PostgreSQL queue]
    Q --> W[PG queue consumer]
    W --> T[Registered worker task]

References: workers/…/routing.py• L1-56 workers/…/dispatch.py• L1-19 workers/…/dispatch.py• L74-112 backend/…/workflow_helper.py• L484-526 workers/…/tasks.py• L162-208

Task payloads

Each PostgreSQL queue row carries a task payload. The payload identifies the task and carries its arguments, keyword arguments, queue, fairness data, and one optional return channel. The backend producer uses the same wire shape as the worker producer, so the queue remains a transport rather than a second task API.

The producer converts values such as UUIDs and datetimes to JSON-safe values before writing the JSON payload. It rejects non-finite numbers before the database insert and removes characters that PostgreSQL JSONB cannot store. The return channel is either a blocking reply key or asynchronous success and error continuations. These choices are exclusive because they describe different ways to finish the request.

References: workers/…/task_payload.py• L1-77 backend/…/producer.py• L54-73 backend/…/producer.py• L103-205 backend/…/test_producer.py• L21-65 backend/…/test_producer.py• L102-157

Message consumption

The consumer polls each configured queue, claims a small batch, and runs each claimed task in the worker process. A claim gives the message a temporary lease. The consumer confirms success by removing the row. A task failure leaves a fire-and-forget message available for redelivery, while malformed, unknown, or permanently failing messages are removed through an explicit poison-message path.

Claim and acknowledgement

The queue provides at-least-once delivery rather than exactly-once execution. PostgreSQL prevents two active consumers from claiming the same visible row at the same time. It does not prevent a second delivery after a worker dies or loses its lease before acknowledgement.

The lease renewal loop keeps a live long-running task hidden. When the worker dies, renewal stops and the reaper makes the expired claim ready again. This separates fast claim scans from recovery scans and keeps the delivery guarantee visible in the state of the row.

sequenceDiagram
    participant Q as PostgreSQL queue
    participant W as Consumer
    participant R as Reaper
    participant T as Task

    W->>Q: Claim ready message
    Q-->>W: Claimed message with lease
    W->>T: Run task
    W->>Q: Renew lease while task runs
    alt Task succeeds
        W->>Q: Delete message
    else Worker stops before acknowledgement
        R->>Q: Re-arm expired claim
        Q-->>W: Deliver message again
    end

References: workers/…/client.py• L1-23 workers/…/client.py• L357-427 workers/…/consumer.py• L263-390 workers/…/consumer.py• L392-488 workers/…/reaper.py• L347-379 workers/…/reaper.py• L1241-1267

Task outcomes

The consumer chooses the completion path from the payload. Fire-and-forget work uses acknowledgement and redelivery. Request-reply work stores a finished or failed result before acknowledgement. Callback work enqueues the next continuation before acknowledgement. These orders protect the caller from an acknowledged message with no visible outcome, while avoiding an expensive executor rerun when a result hand-off has already been attempted.

Unknown task names and malformed payloads cannot run. The consumer acknowledges them after it records the available failure signal. A task that exceeds the retry cap is a poison message. Pipeline messages try to mark the related execution as ERROR before they are discarded, and a temporary failure to make that mark causes the message to wait for another recovery attempt instead of disappearing.

References: workers/…/consumer.py• L490-614 workers/…/consumer.py• L616-801 workers/…/consumer.py• L842-990

Batch barriers

A barrier is the fan-out and fan-in contract for a batch. It starts several header tasks and fires one callback only after all required results arrive. The barrier hides the coordination substrate from workflow callers, so the same execution shape can use Celery, Redis, or PostgreSQL coordination.

PostgreSQL barrier

The PostgreSQL barrier stores one row for an execution. The row tracks unfinished header tasks and the results collected so far. Each successful header completion adds one result and reduces the count. The one completion that reaches zero owns the callback dispatch. A failed header removes the barrier instead of allowing a callback with partial results.

The callback is sent before barrier cleanup. If callback dispatch fails, the barrier remains as a recovery handle until the reaper handles it. The callback path can continue on PostgreSQL when the workflow transport is PostgreSQL; otherwise it can preserve the Celery path.

flowchart TD
    S[Start execution] --> B[Create barrier state]
    B --> H1[Header task]
    B --> H2[Header task]
    B --> HN[Header task]
    H1 --> D[Record result and reduce remaining count]
    H2 --> D
    HN --> D
    D -->|remaining > 0| D
    D -->|header failure| A[Abort barrier]
    D -->|remaining = 0| C[Dispatch aggregate callback]
    C --> X[Clean up coordination state]

References: workers/…/barrier.py• L182-230 workers/…/pg_barrier.py• L1-62 workers/…/pg_barrier.py• L553-701 workers/…/pg_barrier.py• L1006-1163 backend/…/models.py• L259-323

Barrier progress

Barrier progress has two limits. A progress timeout detects a batch that has stopped making progress. An absolute expiry bounds any remaining orphan state. The progress time is refreshed when a batch completes, so a large execution can continue as long as it keeps making progress.

References: workers/…/barrier.py• L96-123 backend/…/models.py• L283-306

Scheduling

The PostgreSQL scheduler is the periodic-trigger side of orchestration. It reads enabled schedules that have been handed to PostgreSQL, creates a queue message for each due pipeline or generic periodic task, and advances that schedule's next run. It replaces Celery Beat only for schedules that have explicitly changed ownership.

Schedule ownership

The schedule mirror keeps the pipeline cron definition beside the current scheduler state. Ownership is transferred per schedule and in one transaction: PostgreSQL becomes the owner while the matching Celery Beat task becomes disabled. A failed or rolled-back hand-over therefore leaves one known firer instead of two.

Newly owned schedules first record their next fire time. They do not fire during that baseline step. This prevents a hand-over from causing an immediate burst.

References: backend/…/models.py• L326-381 backend/…/ownership.py• L1-17 backend/…/ownership.py• L80-146

Schedule dispatch

The leader runs due-schedule dispatch as part of the reaper cycle. Each schedule gets its own transaction. That transaction enqueues the trigger and advances the next-run time together, so a crash cannot commit one action without the other. An invalid cron or a row-level database error disables or skips only the affected schedule.

Pipeline schedules send a fixed trigger to the scheduler queue. The worker then creates the workflow execution and dispatches its asynchronous execution on the transport selected for that execution. Generic periodic tasks keep their own task name, arguments, keyword arguments, and target queue, so the same scheduler can fire non-pipeline work without changing the pipeline trigger contract.

References: workers/…/pg_scheduler.py• L53-109 workers/…/pg_scheduler.py• L136-237 workers/…/pg_scheduler.py• L240-387 workers/…/tasks.py• L253-273 workers/…/tasks.py• L276-425

Delayed message delivery

Delayed messages use a scheduled queue state until their availability time. Producers accept either a relative countdown or an absolute ETA, but not both. A non-positive countdown or past ETA uses the immediate path. The leader promotes due rows to ready on every recovery tick, so delivery is not early but can occur after the requested time by up to the reaper cadence.

This path gives countdown and ETA work a lower-bound delivery time without adding a separate scheduler. It requires the reaper because no consumer promotes scheduled rows by itself.

References: backend/…/producer.py• L76-100 backend/…/producer.py• L137-151 backend/…/test_producer.py• L196-280 backend/…/models.py• L74-92 workers/…/reaper.py• L382-420 workers/…/reaper.py• L1268-1292

Result signaling

Request-reply execution uses PostgreSQL as the durable result store. The consumer writes a row only after the task finishes. The caller treats no row as “not finished,” then reads either a completed result or a failure. After the caller receives the reply, the payload is cleared while the small tombstone remains until retention cleanup.

Result readiness

The database row is the source of truth. Callers can use a capped database poll, or they can wait on a Redis ready token when result signaling is enabled. The Redis token contains only the reply key. A missing signal, Redis outage, or producer-consumer timing race falls back to a database read and affects latency rather than correctness.

References: workers/…/result_backend.py• L1-49 workers/…/result_backend.py• L350-437 backend/…/executor_rpc.py• L58-122 backend/…/models.py• L462-509

Idempotency and recovery

At-least-once delivery makes idempotency a system contract. The queue prevents concurrent visible claims, but every operation that can be repeated after a crash needs a durable guard or a safe no-op. Recovery keeps those guards from turning transient failures into permanent execution strands.

Idempotency guards

The orchestration level uses one claim per execution. The first delivery may start orchestration. Later deliveries skip it. A successful claim remains as a tombstone so a late redelivery cannot start a completed execution again. A failed orchestration releases the claim so a later delivery can retry.

The batch level uses one claim per execution and batch number. Only the first delivery performs the batch's barrier completion. A redelivery skips the batch and therefore cannot reduce the barrier count twice. Result writes use first-write-wins behavior, so a redelivered request cannot replace the outcome already seen by its caller.

References: workers/…/pg_barrier.py• L342-447 backend/…/models.py• L198-257 backend/…/models.py• L512-574 workers/…/result_backend.py• L82-99 workers/…/result_backend.py• L350-385

Reaper leadership

The reaper is the recovery and scheduling singleton. Candidate processes compete for a short PostgreSQL lease. Only the lease holder runs recovery and schedule work. A standby takes over after the lease becomes stale. A failed or uncertain renewal causes the current process to stop acting, which prevents two reapers from changing the same recovery state.

References: workers/…/leader_election.py• L1-24 workers/…/leader_election.py• L197-269 workers/…/reaper.py• L1203-1228 backend/…/models.py• L152-195

Recovery sweep

Each leader cycle handles urgent recovery before schedule dispatch. It re-arms expired queue claims, promotes due delayed messages, recovers stranded barriers, and then fires due schedules. A slower retention sweep removes expired result rows, old batch guards, and orphan orchestration claims. Per-row failures remain visible for a later sweep instead of deleting the only recovery handle.

The reaper also asks the backend to terminalise executions that were created but never dispatched. These executions have no queue message, barrier, or claim, so table-based queue recovery cannot find them. The check runs with the slower sweep cadence. A failure is logged and counted but does not stop schedule dispatch for live traffic.

For a stranded barrier, the reaper reads execution status before marking it ERROR. It does not overwrite an execution that is already terminal. It uses the internal API for business status and direct PostgreSQL operations only for queue coordination rows. Orphan orchestration claims receive the same treatment: terminal executions are cleaned up, while non-terminal crash-window executions are marked ERROR and then cleaned up.

flowchart TD
    L[Leader tick] --> B[Recover stranded barriers]
    B --> Q[Re-arm expired claims]
    Q --> D[Promote due delayed messages]
    D --> S[Dispatch owned schedules]
    S --> C{Retention interval reached?}
    C -->|yes| R[Clean results, dedup markers, and orphan claims]
    C -->|yes| U[Terminalise undispatched executions through backend API]
    C -->|no| M[Refresh queue metrics when due]
    R --> M
    U --> M

References: workers/…/reaper.py• L293-420 workers/…/reaper.py• L641-733 workers/…/reaper.py• L912-1007 workers/…/reaper.py• L1203-1320 workers/…/reaper.py• L1322-1472 workers/…/test_reaper_undispatched_sweep.py• L1-94

Queue observability

Queue observability gives operators separate signals for consumer liveness, reaper leadership, queue backlog, barrier state, and recovery outcomes. Consumer metrics are local to each worker. Queue-wide gauges come from the elected reaper so several workers do not publish duplicate database views.

Queue metrics

The reaper refreshes queue depth, oldest-message age, and live or stranded barrier counts on a slower cadence than its recovery tick. It publishes one immutable snapshot for each scrape. A failed refresh leaves the last snapshot in place and increases its age, while losing leadership clears the queue-wide series so a standby does not present stale data as current.

Recovery counters distinguish expired-claim rearming, delayed-message promotion, barrier recovery, orphan-claim recovery, undispatched execution cleanup, and their failures. The undispatched counter measures executions terminalised by the backend. A non-zero sustained rate points to a failure between execution creation and dispatch.

References: workers/…/metrics.py• L11-25 workers/…/metrics.py• L74-108 workers/…/metrics.py• L112-195 workers/…/metrics.py• L198-348 workers/…/reaper.py• L1017-1060 workers/…/reaper.py• L1501-1538 workers/…/test_reaper_undispatched_sweep.py• L35-94

PostgreSQL queue model

The PostgreSQL queue is an extension-free set of tables managed by the backend and used by workers through direct database connections. The queue message table holds opaque task payloads. Companion tables hold results, barriers, deduplication claims, orchestration claims, scheduler state, and the leader lease.

Queue state

Queue messages have three delivery states: ready, claimed, and scheduled. A ready row can be selected by a consumer. A claimed row is in flight and carries the lease used to decide whether recovery may re-arm it. A scheduled row is hidden until its availability time, after which the reaper promotes it to ready.

Claim order favors higher priority and then older message identifiers within a queue. The claim query uses row locks that skip rows held by other consumers. Separate partial indexes keep normal claims away from the in-flight and future-delivery backlogs. The reaper has matching paths for expired claimed rows and due scheduled rows, so the state transitions remain recoverable.

References: workers/…/client.py• L65-136 backend/…/models.py• L5-11 backend/…/models.py• L25-148 workers/…/reaper.py• L347-420

Queue tables

The queue tables have distinct roles. Their relationships form the control plane around task execution rather than storing workflow business state.

TableSystem role
pg_queue_messageDurable task messages and delivery state
pg_task_resultRequest-reply outcomes and short-lived tombstones
pg_barrier_statePer-execution fan-in count and collected results
pg_batch_dedupFirst-delivery guard for each execution batch
pg_orchestration_claimFirst-delivery guard for orchestration
pg_periodic_schedulePostgreSQL-owned pipeline schedule mirror and next-run state
pg_periodic_taskPostgreSQL-owned generic periodic task and next-run state
pg_orchestrator_lockLeader lease for reaping and scheduling

References: workers/…/schema.py• L42-57 backend/…/models.py• L120-460 workers/…/pg_scheduler.py• L240-387

Database boundary

Workers use the backend database settings and can connect through transaction-pooled PgBouncer. Queue SQL names its schema explicitly instead of relying on a session search path. This keeps queue operations tied to the same schema across pooled connections and supports both hosted and on-premise deployments.

The schema helper also keeps a fixed registry of queue tables and validates the configured schema name before building SQL. A new coordination table must enter that registry before queue code can address it.

References: workers/…/connection.py• L1-13 workers/…/schema.py• L1-91

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the shared task-payload fields aligned between the worker producer, backend producer, and consumer. A renamed return-channel field can acknowledge work without waking or replying to its caller.
  • Keep JSON-safe conversion rules aligned with every JSONB writer. Non-finite numbers must fail before insert, while values that PostgreSQL can accept only after cleanup must be normalized before the task is written.
  • Keep reply keys exclusive from callback continuations. A payload that carries both modes can acknowledge work without delivering the intended callback or reply.
  • Keep countdown and eta mutually exclusive, and keep the scheduled state paired with available_at. A partial change can make delayed work run early or remain hidden.
  • Keep claim state, lease expiry, scheduled visibility, and the reaper's re-arm or promotion queries aligned. A state change without a matching recovery path can leave messages permanently hidden.
  • Keep the barrier count, batch dedup guard, and callback transport marker aligned. A mismatch can fire a callback twice or leave the execution non-terminal.
  • Keep schedule ownership and Celery Beat enablement in the same transaction. Updating only one owner can cause duplicate pipeline fires or no pipeline fires.
  • Keep pg_periodic_schedule and pg_periodic_task field names aligned with their separate SQL scans. Similar names such as organization_id and org_id belong to different tables and must not be merged casually.
  • Keep the undispatched-execution grace period longer than the create-to-dispatch and callback timing windows. A short grace period can terminalise a live execution before its queue message is written.
  • Keep queue table names registered in the schema helper when a new coordination table is added. Unregistered tables fail at query construction rather than reaching the configured database.
  • Keep result retention at or above the longest caller wait. A shorter horizon can delete a valid reply before the caller reads it.
  • Keep queue-wide metric snapshots and leadership state coupled. A newly elected reaper must refresh after step-down rather than serve an empty or stale snapshot.

Important failure modes

TriggerConsequenceGuard
PG task is enabled without a running consumerThe message remains durable and no task runsDeploy the matching PG consumer before routing work to PostgreSQL
PG enqueue receives an unsupported JSON valueThe task is not written and the caller sees an enqueue errorConvert supported values before insert and reject non-finite numbers at the producer boundary
Worker dies before acknowledgementThe task is delivered again after its lease expiresLeader reaper re-arms expired claims; task and batch paths use idempotency guards
A delayed message has no live reaperThe row stays scheduled after its availability timeKeep the reaper live and alert on its claim-state recovery signal
Barrier header task failsThe aggregate callback must not run with partial resultsBarrier abort removes coordination state and late completions find no barrier
Reaper loses or cannot confirm its leader leaseRecovery or scheduling could be duplicatedThe reaper steps down and only the lease holder acts
Schedule ownership changes without disabling the other firerCelery Beat and PostgreSQL can fire the same pipelineOwnership and Beat enablement change in one transaction
Delayed-message promotion failsDue countdown or ETA work stays hidden from consumersDedicated promotion failure metrics and the next leader tick retry the sweep
Execution creation commits before dispatch failsA PENDING execution has no queue or barrier row and can remain unresolvedCadence-gated backend undispatched-execution sweep terminalises the orphan and counts failures
Redis result signal is lostThe caller wakes late or waits by pollPostgreSQL remains authoritative and the wait path falls back to a database poll
PostgreSQL schema is missing or not explicitly addressedQueue queries fail or target the wrong schemaBackend migrations and schema-qualified queue SQL are required

Key files

FileWhy to read it
workers/…/dispatch.pyShows the transport boundary for task dispatch
workers/…/task_payload.pyDefines the task message contract shared by producers and consumers
workers/…/client.pyDefines the queue message lifecycle and delivery guarantee
workers/…/consumer.pyShows how claimed work becomes task execution and an outcome
workers/…/pg_barrier.pyDefines PostgreSQL fan-out, fan-in, and callback behavior
workers/…/reaper.pyDefines leader-only recovery, delayed delivery, retention, metrics, and schedule order
workers/…/pg_scheduler.pyDefines pipeline and generic periodic dispatch with atomic schedule advancement
workers/…/result_backend.pyDefines request-reply storage and result signaling
workers/…/metrics.pyDefines consumer and queue-wide health signals
workers/…/__init__.pyShows runtime selection of the barrier coordination substrate
backend/…/models.pyDescribes the PostgreSQL coordination tables, delivery states, and queue invariants
backend/…/producer.pyShows the backend-side producer, payload normalization, and delayed delivery contract for PG-routed orchestration
backend/…/test_producer.pyCaptures the producer wire shape, JSON boundary, priority checks, and delayed visibility contract
backend/…/ownership.pyShows the safe hand-over between Beat and PostgreSQL scheduling
workers/…/tasks.pyShows how a scheduled trigger creates and dispatches a workflow execution
workers/…/test_reaper_undispatched_sweep.pyCaptures the leader-only, cadence-gated, non-blocking contract for undispatched cleanup