Skip to content
Edit this page View source of this page

How jobs work

This page explains the mankai-jobs model: when to use a job, what a job is, what happens between enqueuing a job and running it, and how the backends differ. Read it before you design jobs for a real feature. To set up jobs, see Install Mankai and Run your first background job.

When to use a job

A background job is work that runs outside the request that asked for it. Use a job when the response doesn't need the result, for example for the following kinds of work:

  • Sending email or notifications.
  • Importing or exporting a file.
  • Calling a slow or unreliable external API.
  • Rebuilding a report or a cache entry.
  • Work that might fail temporarily and should be retried.

Don't use a job when the response needs the result, such as validating input, loading the record that a page renders, or enforcing a rule that the user must see immediately.

A job is a component

A job is a Hanami component, like a repository or an operation: Hanami creates it, injects its dependencies through Deps, and registers it in the app container. Put a job in app/jobs/, and Hanami registers it under the jobs namespace. The following job sends a welcome email:

# app/jobs/send_welcome.rb
module Bookshelf
  module Jobs
    class SendWelcome < Bookshelf::Job
      include Deps["repos.user_repo", "mailers.welcome"]

      def call(user_id:)
        user = user_repo.find(user_id) or return Failure(:user_missing)
        welcome.deliver(user:)
        Success()
      end
    end
  end
end

The job's container key, jobs.send_welcome, is its job key. You enqueue a job by its job key, and mankai-jobs finds the job by that key, never by its Ruby class name. It runs only keys under the jobs namespace that resolve to a job, so nobody can put an arbitrary class name in the queue and get it run.

The lifecycle

A job passes through the following parts of mankai-jobs:

  • The enqueuer (queue.enqueuer) checks the job key and arguments, and builds an envelope.
  • An envelope is the stored form of a job: its ID, job key, arguments, queue, priority, attempts, metadata, and scheduled time.
  • The backend (queue.backend) stores envelopes and decides what runs them.
  • A worker is a process that takes due jobs from the backend and runs them.
  • The runner (queue.runner) runs one job: it resolves the job key, calls the job's #call, and turns the result into an outcome.

The following diagram shows the path that a job takes from the code that enqueues it to its main outcomes:

action, operation, or console
        │
        ▼
   queue.enqueuer ──► backend
                       │  stores the envelope
                       ▼
                 worker process (hanami jobs start)
                       │  claims a due job
                       ▼
                  job#call(args)
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
      succeeded     retry        failed

A run can also end as discarded, which means the job finished without doing its work and isn't recorded as failed. Middleware and callbacks receive the envelope as an argument.

The value that #call returns decides the outcome. Success(...), or any value that isn't a Result, means that the job succeeded. A Failure or a raised exception goes to the job's retry and discard rules. discard, retry_later, and snooze request an outcome directly. For how to use them, see Define and enqueue jobs and Make jobs reliable.

The provider

The queue provider wires mankai-jobs into your app. It registers the following components:

Component Purpose
queue.enqueuer Stores jobs and returns a Result.
queue.backend Stores jobs and runs them.
queue.runner Runs one envelope and returns an outcome.
queue.builder Builds envelopes from a job key and arguments.
queue.registry Resolves job keys across the app and its slices.

The provider's name differs from the jobs namespace, so these components can't be mistaken for jobs. queue is the convention.

Backends

A backend decides where jobs live and what runs them. The same job code works with every backend, but not every backend supports every feature. The following table compares them:

Backend Runs jobs Keeps jobs across a restart Use it for
:memory When the test calls drain No Tests
:inline Immediately, in the caller No Scripts and one-off tasks
:async On threads in the current process No Trying jobs without a database
Mankai::Jobs::SQL.backend In worker processes from hanami jobs start Yes Development and production

Every backend supports unique jobs. The memory, async, and SQL backends also support scheduling and retries; the inline backend runs each job once, immediately. Only the SQL backend stores jobs durably, and only it supports priorities, concurrency limits, transactional jobs, finished-job records, and recurring tasks. A backend ignores the settings that it doesn't support, and the job still enqueues and runs. For the full comparison, see Backends.

Use :memory in tests. In development, use the SQL backend with a worker, as in production, so that jobs behave the way they do when deployed. :async needs no database and no worker, but jobs that are still waiting when the process exits are lost.

Thread safety

Outside tests, Hanami creates each component once and reuses it, so several threads might run the same job instance at the same time. A job must not keep per-run state in instance variables. Everything that a run needs arrives as an argument, including the envelope if #call declares an envelope: keyword.

Delivery is at least once

With the SQL backend, a job can run more than once. A worker that stops on purpose puts its job back on the queue, where it runs again. A job whose worker crashed, or whose host disappeared, is recorded as failed, and you can retry it by hand. Either way, part of the job might already have run.

Design each job to be idempotent: running it twice must have the same effect as running it once. For example, use a unique database constraint, or check whether the email was already sent before you send it.

The built-in backends don't store jobs durably, so this guarantee doesn't apply to them.

What's next