Skip to content
Edit this page View source of this page

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-jobs and mankai-jobs-sql to your Gemfile in the :default and :cli groups, 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=true to 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:

  1. Configure the backend in config/providers/queue.rb. The following provider uses the memory backend in tests and the SQL backend everywhere else:

    # 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
          end
      end
    end
    
  2. Generate the migrations:

    bundle exec hanami jobs install
    

    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.

  3. Run the migrations:

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

    bundle exec hanami jobs start
    

    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.

  5. In another terminal, enqueue a job from bundle exec hanami console:

    Hanami.app["queue.enqueuer"].call("jobs.send_welcome", {user_id: 1})
    

    Replace jobs.send_welcome and 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 worker line to Procfile.dev, so that bin/dev starts it with the web server:

    web: bundle exec hanami server
    worker: bundle exec hanami jobs start
    
  • 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:

bundle exec hanami jobs start --only=worker,dispatcher
bundle exec hanami jobs start --prepare

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:

Mankai::Jobs::SQL.backend(in_transaction: :after_commit)

: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:

Mankai::Jobs::SQL.backend(
  retention: {"mailers" => 3600, "*" => 7 * 86_400}
)

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:

bundle exec hanami jobs clear --older-than=SECONDS

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:

  1. 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.

  2. Retry a job by its job ID:

    backend.retry_failed(JOB_ID)
    

    Replace JOB_ID with a :uuid value 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