# Soniq - Full canonical docs (for LLM context) > This file concatenates the canonical Soniq pages so an agent can load the whole working surface in one fetch. For the indexed list of all docs (including tutorials, guides, recipes, production, migration), see [llms.txt](llms.txt). > Not included here (fetch separately if you need them): webhook delivery ([recipes/webhook-delivery.md](recipes/webhook-delivery.md), tables `soniq_webhook_endpoints` / `soniq_webhook_deliveries`), job logs (table `soniq_logs`, service `app.logs`), and the task registry ([cli/commands.md#tasks-check](cli/commands.md), table `soniq_task_registry` populated by workers on startup and checked by `soniq tasks-check`). `soniq setup` creates all of these tables; the pages below do not cover them. > Generated by `scripts/build_llms_full.py`. Do not edit by hand. Pages included, in order: 1. Quickstart - canonical end-to-end shape 2. API - Jobs - decorator, enqueue, schedule, JobContext, cron DSL 3. API - Worker - CLI, run_worker, env-var configuration 4. API - Hooks - before_job, after_job, on_error 5. Guide - FastAPI - lifespan helper, single-process worker, BackgroundTasks 6. Guide - Transactional enqueue - SQLAlchemy, asyncpg and psycopg connections 7. Reference - Glossary - one-paragraph definitions of every term the docs use --- # Page 1: Quickstart *(source: docs/quickstart.md)* # Quickstart: run a Python background job with PostgreSQL Soniq is a Python background job library that uses PostgreSQL as its queue. This page takes you from `pip install` to a running worker in about 5 minutes. ## 1. Install ```bash pip install soniq ``` You need a running PostgreSQL. If you do not have one, start one with Docker: ```bash docker run -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18 ``` > To try Soniq without PostgreSQL, run `pip install "soniq[sqlite]"`. Then pass a file path instead of a URL: `Soniq(database_url="dev.db")`. SQLite and the in-memory backend (`Soniq(backend="memory")`) are for local development and tests only. See the [testing guide](guides/testing.md#sqlite-for-integration-tests) and the [Backend](reference/glossary.md#backend) glossary entry. ## 2. Set the environment The `soniq` command and your Python code both read the database URL from the environment. Set both variables in your shell: ```bash export SONIQ_DATABASE_URL="postgresql://localhost/myapp" export SONIQ_JOBS_MODULES=jobs ``` `SONIQ_JOBS_MODULES` lists the Python modules that the worker imports on startup. The import runs the `@soniq.job()` decorators, which register your jobs. Without it, the worker does not know which jobs exist. ## 3. Define a job Create a file named `jobs.py`: ```python # jobs.py import asyncio from soniq import Soniq soniq = Soniq() @soniq.job(name="emails.send_welcome") async def send_welcome(to: str): print(f"Sending welcome email to {to}") if __name__ == "__main__": async def main(): await soniq.enqueue(send_welcome, to="dev@example.com") await soniq.close() asyncio.run(main()) ``` The job has an explicit `name`. When you run `python jobs.py`, Python calls the file `__main__`. Without a fixed name, Soniq stores the job as `__main__.send_welcome`. The worker imports the file as `jobs`, so it cannot find that name. ## 4. Set up the database ```bash soniq setup ``` This command creates the tables that Soniq needs. It is idempotent: you can run it more than once and it changes nothing the second time. ## 5. Start a worker ```bash soniq worker --concurrency 4 ``` The worker process must be able to import your job code. For cross-service setups and per-worker overrides, see [Job module discovery](getting-started/installation.md#job-module-discovery). ## 6. Enqueue a job Open another terminal and run: ```bash python jobs.py ``` The worker prints "Sending welcome email to dev@example.com". You now have a working background queue. ## What changes in production Make these changes before you deploy. - **Read settings from the environment.** Do not hardcode `database_url`. Soniq reads `SONIQ_DATABASE_URL` automatically. - **Set `SONIQ_JOBS_MODULES`** so workers import your job functions on startup. - **Run `soniq setup` once per deploy.** Do not run it from every replica. See [going to production](production/going-to-production.md). - **Make handlers idempotent.** An idempotent handler gives the same end result when it runs more than once. Soniq guarantees *at-least-once* delivery. If a worker crashes after it runs your function but before it marks the job done, another worker runs the job again. To make a rerun harmless, use `INSERT ... ON CONFLICT DO UPDATE` instead of a plain insert. You can also check whether you already sent the email, or store an idempotency token with the side effect. - **Tune timeouts.** Every job has a default timeout of 300 seconds. Override it per job: `@soniq.job(name="reports.build", timeout=600)`. > **New to job queues?** The [tutorial](tutorial/01-defining-jobs.md) explains each term in depth. You do not need to learn all of this now. ## Next steps To learn each concept, work through the [tutorial](tutorial/01-defining-jobs.md). It has six chapters and takes about 30 minutes. If you already know job queues, go to one of these pages: - [FastAPI guide](guides/fastapi.md) - the most common producer setup - [Going to production](production/going-to-production.md) - the checklist for a healthy deploy - [Migrating from Celery](migration/from-celery.md) or [from RQ](migration/from-rq.md) --- *Working with an AI coding agent? Point it at [`AGENTS.md`](https://github.com/abhinavs/soniq/blob/main/AGENTS.md) and [`llms.txt`](llms.txt). They cover the canonical patterns and the mistakes agents make most often.* --- # Page 2: API - Jobs *(source: docs/api/jobs.md)* # Define, enqueue and schedule jobs A job in Soniq is an async Python function that you register with `@soniq.job()`. Soniq stores each call to `enqueue()` as a row in PostgreSQL, and a worker runs the function later. This page covers defining, enqueueing, scheduling and inspecting jobs. ## @soniq.job decorator Registers a function as a job. Always called with parentheses, even with no kwargs. ```python soniq = Soniq(database_url="postgresql://localhost/myapp") @soniq.job(name="emails.send_email") async def send_email(to: str, subject: str, body: str): ... @soniq.job(name="emails.send_password_reset", retries=5, queue="urgent") async def send_password_reset(to: str, token: str): ... ``` ### Parameters All parameters are optional. | Parameter | Type | Default | Description | |---|---|---|---| | `name` | `str \| None` | `None` | Task name stored in the job's row. Always pass it. The name must match the `task_name_pattern` setting, which by default means lowercase dotted segments such as `emails.send_email`. When omitted, Soniq derives the name from `f"{module}.{function_name}"`. This is deprecated since 0.2.0 and warns. See [Storage format](../reference/storage-format.md#job-names). | | `retries` | `int` | `3` | Maximum retries after the first failure. A job runs at most `retries + 1` times. Alias: `max_retries`. | | `priority` | `int` | `100` | A lower number runs first. | | `queue` | `str` | `"default"` | Queue name for this job. | | `unique` | `bool` | `False` | Deduplicate by job name and argument hash. If a matching job is still `queued`, `enqueue()` creates no job and returns the id of the existing one. | | `retry_delay` | `int \| float \| list[int \| float]` | `0` | Seconds to wait before each retry. Pass a list to set per-attempt delays (e.g. `[1, 5, 30]`). | | `retry_backoff` | `bool` | `False` | Double the delay on each attempt. The base is `retry_delay`, or 1 second when `retry_delay` is `0`. | | `retry_max_delay` | `int \| float \| None` | `None` | Cap on retry delay in seconds. | | `retry_jitter` | `bool` | `True` | With `retry_backoff`, pick a random delay between half of the backoff delay and the full delay. Ignored without `retry_backoff`. | | `timeout` | `int \| float \| None` | `None` | Per-job timeout in seconds. `None` uses the `job_timeout` setting (default 300 seconds). A timeout counts as a failure and follows the retry rules. | | `validate` | `type[BaseModel] \| None` | `None` | Pydantic model that checks the job arguments at enqueue time. Alias: `args_model`. | ```python @soniq.job( name="payments.process_payment", retries=5, priority=10, queue="urgent", retry_delay=[1, 5, 30, 60], timeout=120, ) async def process_payment(order_id: int, amount: float): ... ``` ## enqueue() Dispatches a registered job for processing. Three input shapes: ```python # 1. Callable (same codebase) job_id = await soniq.enqueue(send_email, to="a@b.com", subject="Hi", body="Hello") # 2. String task name (cross-service / by-name) job_id = await soniq.enqueue( "users.send_email", args={"to": "a@b.com", "subject": "Hi", "body": "Hello"}, ) # 3. TaskRef (typed cross-repo stub) job_id = await soniq.enqueue(send_email_ref, args={"to": "a@b.com", "subject": "Hi", "body": "Hello"}) ``` ### Signature ```python async def enqueue( target, # Callable, string task name, or TaskRef (positional only) /, *, args: dict | None = None, # Function args (string / TaskRef shapes) priority: int | None = None, # Override the job's default priority queue: str | None = None, # Override the job's default queue scheduled_at: datetime | timedelta | int | float | None = None, # Run at a time, or after a delay unique: bool | None = None, # Override the job's default uniqueness dedup_key: str | None = None, # Custom deduplication key (instead of args hash) connection = None, # Connection for transactional enqueue **func_kwargs, # Function args (callable shape) ) -> str # Returns the job UUID ``` `target` is the first positional argument and selects the input shape: - **Callable**: function args travel as `**func_kwargs`. Don't pass `args=`. - **String task name**: function args travel in `args=dict`. Don't pass `**func_kwargs` (they would collide with enqueue options). - **`TaskRef`**: function args travel in `args=dict` and are validated against `ref.args_model` if set. All option parameters are optional. When you omit one, the value from the `@soniq.job()` registration applies. A job with no local registration gets priority 100, queue `default` and `max_retries + 1` attempts (from the `max_retries` setting). `scheduled_at` accepts a timezone-aware `datetime`, a `timedelta`, or a number of seconds from now. A naive `datetime` raises `ValueError`. `enqueue()` rejects bad arguments before it writes a row. It raises `SoniqError` with code `SONIQ_TASK_ARGS_INVALID` when an argument is not JSON-serializable, does not fit the handler signature, or fails the `validate=` model. It raises `SONIQ_UNKNOWN_TASK_NAME` when you enqueue an unregistered string name and `enqueue_validation` is `"strict"` (the default). ### Transactional enqueue Pass a `connection` to enqueue a job inside an existing database transaction. If the transaction rolls back, the job is never created. The connection must have an active transaction. Soniq accepts an `asyncpg` connection, a SQLAlchemy `AsyncSession` or `AsyncConnection`, and a `psycopg` `AsyncConnection`. ```python await soniq.ensure_initialized() async with soniq.backend.acquire() as conn: async with conn.transaction(): await conn.execute("INSERT INTO orders (id) VALUES ($1)", order_id) await soniq.enqueue(fulfill_order, connection=conn, order_id=order_id) ``` Transactional enqueue requires the PostgreSQL backend. See [Transactional enqueue](../guides/transactional-enqueue.md) for the other connection types. ## job.enqueue() and job.options() The decorator adds two methods to the job function: `.enqueue()` and `.options()`. Use them to enqueue a job without passing the function to `soniq.enqueue()`. ```python soniq = Soniq(database_url="postgresql://localhost/myapp") @soniq.job(name="emails.send_welcome") async def send_welcome(to: str) -> None: ... # Enqueue with the job's own arguments. job_id = await send_welcome.enqueue(to="dev@example.com") # Set enqueue options, then enqueue. job_id = await send_welcome.options(queue="emails", priority=10).enqueue( to="dev@example.com" ) # The function is still a plain async function. await send_welcome(to="dev@example.com") ``` `send_welcome.enqueue(**kwargs)` does the same thing as `soniq.enqueue(send_welcome, **kwargs)`. It uses the `Soniq` instance that registered the job, and the same task name, also when you set `name=` on the decorator. `.options()` accepts the enqueue options of `enqueue()`: `queue`, `priority`, `scheduled_at`, `unique`, `dedup_key` and `connection`. It returns an object with one method, `.enqueue(**kwargs)`. You can keep this object and use it more than one time. ```python async with soniq.backend.acquire() as conn: async with conn.transaction(): await conn.execute("INSERT INTO users (email) VALUES ($1)", email) await send_welcome.options(connection=conn).enqueue(to=email) ``` Use `.options()` when the job has an argument with the same name as an enqueue option, for example `queue`. In `send_welcome.enqueue(queue="x")`, `queue` is the enqueue option, not the job argument. This is the same rule as for `soniq.enqueue()`. ### Type checking A type checker such as mypy or pyright checks the arguments of `.enqueue()` against the job signature. A wrong argument name or type is an error before the code runs: ```python await send_welcome.enqueue(too="dev@example.com") # error: unexpected keyword "too" ``` The static return type of `@soniq.job()` is `soniq.types.JobFunction[P, R]`. It is a typing aid only. At runtime the decorator returns the same plain function as before, with the extra attributes. A `JobFunction` is still a `Callable[P, Awaitable[R]]`, so code that wraps or calls the job type-checks without changes. Pass job arguments as keywords. A positional argument to `.enqueue()` raises `TypeError`. A type checker does not report it. ### Compatibility `soniq.enqueue(send_welcome, ...)` stays supported. It is not deprecated, and there is no plan to remove it. Both forms write the same job row. Use the form that you prefer. If your function already has an attribute named `enqueue` or `options`, Soniq does not replace it. Soniq writes a debug log message and does not add that method. ## enqueue_many() Bulk-enqueue many jobs that share the same target. Returns a list of job IDs in input order. ```python ids = await soniq.enqueue_many( send_email, [ {"to": "a@example.com", "subject": "Hi", "body": "Hello"}, {"to": "b@example.com", "subject": "Hi", "body": "Hello"}, {"to": "c@example.com", "subject": "Hi", "body": "Hello"}, ], queue="emails", # optional, applies to all rows priority=50, # optional, applies to all rows ) ``` ### Signature ```python async def enqueue_many( target, # Callable, string task name, or TaskRef args_list: list[dict], # One args dict per job *, queue: str | None = None, # Shared override for all rows priority: int | None = None, # Shared override for all rows scheduled_at = None, # Shared override for all rows ) -> list[str] ``` On PostgreSQL, `enqueue_many()` writes all rows with one batched INSERT. On SQLite and the in-memory backend, it inserts the rows one by one. Soniq checks every `args_list[i]` before it writes any row, so one bad item fails the whole call. `enqueue_many()` has no `unique=` or `dedup_key=` option. If the registered job declares `unique=True`, `enqueue_many()` raises `TypeError`. For per-row deduplication, call `enqueue()` in a loop. An empty `args_list` returns `[]`. ## schedule() Schedule a job to run at a later time. `schedule()` is `enqueue()` with `scheduled_at=run_at`. ```python from datetime import datetime, timezone # Absolute UTC datetime await soniq.schedule( send_report, run_at=datetime(2025, 1, 1, 9, 0, tzinfo=timezone.utc), user_id=42, ) ``` ```python async def schedule( target, run_at, # Timezone-aware datetime, timedelta, or seconds from now (int/float) *, args: dict | None = None, **kwargs, ) -> str # Returns job UUID ``` `soniq.schedule()` passes `**kwargs` to `enqueue()`, so `kwargs` are job arguments for the callable shape. A naive `datetime` raises `ValueError`. For a recurring schedule, use `@soniq.periodic()`. ## @soniq.periodic() Declares a job that runs on a recurring schedule. Single decorator: registers the function as a regular `@soniq.job` and stamps the schedule on it. The scheduler process (`soniq scheduler`) picks up all `@periodic` functions automatically. ```python from datetime import timedelta from soniq import cron, daily, every @soniq.periodic(cron=daily().at("09:00"), name="reports.daily") async def daily_report(): ... @soniq.periodic(cron=every(10).minutes(), queue="maintenance", name="cleanup") async def cleanup_old_sessions(): ... @soniq.periodic(every=timedelta(seconds=30), name="metrics.flush") async def flush_metrics(): ... ``` The scheduler checks for due jobs every `--check-interval` seconds (default 60). If an `every=` interval is shorter, the scheduler lowers its check interval to match at startup, so the 30-second job above fires every 30 seconds. The first run comes about one check interval after the scheduler starts. ### Parameters | Parameter | Type | Description | |---|---|---| | `cron` | `str` or builder | A 5-field cron expression, or any object whose `__str__` is one (e.g. `daily().at("09:00")` from `soniq.schedules`). Soniq validates the expression when the decorator runs. | | `every` | `timedelta` or `int`/`float` | Interval between runs. Use `timedelta` for clarity; numbers are seconds. The minimum is 1 second. | | `**job_kwargs` | | Any parameter accepted by `@soniq.job` (`name`, `queue`, `priority`, `retries`, etc.). Always pass `name`: without it the name falls back to `f"{module}.{function_name}"`, which is deprecated since 0.2.0 and warns. | Rules: - Specify exactly one of `cron=` or `every=`. - They cannot be combined. Requires a running `soniq scheduler` process to actually fire the jobs. ## Snooze A handler returns `Snooze` to run again later without using a retry. Use it when the job must wait for something outside Soniq, such as a rate limit. ```python from soniq import Snooze @soniq.job(name="sync.pull_orders") async def pull_orders(): if rate_limited(): return Snooze(seconds=60, reason="rate limited") ``` `Snooze(seconds, reason=None)` puts the job back in `queued` with a new run time. The attempt count does not go up. The `snooze_max_seconds` setting caps the delay (default 86400 seconds). Soniq fires no `after_job` or `on_error` hook for a snoozed run. ## JobContext Runtime metadata injected into your job function. Declare a parameter with type annotation `JobContext` and Soniq fills it in automatically. ```python from soniq import JobContext @soniq.job(name="orders.process_order") async def process_order(order_id: int, ctx: JobContext): print(f"Job {ctx.job_id}, attempt {ctx.attempt} of {ctx.max_attempts}") ``` ### Attributes | Attribute | Type | Description | |---|---|---| | `job_id` | `str` | UUID of this job. | | `job_name` | `str` | The registered job name (the `name=` you gave the decorator). | | `attempt` | `int` | Current attempt number (starts at 1). | | `max_attempts` | `int` | Total allowed attempts (`retries + 1`). | | `queue` | `str` | Queue this job is running in. | | `worker_id` | `str` | UUID of the worker processing this job. Empty string when the context is built outside a worker claim. | | `scheduled_at` | `datetime \| None` | When the job was scheduled to run, if it was delayed. | | `created_at` | `datetime \| None` | When the job was created. | `JobContext` is a frozen dataclass. It is read-only. ## JobStatus Enum of the lifecycle states a `soniq_jobs` row can hold. ```python from soniq import JobStatus ``` | Value | Meaning | |---|---| | `JobStatus.QUEUED` | Waiting to be picked up by a worker. Retries also re-enter this state. | | `JobStatus.PROCESSING` | Currently being executed. | | `JobStatus.DONE` | Completed successfully. | | `JobStatus.CANCELLED` | Cancelled before execution. | Jobs that exhaust all retries are moved into the `soniq_dead_letter_jobs` table; they do not remain in `soniq_jobs`. See [Dead-letter queue](../reference/dead-letter.md). ## Imperative scheduling: `soniq.scheduler` For schedules computed at runtime (per-tenant, per-flag, ...) use the `Scheduler` service exposed on the Soniq instance: ```python await soniq.scheduler.add( target=cleanup, # callable, task-name string, or pass name= cron="0 9 * * *", # OR: every=timedelta(...) args={"region": "US"}, queue="reports", priority=10, max_attempts=3, ) await soniq.scheduler.pause("reports.daily") await soniq.scheduler.resume("reports.daily") await soniq.scheduler.remove("reports.daily") schedules = await soniq.scheduler.list(status="active") sched = await soniq.scheduler.get("reports.daily") ``` `add()` takes `target`, `cron`, `every`, `args`, `queue`, `priority`, `max_attempts` and `name`. Pass exactly one of `cron` or `every`. It returns the schedule name. Schedules are keyed by the resolved task name. Re-adding the same name updates the schedule in place rather than creating a duplicate. ## Cron-string DSL `soniq.schedules` (also re-exported from the `soniq` package root) is a small, pure-Python builder layer that returns plain cron strings: ```python from datetime import timedelta from soniq import cron, daily, every, monthly, weekly every(5).minutes() # "*/5 * * * *" every(2).hours() # "0 */2 * * *" every(30).seconds() # timedelta(seconds=30) every(2).days() # "0 0 */2 * *" daily().at("09:00") # "0 9 * * *" weekly().on("monday").at("09:00") # "0 9 * * 1" monthly().on_day(15).at("12:00") # "0 12 15 * *" cron("*/15 * * * *") # identity passthrough ``` Each terminal returns a `str`, so `cron=daily().at("09:00")` plugs straight into `@soniq.periodic(cron=...)` or `soniq.scheduler.add(cron=...)`. --- # Page 3: API - Worker *(source: docs/api/worker.md)* # Run Soniq workers A Soniq worker claims jobs from PostgreSQL, runs your handlers and records the result. Run workers with the `soniq worker` command from a process manager such as systemd, Kubernetes or supervisord. The manager restarts and scales them. The `Worker` class and `soniq.run_worker()` are documented here for advanced use cases (tests, embedding, custom orchestration). ## soniq worker ```bash soniq worker myapp.jobs:soniq # import the module and use that Soniq instance soniq worker myapp.jobs:soniq --concurrency 8 --queues emails,billing soniq worker myapp.jobs:soniq --run-once # process available jobs once and exit SONIQ_JOBS_MODULES=myapp.jobs soniq worker # no app path: name the job modules ``` The command reads `SONIQ_DATABASE_URL` and the other `SONIQ_*` settings from the environment. Without an app path, the command exits with an error unless `SONIQ_JOBS_MODULES` or `--jobs-modules` names the job modules. | Flag | Default | Description | |---|---|---| | `APP` (positional) | none | `module:attribute` of your `Soniq` instance. | | `--concurrency` | `4` | Number of concurrent job tasks. | | `--queues` | all queues | Comma-separated queue names. | | `--jobs-modules` | none | Extra modules to import. Soniq merges them with `SONIQ_JOBS_MODULES`. | | `--run-once` | off | Process available jobs and exit. | | `--log-level` | `INFO` | Root logger level. Also read from `SONIQ_LOG_LEVEL`. | | `--database-url` | none | Overrides the instance's database URL. | See the [CLI reference](../cli/commands.md) for all commands. ## run_worker() The in-process entry point. Use this for tests or when embedding Soniq inside a larger Python application that owns the lifecycle. ```python soniq = Soniq(database_url="postgresql://localhost/myapp") await soniq.run_worker( concurrency=4, run_once=False, queues=None, shutdown_event=None, ) ``` ### Parameters | Parameter | Type | Default | Description | |---|---|---|---| | `concurrency` | `int` | `4` | Number of concurrent asyncio tasks fetching and executing jobs. | | `run_once` | `bool` | `False` | Process all available jobs and exit. Useful for testing and cron-driven setups. | | `queues` | `list[str] \| None` | `None` | Restrict to these queue names. `None` means process all queues. This is the in-process default; the `soniq worker` CLI also defaults to all queues when `--queues` is omitted. | | `shutdown_event` | `asyncio.Event \| None` | `None` | Set it to shut the worker down and drain in-flight jobs. When you pass one, the worker installs no signal handlers. Ignored when `run_once` is `True`. | On PostgreSQL, `run_worker()` raises `SoniqError` with code `SONIQ_POOL_TOO_SMALL` when `concurrency + pool_headroom` is greater than `pool_max_size`. Raise `pool_max_size` or lower `concurrency`. ### What happens during run_worker 1. The instance auto-initializes if needed (connects to the database, runs lazy setup). 2. A `Worker` instance is created with the instance's backend, job registry, settings, and hooks. 3. In continuous mode, the worker registers itself in the database, starts a heartbeat loop, subscribes to `LISTEN/NOTIFY` for instant job pickup, and launches `concurrency` processing tasks. 4. In `run_once` mode, the worker processes available jobs sequentially until the queue is empty, then returns. ## Worker configuration via environment variables These environment variables control worker behavior when using the CLI or default settings: | Env var | Default | Description | |---|---|---| | `SONIQ_POLL_INTERVAL` | `5.0` | Seconds to wait when no jobs are available before polling again. Also the `LISTEN/NOTIFY` timeout. | | `SONIQ_HEARTBEAT_INTERVAL` | `5.0` | Seconds between heartbeat updates. | | `SONIQ_HEARTBEAT_TIMEOUT` | `300.0` | Seconds after which a worker with no heartbeat is considered stale. | | `SONIQ_CLEANUP_INTERVAL` | `300.0` | Seconds between expired-job and stale-worker cleanup runs. | | `SONIQ_ERROR_RETRY_DELAY` | `5.0` | Seconds to sleep after an unexpected worker-level error before resuming. | | `SONIQ_SHUTDOWN_TIMEOUT` | `30.0` | Seconds that running jobs get to finish during shutdown. | | `SONIQ_SYNC_HANDLER_POOL_SIZE` | `8` | Threads that run sync (non-async) handlers. | | `SONIQ_JOBS_MODULES` | (empty) | Comma-separated list of modules to import on worker startup. The CLI needs it unless you pass an app path (`soniq worker myapp.jobs:soniq`), which Soniq imports for you. See [Job module discovery](../getting-started/installation.md#job-module-discovery). | !!! note "Concurrency and queue selection" Soniq does not read `SONIQ_CONCURRENCY` or `SONIQ_QUEUES` when it starts a worker. The `soniq worker` command uses `--concurrency` (default 4) and processes all queues unless you pass `--queues name1,name2`. ## Worker class (advanced) Most users never instantiate `Worker` directly. It is documented here for contributors and users who need fine-grained control. ```python from soniq.core.worker import Worker from soniq.core.registry import JobRegistry from soniq.settings import SoniqSettings worker = Worker( backend=backend, # A StorageBackend instance registry=registry, # A JobRegistry with registered jobs settings=settings, # SoniqSettings (optional, uses global defaults) hooks=hooks, # Dict of hook lists (optional) middleware=None, # List of middleware (optional) ) ``` ### Constructor parameters | Parameter | Type | Default | Description | |---|---|---|---| | `backend` | `StorageBackend` | (required) | The storage backend (PostgresBackend, SQLiteBackend, or MemoryBackend). | | `registry` | `JobRegistry` | (required) | Job registry containing all `@soniq.job()` registrations. | | `settings` | `SoniqSettings \| None` | `None` | Settings instance. Falls back to global settings when `None`. | | `hooks` | `dict \| None` | `None` | Hook dictionary with keys `"before_job"`, `"after_job"`, `"on_error"`, each mapping to a list of callables. | | `middleware` | `list \| None` | `None` | Middleware callables, outermost first. | | `retry_policy` | `RetryPolicy \| None` | `None` | Computes the delay before each retry. | | `metrics_sink` | `MetricsSink \| None` | `None` | Receives job start and end events. | | `sync_executor` | `ThreadPoolExecutor \| None` | `None` | Thread pool for sync handlers. A `Soniq` instance supplies it. | | `sync_pool_semaphore` | `asyncio.Semaphore \| None` | `None` | Limits claimed sync jobs. A `Soniq` instance supplies it. | ### run() ```python async def run( self, concurrency: int = 4, run_once: bool = False, queues: list[str] | None = None, shutdown_event: asyncio.Event | None = None, ) -> bool ``` Returns `True` if any jobs were processed. `shutdown_event` is ignored when `run_once` is `True`. ### run_once() ```python async def run_once( self, queues: list[str] | None = None, max_jobs: int | None = None, ) -> bool ``` Process available jobs and return. Pass `max_jobs` to cap how many jobs are processed in one call. ## Graceful shutdown In continuous mode, the worker installs signal handlers for `SIGINT`, `SIGTERM` and `SIGHUP`. On receiving either signal: 1. The shutdown event is set and the worker stops taking new jobs. 2. Running jobs get up to `shutdown_timeout` seconds (default 30) to finish. 3. Async jobs still running after that are cancelled and put back in the queue with their attempt count kept. Sync handlers are not cancelled. They get an extra `sync_handler_grace_seconds` (default: the `job_timeout` value), and after that the worker keeps waiting for the thread. 4. The worker deregisters itself from the database. 5. The `LISTEN/NOTIFY` connection is released. A second signal does not force an exit. To stop a stuck worker, send `SIGKILL`. Jobs run at least once, so make handlers idempotent. ## LISTEN/NOTIFY When the backend supports push notifications (PostgreSQL), the worker subscribes to the `soniq_new_job` channel. When a job is enqueued, the worker wakes up immediately instead of waiting for the next poll cycle. This keeps latency low without hammering the database with frequent polls. If `LISTEN/NOTIFY` setup fails (for example behind PgBouncer in transaction mode), the worker falls back to polling at `poll_interval`. --- # Page 4: API - Hooks *(source: docs/api/hooks.md)* # Hooks and middleware for job events Hooks run your code before a Soniq job, after it succeeds, and when it fails. Use them for logging, metrics, tracing and alerting without changing your job functions. Middleware wraps the whole job call when you need more control. ## Registering hooks Use the decorator methods on your `Soniq` instance: ```python soniq = Soniq(database_url="postgresql://localhost/myapp") @soniq.before_job async def log_start(job_name: str, job_id: str, attempt: int): print(f"Starting {job_name} ({job_id}), attempt {attempt}") @soniq.after_job async def log_success(job_name: str, job_id: str, duration_ms: float): print(f"Completed {job_name} ({job_id}) in {duration_ms}ms") @soniq.on_error async def log_failure(job_name: str, job_id: str, error: str, attempt: int): print(f"Failed {job_name} ({job_id}): {error} (attempt {attempt})") ``` You can register multiple hooks for the same event. They run in registration order. Soniq passes the arguments positionally, in the order shown below, so keep the argument order in your hook functions. ## Hook signatures ### @soniq.before_job Called immediately before a job function executes. ```python async def before_job_hook(job_name: str, job_id: str, attempt: int) -> None ``` | Argument | Type | Description | |---|---|---| | `job_name` | `str` | The registered job name (the `name=` you gave the decorator). | | `job_id` | `str` | UUID of the job. | | `attempt` | `int` | Current attempt number, starting at 1. | ### @soniq.after_job Called after a job completes successfully. ```python async def after_job_hook(job_name: str, job_id: str, duration_ms: float) -> None ``` | Argument | Type | Description | |---|---|---| | `job_name` | `str` | The registered job name. | | `job_id` | `str` | UUID of the job. | | `duration_ms` | `float` | Wall-clock execution time in milliseconds, rounded to 2 decimals. | ### @soniq.on_error Called each time a job attempt fails, including the final attempt. Runs before the retry or dead-letter decision. ```python async def on_error_hook(job_name: str, job_id: str, error: str, attempt: int) -> None ``` | Argument | Type | Description | |---|---|---| | `job_name` | `str` | The registered job name. | | `job_id` | `str` | UUID of the job. | | `error` | `str` | String representation of the exception. | | `attempt` | `int` | The attempt number that failed. | ## Execution order For a successful job: ``` before_job -> job function -> after_job ``` For a failed job: ``` before_job -> job function (raises) -> on_error ``` `after_job` and `on_error` are mutually exclusive for a given execution. `before_job` always runs, even if the job will ultimately fail. A job that returns [`Snooze`](jobs.md#snooze) fires `before_job` but neither `after_job` nor `on_error`. A job whose stored arguments are corrupt goes to the dead-letter queue and fires no hooks. If you open a resource in `before_job` (such as a tracing span), do not rely on `after_job` or `on_error` alone to close it. ## Sync and async hooks Hooks can be either sync or async. Soniq inspects each hook at call time and awaits it if it is a coroutine function. A sync hook runs on the event loop, so keep it fast. ```python # Async hook @soniq.before_job async def async_hook(job_name, job_id, attempt): await some_async_operation() # Sync hook works too @soniq.before_job def sync_hook(job_name, job_id, attempt): some_sync_operation() ``` ## Error handling in hooks If a hook raises an exception, Soniq logs a warning and continues. A broken hook never prevents a job from running or its result from being recorded. ``` WARNING - Hook before_job failed: ConnectionError(...) ``` The log message has the form `Hook failed: `. This means hooks are safe for non-critical operations like metrics and logging. If you need a hook failure to stop job execution, handle that logic inside the job function itself. ## Practical examples ### Structured logging ```python import logging import json logger = logging.getLogger("soniq.hooks") @soniq.before_job async def structured_log_start(job_name, job_id, attempt): logger.info(json.dumps({ "event": "job_started", "job_name": job_name, "job_id": job_id, "attempt": attempt, })) @soniq.after_job async def structured_log_done(job_name, job_id, duration_ms): logger.info(json.dumps({ "event": "job_completed", "job_name": job_name, "job_id": job_id, "duration_ms": duration_ms, })) ``` ### Prometheus metrics ```python from prometheus_client import Counter, Histogram jobs_started = Counter("soniq_jobs_started", "Jobs started", ["job_name"]) jobs_completed = Histogram("soniq_jobs_duration_ms", "Job duration", ["job_name"]) jobs_failed = Counter("soniq_jobs_failed", "Jobs failed", ["job_name"]) @soniq.before_job async def track_start(job_name, job_id, attempt): jobs_started.labels(job_name=job_name).inc() @soniq.after_job async def track_duration(job_name, job_id, duration_ms): jobs_completed.labels(job_name=job_name).observe(duration_ms) @soniq.on_error async def track_failure(job_name, job_id, error, attempt): jobs_failed.labels(job_name=job_name).inc() ``` ### Slack alerting on dead-letter ```python @soniq.on_error async def alert_on_final_failure(job_name, job_id, error, attempt): # Look up the job's max_attempts from the registry job_meta = soniq.registry.get_job(job_name) if job_meta and attempt >= job_meta["max_retries"] + 1: await send_slack_message( f"Job {job_name} ({job_id}) moved to dead-letter queue: {error}" ) ``` ### OpenTelemetry tracing ```python from opentelemetry import trace tracer = trace.get_tracer("soniq") _spans = {} @soniq.before_job async def start_span(job_name, job_id, attempt): span = tracer.start_span(f"job:{job_name}", attributes={ "job.id": job_id, "job.attempt": attempt, }) _spans[job_id] = span @soniq.after_job async def end_span_success(job_name, job_id, duration_ms): span = _spans.pop(job_id, None) if span: span.set_attribute("job.duration_ms", duration_ms) span.end() @soniq.on_error async def end_span_error(job_name, job_id, error, attempt): span = _spans.pop(job_id, None) if span: span.set_status(trace.StatusCode.ERROR, error) span.end() ``` ## Middleware Middleware wraps every job call. Register it with `@soniq.middleware`. The first middleware you register is the outermost. ```python import time from soniq import JobContext @soniq.middleware async def timing(ctx: JobContext, call_next): started = time.monotonic() try: return await call_next(ctx) finally: print(f"{ctx.job_name} took {time.monotonic() - started:.2f}s") ``` Call `await call_next(ctx)` to continue the chain, and return its result. ## Next steps - [Jobs API](jobs.md) - `JobContext`, `Snooze` and retry options. - [Custom metrics sink](../recipes/custom-metrics-sink.md) - send job metrics without hooks. --- # Page 5: Guide - FastAPI *(source: docs/guides/fastapi.md)* # FastAPI background tasks with Soniq Soniq gives FastAPI durable background tasks stored in PostgreSQL. The `lifespan()` helper opens the connection pool, optionally starts a worker in the same process, and closes both on shutdown. ## Start with one process The simplest setup runs the API and the worker in one process. You need no second service. ```python # app/main.py from fastapi import FastAPI from soniq import Soniq from soniq.integrations.fastapi import lifespan soniq = Soniq(database_url="postgresql://localhost/myapp") app = FastAPI(lifespan=lifespan(soniq, run_worker=True, concurrency=2)) @soniq.job(name="emails.send_welcome", queue="emails", retries=3) async def send_welcome(user_id: int): user = await get_user(user_id) await send_email(to=user.email, template="welcome") @app.post("/users") async def create_user(name: str, email: str): user = await save_user(name=name, email=email) await soniq.enqueue(send_welcome, user_id=user.id) return {"id": user.id, "queued": True} ``` Run it with `uvicorn app.main:app`. `lifespan()` takes these arguments: | Argument | Default | Meaning | |---|---|---| | `run_worker` | `False` | Start a worker in the same event loop as the API. | | `concurrency` | `2` | Number of jobs the worker runs at the same time. | | `queues` | `None` | Queue names for the worker. `None` means all queues. | | `extra` | `None` | Your own lifespan. See [Chain your own lifespan](#chain-your-own-lifespan). | On startup, the helper initializes the connection pool and starts the worker. On shutdown, it stops the worker and closes the pool. The worker stops in the normal graceful way. It stops taking new jobs and waits for running jobs to finish. If a job runs longer than `shutdown_timeout` (30 seconds by default), Soniq cancels it and puts it back in the queue. See the [shutdown contract](../_internals/contracts/shutdown.md) for the full rules. A job can run again after a crash, so write handlers to be idempotent. !!! warning "Run migrations at deploy time, not app startup" Use `soniq setup` in your deploy pipeline (CI step, Dockerfile entrypoint, k8s init container). Do not run it in the lifespan. Running migrations on every boot creates race conditions when many replicas start at the same time. !!! warning "One Uvicorn process only" With `run_worker=True`, each Uvicorn process starts its own Soniq worker. With `uvicorn --workers 4`, or Gunicorn with four workers, you get four Soniq workers. This is safe, because Soniq workers never claim the same job twice. The number of jobs that run at once is `processes x concurrency`, and the database pool grows with each process. Set `concurrency` with this in mind, or move the worker to its own process (see the next section). Keep CPU-heavy jobs out of the API process. A job that blocks the event loop slows down your HTTP requests. ### Chain your own lifespan Pass `extra` if you already have a lifespan. It takes the app and returns an async context manager: ```python from contextlib import asynccontextmanager @asynccontextmanager async def my_lifespan(app: FastAPI): app.state.http = make_http_client() yield await app.state.http.aclose() app = FastAPI(lifespan=lifespan(soniq, run_worker=True, extra=my_lifespan)) ``` Soniq is ready before `my_lifespan` starts. `my_lifespan` stops before the worker stops. ## Move the worker to its own process When the load grows, run the worker as a separate process. Remove `run_worker=True`. The API keeps the same lifespan, so the pool still opens and closes correctly: ```python app = FastAPI(lifespan=lifespan(soniq)) ``` Start the worker with the CLI. Point it at the module where your jobs are defined: ```bash SONIQ_DATABASE_URL="postgresql://localhost/myapp" \ SONIQ_JOBS_MODULES="app.main" \ soniq worker --concurrency 4 ``` `SONIQ_JOBS_MODULES` is a comma-separated list of Python modules that the worker imports on startup. This is how it finds all `@soniq.job()` decorators. See [Job module discovery](../getting-started/installation.md#job-module-discovery) for cross-service setups and per-worker overrides. You can limit a worker to some queues: ```bash soniq worker --concurrency 2 --queues emails,notifications ``` Run the API and the worker as separate processes: ```bash # Terminal 1: API server uvicorn app.main:app --reload # Terminal 2: Worker SONIQ_DATABASE_URL="postgresql://localhost/myapp" \ SONIQ_JOBS_MODULES="app.main" \ soniq worker --concurrency 4 ``` Your job code and your `enqueue()` calls do not change. ## Replace FastAPI BackgroundTasks with a durable job queue FastAPI's `BackgroundTasks` runs a function after the response is sent, in the same process. If the process stops, the task is lost. It has no retries and no queue. With Soniq, the job is a row in PostgreSQL. It survives a restart and it retries on failure. ```diff -from fastapi import BackgroundTasks, FastAPI +from fastapi import FastAPI +from soniq import Soniq +from soniq.integrations.fastapi import lifespan -app = FastAPI() +soniq = Soniq(database_url="postgresql://localhost/myapp") +app = FastAPI(lifespan=lifespan(soniq, run_worker=True)) +@soniq.job(name="emails.send_welcome", retries=3) async def send_welcome(user_id: int): ... @app.post("/users") -async def create_user(name: str, background_tasks: BackgroundTasks): +async def create_user(name: str): user = await save_user(name=name) - background_tasks.add_task(send_welcome, user.id) + await soniq.enqueue(send_welcome, user_id=user.id) return {"id": user.id} ``` Job arguments are keyword-only and must be JSON-serializable. ## Defining jobs Register jobs with the `@soniq.job()` decorator. Jobs are regular async functions: ```python @soniq.job(name="emails.send_welcome", queue="emails", retries=3) async def send_welcome(user_id: int): user = await get_user(user_id) await send_email(to=user.email, template="welcome") ``` ## Enqueuing from route handlers Call `soniq.enqueue()` from any route: ```python @app.post("/orders") async def create_order(product_id: int, quantity: int): order = await save_order(product_id=product_id, quantity=quantity) await soniq.enqueue(process_order, order_id=order.id) return {"order_id": order.id} ``` ## Multiple instances Each `Soniq` instance is isolated. It has its own connection pool and job registry. This is useful for multi-tenant setups. The helper takes one instance, so close the others in your own lifespan: ```python tenant_a = Soniq(database_url="postgresql://localhost/tenant_a") tenant_b = Soniq(database_url="postgresql://localhost/tenant_b") @asynccontextmanager async def close_tenant_b(app: FastAPI): yield await tenant_b.close() app = FastAPI(lifespan=lifespan(tenant_a, extra=close_tenant_b)) ``` ## Borrowing a connection For [transactional enqueue](transactional-enqueue.md), borrow a connection from the backend: ```python await soniq.ensure_initialized() async with soniq.backend.acquire() as conn: async with conn.transaction(): await conn.execute("INSERT INTO orders ...") await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) ``` ## Next steps - [Transactional enqueue](transactional-enqueue.md) - enqueue a job in the same transaction as your data - [Testing](testing.md) - test jobs with the memory backend - [Going to production](../production/going-to-production.md) - deploy the API and worker --- # Page 6: Guide - Transactional enqueue *(source: docs/guides/transactional-enqueue.md)* # Transactional enqueue: add a job in the same PostgreSQL transaction Soniq can write a job row on the same PostgreSQL connection as your business data. If your transaction rolls back, the job rolls back too. This works with SQLAlchemy async, raw asyncpg, and psycopg 3. ## How it works When you pass `connection=conn` to `enqueue()`, Soniq inserts the job row into `soniq_jobs` on that connection. The INSERT is part of your transaction, so workers see the job only after `COMMIT`. Your business data and the job are either both committed or both rolled back. ## Pattern 1: Pass your SQLAlchemy session If your app uses SQLAlchemy async, pass the `AsyncSession` as `connection=`. Soniq writes the job on the same connection, in the same transaction: ```python import os from fastapi import Depends, FastAPI from sqlalchemy.ext.asyncio import AsyncSession from soniq import Soniq app = FastAPI() soniq = Soniq(database_url=os.environ["DATABASE_URL"]) @app.post("/orders") async def create_order( product_id: int, quantity: int, db: AsyncSession = Depends(get_db), ): async with db.begin(): order = Order(product_id=product_id, quantity=quantity) db.add(order) await db.flush() # populate order.id without committing await soniq.enqueue(send_invoice, connection=db, order_id=order.id) # SQLAlchemy commits here. Workers see the job at the same moment. return {"order_id": order.id} ``` An `AsyncConnection` works too: ```python async with engine.begin() as conn: await conn.execute(insert(orders).values(id=order_id, total=total)) await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) ``` Rules: - **Use the asyncpg or psycopg 3 driver.** Create the engine with a `postgresql+asyncpg://` or `postgresql+psycopg://` URL. Other drivers raise a `SoniqError`. - **Open a transaction first.** Call `enqueue()` inside `async with db.begin():` or after a statement that started one. A session with no active transaction raises a `SoniqError`. - **SQLAlchemy stays in charge.** Soniq does not open or commit a transaction. If SQLAlchemy rolls back, the job is removed too. - **Use the same database.** The engine must point at the database that holds the Soniq tables. Soniq does not import SQLAlchemy unless you pass a SQLAlchemy object. ## Raw asyncpg connections You can also pass a raw `asyncpg` connection. It can come from Soniq's pool or from your own pool. The connection must be inside an active transaction. Without one, `enqueue()` raises a `SoniqError` with code `SONIQ_UNSUPPORTED_CONNECTION`. ## Pattern 2: Raw asyncpg via Soniq's pool Borrow a connection from Soniq's own backend pool. You need no second pool: ```python await soniq.ensure_initialized() async with soniq.backend.acquire() as conn: async with conn.transaction(): await conn.execute("INSERT INTO orders (id, total) VALUES ($1, $2)", order_id, total) await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) ``` The `connection=conn` parameter is the only thing that changes from a normal enqueue call. Job options, priority and scheduling work the same way. ## FastAPI route example This order endpoint commits the order record and the follow-up job in one transaction: ```python from contextlib import asynccontextmanager from fastapi import FastAPI from soniq import Soniq soniq = Soniq(database_url="postgresql://localhost/myapp") @asynccontextmanager async def lifespan(app: FastAPI): await soniq.ensure_initialized() yield await soniq.close() app = FastAPI(lifespan=lifespan) @soniq.job(name="invoices.send_invoice", queue="invoices", retries=5) async def send_invoice(order_id: int): order = await get_order(order_id) await generate_and_send_invoice(order) @app.post("/orders") async def create_order(product_id: int, quantity: int): async with soniq.backend.acquire() as conn: async with conn.transaction(): order_id = await conn.fetchval( "INSERT INTO orders (product_id, quantity) VALUES ($1, $2) RETURNING id", product_id, quantity, ) await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) return {"order_id": order_id} ``` If the INSERT fails or anything else raises inside the transaction block, both the order row and the job are rolled back. ## Pattern 3: Bring your own asyncpg pool If your app already manages its own `asyncpg.Pool`, you do not need Soniq's pool. Pass the connection from your pool to `enqueue()` and the job row goes through your transaction: ```python from contextlib import asynccontextmanager import asyncpg from fastapi import FastAPI soniq = Soniq(database_url=os.environ["DATABASE_URL"]) db_pool: asyncpg.Pool # your application's pool @asynccontextmanager async def lifespan(app: FastAPI): global db_pool db_pool = await asyncpg.create_pool(os.environ["DATABASE_URL"]) yield await db_pool.close() app = FastAPI(lifespan=lifespan) @app.post("/orders") async def create_order(product_id: int, quantity: int): async with db_pool.acquire() as conn: async with conn.transaction(): order_id = await conn.fetchval( "INSERT INTO orders (product_id, quantity) VALUES ($1, $2) RETURNING id", product_id, quantity, ) await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) return {"order_id": order_id} ``` With this pattern you have no second pool to size. Soniq uses a connection that your app already owns. !!! note The connection must point at the same PostgreSQL database that holds the Soniq tables. ## psycopg 3 connections You can pass a `psycopg.AsyncConnection` too. Soniq writes the job on that connection and does not commit. You commit or roll back yourself: ```python import psycopg async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn: await conn.execute("INSERT INTO orders (id, total) VALUES (%s, %s)", (order_id, total)) await soniq.enqueue(send_invoice, connection=conn, order_id=order_id) await conn.commit() ``` Install the driver with `pip install "soniq[psycopg]"`. ## Pattern 4: Tortoise ORM Tortoise exposes the raw `asyncpg` connection on the transaction context only through a private attribute. The attribute works today, but Tortoise can change it in any release. ```python from tortoise.transactions import in_transaction @app.post("/orders") async def create_order(product_id: int, quantity: int): async with in_transaction() as conn: order = await Order.create( using_db=conn, product_id=product_id, quantity=quantity, ) # conn._connection is the raw asyncpg connection. It is a private # Tortoise attribute, so it can break in a Tortoise upgrade. await soniq.enqueue(send_invoice, connection=conn._connection, order_id=order.id) ``` Soniq has no Tortoise integration. If you want one that does not depend on a private attribute, open an issue. ## Use cases **Order and invoice.** Create the order and enqueue the invoice job in one transaction. No order exists without its invoice job. **User signup and welcome email.** Insert the user row and enqueue the welcome email together. If the INSERT hits a unique constraint, Soniq queues no email. **Payment and receipt.** Record the payment and enqueue the receipt job in one transaction. A recorded payment always has a receipt job. Use this pattern when a row without its job would be a data integrity bug. ## Delivery semantics Transactional enqueue guarantees the job enters the queue if and only if the transaction commits. It does not guarantee single execution. Soniq provides **at-least-once delivery**. If a worker crashes after it runs the job but before it marks the job done, stale worker recovery puts the job back in the queue. Write idempotent handlers. Use upserts, deduplication keys, or check-before-act patterns for side effects such as sending emails or charging payments. ## What transactional enqueue does NOT guarantee - **Single execution.** The guarantee applies to enqueue only. Re-execution after worker crashes is still possible. - **Rollback after commit.** After the commit, the job is in the queue. You can cancel it with `soniq.cancel_job(job_id)`, but a fast worker can claim it first. !!! note Transactional enqueue needs PostgreSQL. With the SQLite or memory backend, `enqueue(..., connection=conn)` and `soniq.backend.acquire()` raise a `ValueError`. ## Next steps - [FastAPI integration](fastapi.md) - set up the lifespan and the worker - [Common patterns](common-patterns.md) - deduplication and job results - [Troubleshooting](../troubleshooting.md) - fix `SONIQ_UNSUPPORTED_CONNECTION` errors --- # Page 7: Reference - Glossary *(source: docs/reference/glossary.md)* # Soniq glossary: job, worker, queue and dead-letter terms This page defines the words Soniq's docs use for its PostgreSQL-backed Python background jobs, in one paragraph each. ## Job A unit of work. Either the function you decorate with `@soniq.job()` (the **handler**), or a specific row in `soniq_jobs` representing one scheduled invocation of that function (the **job instance**). Most of the docs say "job" for both and the meaning is clear from context. When ambiguity matters, "handler" and "job row" are the disambiguating terms. ## Handler The Python function that runs when a job is processed. Registered with `@soniq.job()`. ## Task name The string identifier under which a handler is registered. Set it with `@soniq.job(name="...")`. If you omit `name=`, Soniq derives `f"{module}.{qualname}"`, which is deprecated since 0.2.0 and warns. The task name is the wire protocol for cross-service deployments. Producers refer to handlers by name, not by import. ## TaskRef A typed stub that lets a producer enqueue a job by name without importing the consumer's code. Created via `task_ref(name="billing.send_invoice", args_model=InvoiceArgs)` - the arguments are keyword-only. Use it when the producer must not own the handler code, as in a cross-service setup. See [cross-service jobs](../guides/cross-service-jobs.md). ## Worker A long-running process that polls for jobs (or receives a PostgreSQL `NOTIFY`), claims them with `SELECT ... FOR UPDATE SKIP LOCKED`, and runs the handler. Start it with `soniq worker`. Several workers can safely take jobs from the same queue. ## Scheduler A separate long-running process (`soniq scheduler`) that evaluates `@soniq.periodic` jobs and writes due instances into `soniq_jobs` for workers to pick up. The worker does not evaluate recurring jobs. This is intentional: scaling workers does not duplicate scheduler work. Several scheduler instances coordinate with a PostgreSQL advisory lock, and only one does work at a time. ## Queue A `varchar` column on `soniq_jobs` used for routing. Start a worker with `--queues=foo,bar` to consume from a subset. The default queue name is `"default"`. Queues are not separate tables. A queue is a routing tag. ## Concurrency The number of jobs a single worker process runs at once. The default is 4. Raise it for I/O-bound workloads and lower it for CPU-bound ones. Set it with `soniq worker --concurrency N`, or with `concurrency=` on `run_worker()`. ## Heartbeat A periodic write that each worker makes to `soniq_workers` to show it is alive. If a worker stops its heartbeat for `SONIQ_HEARTBEAT_TIMEOUT` seconds (default 300), the surviving workers mark it `stopped` and reset its in-flight jobs to `queued`. ## Dead-letter queue (DLQ) The `soniq_dead_letter_jobs` table. Jobs that exhaust all retries land here instead of staying in `soniq_jobs`. To inspect and recover them, use `soniq.dead_letter.list_dead_letter_jobs()`, `soniq.dead_letter.replay(dead_letter_id)` or the `soniq dead-letter` CLI. See the [dead-letter Python API](../api/dead-letter.md). ## Replay Re-running a dead-letter job by minting a fresh `soniq_jobs` row from it. The original DLQ row stays put with `resurrection_count` incremented; replay does not delete the dead-letter record. ## At-least-once delivery Soniq's delivery guarantee. A job runs at least once. It can run more than once if a worker crashes in the handler before it marks the row done. Handlers must be **idempotent**: running them again must produce the same end state. Soniq has no exactly-once mode, because PostgreSQL alone cannot guarantee it. ## Transactional enqueue Enqueueing a job inside the same Postgres transaction as your business writes by passing `connection=conn` to `enqueue()`. If the transaction rolls back, the job row is also rolled back. It is the main reason to pick a PostgreSQL-backed queue. It works on PostgreSQL only - SQLite and the in-memory backend do not support it. ## Backend The storage layer. The production backend is `asyncpg` against PostgreSQL. SQLite and an in-memory backend exist for local development and tests; both have hard limits (single writer, no transactional enqueue, polling only) and are not for production.