Package Overview¶
TaskQ public API. The taskq package re-exports the primary types used by application
code: the @actor decorator, JobsClient / TaskQ, JobHandle, exceptions,
RetryPolicy, cron scheduling, and batch helpers.
from taskq import actor, TaskQ, JobHandle, JobFailed, RetryPolicy
from taskq import cron, ScheduleHandle
from taskq.context import JobContext
from taskq.di import ProviderRegistry, Scope
taskq ¶
TaskQ — async-native, Postgres-backed background job library.
Canonical imports:
from taskq import actor, TaskQ, JobHandle, JobFailed, RetryPolicy
from taskq import cron, ScheduleHandle
from taskq.context import JobContext
from taskq.di import ProviderRegistry, Scope
IdempotencyKey
module-attribute
¶
Distinguishes idempotency keys from identity keys at call sites.
IdentityKey
module-attribute
¶
Distinguishes identity keys from idempotency keys at call sites.
JobId
module-attribute
¶
Opaque job identifier — prevents UUID mixups across the API.
QueueName
module-attribute
¶
Validator alias for queue names — accepts plain str literals.
Why Annotated and not NewType: every studied vendor (river,
dramatiq, arq, procrastinate) uses raw str + a separate validator
for queue names; no nominal type because no other str field at any
call site could be confused with queue. Annotated gives runtime
validation in Pydantic models without forcing every caller to wrap
literals in QueueName("default").
__all__
module-attribute
¶
__all__ = [
"ActorConfigDriftError",
"ActorConfigDriftList",
"ActorFn",
"ActorFnWithCtx",
"ActorHandler",
"ActorRef",
"BackpressureError",
"BatchCompletionStatus",
"BatchHandle",
"CancelPhase",
"CancelResult",
"CronScheduleSpec",
"DIError",
"DependencyCycle",
"DstStrategy",
"EnqueueItem",
"ErrorReporter",
"Fail",
"IdempotencyKey",
"IdentityKey",
"IllegalStateTransition",
"JobContext",
"JobEvent",
"JobFailed",
"JobFilter",
"JobHandle",
"JobId",
"JobRetryState",
"JobSortField",
"JobsClient",
"MaxPendingExceededError",
"MissingProvider",
"NullErrorReporter",
"OnSuccess",
"PartialBatchError",
"PayloadValidationError",
"ProgressEvent",
"ProgressTooLarge",
"QueueMode",
"QueueName",
"RateLimitBackend",
"ReservationUnavailable",
"ResultTooLarge",
"ResultUnavailable",
"Retry",
"RetryAfter",
"RetryClassifier",
"RetryClassifierHook",
"RetryDecision",
"RetryKind",
"RetryOverride",
"RetryPolicy",
"ScheduleHandle",
"ScheduleRecord",
"SchemaNotMigratedError",
"ScopeViolation",
"SingletonCollisionError",
"Snooze",
"SubEnqueueError",
"SubJobEnqueuer",
"TaskQ",
"TaskQError",
"WorkerOwnershipMismatch",
"__version__",
"actor",
"cron",
"register_cron",
"wait_for_batch",
]
ActorFn ¶
Actor handler that takes only a payload.
The dispatcher injects nothing beyond the validated payload model. Use this shape for actors that don't need cancellation cooperation, attempt counters, or other context fields.
ActorFnWithCtx ¶
Actor handler that takes a payload and a typed :class:JobContext.
Declare ctx: JobContext[YourPayload] as the second parameter to
opt into context injection. The dispatcher constructs the context per
attempt, populates it with the validated payload and a fresh
:class:asyncio.Event for cooperative cancellation, then passes it
to the handler. Handlers that don't declare ctx skip this work.
RetryKind ¶
Closed set of retry tiers.
Why Literal and not an Enum: serialization round-trips through
model_dump(mode="json") produce plain strings without
use_enum_values configuration; pyright exhaustive matching works
identically for either; no .value access required at call sites.
OnSuccess ¶
Hook fired when a job succeeds. Receives (job_row, result).
Why object for the result type (not Any or generic R): the
hook is dispatched from the consumer loop, which erases the actor's
return type to object. This mirrors the non-generic
:data:OnRetryExhausted at the same payload-erasure boundary. Hooks
that need a typed result re-validate via the actor's
result_adapter.
RetryClassifierHook ¶
Optional per-actor hook for exception-instance-level retry classification.
non_retryable_exceptions and the built-in :class:PayloadValidationError
check classify by exception type alone. Some integrations need finer
granularity — a single exception type (e.g. an HTTP client's status-code
error) that should retry indefinitely on a 429, fail immediately on a 404,
and use a bounded transient budget on a 5xx, or a server-provided
Retry-After value that should drive the actual backoff delay. Register
one via @actor(retry_classifier=...).
Invoked with (exception, attempt) for every exception that survives the
non_retryable_exceptions/PayloadValidationError checks. Return
None to fall back to the actor's static RetryPolicy unchanged, or a
:class:RetryOverride to refine kind and/or delay for this specific
occurrence. Exceptions raised by the hook itself are caught and logged by
:func:decide_after_failure; classification falls back to the static
policy in that case — a broken hook can never crash the retry pipeline.
ActorHandler ¶
Bases: Protocol
Most-general actor signature: payload first, then ctx and/or DI deps.
Pyright infers P_ from the first positional parameter (the
payload model) and R_ from the awaited return type, regardless
of how many additional ctx / DI parameters the handler
declares. This lets the :func:actor decorator preserve full
payload-and-result inference for FastAPI-style handlers like::
async def my_actor(
payload: OrderPayload,
ctx: JobContext[OrderPayload],
*,
db: DbSession,
http: HttpClient,
) -> OrderResult: ...
Without ActorHandler, callers would have to choose between
:data:ActorFn (payload only) and :data:ActorFnWithCtx (payload
+ ctx), neither of which describes the DI case.
ActorRef ¶
ActorRef(
*,
name: str,
queue: str,
fn: Callable[..., object],
is_sync: bool = False,
wants_ctx: bool,
dependencies: dict[str, type[object]],
payload_type: type[P],
result_adapter: TypeAdapter[R],
retry: RetryPolicy,
result_ttl: timedelta | None,
singleton: bool = False,
max_concurrent: int | None = None,
max_pending: int | None = None,
metadata: dict[str, object] | None = None,
unique_for: timedelta | None = None,
unique_states: tuple[JobStatus, ...] = (
"pending",
"scheduled",
"running",
),
start_to_close: timedelta | None = None,
rate_limits: list[str] | None = None,
reservations: list[str | KeyedReservationRef]
| None = None,
non_retryable_exceptions: tuple[
type[BaseException], ...
] = (),
retry_classifier: RetryClassifierHook | None = None,
on_retry_exhausted: OnRetryExhausted | None = None,
on_retry_exhausted_timeout: float = 3.0,
on_success: OnSuccess | None = None,
on_success_timeout: float = 3.0,
priority: int = 0,
)
Typed reference to a registered actor.
Created by the :func:actor decorator. Not callable directly via
the queue path — enqueue jobs by passing this ref to
:meth:JobsClient.enqueue(ref, payload) <taskq.client.JobsClient.enqueue>.
Direct in-process invocation (await my_actor(payload, ...)) is
available for tests and simulators.
The two type parameters carry the actor's payload and result types end-to-end:
payload_typere-validates raw dispatch-time payloads back toP(via :meth:pydantic.BaseModel.model_validate).result_adapterround-trips actor returns through the JSONBresultcolumn (dump_python(mode="json")on the worker side,validate_pythonon the client side).
Attributes:
| Name | Type | Description |
|---|---|---|
max_concurrent |
Fleet-wide concurrency cap for this actor.
max_concurrent may transiently exceed configured value by up to (num_active_producers - 1) * max_concurrent per actor under heavy contention (or (num_producers - 1) * limit_n when limit_n < max_concurrent). For strict correctness, use ConcurrencyReservation. |
|
metadata |
Arbitrary key-value metadata stored in
|
Both are stored as instance fields rather than class metadata so
pyright can infer P and R from a constructor call without
relying on phantom-type tricks.
wants_ctx records whether the handler declared a
:class:JobContext parameter; the dispatcher passes ctx only
when set. dependencies maps each DI parameter name to its
annotated type — the worker's DI pass resolves these at dispatch
time and passes them as keyword arguments to the handler. The DI
resolver itself is an erasure boundary (see
the resolver operates on the registered provider graph at runtime): user-declared annotations on
DI parameters are captured here as type[object] because the
resolver operates on the registered provider graph at runtime.
Source code in src/taskq/actor.py
__slots__
class-attribute
instance-attribute
¶
__slots__ = (
"_fn",
"dependencies",
"is_sync",
"max_concurrent",
"max_pending",
"metadata",
"name",
"non_retryable_exceptions",
"on_retry_exhausted",
"on_retry_exhausted_timeout",
"on_success",
"on_success_timeout",
"payload_type",
"priority",
"queue",
"rate_limits",
"reservations",
"result_adapter",
"result_ttl",
"retry",
"retry_classifier",
"singleton",
"start_to_close",
"unique_for",
"unique_states",
"wants_ctx",
)
on_retry_exhausted_timeout
instance-attribute
¶
fn
property
¶
Return the underlying handler.
May be sync (def) or async (async def). Direct
invocation through :meth:__call__ is the safer path because
it handles both shapes and enforces the declared signature.
__call__
async
¶
Direct invocation — bypasses enqueue, runs the handler in-process.
Pass a :class:JobContext only when the registered handler
declared one (when :attr:wants_ctx is True); calling with
a context against a no-ctx handler raises :class:TypeError,
and calling without a context against a ctx handler also
raises :class:TypeError.
deps mirrors the keyword arguments the worker's
dependency-injection pass supplies in production. Tests may
pass them explicitly; the call site is responsible for
matching the names recorded in :attr:dependencies. Missing
dependencies surface as a runtime TypeError from Python's
argument binding.
Production callers go through :meth:JobsClient.enqueue.
Source code in src/taskq/actor.py
CancelPhase ¶
Bases: IntEnum
Phases of cooperative-then-forced cancellation.
Why IntEnum and not Literal[0, 1, 2]: the cancel-poll loop
performs arithmetic comparisons (db_phase >= 1,
active.cancel_phase < 2) that Literal[int] does not narrow
correctly under pyright strict. IntEnum subclasses int, so
every existing comparison continues to work, while the typed enum
carries the OTel attribute semantics (cancel_phase attribute on
transition counters) and prevents bare-int values like 99 from
slipping past the type checker.
and
Values NONE, COOPERATIVE, and FORCED are persistable —
they map directly to the PG cancel_phase column whose check
constraint is BETWEEN 0 AND 2. ABANDON_PENDING is an
in-process sentinel only: the cancel-poll loop sets it on
_ActiveJob to mark a job as queued for post-transaction
abandonment. It is never written to PG. Keeping it on the same
enum lets cancel_phase stay strongly typed end-to-end.
JobFilter
dataclass
¶
JobFilter(
queue: str | None = None,
status: JobStatus | None = None,
actor: str | None = None,
identity_key: IdentityKey | None = None,
batch_id: UUID | None = None,
limit: int = 100,
cursor: str | None = None,
tags: tuple[str, ...] | None = None,
order_by: JobSortField | None = None,
)
Filter parameters for :meth:Backend.list_jobs. cursor is an
opaque keyset-pagination token encoding (priority, scheduled_at, id)
from the last row of the previous page. Both backends must
agree on cursor encoding and comparison semantics.
batch_id is a :class:UUID. The PG backend converts it to its
canonical string form at the SQL boundary; the in-memory backend
compares the UUID directly. Keeping the typed shape here means
JobsClient.list(batch_id=UUID(...)) flows without an implicit
str(uuid) coercion. See / audit M102-3.
__post_init__ ¶
Source code in src/taskq/backend/_protocol.py
JobSortField ¶
Bases: Enum
Sort ordering for :meth:Backend.list_jobs via :attr:JobFilter.order_by.
SCHEDULED_AT_ASC (and the default None) preserve the canonical
dispatch-friendly ordering — priority DESC, scheduled_at ASC, id ASC —
so existing list_jobs callers see no behaviour change.
CREATED_AT_DESC and FINISHED_AT_DESC serve "latest run by business
key" queries: newest-created first and most-recently-finished first
(NULLS LAST) respectively. Cursor pagination is only valid with the
default ordering; :meth:JobFilter.__post_init__ rejects a cursor
combined with a non-default order_by.
ScheduleRecord ¶
Bases: BaseModel
Read-only snapshot of a cron schedule row from the database.
model_config = ConfigDict(frozen=True) enforces immutability per
public API discipline.
BatchCompletionStatus ¶
Bases: BaseModel
Aggregated completion counts for a batch of jobs.
pending counts jobs still in flight (pending, scheduled,
or running status). is_complete is True when all jobs
have reached a terminal status.
BatchHandle ¶
Bases: BaseModel
Handle to a group of jobs inserted by a single
:meth:~taskq.client.JobsClient.enqueue_batch call.
job_handles contains one :class:~taskq.client.JobHandle per
item in the original list (including idempotency-key collisions that
returned existing rows). size equals len(job_handles).
:meth:status queries the database for the current completion
counts of the batch.
job_handles
instance-attribute
¶
List of :class:~taskq.client.JobHandle instances, one per enqueued item.
status
async
¶
Query live completion counts for all jobs in this batch.
Uses a JSONB containment query against the metadata column so
the jobs_metadata_gin_idx GIN index is used (@> is
supported by jsonb_path_ops). The query groups by status in a
single round-trip.
schema must match the schema used when the :class:PostgresBackend
was constructed (default "taskq").
Source code in src/taskq/batch.py
EnqueueItem ¶
Bases: BaseModel
One item in a :meth:~taskq.client.JobsClient.enqueue_batch call.
actor_ref is an :class:~taskq.actor.ActorRef for any payload and
result type. payload is the Pydantic model that will be
serialized into the job row — it is validated by the actor's
payload_type inside :meth:~taskq.client.JobsClient.enqueue_batch
before any INSERT.
metadata is merged with the library-injected batch_id key
before the row is written; callers MUST NOT set metadata.batch_id
manually.
CancelResult ¶
Bases: BaseModel
Structured outcome of a cancellation request.
Returned by JobsClient.cancel() so callers can inspect whether
the cancellation was initiated and what the status transition was.
JobEvent ¶
Bases: BaseModel
A single event yielded by :meth:TaskQ.stream.
Represents a point-in-time snapshot of a job's observable state.
Yielded on every status transition or progress update; the final
event always has terminal=True.
The progress_state and progress_seq fields reflect the last
values written by the worker. They are None / 0 until the
worker emits a progress update.
Serialises cleanly to JSON via model_dump() for SSE or WebSocket
fanout — fields are deliberately flat so the caller can forward the
event without transformation::
async for event in tq.stream(job_id):
await websocket.send_json(event.model_dump())
JobHandle ¶
JobHandle(
*,
row: JobRow,
result_adapter: TypeAdapter[R],
was_existing: bool,
client: JobsClient | None = None,
backend: Backend | None = None,
_redis_client: Redis | None = None,
_settings: TaskQSettings | None = None,
)
Typed handle to a single enqueued job.
Created by :class:JobsClient methods (:meth:~JobsClient.enqueue,
:meth:~JobsClient.get) or by :class:SubJobEnqueuer (with
backend= only). The type parameter R flows from the
actor's declared return type through :class:ActorRef into this
handle: JobHandle[OrderResult] for an actor returning
OrderResult, JobHandle[None] for fire-and-forget actors.
At least one of client or backend must be supplied. When
client is provided, _backend is filled from
client.backend. When only backend is provided, the four
read-back methods (:meth:status, :meth:refresh,
:meth:attempts, :meth:cancel) raise :class:RuntimeError
because they require the client's higher-level coordination.
:meth:wait always works (it reads through _backend directly).
Why result_adapter: TypeAdapter[R] is a constructor arg: pyright
only infers R for a generic class when the type parameter
appears in at least one field or method signature. The adapter is
that field — without it R would be phantom and inference would
silently fall back to Unknown.
Source code in src/taskq/client/_handle.py
status
async
¶
Return the current status of this job (live read).
Cheap, non-blocking: a single backend.get and a status
projection. No polling. Use this when you want to know the
state without waiting for a terminal transition.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
this handle was constructed without a
:class: |
Source code in src/taskq/client/_handle.py
refresh
async
¶
Re-read the row from the backend and return the raw
:class:JobRow.
Useful for callers that want full row state (timestamps,
attempt counts, error metadata) without going through
:meth:wait. Does not block on terminal state — returns the
current row whatever its status.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
this handle was constructed without a
:class: |
Source code in src/taskq/client/_handle.py
attempts
async
¶
Return the attempt rows for this job, ordered by attempt number.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
this handle was constructed without a
:class: |
Source code in src/taskq/client/_handle.py
cancel
async
¶
Delegate to :meth:JobsClient.cancel.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
this handle was constructed without a
:class: |
Source code in src/taskq/client/_handle.py
wait
async
¶
Block until the job reaches a terminal status, then return R.
Returns the actor's return value, validated through
:attr:result_adapter. The result type is R exactly —
never R | None. Missing or failed results raise.
Raises:
| Type | Description |
|---|---|
ResultUnavailable
|
terminal state reached but no result was
stored (result TTL expired, actor returned |
JobFailed
|
the job ended in a non-success terminal state
( |
TimeoutError
|
|
Source code in src/taskq/client/_handle.py
progress_stream
async
¶
Stream live progress events for this job.
When Redis is configured, subscribes to the per-job Redis pub/sub
channel and yields :class:~taskq.progress.ProgressEvent objects in
real time. When Redis is not available, falls back to polling Postgres
at 500 ms intervals and synthesising events from row diffs.
Raises :class:NotImplementedError when the in-memory backend is
detected — the in-memory backend does not support pub/sub.
Yields events until a terminal=True event is produced.
Source code in src/taskq/client/_handle.py
JobsClient ¶
JobsClient(
backend: Backend,
*,
clock: Clock | None = None,
settings: TaskQSettings | None = None,
)
Public API for job operations.
Delegates to the injected :class:Backend and wraps results in
typed :class:JobHandle[R] instances. The client owns the
payload-serialization step that turns a typed P into the
dict[str, object] carried by :class:EnqueueArgs; the backend
sees only erased payloads.
Source code in src/taskq/client/_jobs.py
backend
property
¶
The underlying :class:Backend this client delegates to.
Exposed so :class:JobHandle can read the backend through the
client without accessing the private _backend attribute.
close
async
¶
enqueue
async
¶
enqueue(
ref: ActorRef[P, R],
payload: P,
*,
queue: QueueName | None = None,
scheduled_at: datetime | None = None,
priority: int | None = None,
schedule_to_close: datetime | None = None,
start_to_close: timedelta | None = None,
heartbeat_timeout: timedelta | None = None,
identity_key: IdentityKey | None = None,
fairness_key: str | None = None,
idempotency_key: IdempotencyKey | None = None,
trace_id: str | None = None,
span_id: str | None = None,
metadata: dict[str, object] | None = None,
tags: list[str] | None = None,
) -> JobHandle[R]
Enqueue a job for the given actor and return a typed handle.
The payload is serialized through ref.payload_type so the
EnqueueArgs.payload carried over the backend boundary is a
plain dict[str, object] ready for the JSONB column. The
returned :class:JobHandle[R] carries ref.result_adapter so
:meth:JobHandle.wait can validate the stored result back to
R.
The metadata.singleton key is reserved by the library for
singleton enforcement. When ref.singleton is True the
library unconditionally writes metadata.singleton = True,
overriding any caller-supplied value. Callers MUST NOT set
metadata.singleton manually.
max_pending:
-
When the actor's
max_pendingis set, a pre-flight count ofpending+scheduledjobs for the actor is compared to the limit. Ifcount >= max_pending, :class:MaxPendingExceededErroris raised synchronously — the caller decides whether to retry, fail, or wait; the library does not block on capacity. -
Evaluation order at enqueue:
unique_fordedup → singleton pre-flight →max_pendingcount check →idempotency_keyINSERT → job INSERT. Aunique_forhit bypasses all remaining checks; a singleton collision fires beforemax_pendingto give the caller the more specificSingletonCollisionError. -
idempotency_keydoes not bypassmax_pending— the idempotency ON CONFLICT fires at step 5, after the max_pending check at step 3. Re-enqueuing with a duplicateidempotency_keywhen the queue is full raisesMaxPendingExceededError, not the deduplicated handle. Onlyunique_for(step 1) bypasses max_pending.
idempotency_key:
-
idempotency_keyis globally unique (not per-actor scoped). Callers must namespace keys to avoid collisions between actors (e.g."actor_name:delivery_id"). -
Key length is bounded at 256 characters. Empty keys and whitespace-only keys raise :class:
ValueErrorat the client boundary before any backend call.
unique_for:
-
unique_fordeduplication is best-effort. Concurrent enqueues for the same(actor, identity_key)may both insert; the dispatch CTE'srunning_identitiesfilter ensures only one runs. -
When either dedup mechanism matches an existing job,
JobHandle.was_existingisTrue. This field replaces the need for callers to inspect the row'screated_atto detect a dedup return.
Source code in src/taskq/client/_jobs.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
enqueue_batch
async
¶
enqueue_batch(
items: list[EnqueueItem],
*,
batch_id: UUID | None = None,
connection: Connection | None = None,
) -> BatchHandle
Enqueue multiple jobs in a single batched INSERT and return a
:class:~taskq.batch.BatchHandle.
All items share a single batch_id UUID written into each
job's metadata.batch_id field (as a string). When
batch_id is not supplied it is auto-generated as a UUIDv7 via
:func:~taskq._ids.new_job_id.
Validation rules:
len(items) == 0raises :class:ValueError.len(items) > 1000raises :class:ValueError.- ALL payloads are validated before any INSERT. A single failure
raises :class:
~taskq.exceptions.PayloadValidationErrorand leaves no rows inserted.
max_pending:
One aggregated SELECT actor, count(*) … WHERE actor = ANY($1)
GROUP BY actor is issued for the entire batch. Per-actor limits
are checked before the INSERT; any violation raises
:class:~taskq.exceptions.MaxPendingExceededError.
idempotency_key collisions:
Items whose idempotency_key collides with an existing row
return the existing :class:~taskq.client.JobHandle (same
semantics as single-item :meth:enqueue).
Source code in src/taskq/client/_jobs.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
enqueue_batch_fast
async
¶
enqueue_batch_fast(
items: list[EnqueueItem],
*,
batch_id: UUID | None = None,
connection: Connection | None = None,
) -> int
Enqueue jobs via COPY FROM protocol for maximum throughput.
WARNING — bulk-import semantics, not general-purpose enqueue:
this method does NOT enforce max_pending, does NOT detect or
reject idempotency-key collisions (a duplicate key aborts the
whole batch instead of being treated as "already enqueued"), and
returns a bare row count, not per-job handles — there is no
way to await, cancel, or otherwise reference an individual job
from the return value. Use :meth:enqueue_batch unless you
specifically need COPY-level throughput for a one-shot bulk
import/backfill and have already accounted for these gaps.
Returns the count of inserted rows — no :class:~taskq.batch.BatchHandle,
no per-job :class:~taskq.client.JobHandle instances.
Validation rules:
len(items) == 0raises :class:ValueError.len(items) > 50_000raises :class:ValueError.- ALL payloads are validated before any INSERT — a single failure
raises :class:
~taskq.exceptions.PayloadValidationError.
Tradeoffs vs enqueue_batch:
- No idempotency-key collision handling. A duplicate key
aborts the entire batch with
asyncpg.UniqueViolationError. Callers must pre-deduplicate. - No max_pending check. The caller is responsible for ensuring the batch won't exceed actor limits.
- No JobHandle instances. Only the inserted row count is
returned. Use
batch_idto query rows post-insert. - All-or-nothing atomicity. No partial success — the entire COPY fails on any constraint violation.
Use for bulk import / backfill with 1K-50K rows where throughput matters more than idempotency guarantees.
Source code in src/taskq/client/_jobs.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
get
async
¶
Look up a job by id.
Returns None when the job does not exist; otherwise wraps
the row in a :class:JobHandle[R]. The caller may supply
result_adapter because lookups by id do not carry actor
identity — typical sources are
my_actor.result_adapter (when reuniting with an actor) or
TypeAdapter(type(None)) (when only row metadata is needed).
When result_adapter is None it defaults to
TypeAdapter(type(None)), which is suitable for status-only
lookups.
Source code in src/taskq/client/_jobs.py
list
async
¶
List jobs matching filter, returning a :class:JobPage.
Source code in src/taskq/client/_jobs.py
cancel
async
¶
Request cancellation of a job and return a :class:CancelResult.
Reads the row first via :meth:Backend.get. If the job does not
exist, raises :class:KeyError — matching Python's stdlib
idiom for "asked for an entry by id; it isn't there".
Then calls :meth:Backend.write_cancel_request and reads the
row again to capture the new status. The previous_status
reflects the row at the first read, not atomically at
write-time (TOCTOU per ).
: increments taskq.cancellation.requested exactly once
per call, regardless of cancellation_initiated outcome.
Source code in src/taskq/client/_jobs.py
create_schedule
async
¶
create_schedule(
actor: str | ActorRef[P, R],
cron_expr: str,
*,
timezone: str = "UTC",
dst_strategy: DstStrategy = "skip",
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
name: str = "",
identity_key: IdentityKey | None = None,
enabled: bool = True,
) -> ScheduleHandle
Create a cron schedule. Raises :class:ValueError if both
payload_factory and static_payload are provided, or if
cron_expr is invalid.
The (actor, name) UNIQUE constraint means each (actor, name)
pair may have at most one schedule; a second create_schedule for
the same pair raises asyncpg.UniqueViolationError (PG) or
:class:ValueError (in-memory). Pass distinct name values to run
several cron schedules per actor (e.g. a per-property sync).
When identity_key is set, the cron loop propagates it to cron-fired jobs so they dedup against on-demand jobs for the same business key.
Does NOT validate actor existence at creation time — any string actor name is accepted (validation is deferred to fire time).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dst_strategy
|
DstStrategy
|
How to handle DST gaps and overlaps.
|
'skip'
|
Source code in src/taskq/client/_jobs.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 | |
list_schedules
async
¶
List cron schedules, optionally filtered by actor or enabled status.
Source code in src/taskq/client/_jobs.py
update_schedule
async
¶
update_schedule(
schedule_id: UUID,
*,
cron_expr: str | None = None,
enabled: bool | None = None,
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
clear_payload_factory: bool = False,
) -> ScheduleRecord
Update a cron schedule. Setting enabled=True clears
last_fire_error and resets consecutive_failures to 0.
Raises :class:ValueError if both payload_factory and
static_payload are provided, or if cron_expr is invalid.
To explicitly clear payload_factory (set the column to NULL),
pass clear_payload_factory=True — None for payload_factory
means "don't change this field."
Source code in src/taskq/client/_jobs.py
delete_schedule
async
¶
TaskQ ¶
TaskQ(
*,
dsn: str | None = None,
pool: Pool | None = None,
schema: str = "taskq",
min_pool_size: int = 1,
max_pool_size: int = 5,
redis_url: str | None = None,
redis_client: Any | None = None,
poll_timeout: float = 30.0,
)
Postgres-backed TaskQ client.
Manages a connection pool and exposes job operations directly. Supports
both the async context manager pattern and explicit open() / close()
for frameworks like FastAPI that manage their own lifecycle.
Parameters¶
dsn:
Postgres DSN string. Mutually exclusive with pool.
pool:
An already-open asyncpg.Pool. The caller retains ownership;
close() will not close it.
schema:
TaskQ schema name. Defaults to "taskq".
min_pool_size:
Minimum pool connections. Only used when dsn is provided.
max_pool_size:
Maximum pool connections. Only used when dsn is provided.
redis_url:
Redis URL string. Mutually exclusive with redis_client.
The library creates and owns the Redis client; close() will
close it.
redis_client:
An already-open redis.asyncio.Redis client. The caller retains
ownership; close() will not close it. Mutually exclusive with
redis_url.
poll_timeout:
Maximum seconds to wait between transport wakeups before re-fetching
job state. Defaults to 30.0.
Source code in src/taskq/client/_taskq.py
open
async
¶
Open the connection pool and prepare the client.
Called automatically by __aenter__. Safe to call explicitly
for frameworks that manage lifecycle outside an async with block.
Raises :class:RuntimeError if already open.
Source code in src/taskq/client/_taskq.py
close
async
¶
Close the client and release the pool if owned.
Called automatically by __aexit__. Safe to call explicitly.
No-op if already closed.
Source code in src/taskq/client/_taskq.py
__aenter__
async
¶
__aexit__
async
¶
enqueue
async
¶
enqueue(
ref: ActorRef[P, R],
payload: P,
*,
queue: QueueName | None = None,
scheduled_at: datetime | None = None,
priority: int | None = None,
schedule_to_close: datetime | None = None,
start_to_close: timedelta | None = None,
heartbeat_timeout: timedelta | None = None,
identity_key: IdentityKey | None = None,
fairness_key: str | None = None,
idempotency_key: IdempotencyKey | None = None,
trace_id: str | None = None,
span_id: str | None = None,
metadata: dict[str, object] | None = None,
tags: list[str] | None = None,
) -> JobHandle[R]
Enqueue a job and return a typed handle.
Source code in src/taskq/client/_taskq.py
enqueue_batch
async
¶
enqueue_batch(
items: list[EnqueueItem],
*,
batch_id: UUID | None = None,
connection: Connection | None = None,
) -> BatchHandle
Enqueue multiple jobs in a single batched INSERT.
Delegates to :meth:JobsClient.enqueue_batch; see its docstring
for validation rules and idempotency-key collision semantics.
Source code in src/taskq/client/_taskq.py
enqueue_batch_fast
async
¶
enqueue_batch_fast(
items: list[EnqueueItem],
*,
batch_id: UUID | None = None,
connection: Connection | None = None,
) -> int
Enqueue jobs via COPY FROM protocol for maximum throughput.
Delegates to :meth:JobsClient.enqueue_batch_fast; see its
docstring for tradeoffs vs the regular :meth:enqueue_batch.
Source code in src/taskq/client/_taskq.py
get
async
¶
Look up a job by id. Returns None when the job does not exist.
Source code in src/taskq/client/_taskq.py
list
async
¶
cancel
async
¶
Request cancellation of a job. Raises :class:KeyError if not found.
create_schedule
async
¶
create_schedule(
actor: str | ActorRef[P, R],
cron_expr: str,
*,
timezone: str = "UTC",
dst_strategy: DstStrategy = "skip",
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
name: str = "",
identity_key: IdentityKey | None = None,
enabled: bool = True,
) -> ScheduleHandle
Create a cron schedule. Delegates to :meth:JobsClient.create_schedule.
dst_strategy controls how DST gaps/overlaps are handled; see
:meth:JobsClient.create_schedule for the full semantics.
Source code in src/taskq/client/_taskq.py
list_schedules
async
¶
List cron schedules. Delegates to :meth:JobsClient.list_schedules.
Source code in src/taskq/client/_taskq.py
update_schedule
async
¶
update_schedule(
schedule_id: UUID,
*,
cron_expr: str | None = None,
enabled: bool | None = None,
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
clear_payload_factory: bool = False,
) -> ScheduleRecord
Update a cron schedule. Delegates to :meth:JobsClient.update_schedule.
Source code in src/taskq/client/_taskq.py
delete_schedule
async
¶
Delete a cron schedule. Delegates to :meth:JobsClient.delete_schedule.
stream
async
¶
Stream live state changes for a job as :class:JobEvent objects.
Yields one event per observable state transition (status change or
progress update), terminating automatically when the job reaches a
terminal state. The final event always has ``terminal=True``.
Usage::
async for event in tq.stream(job_id):
print(event.status, event.progress_state)
# loop exits automatically when event.terminal is True
# Or wire directly into a FastAPI SSE response:
async def event_generator():
async for event in tq.stream(job_id):
yield f"data: {event.model_dump_json()}
"
Raises
------
RuntimeError
Called before ``tq.open()`` or outside an ``async with`` block.
KeyError
The job does not exist.
RuntimeError
PG LISTEN transport requested but ``dsn`` was not provided at
construction (pool-only mode).
Source code in src/taskq/client/_taskq.py
SubJobEnqueuer ¶
SubJobEnqueuer(
loop_scope_resolved: Mapping[type, object] | None,
worker_pool: Pool | None,
backend: Backend,
*,
clock: Clock | None = None,
)
Enqueue sub-jobs from within an actor body.
Uses the LOOP-scope DB connection by default (transactional enqueue). Falls back to the worker pool if no LOOP-scope connection is registered. One instance per loop — survives across dispatches so the per-100-enqueue re-warning fires on the loop-level counter, not per-job.
Source code in src/taskq/client/_enqueuer.py
enqueue
async
¶
enqueue(
actor_ref: ActorRef[P, R],
payload: P,
*,
connection: Connection | None = None,
scheduled_at: datetime | None = None,
priority: int | None = None,
fairness_key: str | None = None,
metadata: dict[str, object] | None = None,
identity_key: IdentityKey | None = None,
idempotency_key: IdempotencyKey | str | None = None,
unique_for: timedelta | None = None,
unique_states: tuple[JobStatus, ...] | None = None,
max_pending: int | None = None,
) -> JobHandle[R]
Source code in src/taskq/client/_enqueuer.py
enqueue_batch
async
¶
enqueue_batch(
items: Sequence[EnqueueItem[Any, Any]],
*,
batch_id: UUID | None = None,
connection: Connection | None = None,
) -> list[JobHandle[Any]]
Enqueue a batch of sub-jobs sharing a single batch_id.
All items share a single batch_id UUID written into each
job's metadata.batch_id field (as a string). When batch_id
is not supplied it is auto-generated as a UUIDv7 via
:func:~taskq._ids.new_job_id — mirrors
:meth:~taskq.client.JobsClient.enqueue_batch. Pass an explicit
batch_id to correlate this batch with a caller-constructed
identifier (e.g. a finalizer job enqueued separately that needs to
reference the same batch).
Source code in src/taskq/client/_enqueuer.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
flush_buffer
async
¶
Flush buffered EnqueueArgs to the backend (in-memory simulation).
Called by the consumer on actor success, AFTER the LOOP-scope
transaction has committed. Per-item flush failures are collected
and re-raised as :class:~taskq.exceptions.SubEnqueueError after
the loop completes so callers can detect lost sub-jobs.
Source code in src/taskq/client/_enqueuer.py
discard_buffer ¶
drain_for_re_enqueue ¶
Return and clear both loop-scope and pending buffers for re-enqueue.
Source code in src/taskq/client/_enqueuer.py
JobContext
dataclass
¶
JobContext(
job_id: UUID,
actor: str,
queue: str,
attempt: int,
worker_id: UUID,
payload: P,
jobs: SubJobEnqueuer,
log: BoundLogger,
span: Span | None = None,
cancel_event: Event = asyncio.Event(),
_abort_requested: Event = threading.Event(),
_progress_buffers: dict[UUID, _ProgressBuffer]
| None = None,
_redis_client: Redis | None = None,
_worker_settings: WorkerSettings | None = None,
_pending_publish_tasks: set[Task[None]] | None = None,
)
Per-job execution context handed to worker actors.
The cancel_event field is a plain :class:asyncio.Event — never
wrapped in a cancel scope or :class:asyncio.TaskGroup (
PEP 789 mitigation). The consumer constructs a fresh event per
attempt; the cancel-poll hook sets it on phase 1; user actor code
polls :attr:cancellation_requested or awaits cancel_event.wait().
payload is typed as the actor's payload model P. The worker
consumer validates the raw dict[str, object] payload from the
JobRow against actor_ref.payload_type before constructing the
context, so handlers see a fully-validated Pydantic instance.
jobs provides :class:SubJobEnqueuer for enqueuing sub-jobs
from within the actor body. The enqueuer resolves the database
connection via LOOP-scope DI → worker-pool fallback.
cancel_event
class-attribute
instance-attribute
¶
check_cancelled ¶
should_abort ¶
Synchronous cancellation check for sync actors (thread-safe).
Sync actors cannot await the async :attr:cancel_event, so
they poll this method cooperatively. The cancel controller sets
the underlying :class:threading.Event during phase 1.
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
actor should return or raise immediately. |
Source code in src/taskq/context.py
progress
async
¶
progress(
*,
step: int | None = None,
percent: float | None = None,
detail: str | None = None,
data: dict[str, object] | None = None,
) -> None
Report incremental progress for this job.
Updates the in-memory coalesce buffer synchronously, then schedules a
best-effort kind="progress" Redis publish as a background task
when a client is connected — this call never blocks on the network.
Raises :class:~taskq.exceptions.ProgressTooLarge if the serialised
data payload exceeds WorkerSettings.progress_data_max_bytes.
All arguments are optional and merged last-writer-wins into the
accumulated pending_state. Intermediate calls between periodic
flush ticks are coalesced: only the latest value for each field
reaches Postgres. seq is strictly monotone across calls.
The Redis publish is genuinely fire-and-forget: it may complete out
of order relative to other in-flight publishes for the same job.
Consumers reading the SSE/pub-sub stream already discard any event
whose seq is not greater than the last one seen (see
:mod:taskq.web.progress), so out-of-order or dropped publishes
never corrupt displayed state — the buffer mutation above (and the
eventual Postgres flush) is the durable source of truth. Failures
publishing to Redis are logged and recorded as a metric, never
raised here.
Source code in src/taskq/context.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
CronScheduleSpec
dataclass
¶
CronScheduleSpec(
actor: str,
cron_expr: str,
timezone: str = "UTC",
dst_strategy: DstStrategy = "skip",
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
name: str = "",
identity_key: IdentityKey | None = None,
enabled: bool = True,
)
Immutable specification for a cron schedule row.
Created by the :func:cron decorator or constructed directly for
register_cron(). payload_factory and static_payload are
mutually exclusive — setting both raises :class:ValueError at
construction time (via :func:cron).
dst_strategy controls how DST gaps and overlaps are handled.
See :data:DstStrategy for the semantics of each strategy.
ScheduleHandle
dataclass
¶
ScheduleHandle(
schedule_id: UUID,
actor: str,
cron_expr: str,
timezone: str,
enabled: bool,
next_fire_at: datetime,
_backend: Backend = field(),
dst_strategy: DstStrategy = "skip",
name: str = "",
identity_key: IdentityKey | None = None,
)
Immutable handle for a cron schedule, returned by JobsClient methods.
The handle fields are a point-in-time snapshot of schedule state.
Async methods delegate to the Backend injected at construction time
(not part of the public __init__ signature) via ScheduleUpdateArgs.
enable() passes ScheduleUpdateArgs(enabled=True); the backend
resets consecutive_failures=0 and last_fire_error=NULL when
enabled=True is set.
ActorConfigDriftError ¶
ActorConfigDriftError(
actor: str,
field: Literal[
"max_concurrent",
"max_pending",
"queue",
"result_ttl",
"metadata",
],
registered: int
| float
| str
| dict[str, object]
| None,
stored: int | float | str | dict[str, object] | None,
)
Bases: TaskQError
One actor whose registered config differs from the stored row.
Source code in src/taskq/exceptions.py
ActorConfigDriftList ¶
Bases: TaskQError
Collected wrapper raised at worker startup when one or more actors have drift.
Source code in src/taskq/exceptions.py
BackpressureError ¶
Bases: TaskQError
Base class for synchronous enqueue-time backpressure signals.
Subclassed by SingletonCollisionError (singleton collision) and used directly by max_pending enforcement. The caller decides whether to retry, fail, or wait; the library does not block on capacity.
Source code in src/taskq/exceptions.py
DependencyCycle ¶
Bases: TaskQError
A cycle was detected in the provider graph.
Source code in src/taskq/exceptions.py
DIError ¶
Bases: TaskQError
Base for DI engine errors not covered by startup-validation.
Raised by the solver at resolution time for malformed annotations (e.g. multiple Scope markers in one Annotated parameter) or unresolvable forward references in actor signatures. Distinct from MissingProvider / ScopeViolation / DependencyCycle, which are raised at startup validation.
IllegalStateTransition ¶
Bases: TaskQError
Attempted to transition a job to a status not reachable from its current status.
Best-effort fast-path check only; the SQL WHERE clause is the authoritative serialization gate for concurrent writes.
Source code in src/taskq/exceptions.py
JobFailed ¶
Bases: TaskQError
:meth:JobHandle.wait saw a non-success terminal state.
Carries the row so callers can inspect status, error_class,
error_message, and error_traceback. Distinct from
:class:ResultUnavailable (which means terminal but no result
stored) and from the original actor exception (which is recorded on
the row, not raised).
Source code in src/taskq/exceptions.py
MaxPendingExceededError ¶
Bases: BackpressureError
Raised when an actor's max_pending queue-depth limit is reached.
current_count is the count of pending+scheduled jobs at the time
of the pre-flight check. max_pending is the configured limit.
The caller decides whether to retry, fail, or wait; the library does
not block on capacity.
Source code in src/taskq/exceptions.py
MissingProvider ¶
Bases: TaskQError
A type was injected but no provider is registered.
Source code in src/taskq/exceptions.py
PartialBatchError ¶
PartialBatchError(
*,
succeeded_count: int,
failed_items: list[tuple[int, Exception]],
total: int,
)
Bases: TaskQError
Raised when an autonomous enqueue_batch partially fails.
Items enqueued before the first failure are committed; remaining
items are not inserted. succeeded_count is the number of items
that were successfully enqueued. failed_items maps the index
of each failed item to its exception. total is the original
batch size.
Source code in src/taskq/exceptions.py
PayloadValidationError ¶
PayloadValidationError(
detail: str,
*,
actor: str | None = None,
payload_schema_ver: str | None = None,
validation_errors: list[dict[str, object]]
| None = None,
)
Bases: TaskQError
Pydantic validation failed at enqueue or dispatch.
At enqueue: raised before the row is inserted ('fail at the door'). At dispatch: causes the job to transition to 'failed' with error_class='PayloadValidationError'. Non-retryable in both cases regardless of the actor's retry policy.
Source code in src/taskq/exceptions.py
ProgressTooLarge ¶
Bases: TaskQError
Raised when progress data payload exceeds the configured size limit.
limit is the configured cap in bytes (WorkerSettings.progress_data_max_bytes).
actual is the serialised byte length of the data dict that was rejected.
Non-retryable: the caller must reduce the payload before retrying.
Source code in src/taskq/exceptions.py
ReservationUnavailable ¶
ReservationUnavailable(
bucket_name: str,
retry_after: timedelta,
*,
source: Literal[
"reservation", "rate_limit"
] = "reservation",
)
Bases: TaskQError
A ConcurrencyReservation slot could not be acquired.
When the upstream RateLimitDecision.retry_after is None, callers
MUST substitute DEFAULT_RESERVATION_BACKOFF. When it is
timedelta(0) (allowed decisions) callers MUST pass it through
unchanged — do NOT use a truthiness coalesce
(x or DEFAULT_RESERVATION_BACKOFF) because timedelta(0) is falsy
and would be wrongly replaced.
Source code in src/taskq/exceptions.py
ResultTooLarge ¶
Bases: TaskQError
Terminal result exceeded the 64KB cap.
ResultUnavailable ¶
Bases: TaskQError
:meth:JobHandle.wait saw a terminal state but no usable result.
Causes:
- result TTL expired before the call;
- actor returned None while R is non-None
(treated as schema mismatch, not a value);
- row stored result=NULL for a non-success status.
Carries the row for inspection.
Source code in src/taskq/exceptions.py
RetryAfter ¶
Bases: TaskQError
Schedule retry at specific delay. Consumes retry budget by default.
Source code in src/taskq/exceptions.py
SchemaNotMigratedError ¶
Bases: TaskQError
Backend raised UndefinedTableError — the TaskQ schema is missing.
Translated by the client layer (:mod:taskq.client._jobs) from an
asyncpg.exceptions.UndefinedTableError on the enqueue/get/list/cancel
paths, so operators see an actionable message instead of a raw asyncpg
traceback. The original exception is chained via __cause__.
Source code in src/taskq/exceptions.py
ScopeViolation ¶
Bases: TaskQError
A provider depends on a shorter-lived scope than its own.
Source code in src/taskq/exceptions.py
SingletonCollisionError ¶
SingletonCollisionError(
actor: str,
blocking_job_id: UUID | None = None,
retry_after: timedelta | None = None,
)
Bases: BackpressureError
Raised when a singleton actor already has a job in pending/scheduled/running.
blocking_job_id is the UUID of the existing job from the Layer 1
pre-flight query; it is None when raised from the Layer 2
UniqueViolationError catch (the race path) because no pre-flight row
was fetched.
retry_after is computed from the blocking job's schedule_to_close
when available. It is None when the blocking job has no
schedule_to_close set, or when raised from the Layer 2 catch path.
The heartbeat_interval * 4 fallback is intentionally NOT
implemented — retry_after is computed from schedule_to_close only.
Callers who need a poll cadence when retry_after is None should poll on
their own schedule (research.md Gap 1, resolution path (a)). Reason:
heartbeat_interval is not available at the backend enqueue boundary;
propagating it would require enlarging the backend constructor surface and
is out of scope.
Source code in src/taskq/exceptions.py
Snooze ¶
Bases: TaskQError
Job returns control with new scheduled_at; does not consume retry budget.
Source code in src/taskq/exceptions.py
SubEnqueueError ¶
Bases: TaskQError
Raised by flush_buffer() when one or more buffered sub-job enqueues fail after parent commit.
failed_items carries each failed EnqueueArgs and the exception
that caused the enqueue to fail. The parent job has already been
marked succeeded — this exception signals that child jobs were lost.
Source code in src/taskq/exceptions.py
TaskQError ¶
Bases: Exception
Base for all library-raised exceptions.
WorkerOwnershipMismatch ¶
Bases: TaskQError
Terminal write predicate failed: job exists but is owned by a different worker.
Source code in src/taskq/exceptions.py
ErrorReporter ¶
Bases: Protocol
Vendor-neutral hook for routing terminal job failures to external systems.
Implementations capture the error and job row, then forward to a
vendor-specific backend (Sentry, Datadog, a DLQ, etc.). The library
calls :meth:report when a job reaches a terminal failure state —
either because retries were exhausted or because the error was
non-retryable.
The call is wrapped in a try/except by :func:invoke_error_reporter;
a failing reporter never crashes the worker. Reporter failures are
counted on the taskq.error_reporter.failures counter with a
reporter_type attribute.
Register an :class:ErrorReporter instance as a DI provider
(registry.register_value(ErrorReporter, Scope.PROCESS, my_reporter))
or pass it directly to the worker bootstrap.
NullErrorReporter ¶
Default no-op :class:ErrorReporter — silently drops all reports.
Used when no vendor-specific error routing is configured. Instances are stateless and safe to share.
ProgressEvent ¶
Bases: BaseModel
Point-in-time progress snapshot published to Redis for SSE/stream fanout.
Covers both kind="progress" (incremental update) and
kind="state_change" (terminal or status transition) events. The
exclude_none=True flag on :meth:model_dump_json suppresses null
fields so the JSON payload stays compact on the wire.
Fail ¶
JobRetryState ¶
Bases: NamedTuple
Projection of JobRow columns consumed by the retry classifier.
Retry ¶
RetryClassifier ¶
Pure classifier that maps an exception + policy to a RetryDecision.
classify
staticmethod
¶
classify(
policy: RetryPolicy,
non_retryable_exceptions: tuple[
type[BaseException], ...
],
exception: BaseException,
attempt: int,
schedule_to_close: datetime | None,
now: datetime,
*,
max_retry_backoff: timedelta = timedelta(hours=24),
override: RetryOverride | None = None,
) -> RetryDecision
Source code in src/taskq/retry.py
RetryOverride ¶
Bases: BaseModel
Per-exception override returned by an actor's retry_classifier hook.
Both fields are optional; None means "use the actor's static
RetryPolicy/computed backoff for this field." Returning a
RetryOverride with only kind set lets one exception type
branch into different retry behaviour per occurrence — e.g. an HTTP
429 response goes indefinite while a 404 response on the same
exception type goes non_retryable. Returning one with only
delay set lets the actor honour a server-provided retry-after
duration instead of the policy's computed exponential/linear
backoff, while max_retry_backoff still applies as a safety
ceiling so a malicious or malformed header cannot strand a job.
RetryPolicy ¶
Bases: BaseModel
Policy controlling retry behaviour for an actor.
backoff
class-attribute
instance-attribute
¶
wait_for_batch
async
¶
wait_for_batch(
db: Connection | Pool,
batch_id: UUID,
*,
schema: str = "taskq",
snooze_interval: timedelta = timedelta(seconds=10),
snooze_via_exception: bool = True,
) -> BatchCompletionStatus
Convenience helper for the fan-out-then-finalize pattern.
Queries batch children by batch_id using the GIN-indexed
WHERE metadata @> $1::jsonb predicate.
Inside an actor (snooze_via_exception=True, the default): - If any children are in-flight, raises Snooze(snooze_interval). The consumer transitions the job to scheduled; the actor is retried after snooze_interval without consuming retry budget. - If all children are terminal, returns BatchCompletionStatus.
Outside an actor (snooze_via_exception=False): - Blocks via asyncio.sleep(snooze_interval) in a loop until all children are terminal, then returns BatchCompletionStatus. - Use this form from scripts and integration tests where no consumer is present to translate a Snooze into a rescheduled job.
Empty batch: if batch_id matches no rows, returns BatchCompletionStatus(total=0, pending=0, is_complete=True) and logs a WARNING (may indicate a wrong batch_id).
snooze_interval is clamped to a minimum of 1 second.
schema must match the schema used when the PostgresBackend was
constructed (default "taskq").
Source code in src/taskq/batch.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
register_cron ¶
Add schedule to the module-level registry.
Validates the cron expression at call time. Raises :class:ValueError
on bad expression or mutually exclusive fields. Duplicate calls append
again — deduplication is the caller's responsibility (the DB
(actor, name) UNIQUE constraint is the authoritative gate at
startup time).
Source code in src/taskq/scheduler.py
cron()¶
taskq.cron is both a submodule (src/taskq/cron.py) and, via from taskq.cron import
cron, the name of a re-exported function on the taskq package. This name collision means
the cron() function does not render under the taskq package-level directive above —
mkdocstrings resolves taskq.cron to the submodule. The explicit directive below documents
the function itself; see the Cron Scheduling guide for usage.
cron ¶
cron(
expression: str,
actor: str,
*,
payload_factory: str | None = None,
static_payload: dict[str, object] | None = None,
name: str = "",
identity_key: IdentityKey | None = None,
timezone: str = "UTC",
dst_strategy: DstStrategy = "skip",
enabled: bool = True,
) -> CronScheduleSpec
Declare a cron schedule and auto-register it.
Validates expression via croniter.is_valid(); raises
:class:ValueError on invalid expressions. Raises
:class:ValueError if both payload_factory and static_payload
are provided.
The returned :class:CronScheduleSpec is registered via
:func:~taskq.scheduler.register_cron at decoration time so
decorated schedules are auto-discovered at worker startup without
any explicit register_cron() call.
Startup auto-discovery is create-only, skip-on-conflict. Existing
cron_schedules rows are never modified by the decorator
registration pass. If a @cron decorator's parameters change
after the schedule was first registered, the operator must manually
update or delete and recreate the schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dst_strategy
|
DstStrategy
|
How to handle DST gaps and overlaps.
|
'skip'
|