Skip to content
Edit this page View source of this page

Make jobs reliable

Jobs fail, processes stop, and hosts disappear. This guide shows you how to retry failed jobs, prevent duplicate jobs, limit how many jobs run at the same time, stop jobs that run too long, and make jobs safe to run twice. It assumes that you can already define and enqueue jobs. For every setting and its default, see Job settings in the mankai-jobs reference.

Some features depend on the backend. Retries work with every backend except :inline, and concurrency limits and transactional jobs work only with the SQL backend. See Backends.

Retry failed jobs

By default, a job never retries: max_attempts is 1, and no rules are declared. A job that returns a Failure or raises an exception fails after its first run. To retry it, declare a retry_on rule, raise max_attempts, or both.

A retry_on rule retries the errors that it matches. A rule matches an exception class, a class name as a string (for classes that might not be loaded), or a failure symbol such as the one in Failure(:rate_limited). The following rules retry a timeout 5 times with exponential backoff, a Faraday timeout 3 times, and a rate limit forever, waiting a minute longer each time:

retry_on Net::ReadTimeout, attempts: 5, wait: :exponential
retry_on "Faraday::TimeoutError", attempts: 3
retry_on :rate_limited, attempts: :unlimited, wait: ->(attempt, _error) { 60 * attempt }

Each rule counts its own attempts, 5 by default. When a rule runs out of attempts, the job fails.

To retry errors that no rule matches, raise max_attempts. It counts every run, including the first:

config.max_attempts = 5

Backoff is the delay before each retry. Set config.backoff to :polynomial (the default), :exponential, a fixed number of seconds, or a lambda that receives the attempt number and the error. config.jitter adds a random amount to each delay, 15% at most by default, so that many failed jobs don't all retry at the same moment.

The runner checks rules in the following order: discard_on rules first, then retry_on rules, then max_attempts.

Discard jobs that can't succeed

Some failures mean that the job has nothing left to do, such as a user who was deleted. To finish the job as discarded instead of failed, declare a discard_on rule:

discard_on :user_missing

The rule matches a job that returns Failure(:user_missing). To also send the error to the provider's error_reporter, add report: true. You can also return discard(reason) from #call.

Try again later

To defer a run from inside #call, return one of the following values:

  • retry_later(reason, wait: seconds) runs the job again after wait seconds and uses up an attempt. Raise max_attempts on jobs that return it; with the default of 1, the job fails immediately.
  • snooze(seconds) runs the job again after seconds without using up an attempt. Use it when waiting isn't a failure, such as a file that's still uploading.

The following job waits for a report to be ready, and gives up after 10 tries:

config.max_attempts = 10

def call(report_id:)
  return retry_later(:not_ready, wait: 30) unless report_ready?(report_id)

  send_report(report_id)
  Success()
end

Prevent duplicate jobs

A unique job blocks duplicates while it's waiting, running, or retrying. Enqueuing a duplicate returns Failure[:duplicate, existing_job_id] and doesn't store the job. Every backend enforces uniqueness.

To make a job unique, set config.unique. The following setting treats two jobs as duplicates when they have the same user_id:

config.unique = {by: :user_id}

You can adjust the rule as follows:

  • To compare all arguments, set config.unique = {}.
  • To treat jobs on different queues as different, add queue: true.
  • To keep blocking duplicates after a job succeeds, add period: in seconds. For example, with period: 3600, the backend divides time into one-hour windows that start at the Unix epoch, and allows one successful job per window.

Without period, a job stops blocking duplicates when it succeeds, fails, or is discarded. For every option, see Unique jobs.

Limit concurrent jobs

A concurrency limit caps how many jobs that share a key run at the same time. Only the SQL backend enforces limits; the other backends ignore them. The following setting runs at most one job per account at a time:

config.concurrency = {limit: 1, key: :account_id}

By default, a job that finds no free slot waits. To drop it instead, and record it as discarded, add on_conflict: :discard.

A running job holds its slot for at most duration seconds, 900 by default. This frees the slot if a worker dies without releasing it. duration isn't a timeout: if a job runs longer, another job with the same key might start. Set it well above the job's normal run time. For every option, see Concurrency limits.

Stop jobs that run too long

To set a time limit on a job, set config.timeout in seconds. When the time runs out, the runner raises Mankai::Jobs::JobTimeoutError inside the job and handles it like any other error. The following settings stop a run after 30 seconds and retry it once:

config.timeout = 30
retry_on Mankai::Jobs::JobTimeoutError, attempts: 2

config.timeout uses Ruby's Timeout, which can interrupt a job in the middle of any operation, including a database write. Prefer the timeouts of the libraries that the job calls, such as HTTP client timeouts and database statement timeouts, and use config.timeout as a last resort.

Commit a job's writes with its completion

With the SQL backend, a job can run inside a database transaction that also marks it finished. Its writes and its completion then commit or roll back together, so a crash can't leave the work done but the job unfinished. To run a job this way, set config.transactional:

config.transactional = true

The transaction stays open for the whole run, so keep transactional jobs short. They can't use resumable steps, because a rollback would undo work that the steps recorded as done. For details, see Job settings on this backend.

Make jobs safe to run twice

The SQL backend delivers each job at least once. If a worker stops in the middle of a job, the job runs again, or is recorded as failed so that you can retry it. 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. Use one or more of the following techniques:

  • Use a natural key or a unique database constraint, so that a second insert fails.
  • Check whether the side effect already happened before you repeat it, for example whether the email was already sent.
  • Store progress in the job's own rows, or make the job resumable with steps:. See Make a job resumable.

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.

To recover jobs that failed because their worker crashed, see Retry jobs that failed. For what happens in each kind of stop, see Delivery guarantees.

What's next