Reactor: Scheduling and Batched Communication

Read with Rechain and Takt, or use the combined reference.

Contents

Reactor's role

Reactor lets many small operations share an intercanister call. It also gives the participating libraries one scheduler for ready work, deadlines and outgoing-call capacity. Put one Reactor instance in each participating canister; those instances form the application's communication mesh.

Think of a purchase workflow that reads an offer, reserves an NFT, collects payment and pays a seller. These are separate business operations. When several workflows have operations ready for the same peer, Reactor puts their messages into batches. The workflow still receives its own addressed result.

Owner Responsibility
Application Authentication, authorization, concrete endpoint contracts and business rules.
Rechain Local reducer validation, atomic business commits and optional recorded history.
Takt Workflow steps, dependencies, waits, business recovery and execution inspection.
Reactor Shared scheduling, priorities, physical call budgets and durable batched delivery.

The package is currently a development package named n-reactor, imported as mo:n-reactor, and is not published to Mops. Reactor can run independently of Takt and Rechain. It carries requests between state owners; it does not copy a peer's business state into the sender. Source: package and integration overview.

Follow a request and its result

Suppose a workflow in A needs B to perform a local action.

  1. A's adapter prepares the concrete input, preserves its operation identity and queues it with a result address. The public API can return a pending workflow ID.
  2. Reactor gathers available messages for B into a physical batch. It sends when scheduled, without waiting for the batch to fill.
  3. B authenticates A and stores an accepted prefix of the batch in its durable inbox. The reply acknowledges storage, not the outcome of the action.
  4. B's scheduler runs the endpoint handler synchronously. The handler can read selectors, dispatch a Rechain action or admit a workflow. Its local effect, inbox removal and result enqueue commit in the same synchronous message.
  5. B sends the business result in a separate batch. A acknowledges its storage, then deposits it into the exact waiting address.
  6. The address's wake hook queues the owning workflow. Takt interprets the result, updates progress and consumes the mailbox together, then follows the graph.
sequenceDiagram
    participant A as Reactor in A
    participant B as Reactor in B
    A->>B: Batch of requests
    B-->>A: Stored-prefix ACK
    Note over B: Run synchronous endpoint handlers
    B->>A: Batch of addressed results
    A-->>B: Stored-prefix ACK
    Note over A: Resume each matching workflow

There are two durable delivery legs: requests and results. Only the short batch/acknowledgement exchange occupies a physical transport slot. Waiting for a business result does not keep that slot occupied throughout a long workflow.

Several handlers can run in one scheduler message. Their changes share that message's commit boundary, so a synchronous trap rolls back the turn. Handlers must be bounded and use typed returns for expected errors. This local atomicity does not create an atomic transaction spanning A and B.

Transport sequencing also does not establish business dependencies: an older deferred operation can finish after later independent work. Put necessary order in the workflow graph. Sources: request lifecycle, transport processing.

Compose one runtime and authenticate peers

Persist Reactor's memory and reconstruct its behavior once per actor lifetime. This is a composition excerpt; the application still supplies its concrete routes and permission policy:

import Principal "mo:core/Principal";
import Reactor "mo:n-reactor";

persistent actor class Example(owner : Principal) = this {
  let reactorMemory = Reactor.newMemory(Reactor.DEFAULT_SETTINGS);
  transient let reactor = Reactor.Reactor<system>(
    reactorMemory, Principal.fromActor(this), 1
  );

  public shared ({caller}) func addPeer(peer : Principal) : async Bool {
    if (caller != owner or Principal.isAnonymous(peer)) return false;
    reactor.addPeer<system>(peer);
    true
  };

  public shared ({caller}) func reactor_receive(
    batch : Reactor.Batch
  ) : async Reactor.Acknowledgement {
    reactor.receive<system>(caller, batch)
  };
}

The constructor's final argument is the installed fleet reader generation, explained under upgrades. Register routes during composition, before scheduled work can run. Authorize peers in both directions because the business result travels back through another batch call.

Peer membership is persistent and append-only. Adding a duplicate is a no-op; there is no peer-removal or cursor-reset API. Membership protects this trusted internal wire, while public ingress remains an application API.

Construct Takt's runtime with reactor.scheduler and attach Rechain and its Readers to that same scheduler. Rechain attachment cancels private maintenance timers; Takt already uses the supplied scheduler. Each library registers its workers while retaining ownership of its own persisted work. Takt's Rechain cleanup adapter also uses the shared scheduler. Ordinary actor methods are not intercepted: a business operation uses batching only when explicitly exposed through a typed Reactor adapter. Sources: composition, Takt runtime construction, public API.

Typed endpoints and caller authority

An Endpoint<Input, Output> combines a stable route with concrete encoders and decoders. Both sides import the same contract. This simple endpoint module illustrates the actual API:

import Reactor "mo:n-reactor";

module {
  public type Input = {name : Text};
  public type Output = {greeting : Text; caller : Principal};

  public let greet : Reactor.Endpoint<Input, Output> = {
    route = "greet";
    input = {
      encode = func(value : Input) : Blob {to_candid(value)};
      decode = func(bytes : Blob) : ?Input {from_candid(bytes)};
    };
    output = {
      encode = func(value : Output) : Blob {to_candid(value)};
      decode = func(bytes : Blob) : ?Output {from_candid(bytes)};
    };
  };
}

With that module imported as Greeting, the receiving actor registers a synchronous handler:

reactor.router.register<Greeting.Input, Greeting.Output>(
  Greeting.greet,
  func<system>(context : Reactor.Context, input : Greeting.Input)
    : Greeting.Output {
    {greeting = "Hello " # input.name; caller = context.origin.caller}
  }
);

Reactor uses ordinary Candid serialization. Rechain's canonical block hashing is a separate contract. Durable retry sends saved bytes unchanged rather than decoding and reconstructing the request.

The handler receives several identities with different meanings:

Context field Meaning
peer Immediate sending canister, authenticated by the IC and membership list.
origin.caller Original authenticated user, forwarded through trusted services.
origin.issuer Canister that issued this operation.
origin.operation Saved operation identity, distinct from packet sequence and workflow attempt.
request Optional response address; absent for notifications.

reactor.origin(caller, operation) sets this canister as issuer. A new downstream operation gets its own identity while retaining the user; forwarding an existing operation preserves its saved origin.

Ingress obtains the user from Motoko's authenticated caller, never an arbitrary client-supplied origin. A handler still checks application permissions. A trusted peer forwarding Alice's identity does not automatically acquire Alice's token allowance or permission to spend from an escrow account.

registerDeferred additionally allows #Later and #Blocked. These outcomes must make no business effect. Use an ordinary synchronous handler for a bounded operation; for long work, admit a workflow and return its reference. Sources: typed router, caller contract.

Requests, results, notifications and events

These messages share transport but serve different purposes:

Kind Purpose Completion
Request Run a typed endpoint operation. An addressed response, containing reply bytes or #Expired.
Response Deliver the operation's result to its requester. Stored in the original result address.
Notification Run a typed operation without an ordinary response. No request-result mailbox; use an explicit event contract if needed.
Event Deliver a producer's publication to a subscribed interest. Stored in an event address for that expected producer.

request and requestUntil return #ok(address) after local enqueue, or #err(error) where the error is #UnknownPeer or #TooLarge. They do not return the business result. For the greeting contract above, a sender with an authorized peer and a prepared authenticated origin uses:

let queued = reactor.request<system, Greeting.Input, Greeting.Output>(
  peer, #Interactive, origin, Greeting.greet, {name = "Ada"}
);

The #ok(address) branch saves that address with durable progress and waits for its result; #err(error) means this local enqueue did not happen. requestUntil additionally takes an optional absolute admission expiry in nanoseconds.

result(address) peeks at a completion. takeResult(address) removes it and its watcher; call it in the same synchronous boundary that saves the consumer's progress. watch(address, dispatcher) arranges a wake when the result arrives. Use a shared dispatcher that queues the addressed work, leaving decoding and state changes to its consumer. Registering a watcher after arrival immediately signals the saved result.

Completion matching checks the expected producer, kind and, for ordinary requests, route. A second distinct completion cannot overwrite the first. Addresses belong to one canister and are never recycled for unresolved work. Sources: message types, request and mailbox API, addressed-wake tests.

Scheduling, priorities and concurrency

Reactor runs eligible work in three priority classes:

Priority Work
Control Library replies, events and integrated required cleanup.
Interactive Operations affecting the user's current flow.
Maintenance Ordinary background work.

Application request APIs allow Interactive or Maintenance. Control is reserved for library obligations, so user operations cannot promote themselves above the work needed to complete existing exchanges.

The scheduler selects priority between driver batches. A selected driver runs at most 32 synchronous commands before rotating behind peers in its class. It stops earlier when blocked, when its priority changes, when launching a native call, or when the instruction budget is reached. Thirty-two is a rotation quantum, not the total work allowed in one message.

The whole-message instruction counter is checked between commands. The default soft threshold is one billion instructions. Remaining ready work continues in a fresh message. A single expensive command cannot be preempted; each command must stay bounded. Maintenance may wait indefinitely while higher-priority work stays continuously ready.

Ready work uses one coalesced immediate wake. Sustained ready work uses a serial continuation controller, while future work uses a separate timer for the earliest absolute deadline. An idle scheduler starts no polling loop; waiting only for replies does not create polling.

Drivers retain their own typed queues and publish readiness changes through lease.changed() or lease.refresh(). The scheduler does not scan every registered worker to rediscover changes. Drivers whose readiness depends on callback permits declare that dependency. Prepared drivers can perform synchronous work and then explicitly launch native calls.

Local execution stays sequential. Exchanges with different peers can overlap; each peer has at most one live batch. A logical workflow timeout does not release a physical call that is still outstanding. Sources: scheduling contract, scheduler implementation, priority and recovery tests.

Batching, limits and admission

Batching lets one physical call carry many logical operations. Each peer has independent priority lanes with their own sequences and acknowledgement cursors. A physical batch can contain several lanes, bounded by its total items and bytes.

Setting Current default What it bounds
maxBatchItems 64 Logical frames across one batch.
maxBatchBytes 1,900,000 bytes Conservative encoded-wire accounting.
scheduler.instructionBudget 1,000,000,000 Soft whole-message threshold between commands.
scheduler.maxCallbacks 40 weighted units Managed physical callback reservations.
scheduler.reservedControl 4 of those units Capacity reserved for Control work.
callTimeoutMillis 10,000 ms Batch/ACK exchange timeout.
retryMillis / maxRetryMillis 1,000 / 60,000 ms Initial delivery backoff and cap.

The implementation accepts item limits up to 1,024 and byte limits up to 1,900,000. A demonstration sending hundreds of messages in one batch therefore needs a larger configured item limit than the default. Both peers need compatible limits. Available work sends without waiting for a full batch; items beyond an accepted prefix remain with the sender.

A transport exchange reserves two weighted callback units for its wrapper and peer call. These units are managed accounting, not an exact count of every live compiler callback. Timers, continuation machinery and other native calls also need headroom. Keep the default callback budget unless measurements justify a different value.

Reactor has no inbox/outbox memory quotas, capacity credits, backlog rejection or eviction. Wire limits and callback permits control transport and execution resources; they do not bound retained backlog. Accepted work and committed notifications are preserved. Application admission and Takt execution limits are separate responsibilities.

Settings are persisted when memory is created. Changing a source default does not alter an existing canister's saved settings. Batching improves use of physical calls; it does not promise a universal throughput number or that a workflow finishes within one IC round. Sources: defaults, settings validation and transport.

Identity, retries and uncertain outcomes

Keep these identifiers separate:

Identity Identifies Retry rule
Peer + priority lane + sequence One transport frame in a durable stream. Resend the same frame without changing its sequence.
Address {canister; id} One response or event mailbox. Keep the address attached to its unresolved operation.
origin.issuer + origin.operation The issued application operation. Preserve it when forwarding or retrying that operation.
Participant transaction metadata The participant's idempotency/replay contract. Preserve its required caller, request, timestamp and memo within that contract.

The sender keeps each frame until the receiver acknowledges storing it. Lost acknowledgement causes the same frames to be resent. Durable lane cursors suppress duplicate acceptance. Once an operation is processed, the receiver owns its queued result until the original sender stores that result and acknowledges it.

Retries preserve the frame's exact bytes, sequence, origin, operation identity and reader generation. Each lane backs off when it makes no progress; contact failures also delay the peer. Delay grows by roughly 1.5 times up to the configured cap. New traffic does not reset an offline peer's delay, and other peers can continue. Delivery retries have no attempt limit.

This is transport retry, not a new business attempt. An independently submitted transfer still needs the participant's transaction idempotency. Preserve its exact memo, timestamp, request and replay horizon; a new packet sequence does not make an unsafe financial retry safe. See Rechain's bounded idempotency and Takt's remote-effect contracts.

#Expired means the receiver declined to begin this request because its admission deadline had passed. It does not prove the outcome of an earlier related attempt. Takt's Reactor adapter treats it as uncertainty. Likewise, a timeout does not prove rejection and cannot authorize a refund or replacement effect.

This transport outcome is distinct from a participant's #TransactionExpired response. The latter is interpreted under that participant's documented replay contract, including duplicate-first lookup and retention guarantees; the two errors are not interchangeable.

After explicit authoritative reconciliation, fence(address) retires its business consumer while allowing a unique late result to drain. Watching again cannot reactivate the fenced address. Until resolution or such reconciliation, keep the original address attached to the operation.

Unknown routes, invalid input and incompatible result handling remain available for repair. Register a missing route, or upgrade a faulty decoder or handler, then explicitly resume the blocked inbox entry. An already registered route cannot be replaced by calling register again. Oversized committed results stay queued rather than disappearing. Progress depends on reachable peers, compatible contracts and bounded handlers; preservation alone cannot guarantee eventual completion. Sources: recovery contract, transport tests, Takt Reactor adapter.

Events from committed business state

A parent sometimes needs a particular committed fact rather than an immediate operation reply. For example, a child can publish a block confirming its audit completed. Reactor's events provide one-shot addressed interests:

  1. The waiting canister opens an event address for the expected producer.
  2. A typed request registers that address on the producer's topic before starting the child or effect that can publish.
  3. A successful Rechain commit listener calls publish(origin, topic, payload) synchronously.
  4. Publication detaches the current recipient set. Scheduled work fans out durable Control events one recipient at a time.
  5. Delivery deposits each event into its exact address, even if the workflow has not reached its wait node yet.

The listener does not loop over subscribers or reject the committed block because of transport backlog. Later subscribe/unsubscribe calls cannot change the set captured by that publication.

Use one address for one interest. Registration is idempotent only while that address remains in the same topic's current recipient set. Do not register it under another topic or reuse it after publication. A topic names an application-defined fact; observing one block does not inherently prove an entire child workflow terminated successfully.

Takt's generated ScheduleWorkflow / AwaitEvent integration uses notifyWithEvent to allocate the address and enqueue the child request atomically. The producer subscribes before admission, avoiding a child that finishes before its parent is listening. See Takt events and children. Sources: event implementation, coordination adapter.

Persistence and fleet upgrades

Reactor persists peer membership, lane cursors, exact frames, retry deadlines, inbox entries, completion mailboxes, subscriptions and pending publication recipients. Timer IDs, drivers, watchers and scheduling indexes are transient and rebuilt on binding. Absolute deadlines retain elapsed time rather than restarting their duration.

Durable queues do not make a live Motoko continuation upgradeable. Physical callbacks must finish before rebinding. Stop the canister, let callbacks drain, upgrade and reconstruct the runtime. Stop/start without an upgrade also preserves and resumes ready work. A logical operation can remain unresolved across upgrade once its physical exchanges have drained.

Message evolution uses a fleet reader generation, independent of persisted-memory version and workflow-definition version. New frames record their encoder's generation. Older code durably accepts newer frames but postpones decoding and completion delivery until upgraded code supports them. inbox reports waitingForUpgrade; these items do not poll. After reconstruction they become schedulable automatically. Waiting for code does not extend an admission deadline.

Keep route names stable and evolve interfaces additively, preserving existing fields and meanings. New handlers must understand older payloads. Requests, replies and events retain their original bytes and reader generation through retries and storage conversions. A reply carries its own encoder's generation even when the request was older.

Takt executions with unresolved external addresses remain pinned to their original definition. A migration must resolve those operations or use explicit safe reconciliation; changing a definition version cannot invent a new operation identity. Sources: persisted memory, upgrade contract, fleet-evolution tests.

A workflow across canisters

The generated Reactor example deploys the same actor as A, B and C. One shared Reactor and Takt runtime serve many executions inside each actor.

On A, a typed Parallel graph creates one counter operation for B and one for C. Each destination endpoint dispatches a local Rechain action and returns its block reference. Reactor batches the independently queued operations and their addressed results. Takt's join waits for the required branch results before completing A's execution.

Many executions can share a batch while keeping separate addresses and progress. B and C commit independently; a successful B result does not imply C succeeded. The returned block reference identifies that participant's local commit, not a global block shared by all canisters. The example's counter reconciliation policy is not a financial settlement protocol.

For the marketplace workflow, the same ownership split holds: Takt determines the next safe step, Reactor moves the explicitly adapted request, and each participant's Rechain reducer changes only its local business state. A native actor or management call remains native unless a specific adapter exposes it through Reactor. Sources: example composition, Reactor integration status.

Diagnostics and operational checklist

API Useful observation
reactor.scheduler.stats() Shared readiness, deadlines and managed callback capacity.
reactor.stats() Peers, outgoing/incoming items, completions and active exchanges.
reactor.metrics() Batch attempts, acknowledgements, failures and logical-frame counters.
reactor.inbox(after, limit) Paginated retained entries, blocked state and required reader generation.
reactor.resume(key) Resume a repaired blocked entry; it does not upgrade its decoder.
reactor.events.stats() Current subscriptions, pending publications and recipients.

processedRequests + processedNotifications counts completed destination router deliveries. It excludes replies, events, expired requests, duplicates and deferred/blocked attempts. It is therefore different from both physical batch calls and completed round trips. Diagnostic metrics are transient and reset on upgrade. Takt supplies the graph, timeline and instruction views; Reactor does not create another permanent telemetry chain.

Before using an endpoint in production-shaped application code:

  • Authenticate ingress and peers; check application and spender authority inside the handler.
  • Keep handlers synchronous and bounded; return expected errors instead of trapping.
  • Persist exact requests and operation identities before effects; interpret ACKs only as storage.
  • Save and restore outstanding addresses; consume results atomically with progress.
  • Subscribe before starting a producer; give every one-shot interest a distinct address.
  • Bound application admission separately from Reactor's wire and callback settings.
  • Test lost ACKs, unavailable peers, late results, malformed contracts and staggered upgrades.
  • Inspect retained backlog and repair blocked work without resetting cursors or changing unresolved identities.

The repository's runtime and compiler-negative tests exercise these contracts. Its bounded formal models check selected designs and defects; they are not a proof of the full Motoko implementation. Sources: diagnostics, test inventory, formal-model scope.

Sources

Researched against the local Reactor checkout at be86e32e6638 on 2026-10-14. These links reference the sibling working repositories. The current README and implementation take precedence over historical proposals in design notes.

Source What to consult it for
Reactor README Usage, current defaults, integration status and operational contracts.
Public composition and typed router Constructor, API aliases, endpoint codecs and synchronous handlers.
Transport Prefix ACKs, request/result addresses, retry, expiry, inspection and repair.
Scheduler Priority batches, deadlines, continuations and callback permits.
Events One-shot subscriptions and durable publication fanout.
Memory V1 Persisted contracts, wire types and saved defaults.
Transport tests, prefix tests, addressed-wake tests Lost ACKs, duplicate suppression, early and late completions.
Scheduler tests and evolution tests Priority, bounded turns, stop/start recovery and mixed reader generations.
Takt Reactor adapter and coordination adapter Prepared requests, addressed workflow progress and child/event integration.
Running example Generated fan-out with real local participant commits.