An experimental jobs library for ocaml inspired by Oban.
README.md

oban #

Oban is a background-job library for OCaml 5 applications using Eio. Jobs are stored in SQLite, PostgreSQL, or MariaDB through Repodb, and their arguments and metadata are Simdjsont.Json.t values.

A job starts as a Job.spec. Enqueueing it creates a durable job in an available state. A runtime claims available jobs, passes them to registered workers, and records the outcome. Jobs may complete, retry after an error, snooze until the current time or later, or finish as cancelled or discarded.

Installation #

Install the library with the Repodb driver used by your application:

opam install oban eio_main repodb-sqlite

Use repodb-postgresql instead of repodb-sqlite for PostgreSQL, or repodb-mariadb for MariaDB. Oban requires Repodb >= 0.8.0 and targets PostgreSQL 12 or later, SQLite 3.35 or later, and MariaDB 11.4 or later. MariaDB integration is tested against MariaDB 11.4 LTS. A matching Dune executable stanza looks like this:

(executable
 (name main)
 (libraries oban eio_main repodb-sqlite))

Quick start #

The following example creates a SQLite-backed queue and runs four worker fibers:

module Backend = Oban.Make (Repodb_sqlite.Driver)
module Store = Backend.Store
module Runtime = Backend.Runtime

let get = function
  | Ok value -> value
  | Error _ -> failwith "oban operation failed"

let wall_now () =
  Unix.gettimeofday () |> Ptime.of_float_s |> Option.get

let queue = get (Oban.Job.parse_queue "mailers")
let worker_name = get (Oban.Job.parse_worker_name "Email")

module Email = struct
  let name = worker_name

  let perform job =
    let args = (Oban.Job.view job).args in
    ignore args;
    (* Send the email here. *)
    Oban.Worker.Ok

  let backoff = Oban.Worker.default_backoff
  let timeout = Oban.Worker.default_timeout
end

let () =
  Eio_main.run @@ fun env ->
  let store = get (Store.connect ~pool_size:4 "jobs.sqlite") in
  Fun.protect ~finally:(fun () -> Store.close store) @@ fun () ->
  get (Store.migrate store);

  let config =
    get
      (Runtime.configure ~node:"mailer-1"
         ~queues:[ { queue; concurrency = 4 } ] ~poll_interval:1.)
  in
  let runtime =
    get
      (Runtime.create ~config ~store
         ~workers:[ Oban.Worker.pack (module Email) ] ())
  in

  let args =
    Simdjsont.Json.Object [ ("user_id", Simdjsont.Json.Int 42L) ]
  in
  let job =
    get
      (Oban.Job.create ~now:(wall_now ()) ~queue ~worker:worker_name ~args ())
  in
  ignore (get (Runtime.enqueue runtime job));

  Runtime.run ~clock:(Eio.Stdenv.clock env) ~wall_now runtime

Runtime.run blocks until its Eio scope is cancelled or a storage loop raises Runtime.Loop_error. Runtime.run_one is available when an application wants to claim and execute at most one job itself.

For PostgreSQL, instantiate the backend with Repodb_postgresql.Driver and pass a PostgreSQL connection string to Store.connect:

module Backend = Oban.Make (Repodb_postgresql.Driver)

For MariaDB 11.4 or later, add repodb-mariadb to the executable's Dune libraries and use its driver with a MariaDB connection string:

module Backend = Oban.Make (Repodb_mariadb.Driver)

let store =
  Backend.Store.connect
    "host=127.0.0.1 port=3306 dbname=app user=app password=secret charset=utf8mb4"

Jobs and workers #

Queue and worker names are parsed values rather than plain strings. A job spec contains a queue, worker name, JSON arguments, JSON-object metadata, up to 20 tags, priority, attempt limit, and optional schedule time. Tags are sorted, deduplicated, and can be used in Store.list filters; every tag in a filter must be present. Enqueueing returns either the inserted available job or an existing active job when active-job uniqueness is requested with Runtime.enqueue_unique. Metadata and tags do not participate in the uniqueness key.

All persisted size limits are serialized UTF-8 byte counts and are available from Oban.Limits:

Value Default or limit
queue, worker, and execution-owner names non-empty UTF-8 without U+0000; 255 bytes each; queue defaults to default
arguments 1,000,000 bytes
metadata JSON object, 65,536 bytes
tags 20 distinct, case-sensitive values; 255 bytes each and 65,536 serialized bytes
priority 0 (highest) through 9; default 0
maximum attempts 1 through 2,147,483,647; default 20
recorded errors 20 entries, 100,000 serialized bytes total
error kind and message 64 and 2,048 bytes per entry

Oversized error fields are clipped at a valid UTF-8 boundary and the oldest error entries are removed until the serialized history fits. These are fixed cross-database representation limits; changing them per process could make the schema and job validation disagree.

A worker implements Oban.Worker.S and receives an executing job. Its perform function returns one of these outcomes:

  • Ok completes the job.
  • Error message schedules a retry or discards the job after its final attempt.
  • Snooze seconds makes the job available again at the current time or later without using an attempt.
  • Cancel reason finishes the job as cancelled.

backoff chooses the delay after Error. Worker.default_backoff starts at 15 seconds, grows exponentially, and caps at one day. timeout returns Unlimited or After seconds; a timeout is recorded as a worker error and follows the normal attempt and backoff policy. Worker.default_timeout is unlimited. Cancellation of the surrounding Eio scope is propagated instead of being recorded as a worker timeout.

Queues and persistence #

Runtime configuration assigns a concurrency count to each queue. Each slot claims one job immediately before running it. Priority, schedule time, and job ID determine claim order within a queue.

Call Store.migrate before enqueueing or running jobs. Store operations include point fetches, paginated lists, cancellation, retry, queue pause and resume, rescue, and pruning. Cancellation and retry take an observed job ID and revision so callers can handle a concurrent state change as Stale.

Runtime.enqueue_many atomically enqueues an ordered list of standard and unique requests. Store.cancel_many and Store.retry_many apply ordered, revision-aware administration batches in one transaction. An error rolls back the entire batch while individual stale targets remain ordered results.

Store.default_settings bounds batches, pages, and maintenance runs at 500 jobs. Those three positive ceilings may be raised independently; there is no arbitrary library maximum above the configured value, but database parameter, packet, memory, and transaction-duration limits still apply. The settings also make SQLite's 5,000ms busy timeout and MariaDB's 30s migration-lock timeout configurable:

let settings =
  { Store.default_settings with
    max_batch_size = 2_000;
    max_maintenance_batch_size = 10_000 }

let store = get (Store.connect ~settings "jobs.sqlite")

Runtime.default_limits allows 64 queues, 1,024 slots per queue, and 4,096 slots in total. Applications that intentionally need more can pass a modified record to Runtime.configure_with_limits.

Store.transaction runs a synchronous, non-Eio callback on one pooled connection. Inside that callback, Store.enqueue_with_conn store connection or Store.enqueue_many_with_conn store connection can join application writes to the same database transaction and retain the configured batch bound.

Comparison with Elixir Oban 2.24 #

The attempt default (20), priority default and range (0 through 9), and unlimited worker timeout match Elixir Oban. Elixir validates queue and worker names at 128 characters, but doesn't define numeric caps for payload bytes, tags, error history, bulk insertion, queue concurrency, or node length. This library uses portable byte-oriented job bounds and configurable operational ceilings because it supports three databases and decodes jobs into memory. Elixir's pruner defaults to 10,000 jobs and its stager to 5,000; here rescue and pruning are application-scheduled and use the store's configurable maintenance bound.

Scheduling and maintenance #

Oban.Cron parses five-field UTC cron expressions and can test or find times with Ptime.t. Cron only calculates times; the application decides when to enqueue the associated jobs.

Rescue and pruning are also application-scheduled operations. Jobs do not send heartbeats while a worker is running, so a rescue threshold should be longer than the expected worker duration.

Job execution is at least once. A worker may perform an external effect and stop before its completion is stored, or rescued work may overlap an older worker. Worker-side effects should therefore be idempotent.