Run jobs on the SQL backend¶
This guide shows you how to store jobs in your app's database with mankai-jobs-sql, run them in worker processes, and manage them in production. It's for Hanami developers who can already define and enqueue jobs. Every option, event, and administration method is listed in the mankai-jobs-sql reference.
Use the SQL backend when jobs must survive a restart or run outside the web process. It's also the
only backend that supports priorities, concurrency limits, transactional jobs, finished-job records,
and recurring tasks. Unique jobs work with every backend. Scheduling and retries work with every
backend except :inline, which runs each job once, immediately. For a comparison, see
Backends.
Before you begin¶
- Add
mankai-jobsandmankai-jobs-sqlto yourGemfilein the:defaultand:cligroups, and create a base job class. See Install Mankai. - Use PostgreSQL, MySQL 8 or later, MariaDB 10.6 or later, or SQLite.
- On MySQL or MariaDB, add
fractional_seconds=trueto the database URL before you run the migrations. Without it, times are stored in whole seconds, and jobs can run up to a second late. - On SQLite, set a busy handler on the connection, so that worker threads don't stall while they wait for a lock. See SQLite in the reference.
Set up the backend¶
To store jobs in your database, follow these steps:
-
Configure the backend in
config/providers/queue.rb. The following provider uses the memory backend in tests and the SQL backend everywhere else: -
Generate the migrations:
The command writes two migrations into
config/db/migrate/. Keep their filenames, because the command uses them to detect which migrations your app already has. -
Run the migrations:
-
Start the jobs processes:
The command starts a supervisor process, which starts the workers that run jobs and a dispatcher. If you define recurring tasks, it also starts a scheduler. For what each process does, see How it works.
-
In another terminal, enqueue a job from
bundle exec hanami console:Replace
jobs.send_welcomeand its arguments with one of your jobs.
To confirm that the job ran, check the counts in the console. The SQL backend keeps finished jobs by
default, so finished goes up by one:
Hanami.app["queue.backend"].counts
# => {ready: 0, scheduled: 0, claimed: 0, blocked: 0, failed: 0, finished: 1}
After you upgrade mankai-jobs-sql, run bundle exec hanami jobs install again. It adds only the
migrations that your app doesn't have yet.
Run the jobs processes with your app¶
Jobs run only while hanami jobs start is running. Run it in every environment where your app
enqueues jobs:
-
Development: Add a
workerline toProcfile.dev, so thatbin/devstarts it with the web server: -
Production: Run the same command as its own process, from the same release and environment as the web process. See Deploy to production.
To stop the processes gracefully, send TERM or INT, or press Ctrl+C. Running jobs
get shutdown_timeout seconds (5 by default) to finish. To stop immediately, send QUIT.
To run only some of the processes, or to start faster, pass options to start:
For every option, see CLI in the mankai-jobs reference.
Configure workers and queues¶
By default, one worker process with 3 threads serves every queue. To give some queues more capacity,
list several kinds of workers. The following configuration runs two processes with 5 threads for the
realtime and default queues, and one slower-polling process for every queue whose name starts with
low:
Mankai::Jobs::SQL.backend(
workers: [
{queues: ["realtime", "default"], threads: 5, processes: 2},
{queues: ["low*"], threads: 1, polling_interval: 1}
]
)
A worker polls its queues in the order listed, then by priority. Make sure that some worker serves
every queue that your jobs use. For example, MailerJob uses the mailers queue.
Each worker process needs threads + 2 database connections. Set max_connections on the database
URL, and count up to twice that number against the database's connection limit, because polling uses
a second pool by default. See Connection pool size.
Choose what happens 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 it until the transaction commits.
If you plan to store jobs in a separate database, the enqueue can't join your transaction anymore.
To make the behavior explicit, set in_transaction:
:after_commit writes the job after the transaction commits, but the job is lost if the process dies
in between. :raise raises an error instead, which helps you find code that depends on either
behavior. For details, see
Enqueue inside a transaction.
Clean up finished jobs¶
The SQL backend keeps finished jobs until you delete them. To delete them automatically, set a
retention per queue. The following configuration keeps mailers jobs for an hour and every other
queue's jobs for a week:
Dispatchers apply the retention every 10 minutes. Retention never deletes failed jobs.
To delete finished jobs yourself, run the following command. Replace SECONDS with the minimum age of
the jobs to delete:
Retry jobs that failed¶
Delivery is at least once, so a job can run more than once. If a worker crashes or its host is lost,
the backend records its running jobs as failed with ProcessExitError or ProcessPrunedError. These
failures skip the job's retry rules. To find and retry them, follow these steps:
-
In
bundle exec hanami console, list the failed jobs:backend = Hanami.app["queue.backend"] backend.failed_jobs(limit: 20).map { |job| [job[:uuid], job[:job], job[:error]["class"]] }Each entry shows the job ID, the job key, and the error class.
-
Retry a job by its job ID:
Replace
JOB_IDwith a:uuidvalue from the previous step. The method returns the number of jobs that it retried.
To hear about these failures as they happen, subscribe to the mankai.jobs.sql.fail_claims event. See
Subscribe to job events. For the other
administration methods, such as pausing a queue, see
Administration API.
What's next¶
- Make jobs reliable: retries, unique jobs, concurrency limits, and transactional jobs.
- Schedule and monitor jobs: recurring tasks, middleware, and events.
- Deploy to production: run the jobs processes in production.