Skip to content
Edit this page View source of this page

If you're new to background jobs, read How jobs work and follow Run your first background job before you use this reference.

Mankai

mankai-jobs-sql

mankai-jobs-sql is the SQL backend for mankai-jobs. It stores jobs in your app's database and runs them in separate worker, dispatcher, and scheduler processes. Use it when jobs must survive a restart or run outside the web process, or when you need priorities, concurrency limits, transactional jobs, finished-job records, or recurring tasks.

This page is the reference for its installation, options, process model, delivery guarantees, administration API, and events. For a task-focused walkthrough, see Run jobs on the SQL backend.

Supported databases

The following table lists the supported databases and the versions that the test suite runs on:

Database Tested on Notes
PostgreSQL 9.5 or later 16.16, 17.12, 18.7, 19.0 None.
MySQL 8 or later 9.7.4, 26.10.0 Claims use FOR UPDATE SKIP LOCKED. Connect with fractional_seconds=true.
MariaDB 10.6 or later 12.3.4, 13.1.2 The same as MySQL.
SQLite 3 Writes are serialized, which suits small apps. Set a busy handler.

MySQL and MariaDB

Add fractional_seconds=true to the database URL before you run the migrations, for example mysql2://HOST/DATABASE?fractional_seconds=true. Without this option, Sequel stores times in whole seconds, so a job that's due in 0.2 seconds can run up to a second off. If the option is missing, mankai-jobs logs a warning at boot.

If the migrations already ran without the option, fix the time columns:

  1. Add fractional_seconds=true to the database URL.
  2. Copy the TIMESTAMP_add_mankai_jobs_controls.rb migration into a new migration file with a new timestamp.
  3. Run bundle exec hanami db migrate. The migration is idempotent, and with the option on, it converts the time columns to microsecond precision.

SQLite

By default, a SQLite connection that waits for a database lock also holds Ruby's global VM lock (GVL), the lock that lets only one thread run Ruby code at a time. Every other thread in the process stops for up to 5 seconds, including the thread that holds the database lock. Worker threads then stall, and can fail with "database is locked".

To make the connection wait without blocking other threads, set a busy handler in the database provider:

# config/providers/db.rb
Hanami.app.configure_provider :db do
  config.gateway :default do |gw|
    gw.connection_options after_connect: ->(conn) { conn.busy_handler_timeout = 5000 }
  end
end

mankai-jobs doesn't change your connection settings. Until the connection has an after_connect handler, mankai-jobs logs a warning at boot. The polling connections that mankai-jobs opens itself (see silence_polling) already use a busy handler.

Installation

To install the SQL backend, follow these steps:

  1. Configure the backend in config/providers/queue.rb. The following provider uses the memory backend in tests and the SQL backend everywhere else, with two kinds of workers:

    # config/providers/queue.rb
    require "mankai/jobs"
    require "mankai/jobs/sql"
    
    Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
      configure do |config|
        config.backend =
          if Hanami.env?(:test)
            :memory
          else
            Mankai::Jobs::SQL.backend(
              workers: [
                {queues: ["realtime", "default"], threads: 5, processes: 2},
                {queues: ["low*"], threads: 1, polling_interval: 1}
              ]
            )
          end
      end
    end
    
  2. Generate the migrations:

    bundle exec hanami jobs install
    

    The command writes the migrations that your app doesn't have yet into config/db/migrate/.

  3. Run the migrations:

    bundle exec hanami db migrate
    
  4. Start the jobs processes:

    bundle exec hanami jobs start
    

    Jobs run only while this command is running. Run it next to your web server in every environment that uses this backend. If you use bin/dev, add a worker line to Procfile.dev:

    web: bundle exec hanami server
    worker: bundle exec hanami jobs start
    

    In production, run it as its own process, such as a worker: line in a Procfile, a systemd unit, or a container, from the same release and environment as the web process.

On Hanami 3.1 or later in development, if the jobs tables are missing, the error page explains the problem and offers to install and run the migrations.

Migrations

hanami jobs install writes the following migrations, where TIMESTAMP is the time the file was generated:

  • TIMESTAMP_create_mankai_jobs_tables.rb creates the tables.
  • TIMESTAMP_add_mankai_jobs_controls.rb adds unique keys, recorded output, per-job retention, and an index for per-queue cleanup.

The command identifies the migrations by these filenames, so keep the names if you edit the files. If you use a custom table_prefix, pass the same prefix to the command, for example hanami jobs install --table-prefix=queue_.

After you upgrade the gem, run hanami jobs install again. It adds only new migrations, and does nothing when there are none. Until the second migration has run, jobs that don't use its features keep working.

The migrations are idempotent: they create only the tables, columns, and indexes that don't exist yet, and their rollbacks drop only the objects that exist. Running a migration twice, or keeping two copies of a migration file, is harmless, and install warns you about duplicate copies. Rolling back any copy of the create migration drops the tables.

The migrations belong to your app, and you can edit them. Put your own schema changes in regular migrations.

Options

Pass the following options to Mankai::Jobs::SQL.backend(...):

Option Default Description
gateway "db.gateway" The database: a container key, a ROM gateway, or a Sequel::Database. For a separate database, use a key such as "db.gateways.jobs".
table_prefix "jobs_" The prefix for the table names. Install the migrations with the same --table-prefix.
preserve_finished true If true, keeps finished jobs until hanami jobs clear, backend.clear_finished, or retention deletes them.
in_transaction :join What an enqueue does inside an open transaction on the same database. See Enqueue inside a transaction.
workers [{queues: ["*"], threads: 3, processes: 1, polling_interval: 0.1}] One entry per kind of worker. See Worker options.
dispatchers [{polling_interval: 1, batch_size: 500, concurrency_maintenance_interval: 600}] One entry per dispatcher. See Dispatcher options.
scheduler true If true, runs a scheduler when there are recurring tasks.
dynamic_recurring_tasks false If true, also runs the recurring tasks that you add at runtime. See Administration API.
recurring_reload_interval 5 The number of seconds between checks for changed runtime tasks.
heartbeat_interval 60 The number of seconds between process heartbeats.
alive_threshold 300 The number of seconds without a heartbeat before a process is pruned.
shutdown_timeout 5 The number of seconds that running jobs get to finish after a TERM signal.
fork_boot_timeout 300 The number of seconds that a forked process can take to register before it's killed and replaced.
silence_polling true If true, processes poll through a second connection pool of the same size, without the app's SQL logging. A process can then hold up to twice the pool's connections. Set it to false if the database's connection limit is tight.
retention {} The number of seconds to keep finished jobs, per queue. See Retention per queue.
retention_interval 600 The number of seconds between the dispatchers' retention passes.
hooks {} Process lifecycle hooks. See Hooks.

Worker options

A worker is a process that claims jobs and runs them on its threads. To claim a job, a worker locks the job's row, so that no other worker can take it. Each entry in workers takes the following keys:

Key Default Description
queues ["*"] The queues the worker serves, in order. Use exact names, prefix*, or *.
threads 3 The number of threads that run jobs in each process.
processes 1 The number of processes that run this kind of worker.
polling_interval 0.1 The number of seconds between polls when the worker is idle.

Dispatcher options

A dispatcher is a process that moves due jobs to the ready state, maintains concurrency limits, and applies retention. Each entry in dispatchers takes the following keys:

Key Default Description
polling_interval 1 The number of seconds between polls.
batch_size 500 The number of due jobs to move per poll.
concurrency_maintenance_interval 600 The number of seconds between concurrency maintenance passes.

Retention per queue

Dispatchers delete finished jobs after they're older than their queue's retention. The following configuration keeps mailers jobs for an hour, audit jobs forever, and every other queue's jobs for a week:

Mankai::Jobs::SQL.backend(
  retention: {
    "mailers" => 3600,    # an hour
    "audit" => nil,       # forever
    "*" => 7 * 86_400     # every other queue: a week
  }
)

Retention follows these rules:

  • If you don't set a "*" entry, the backend keeps finished jobs on unlisted queues forever.
  • Retention never deletes failed jobs.
  • To delete one job as soon as it finishes, set config.preserve_finished = false on the job class.
  • To delete finished jobs yourself, run hanami jobs clear --older-than=SECONDS --queue=NAME, or call backend.clear_finished(older_than:, queue:).

Hooks

A hook is a callable, or an array of callables. The backend calls it with the process, inside that process:

Mankai::Jobs::SQL.backend(
  hooks: {
    worker_start: ->(process) { Metrics.reconnect },
    worker_stop: ->(process) { Metrics.flush }
  }
)

The available hooks are supervisor_start, supervisor_stop, worker_start, worker_stop, dispatcher_start, dispatcher_stop, scheduler_start, and scheduler_stop. If a hook raises an error, the backend logs it, and the process continues.

How it works

Each job has a row in the jobs_records table. A job's state is the execution table that holds it. The following diagram shows how a job moves between states:

enqueue ─► scheduled ─(due)─► ready ─(claim)─► claimed ─► finished_at set
              ▲                 ▲                 │
              │                 │                 ├─(retry)──► scheduled
              │             blocked ◄─(no slot)   └─(failed)─► failed

A job is in one of the following states:

  • Scheduled: The job waits for its scheduled time. Retries wait here too.
  • Ready: The job is due, and a worker can claim it.
  • Blocked: The job waits for a free concurrency slot.
  • Claimed: A worker is running the job.
  • Failed: The job failed permanently.
  • Finished: The job succeeded or was discarded. Its record has finished_at set.

Moving a job between states deletes one row and inserts another in the same transaction. This keeps jobs_ready, the table that workers poll, small and index-only. The record also stores the envelope's metadata: retry counts per rule, step progress, and the locale.

hanami jobs start runs the following processes:

  • Workers claim up to their number of free threads with SELECT … FOR UPDATE SKIP LOCKED, so many workers can poll without blocking each other. They poll queues in the order listed, then by priority, lower first. A worker on * alone takes the lowest priority across all queues.
  • Dispatchers move due scheduled jobs, including retries, to ready. They also run concurrency maintenance, which expires concurrency slots and unblocks waiting jobs.
  • Schedulers enqueue recurring tasks. A unique (task_key, run_at) row makes sure that each run is enqueued once, even with several schedulers.
  • The supervisor forks the other processes, or runs them as threads, and replaces any that exit. When a process dies, the supervisor fails the jobs it left behind. TERM and INT signals stop it gracefully; QUIT stops it immediately. Each child process checks the supervisor's process ID (PID), and stops if the supervisor exits.

Job settings on this backend

Unique jobs, recorded output, and transactional jobs are job settings. See Job settings in the mankai-jobs reference. This backend handles them as follows:

  • Unique jobs: A unique index on jobs_records.unique_key holds each key.
  • A duplicate fails its insert inside a savepoint, so it never aborts the caller's transaction.
  • The backend clears the key when the job succeeds (unless it has a period), fails, or is discarded.
  • Retrying a failed job by hand doesn't restore its key.
  • Recorded output: The backend stores output as JSON in jobs_records.output. Read it with backend.job(id)[:output].
  • The backend drops output larger than about 60 KB, and publishes a mankai.jobs.sql.output_dropped event.
  • A job that's deleted when it finishes (preserve_finished = false, or retention) takes its output with it.
  • Transactional jobs: A worker runs the job inside a transaction on the app's own connection, the one that the job's repositories use, and marks it finished in that same transaction.
  • If the job succeeds, its writes and its completion commit together, so a crash can't leave the work done but the job unfinished.
  • If the job fails, or its claim was taken away, its writes roll back, and the backend records the failure afterward.
  • Jobs that it enqueues join that transaction, with the default in_transaction: :join.
  • The transaction stays open for the whole run, so keep these jobs short. On SQLite, a run holds the database's write lock.

Delivery guarantees

Delivery is at least once: a job can run more than once, so make jobs idempotent. What happens to a running job depends on how its process stopped:

How the process stopped What happens to the job
On purpose: TERM or INT past shutdown_timeout, or QUIT The job goes back to ready and runs again. A resumable job pauses at its next checkpoint instead, without using up an attempt.
A worker crashes or gets kill -9 The backend records the job as failed with ProcessExitError.
The supervisor is killed Its children finish their running jobs, deregister, and exit.
The host is lost After heartbeats stop, the backend records the job as failed with ProcessPrunedError.

The job's own code never sees these errors, and the job's retry_on rules and max_attempts don't apply to them: the job goes straight to failed. The backend doesn't publish mankai.jobs.fail or call the error_reporter. To hear about these failures, subscribe to mankai.jobs.sql.fail_claims. To recover the jobs, call backend.retry_failed(id). See Administration API.

If a job hangs while its process stays alive, the backend can't detect it, because heartbeats track processes, not jobs. Add timeouts inside jobs that might hang.

Enqueue inside a transaction

By default, if you enqueue a job inside an open transaction on the same database, the enqueue joins that transaction. A rollback removes the job, and workers can't see the job until the transaction commits. If you move jobs to a separate database, the enqueue can no longer join, so this behavior changes. To make the behavior explicit, set in_transaction to one of the following values:

Value Description
:join The default. The enqueue joins the open transaction.
:after_commit The backend writes the job after the transaction commits. The job is lost if the process dies in between.
:raise Enqueuing inside a transaction raises an error. Use it to find code that depends on either behavior.

Concurrency and ordering

  • A concurrency limit's duration is a safety net, not a timeout. If a job runs longer, another job with the same key might start.
  • Limits guarantee no overlap, but not order.
  • The backend enqueues limited jobs one at a time, so a bulk enqueue loses its batching for them.
  • Workers order jobs by queue first, then by priority, so a priority can't move a job ahead of an earlier queue. Use queue order or priorities, not both.
  • A prefix* queue pattern costs an extra DISTINCT query per poll. So does *, once any queue is paused. Exact queue names, and * with no paused queues, are cheapest.

Connection pool size

Each worker process needs threads + 2 database connections. Set max_connections on the database URL. If the pool is too small, the backend logs a warning. With silence_polling (the default), polling uses a second pool of the same size, so count up to twice that number against the database's connection limit.

MySQL and MariaDB behavior

  • Transactions use READ COMMITTED, which avoids most gap-lock deadlocks between enqueue and claim.
  • The backend creates concurrency slots with an atomic "insert if absent", and inserts unique jobs in key order.
  • The backend retries any remaining deadlock up to 5 times, because the database rolled back the whole transaction. Inside your own open transaction (with in_transaction: :join), it can't retry: only you can, and the enqueue returns Failure[:backend_error, error].

Other limits

  • The backend truncates error details to about 60 KB.
  • The backend stores times in UTC and compares them with the app's clock, so keep the hosts' clocks in sync.
  • hanami jobs start boots the app before forking, so child processes share its memory. For faster starts, use --prepare.

Administration API

The backend provides methods to inspect and manage jobs, for example from hanami console:

backend = Hanami.app["queue.backend"]

backend.counts                      # => {ready:, scheduled:, claimed:, blocked:, failed:, finished:}
backend.queues                      # => [{name:, size:, latency:, paused:}, ...]
backend.pause("mailers")
backend.resume("mailers")
backend.clear_queue("low")          # deletes a queue's ready jobs

backend.job(id)                     # => {id:, job:, queue:, state:, attempts:, args:, output:, error:, ...}
backend.failed_jobs(limit: 20)      # => [{id: 42, uuid: "8f1c…", job:, queue:, attempts:, error: {...}, ...}, ...]
backend.retry_failed(id1, id2)      # => the number of jobs retried
backend.discard_failed(id1)         # => the number of jobs deleted
backend.clear_finished(older_than: Time.now.utc - 86_400)
backend.clear_finished(older_than: Time.now.utc - 3600, queue: "mailers")
backend.apply_retention             # what dispatchers do every retention_interval

# Recurring tasks added without a deploy (needs dynamic_recurring_tasks: true)
backend.schedule_recurring("nightly_report", job: "jobs.report", schedule: "every day at 2am", args: {kind: "nightly"})
backend.unschedule_recurring("nightly_report")

The methods identify a job by its job ID: the envelope.id that the enqueuer returns, which is also the :id of backend.job(id). In failed_jobs results, the job ID is in :uuid, and :id is the database row ID. retry_failed and discard_failed accept either ID. failed_jobs returns the newest failures first, 100 by default.

The following example retries every failed jobs.import job:

ids = backend.failed_jobs(limit: 1000).select { |job| job[:job] == "jobs.import" }.map { |job| job[:uuid] }
backend.retry_failed(ids)

The methods behave as follows:

  • retry_failed puts a failed job back on its queue as if it were newly enqueued. The job keeps its attempt count, so a job that used up max_attempts fails again after one more error. A unique job's key isn't restored.
  • discard_failed deletes the job.
  • Both methods skip IDs that don't name a failed job.
  • The backend validates runtime recurring tasks like configured ones. If a runtime task has the same key as a configured task, the configured task wins.

Events

The backend publishes the following events on the app's notifications bus, in addition to the core events. They're registered when the queue provider starts, so subscribe in the provider's after(:start) block, as the core events section shows:

Event Published when Payload
mankai.jobs.sql.claim A worker claims jobs. process_id:, size:
mankai.jobs.sql.release_claims Jobs go back to ready. process_id:, size:
mankai.jobs.sql.fail_claims A dead process's jobs are failed. size:, error: (the error class name)
mankai.jobs.sql.dispatch_scheduled Due jobs move to ready. size:
mankai.jobs.sql.prune_processes Processes without heartbeats are pruned. size:
mankai.jobs.sql.enqueue_recurring A scheduler enqueues a recurring run. task:, run_at:, enqueued: (false if another scheduler already enqueued it)
mankai.jobs.sql.apply_retention Finished jobs past their retention are deleted. size:
mankai.jobs.sql.output_dropped A job's output was too large to store. job:, id:, bytes:

Run this gem's tests

This section is for contributors to mankai-jobs-sql. To run the specs on SQLite, run the following command from the gem's directory:

bundle exec rspec

To run the specs on another database, set DATABASE_URL:

DATABASE_URL=postgres:///mankai_jobs_test bundle exec rspec

For MySQL or MariaDB, use a URL such as trilogy://[email protected]:3306/mankai_jobs_test. The specs add fractional_seconds=true.