Skip to content

Background Task Queues & Cron Scheduler

vertebra.framework.queues provides sync and async task queues, retry and dead-letter policies, distributed cron leases, multi-lane worker execution, and pluggable backends for Memory, PostgreSQL, Oracle, Redis, Valkey, and Spanner.

Component Purpose
Queue Core & Runner Enqueue typed tasks onto io, cpu, or agent lanes with scoped DI, heartbeats, exponential backoff, and dead-letter retention.
Queue Store Protocols Runtime-checkable persistence contracts implemented by the PostgreSQL, Oracle, and Spanner queue stores.
Cron Scheduler Run recurring cron schedules with slot-keyed distributed leader leases.
Storage Backends Store and claim task envelopes using SKIP LOCKED SQL tables, hash-sharded Spanner transactions, or Redis and Valkey Streams consumer groups.

Queue Configuration, Store Protocols & Service

QueueConfig

Bases: Struct

Configuration for QueueService across memory, Redis, Valkey, PostgreSQL, Oracle, and Spanner backends.

QueueBackendSettings

Bases: Struct

Declarative configuration settings for QueueService backend initialization.

QueueEntry

Bases: FrozenBaseStruct

Durable background job record leased from or enqueued to a queue store.

SyncQueueStore

Bases: Protocol

Capability protocol for synchronous database-backed background job queues.

AsyncQueueStore

Bases: Protocol

Capability protocol for asynchronous database-backed background job queues.

TaskRetryPolicy

Bases: Struct

Retry and exponential backoff policy for background tasks.

TaskEnvelope

Bases: Struct

Wire-serializable background task execution envelope.

DeadLetterEntry

Bases: Struct

Dead-letter queue payload capturing exhausted task envelopes and error metadata.

QueueService

Multi-lane background task queue service supporting pluggable distributed backends.

Attributes:

Name Type Description
configQueueConfig | QueueBackendSettings

Return the active QueueConfig or QueueBackendSettings.

backendQueueBackend

Return the underlying active QueueBackend instance.

registered_tasksdict[str, TaskDef]

Return registered task definitions keyed by name.

containerContainer | None

Return the bound Container if configured.

schedulerCronScheduler | None

Return the bound CronScheduler if configured.

register

register(task_def)

Register a TaskDef with the queue service.

enqueue_sync

enqueue_sync(
    task_name,
    *args,
    lane=None,
    delay_seconds=None,
    scheduled_at=None,
    idempotency_key=None,
    **kwargs,
)

Synchronously enqueue a task by name with optional scheduling, lane override, and idempotency key.

enqueue

enqueue(
    task_name,
    *args,
    lane=None,
    delay_seconds=None,
    scheduled_at=None,
    idempotency_key=None,
    **kwargs,
)

Enqueue a task by name with optional scheduling, lane override, and idempotency key.

enqueue_delayed

enqueue_delayed(delay_seconds, task_name, *args, **kwargs)

Enqueue a task to be executed after delay_seconds elapses.

process_envelope

process_envelope(envelope, *, container=None)

Execute callable bound to envelope, settling with ack or nack upon completion.

drain_once

drain_once(lanes=None, *, batch_size=100)

Execute ready tasks across selected lanes in FIFO order and return results.

run_next

run_next()

Pop and execute the next ready task across all lanes, retrying on transient failure.

run_due_schedules

run_due_schedules(*, minute=0, hour=0, day_of_month=1, month=1, day_of_week=0)

Enqueue and execute all registered cron tasks matching the specified timestamp components.

close

close()

Close underlying backend resources.

WorkerRunner

Admission-controlled multi-lane worker runner with QueueService integration and lame-duck drain.

Attributes:

Name Type Description
lanesdict[str, LaneConfig]

Return configured worker lanes keyed by queue name.

metricsdict[str, LaneMetrics]

Return current observability metrics keyed by configured queue name.

lame_duckLameDuckController

Return the bound LameDuckController.

queue_serviceQueueService | None

Return the bound QueueService if configured.

schedulerCronScheduler | None

Return the bound CronScheduler if configured.

containerContainer | None

Return the bound Container if configured.

heartbeat_interval_secondsfloat

Return the interval in seconds between visibility lease heartbeats.

reap_interval_secondsfloat

Return the interval in seconds between stale-lease reap maintenance sweeps.

is_stoppingbool

Return whether runner shutdown has commenced.

submit

submit(queue_name, job_factory)

Schedule a job onto the specified queue lane bounded by that lane's semaphore.

process_once

process_once()

Pull and concurrently process a task batch up to configured lane concurrency.

run

run(*, install_signal_handlers=False, poll_interval_s=0.05)

Run continuous concurrent pull loop across lanes until stopped.

stop

stop()

Stop accepting new jobs and drain in-flight tasks within drain timeout.

parse_lanes

parse_lanes(queues, concurrency='10', *, drain_timeout_s=30.0)

Parse comma-separated queue names and concurrency limits into LaneConfig objects.

parse_lane_concurrency

parse_lane_concurrency(
    queues, lane_concurrency="", *, default_concurrency=10, drain_timeout_s=30.0
)

Parse comma-separated queue names and lane=limit assignments into LaneConfig objects.

resolve_job

resolve_job(app, job_name)

Look up a named job callable on a Litestar or Vertebra app.

resolve_queue_service

resolve_queue_service(target)

Resolve a configured QueueService directly or from target.state['vertebra_queue_service'].

run_oneshot

run_oneshot(app, job_name, *, payload=None)

Enter the application lifespan, run a single named job, and return an exit code.

Cron Scheduling

CronSchedule

Bases: Struct

Recurring cron schedule descriptor for background jobs.

Attributes:

Name Type Description
expressionstr
timezonestr
Default: 'UTC'

CronScheduler

Distributed lease-elected cron job scheduler dispatching due tasks into QueueService.

Attributes:

Name Type Description
node_idstr

Return the unique scheduler node identifier.

register

register(name, cron_expr, task_name, *, kwargs=None)

Register a named cron schedule dispatching task_name with kwargs.

tick

tick(*, now=None)

Attempt lease-based slot election and enqueue tasks matching the current minute tick.

run

run(stop_event, *, check_interval_seconds=1.0)

Execute scheduled background loop until stop_event is signaled.

Queue Backends

MemoryQueueBackend

In-memory reference QueueBackend implementation supporting visibility timeout and DLQ.

enqueue_sync

enqueue_sync(envelope)

Synchronously enqueue an envelope into scheduled storage or active lane deque.

enqueue

enqueue(envelope)

Enqueue an envelope into scheduled storage or active lane deque.

dequeue

dequeue(lanes, *, batch_size=1, timeout_seconds=0.0)

Claim ready tasks across lanes, reclaiming visibility-timed-out unacked tasks first.

ack

ack(envelope)

Acknowledge completed task by removing receipt handle from in-flight registry.

nack

nack(envelope, *, error, delay_seconds=None, send_to_dlq=False)

Negatively acknowledge task, routing to DLQ when exhausted or re-enqueuing for retry.

promote_scheduled

promote_scheduled(*, now=None, batch_size=100)

Promote due scheduled envelopes to active lanes.

list_dlq

list_dlq(*, limit=100)

List dead-letter entries up to limit.

replay_dlq

replay_dlq(dlq_id)

Replay dead-letter entry by re-enqueuing with reset attempt count.

acquire_lease

acquire_lease(lease_key, owner_id, ttl_seconds, *, slot=None)

Acquire lease if free, expired, or owned by caller.

renew_lease

renew_lease(lease_key, owner_id, ttl_seconds, *, slot=None)

Renew lease only if owner_id matches existing holder.

close

close()

In-memory cleanup.

PostgreSQLQueueBackend

Bases: _SqlQueueBackendBase

PostgreSQL queue backend using FOR UPDATE SKIP LOCKED and LISTEN/NOTIFY over native stores or an executor.

enqueue

enqueue(envelope)

Insert job row into database and emit pg_notify wakeup.

dequeue

dequeue(lanes, *, batch_size=1, timeout_seconds=0.0)

Claim tasks via FOR UPDATE SKIP LOCKED, with adaptive LISTEN/NOTIFY wakeup.

ack

ack(envelope)

Delete completed job row matching task_id and receipt_handle.

nack

nack(envelope, *, error, delay_seconds=None, send_to_dlq=False)

Route to DLQ or reschedule with exponential backoff.

RedisQueueBackend

Bases: RESPStreamQueueBackend

Distributed task queue backend powered by Redis Streams and Sorted Sets.

ValkeyQueueBackend

Bases: RESPStreamQueueBackend

Distributed task queue backend powered by Valkey Streams and Sorted Sets.

OracleQueueBackend

Bases: _SqlQueueBackendBase

Oracle Database queue backend using FOR UPDATE SKIP LOCKED over native stores or an executor.

enqueue

enqueue(envelope)

Insert task into vertebra_queue_jobs.

dequeue

dequeue(lanes, *, batch_size=1, timeout_seconds=0.0)

Claim tasks with FOR UPDATE SKIP LOCKED.

ack

ack(envelope)

Delete acknowledged task and commit transaction.

nack

nack(envelope, *, error, delay_seconds=None, send_to_dlq=False)

Route to DLQ or reschedule with backoff.

SpannerQueueBackend

Bases: _SqlQueueBackendBase

Google Cloud Spanner queue backend over SyncSpannerQueueStore, AsyncSpannerQueueStore, or an executor.

enqueue

enqueue(envelope)

Insert a task into vertebra_queue_jobs under its deterministic shard_id.

dequeue

dequeue(
    lanes=("io",),
    *,
    batch_size=1,
    timeout_seconds=0.0,
    visibility_timeout_s=None,
)

Claim up to batch_size ready jobs atomically via SELECT ... FOR UPDATE and UPDATE.

ack

ack(envelope)

Delete or mark acknowledged a claimed job row with attempt fencing.

nack

nack(
    envelope,
    *,
    error="",
    delay_seconds=None,
    retry_delay_s=None,
    send_to_dlq=False,
)

Route a failed job to vertebra_queue_dlq or reschedule with backoff.