hive — workers & supervision
Run background work in OCaml with hive, using typed workers, supervision, timers, pubsub and optional clustering.
hive runs work in the background. A worker is a long-lived process with an inbox of messages. Other code sends the worker messages, and the worker handles them one at a time. A supervisor starts workers and restarts them if they fail. With the optional cluster support described below, workers can also run on several machines. This page describes each part in turn, with runnable examples.
The shape of a hive worker
A worker consists of a fiber (a lightweight thread) and a bounded, typed mailbox, both started under an Eio switch. The part the application writes is a pure handle function. It takes an incoming message and the current state, and returns a reaction: the next state, a reply, and a list of actions for the runtime to carry out. The library provides the fiber, the mailbox, ordered delivery and backpressure. Application code supplies the decision logic.
Each worker has its own set of messages, defined as a GADT (a variant type whose constructors can carry different reply types). To build a worker you instantiate Hive.Server.Make with that message type, the same way you instantiate Map.Make with a key type. hive uses a functor because OCaml has no higher-kinded type parameters. The functor attaches the message type to the runtime. The message type also records each message's reply type, so the compiler checks the worker's protocol. A reply with the wrong type does not compile.
A worker is tied to an Eio switch. Stopping is a value-level operation, and when the switch ends, the resources under it are cleaned up.
one worker: mailbox → pure handler → new state
casts & calls
producers ──────────────▶ ┌────────────────┐
│ bounded mailbox │ (typed, ordered)
└───────┬─────────┘
│ one message at a time
▼
┌──────────────────────┐
│ handle msg state │ pure: no fibers, no IO
│ → continue/reply + │
│ effects as data │
└──────────┬────────────┘
│ new state
▼
(loop, in one fiber)A typed counter worker
This example is a complete worker. It has two messages, a pure handle function, a spec, and a main function that exercises the worker lifecycle.
Defining messages with a GADT
(* The message GADT: the type parameter is the reply type.
Casts (fire-and-forget) are [unit msg]; calls carry their reply
type, so an ill-typed send does not compile. *)
type _ msg =
| Incr : int -> unit msg (* cast: add [n] to the counter *)
| Total : int msg (* call: read the current total *)
(* One functor application per worker module, like [Map.Make]. *)
module Counter = Hive.Server.Make (struct
type 'r t = 'r msg
end)Read the message type first. Incr is a cast (fire-and-forget, with reply type unit), while Total is a call that replies with an int. Because the reply type is part of the constructor, call counter Total is an int-typed expression, and answering a call with the wrong type does not compile.
Pure decision logic
(* Pure decision logic: the function takes a message and a state and
returns a reaction. It performs no IO and starts no fibers, so it can
be unit-tested by calling it directly. *)
let handle : type r. r msg -> int -> (int, r) Counter.reaction =
fun msg state ->
match msg with
| Incr n -> Counter.continue (state + n) ()
| Total -> Counter.continue state state
(* The spec bundles the callbacks; defaults cover the rest. *)
let spec =
{
Counter.init = (fun () -> 0);
handle;
handle_info = Counter.ignore_info;
terminate = Counter.no_terminate;
}handle performs no I/O. It also does not spawn fibers. A test can therefore call handle directly and assert that handle (Incr 2) 3 continues with state 5. continue is the reaction with no actions. ignore_info and no_terminate are the defaults for the two callbacks this worker does not need.
Casts, calls, and errors as values
(* Start the server: a fiber plus a typed mailbox under [sw]. *)
let counter = Counter.start ~sw ~clock spec in
(* Casts are asynchronous; a full mailbox applies backpressure. *)
List.iter (fun n -> Counter.cast counter (Incr n)) [ 1; 2; 3; 4 ];
(* A call is synchronous request/reply, with errors as values.
The mailbox is ordered, so this call sees all the casts above. *)
(match Counter.call counter Total with
| Ok total -> Printf.printf "total after increments 1+2+3+4: %d\n" total
| Error `Timeout | Error `Stopped ->
prerr_endline "error: counter unavailable";
exit 1);start runs init in the calling fiber, so a failing init fails start. start then forks the server fiber under the switch. A cast enqueues a message and returns. When the mailbox is full, the producer blocks until space is available. A call is a synchronous request and reply, and it returns a result. The error cases Timeout and Stopped are returned as variants for the caller to match on. The default call timeout is five seconds.
Stop, join, outcomes
(* Orderly shutdown: stop, then await the worker's outcome. *)
Counter.stop counter;
match Eio.Promise.await (Counter.join counter) with
| Hive.Outcome.Completed () -> print_endline "counter stopped cleanly"
| Hive.Outcome.Failed exn ->
Printf.eprintf "error: counter crashed: %s\n" (Printexc.to_string exn);
exit 1
| Hive.Outcome.Cancelled ->
prerr_endline "error: counter was cancelled";
exit 1stop is graceful: it queues behind already-sent messages, runs the terminate callback, then resolves any pending calls with Error `Stopped. join returns a promise of the worker's Hive.Outcome (Completed, Failed with the exception, or Cancelled). A supervisor uses this value when it decides whether to restart the worker.
$ dune exec examples/hive_counter/main.exeSupervision
Workers are usually started by a supervisor. A supervisor owns a sub-switch, starts its children in order under it, and restarts them according to a policy when they fail. Because children live under the supervisor's switch, cancelling the switch shuts the children down.
Child specs and restart policies
(* A transient child is restarted only when it fails. The first run
crashes; the supervisor backs off, restarts it; the second run
completes and stays down. *)
let attempts = ref 0 in
let flaky =
Supervisor.child_spec ~id:"flaky" ~restart:Supervisor.Transient
~backoff:{ Supervisor.initial = 0.01; max_delay = 0.1; multiplier = 2.0 }
(fun child_sw ->
Supervisor.child_of_fn child_sw (fun () ->
incr attempts;
Printf.printf "flaky child: attempt %d\n" !attempts;
match !attempts with 1 -> failwith "first run crashes" | _ -> ()))
in
let sup =
Supervisor.start ~sw ~clock ~strategy:Supervisor.One_for_one [ flaky ]
inA child spec is an id plus a start function that receives the supervisor's sub-switch and is re-run on each restart. The restart policy is set per child. Permanent children are restarted after any outcome. Transient children are restarted after a Failed outcome (the example child completes on its second run and stays down). Temporary children are not restarted. Restart delays back off exponentially up to a cap and reset once a child has stayed up longer than the cap. child_of_fn adapts a plain thunk. A server, a task, or another supervisor can also be a child, as long as it exposes join and shutdown.
Strategies and shutdown
(* A supervisor is itself a joinable unit of work. *)
Supervisor.stop sup;
match Eio.Promise.await (Supervisor.join sup) with
| Outcome.Completed () -> print_endline "supervisor stopped cleanly"
| Outcome.Failed _ | Outcome.Cancelled ->
prerr_endline "error: supervisor did not stop cleanly";
exit 1The strategy decides which children are restarted when one child fails. One_for_one restarts the failed child. One_for_all restarts all of the children. Rest_for_one restarts the failed child and those started after it. The await flag selects what happens on stop. The supervisor either asks each child to shut down (the default) or waits for running children to finish. The supervisor is itself joinable, so supervisors can be arranged in a tree. In an araara application, application.ml starts a supervisor under its root switch.
$ dune exec examples/hive_supervision/main.exeTimers and one-shot tasks
Two other modules cover work that is not a long-lived worker: scheduled callbacks and background one-shot tasks.
Scheduler: after and every
(* Timers run on the Eio clock: periodic [every], one-shot [after],
both cancellable. *)
let ticks = ref 0 in
let ticker =
Scheduler.every ~sw ~clock ~immediate:true 0.01 (fun () -> incr ticks)
in
let fired, resolve = Eio.Promise.create () in
let _once : Scheduler.timer =
Scheduler.after ~sw ~clock 0.05 (fun () -> Eio.Promise.resolve resolve ())
in
Eio.Promise.await fired;
Scheduler.cancel ticker;
Printf.printf "periodic ticks before the one-shot fired: at least %d\n"
(min !ticks 2);Timers run on the Eio clock under your switch. after fires once, and every fires periodically (immediate:true adds a tick at t=0). cancel stops either kind of timer. cancel is idempotent, and it has no effect after a one-shot timer has fired.
Running one-shot work with Task
(* One-shot background work: each task resolves to an outcome. *)
let jobs = List.map (fun n -> Task.async ~sw (fun () -> n * n)) [ 2; 3; 4 ] in
let squares =
List.filter_map (fun o -> Outcome.value o) (Task.await_all jobs)
in
Printf.printf "squares: %s\n"
(String.concat ", " (List.map string_of_int squares));
(* An exception does not escape: it becomes a [Failed] outcome. *)
let risky = Task.async ~sw (fun () -> failwith "out of cheese") in
(match Task.await risky with
| Outcome.Failed _ -> print_endline "risky task failed, as a value"
| Outcome.Completed () | Outcome.Cancelled ->
prerr_endline "error: expected the task to fail";
exit 1);Task.async forks a fiber and returns a typed handle. await (or await_all) blocks for the Outcome. An exception raised inside the task is reported as a Failed outcome for the caller to match on. cancel resolves the outcome to Cancelled. Tasks can be added to a supervisor with child_of_fn.
Actions and out-of-band messages
A handler returns effects as actions in its reaction. The runtime interprets the action list after the reply is delivered. Send enqueues on a typed address, Send_after schedules a named timer, Publish broadcasts through the injected pubsub, and Stop terminates after the current message. Handlers therefore remain pure functions that a test can call directly.
Returning actions from a handler
(* An audit worker records every event it hears about. [Remind] shows
actions-as-data: the handler returns a [Send_after], the runtime
performs it and later delivers [Info.Timer] back to the worker. *)
type _ msg =
| Remind : string -> unit msg (* cast: schedule a named timer *)
| Seen : string list msg (* call: everything recorded so far *)
module Audit = Hive.Server.Make (struct
type 'r t = 'r msg
end)
let handle : type r. r msg -> string list -> (string list, r) Audit.reaction =
fun msg state ->
match msg with
| Remind name ->
let actions = [ Audit.Action.Send_after { delay = 0.01; timer = name } ] in
{ Audit.state; reply = (); actions }
| Seen -> Audit.continue state (List.rev state)The Remind handler does not sleep and does not fork. It returns a Send_after action, and the runtime does the scheduling. A test can assert on the returned action list without using a clock.
handle_info: timers and bridged deliveries
(* Out-of-band messages (fired timers, bridged pubsub deliveries)
arrive in [handle_info], also pure. *)
let handle_info info state =
match info with
| Hive.Server.Info.Timer name -> Audit.continue (("timer " ^ name) :: state) ()
| Hive.Server.Info.Pubsub { topic; payload } ->
Audit.continue ((topic ^ ": " ^ payload) :: state) ()
let spec =
{ Audit.init = (fun () -> []); handle; handle_info;
terminate = Audit.no_terminate }Messages that are not part of the worker's GADT (a named timer firing, or a pubsub delivery) arrive as Info values in handle_info. handle_info is a pure function, like handle. Workers that need neither kind of message use the ignore_info default.
Naming, fan-out, and pubsub
Three capabilities connect workers to each other. Each one is a value that application code creates and passes to the workers that use it.
The pubsub capability
Pubsub is a topic broker represented as a value. The application can subscribe a callback to a topic, publish a payload to the subscribers of a topic, and call the returned function to unsubscribe.
(* A subscriber is a topic and a callback. The callback runs once per
payload published to that topic, synchronously in the publisher's
fiber. subscribe returns a function that releases the subscription. *)
let received_a = ref [] in
let received_b = ref [] in
let unsubscribe_a =
bus.Pubsub.subscribe ~topic:"news" (fun ~payload ->
received_a := payload :: !received_a)
in
let _unsubscribe_b =
bus.Pubsub.subscribe ~topic:"news" (fun ~payload ->
received_b := payload :: !received_b)
in(* publish sends a payload to every subscriber of the topic; a topic
with no subscribers drops it. *)
bus.Pubsub.publish ~topic:"news" ~payload:"headline: pubsub now lives in hive";
bus.Pubsub.publish ~topic:"news" ~payload:"headline: examples build clean";
bus.Pubsub.publish ~topic:"weather" ~payload:"ignored: nobody is listening";Hive.Pubsub.local is the single-process implementation. publish invokes each subscriber synchronously in the publisher's fiber, so a callback that blocks (for example, while enqueuing into a full mailbox) also blocks the publisher. hive does not select an implementation. The application supplies one when it composes the worker, and a clustered application can supply a broker that spans nodes.
The supplied pubsub value also connects pubsub to workers. Server.subscribe turns a topic into Info.Pubsub messages delivered to the worker's mailbox, and the returned function releases the subscription:
(* The pubsub capability is injected; the caller chooses the transport.
[subscribe] delivers a topic into the worker's mailbox. *)
let pubsub = Pubsub.local () in
let audit = Audit.start ~sw ~clock ~pubsub spec in
let unsubscribe = Audit.subscribe audit ~pubsub ~topic:"deploys" in
pubsub.Pubsub.publish ~topic:"deploys" ~payload:"api v42 rolled out";
Audit.cast audit (Remind "rotate-logs");
Eio.Time.sleep clock 0.05;
(match Audit.call audit Seen with
| Ok events -> List.iter print_endline events
| Error `Timeout | Error `Stopped ->
prerr_endline "error: audit worker unavailable";
exit 1);
unsubscribe ();$ dune exec examples/hive_pubsub/main.exeThe typed registry
(* The registry maps a name to a capability, type-safely: a lookup
succeeds only with the same key that registered the value. *)
let registry = Registry.create () in
let audit_key : Audit.t Registry.key = Registry.key "audit" in
(match Registry.register registry audit_key audit with
| Ok () -> ()
| Error `Already_registered ->
prerr_endline "error: the audit name is already taken";
exit 1);
(match Registry.whereis registry audit_key with
| Some _server -> print_endline "audit worker found under its name"
| None ->
prerr_endline "error: audit worker not registered";
exit 1);The registry maps names to capabilities. Keys carry a type witness, so a lookup returns a value when it is made with the same key that registered the value. Registration is atomic, and the first registration for a name is kept. The table behind the registry is lock-free and can be used from multiple domains. Create the key once, next to the worker module that owns the name, and share it.
Groups
(* A group is a named set with no uniqueness constraint, used for
fan-out. *)
let groups = Group.create () in
let auditors : Audit.t Group.key = Group.key "auditors" in
let second = Audit.start ~sw ~clock spec in
let joined =
List.filter_map
(fun worker ->
match Group.join groups auditors worker with
| Ok membership -> Some membership
| Error `Name_in_use -> None)
[ audit; second ]
in
Printf.printf "group members: %d\n" (List.length (Group.members groups auditors));
List.iter (fun m -> Group.leave groups m) joined;
Printf.printf "after leaving: %d\n" (List.length (Group.members groups auditors));A name in the registry maps to one value. A group is a named set that can hold many members under one name, so a message can be sent to all of them. join returns a membership token, and leaving the group requires that token. Two joins create two memberships, and leaving with one token does not remove the other membership.
$ dune exec examples/hive_registry/main.exehive.cluster for multiple nodes
The hive.cluster sub-library applies the worker model across several machines. It adds cross-node capabilities to hive. A name registry and groups can work across the cluster. A message can be sent to a worker running on another node. State can be replicated to other nodes. A singleton can be assigned to an owner node, subject to the consistency limits described below. Cluster support is optional, and a single-node application does not need to link hive.cluster. The rest of this page describes how hive.cluster is built, how nodes find each other, and what each part does.
The layered architecture
hive.cluster is functored over three capabilities
your workers · Dist_registry · Dist_group · Placement · Remote
───────────────────────────────────────────────────────────────
hive.cluster
(functor over 3 capabilities — swappable, testable)
┌──────────────┬───────────────┬────────────────────────────┐
│ MEMBERSHIP │ TRANSPORT │ REPLICA │
│ who is here │ ship bytes │ converging state (CRDT) │
└──────┬───────┴───────┬───────┴──────────────┬─────────────┘
│ │ │
hive.cluster.swim (one adapter) hive.cluster.crdt
swim — SWIM gossip over UDP/TCP crdt — json-joy docsEach cluster feature is built on three capabilities, and an application can supply a different implementation of each one. MEMBERSHIP tracks which nodes are in the cluster and which nodes are reachable. TRANSPORT sends bytes to a named node. REPLICA is a state type that converges as updates arrive. In OCaml terms, each feature is a functor over those three module types. hive.cluster depends on the three interfaces, and it does not depend on swim, crdt or the network directly. Tests can therefore run hive.cluster against in-memory fakes that simulate partitions and message loss.
Two adapters are used for a deployed cluster. hive.cluster.swim supplies MEMBERSHIP and TRANSPORT over the swim gossip protocol, and hive.cluster.crdt supplies REPLICA as json-joy CRDT documents. A node's identity is an id plus an incarnation number, so a message addressed to a node from before it restarted is rejected.
SWIM gossip and ports
two nodes on loopback, one port each
node A node B
127.0.0.1:9471 127.0.0.1:9472
┌──────────────┐ UDP :port probe ───▶ ┌──────────────┐
│ swim node │ ◀─── ack UDP :port │ swim node │
│ │ gossip piggybacked │ │
│ │ on every packet ────▶ │ │
│ │ TCP :port join / │ │
│ │ ◀── push-pull state ─▶│ │
└──────────────┘ └──────────────┘
one port (default 7946) carries both: UDP for probes + gossip,
TCP for the join-time state exchange.Membership runs the SWIM protocol. Each node periodically picks a random peer and sends it a UDP probe. If no ack comes back, the node asks a few other peers to probe that peer on its behalf. These indirect probes cover cases where the direct path failed. If the indirect probes also fail, the peer is marked Suspect. If it remains silent, it is then marked Dead.
News of these changes travels by gossip. Each node piggybacks a few recent membership updates (Alive / Suspect / Dead, Join / Leave) onto its probe packets. A node that receives an update includes it in later packets, so the update spreads through the cluster without a central coordinator.
This traffic uses one configurable port, bind_port, which defaults to 7946. UDP on that port carries the probes, acks and gossip. TCP on the same port carries the join-time push/pull state exchange, where a joining node and a seed exchange their full membership views so the joining node receives the current view at join time. The port must be open for UDP and TCP between nodes. Optional AES-GCM with a shared key encrypts the traffic on that port.
Starting a node
(* The adapter's [config] takes a dotted-quad [bind_addr] (it converts to
swim's raw-byte form internally) and a [bind_port]. We start from
[Swim.default_config] and tighten the gossip interval so the two nodes
converge quickly in this demo. *)
let config ~port =
{
(SwimA.config ~bind_addr:host ~bind_port:port ()) with
Swim.Types.protocol_interval = 0.1;
cluster_name = "hive-cluster-example";
}Hive_cluster_swim.config takes a dotted bind address and the bind_port. The example uses distinct loopback ports so that two nodes can run on one machine. The config also carries the SWIM timing options and the optional cluster_name and secret_key. Hive_cluster_swim.create then opens the sockets and starts the protocol fibers under the switch. The resulting value provides both MEMBERSHIP and TRANSPORT for the functors below.
(* Boot a node: create the swim endpoint, then wire a registry on top of
it BEFORE joining, so nothing the cluster sends can race a missing
subscription. *)
let boot ~sw ~env ~port =
match SwimA.create ~sw ~env ~config:(config ~port) with
| Error `Invalid_key ->
prerr_endline "error: swim secret key must be exactly 16 bytes";
exit 1
| Ok node ->
let reg = Reg.create ~membership:node ~transport:node ~name:"shared" () in
(node, reg)
let () =
Eio_main.run @@ fun env ->
Eio.Switch.run @@ fun sw ->
let clock = Eio.Stdenv.clock env in
let env = swim_env ~sw env in
let node_a, reg_a = boot ~sw ~env ~port:port_a in
let node_b, reg_b = boot ~sw ~env ~port:port_b in
Printf.printf "node A = %s (swim :%d)\n%!"
(Node.to_string (SwimA.Membership.self node_a))
port_a;
Printf.printf "node B = %s (swim :%d)\n%!"
(Node.to_string (SwimA.Membership.self node_b))
port_b;
(* Join B to A's seed. The seed string raw-encodes the dotted address;
joining runs a TCP push/pull state exchange, so both membership views
converge immediately. *)
let seed = SwimA.seed ~host ~port:port_a in
(match SwimA.join node_b ~seed_nodes:[ seed ] with
| Ok () -> Printf.printf "node B joined seed %s:%d\n%!" host port_a
| Error `No_seeds_reachable ->
prerr_endline "error: no seed nodes reachable";
exit 1);A node is configured before it joins. The application builds the registry, groups, placement and remote components over the node, and then joins a seed. join performs the TCP push/pull exchange with the seed's address and returns `No_seeds_reachable if no seed answers. After the join, gossip carries further membership updates to the nodes.
Replicated state, registry and groups
Replica is the replication mechanism used here, and the distributed registry and groups are instances of it. A local update is applied locally and broadcast as a sequence-numbered delta to reachable members. A receiver that detects a gap requests a sync, which replies with the missing tail or, past the bounded buffer, a full snapshot. Reads are served from the local copy, and the read path does not wait for a quorum.
(* Register a name on node A. This mutates A's local replica; the change
then propagates to B over the registry's delta gossip. *)
(match Reg.register reg_a "spawner" ~meta:"worker-7" with
| Ok () -> Printf.printf "node A registered \"spawner\" -> worker-7\n%!"
| Error `Already_registered ->
prerr_endline "error: name already registered";
exit 1);(* Gossip is asynchronous, so poll node B's view until it sees A's
binding. Polling is bounded to about 5s (50 polls of 0.1s), after
which the demo reports a failure and exits. *)
let rec converge n =
match Reg.whereis reg_b "spawner" with
| Some (owner, meta) when Node.same_id owner (SwimA.Membership.self node_a) ->
Printf.printf
"node B sees \"spawner\" held by %s with meta %S after %d poll(s)\n%!"
(Node.to_string owner) meta n;
true
| _ when n >= 50 -> false
| _ ->
Eio.Time.sleep clock 0.1;
converge (n + 1)
in
let converged = converge 0 inDist_registry is a cluster-wide name → (node, metadata) map and uses last-writer-wins on conflict. Dist_group is a cluster-wide set with add-wins semantics. The example registers a name on one node and reads it back on the other node after gossip has carried the update. Convergence is asynchronous, so application code waits on an on_update callback rather than polling.
$ dune exec examples/hive_cluster/main.exeRemote messaging and placement
Remote makes a local worker reachable by name from another node. The receiving node exposes a decoder, and the sender holds a typed address (node, name, encoder). send_to sends a best-effort, cast-style message and returns `Unreachable when the node has left. In this respect send_to corresponds to a cast between nodes.
Placement runs cluster singletons. Each node declares the same named spec. A consistent-hash ring (with virtual nodes for balance) selects an owner, and ownership follows membership. When the owner leaves, the ring reassigns ownership and the worker starts on another node with a state handoff. Placement is AP. Placement_cp is a CP variant that uses majority-quorum leases to run at most one instance at a time. Under Placement_cp, no instance runs when a majority is not available.
Consistency during a network partition
Replication, the registry, groups and Placement are AP. During a network partition both sides remain available, so a name can have two holders for a time and a placed singleton can run on two nodes for a time. The duplicate is detected and stopped when the partition heals. Workers placed under AP must therefore tolerate running twice. Such workers should be idempotent, or they should fence their own side effects. hive.cluster does not provide a consensus log. State is kept in memory, is not persisted, and converges after a partition heals. Applications that require a single writer can use Placement_cp or run an external consensus system behind a worker. The swim and crdt pages document the layers underneath.