Runtime reuse and Daemon

Start with the Runtime lifecycle of a single CLI command, then learn how a daemon owns a Worker Runtime pool and reuses loaded Units across calls.

When a CLI command runs, the expensive part is usually not argument parsing. It is turning a Unit1 into a live Univer that can be read and written: creating Univer, installing plugins, opening the collaboration backend, loading the checkpoint, applying changesets, and waiting for formulas to finish calculating.

Two Runtime2 capabilities perform this work, and this page covers both:

  • @univer-cli/univer-collaboration-runtime loads a Unit and operates on it in the current process;
  • @univer-cli/univer-collaboration-runtime-pool places Runtimes in Workers and leases, reuses, and retires them by Unit identity.

A Worker Runtime survives across CLI invocations only when a long-lived process owns it. In this architecture, that owner is a local daemon.

Start with three lifecycles

Reuse depends on keeping three lifetimes apart:

ObjectCreatedEndsOwns
CLI processOn every command runAfter the command prints its resultArguments, one request, and output formatting
Daemon processOn the first request, or when started directlyWhen stopped, restarted for an upgrade, or crashedRuntime pool, business handlers, and local socket
Worker RuntimeWhen the pool first encounters a keyOn TTL/LRU3 eviction, invalidation, daemon shutdown, or Worker crashOne Worker, one backend handle, one loaded Unit, and collaboration state

One ownership rule governs the design: the CLI makes one call, the daemon owns the pool, the pool owns Workers, and each Worker owns a Runtime.

100%

The daemon forwards only the JSON requests that the application defines. Snapshots, changesets, and blocks are read by the backend inside the Worker, so they never pass through the CLI or the daemon.

Step 1: load a Runtime directly for every CLI command

The simplest implementation creates @univer-cli/univer-collaboration-runtime inside a Commander action and closes it when the operation completes:

TypeScript
const runtime = await runtimeFactory.load(unitId, unitType);try {  const pulled = await runtime.pull();  if (pulled.status === "conflict") throw new Error(pulled.conflict.message);  const execution = await runtime.execute({ mode: "write", code });  let commit = await runtime.commit();  if (commit.status === "pull-required") {    const repulled = await runtime.pull();    if (repulled.status === "conflict") throw new Error(repulled.conflict.message);    commit = await runtime.commit();  }  return { execution, commit };} finally {  await runtime.close();}

runtimeFactory comes from createUniverCollaborationRuntimeFactory(). From load to close, a Runtime is bound to exactly one Unit and keeps that Unit's current revision, pending mutations, awaiting changesets, and conflict state. The caller must also check the final commit status: only confirmed and nothing-to-commit mean the operation has finished.

A load() call does more than read a file. It performs the following steps in order:

  1. Open the collaboration backend supplied by the application.
  2. Create a headless Univer and install the collaboration capabilities.
  3. Load UnitData or a Snapshot checkpoint.
  4. Replay the changesets carried by the checkpoint.
  5. Fetch and replay the gap between the checkpoint and the latest remote revision.
  6. Wait until the latest results from the installed formula modules have been applied.
  7. Return a Runtime that can run execute(), pull(), and commit().

A complete one-off invocation proceeds as follows:

100%

Ownership is direct here, and a failure leaves no state behind, so this arrangement suits low-frequency commands and one-off tasks. The cost is that the next CLI command starts a new Node.js process and repeats the entire loading sequence, so it cannot reuse the Univer and Unit state that the previous command built.

Step 2: host the Runtime in a Worker pool

@univer-cli/univer-collaboration-runtime-pool maintains a separate Worker process and Collaboration Runtime for every resident key. The application supplies a Worker entry; the backend, credentials, and Univer are all created inside the Worker:

TypeScript
import { defineUniverCollaborationRuntimeWorker } from "@univer-cli/univer-collaboration-runtime-pool";export default defineUniverCollaborationRuntimeWorker({  async createRuntime(init: { unitId: string; unitType: number }) {    return createRuntimeFromApplicationInit(init);  },});

The Worker entry must point to a built JavaScript ESM file. init is sent to the Worker only on a cold creation, and it must be compatible with structured clone.

The caller does not need to design a separate Runtime RPC layer. The lease already proxies the public APIs, including getState(), execute(), fetch(), pull(), commit(), and exportUnitData():

TypeScript
import { createUniverCollaborationRuntimePool } from "@univer-cli/univer-collaboration-runtime-pool";const pool = createUniverCollaborationRuntimePool({  entry: new URL("./collaboration-worker.js", import.meta.url),});const lease = await pool.acquire({  key: targetKey,  init: { unitId, unitType },});try {  await lease.pull();  const result = await lease.execute({ mode: "read", code });  console.log(result.value);} catch (error) {  await lease.invalidate();  throw error;} finally {  await lease.release();}

key identifies which Runtime to reuse; it is not merely a query argument. The same key must always mean the same Unit, the same collaboration state chain, and compatible initialization semantics. A plain Unit and a Worktree draft must use different keys even when they share the same unitId.

The pool has four behaviors that determine reuse:

  • Only one lease holds a key at a time. Concurrent requests wait in FIFO order, so two calls cannot modify the same live state simultaneously;
  • release() returns a trusted Runtime to the idle cache, where the next request for that key can reuse it;
  • invalidate() marks the state as no longer trustworthy. The Worker and its Runtime are destroyed, and the next request performs a cold load;
  • Idle Runtimes can be evicted by TTL and LRU. Timeouts, Worker crashes, and protocol errors also invalidate the current instance.

If the pool itself lives inside a short-lived CLI process, however, reuse still cannot cross command boundaries:

100%

Workers provide process isolation for the Runtime, exclusive leasing, and termination on failure. To reuse Workers across CLI invocations, the pool still needs an owner that outlives any single command.

Step 3: make the daemon the long-lived pool owner

The daemon is an on-demand local Node.js process. The CLI calls it through a Unix socket or a Windows named pipe. Exiting the CLI does not terminate the daemon, so its pool, Workers, and idle Runtimes remain alive.

Create the pool once in the daemon entry, then acquire a lease in each business handler:

TypeScript
import { createDaemonServer, DAEMON_SOCKET_ENV } from "@univer-cli/daemon";import { createUniverCollaborationRuntimePool } from "@univer-cli/univer-collaboration-runtime-pool";const socketPath = process.env[DAEMON_SOCKET_ENV];if (!socketPath) throw new Error(`${DAEMON_SOCKET_ENV} is required`);const pool = createUniverCollaborationRuntimePool({  entry: new URL("./collaboration-worker.js", import.meta.url),  cache: { idleTtlMs: 5 * 60_000, maxEntries: 20 },});const server = createDaemonServer({  identity: { id: "my-cli", version: "1.0.0" },  socketPath,  onShutdown: () => pool.close(),});server.handle("unit.execute", async (payload) => {  const input = parseExecuteRequest(payload);  const lease = await pool.acquire({    key: input.targetKey,    init: { unitId: input.unitId, unitType: input.unitType },  });  try {    const pulled = await lease.pull();    if (pulled.status === "conflict") throw new Error(pulled.conflict.message);    const execution =      input.mode === "read"        ? await lease.execute({ mode: "read", code: input.code })        : await lease.execute({ mode: "write", code: input.code });    const commit = input.mode === "write" ? await commitWithPull(lease) : null;    return { commitStatus: commit?.status ?? null, value: execution.value };  } catch (error) {    await lease.invalidate();    throw error;  } finally {    await lease.release();  }});await server.listen();

The application defines parseExecuteRequest() and the targetKey rules. The daemon provides local transport and lifecycle management only; it does not understand Units, Runtimes, or the collaboration protocol. Shutting down the daemon must call pool.close(), so idle and active Workers have a clear final owner. In this example, commitWithPull() handles the pull and commit sequence after pull-required and checks the final commit status. Any unhandled error invalidates the current lease, which keeps the example conservative.

An ordinary CLI command now sends one business request to the daemon:

TypeScript
import { createDaemonClient } from "@univer-cli/daemon";const client = createDaemonClient({  entry: new URL("./daemon-entry.js", import.meta.url),  identity: { id: "my-cli", version: "1.0.0" },  socketPath,});const result = await client.request("unit.execute", {  targetKey,  unitId,  unitType,  mode,  code,});

When the socket does not exist, the client starts the configured daemon entry, waits for the identity and protocol handshake, and then sends the request. If a compatible daemon is already running, the client reuses it directly.

Step 4: compare the first and subsequent requests

The first access to a key follows the cold path: the daemon may need to start, and the pool must create a Worker and a Runtime.

100%

Subsequent access to the same key follows the hot path. The CLI process starts again, but the expensive Runtime load is not repeated:

100%

Reuse applies to a live Runtime that has already been created and loaded. It does not bypass collaboration consistency. After acquiring a lease, the caller should normally call pull(); after commit(), it should inspect the final status and handle pull-required, retry, unknown, or conflict.

Which costs disappear and which remain

CostLoad Runtime directly every timeDaemon + Worker pool
CLI startup, argument parsing, and result outputEvery timeEvery time
Local socket JSON request/responseNoneEvery time
Daemon startup and module loadingNoneFirst request or after a restart
Worker startup and Worker entry loadingNo WorkerOn cold creation for each key
Creating Univer and installing pluginsEvery timeOn cold creation for each key
Loading checkpoint, replaying initial changesets, waiting for formulasEvery timeOn cold creation for each key
pull() for changesets created while idleEvery timeUsually still required every time
execute() and commit()Every timeEvery time
Idle memory, backend handle, and Worker processReleased when the command exitsRetained until eviction, invalidation, or daemon shutdown

Reuse trades resident memory and Worker count for lower startup latency on later calls. Set idleTtlMs, maxEntries, the open timeout, and the operation timeouts from pool events and measured latency, rather than retaining every Unit indefinitely.

Concurrency, failures, and shutdown

Four rules describe the behavior of the system:

  1. Concurrent requests for the same key wait. A live Runtime belongs to one lease at a time, so interleaved calls cannot modify collaboration state.
  2. Different keys can run in parallel in different Workers. The cost is a separate Worker and Runtime allocation for every resident key.
  3. Only trusted state can be reused. Call release() after an operation succeeds and local mutations have been cleared. Call invalidate() after a timeout, a crash, or a protocol error, or whenever the application cannot confirm the local state.
  4. Shutdown responsibility flows downward. The CLI completes one request; daemon shutdown calls pool.close(); the pool terminates Workers and closes their Runtimes and backends.

For low-frequency commands where one-off latency is acceptable, using @univer-cli/univer-collaboration-runtime directly is the simplest option. Combine the daemon with @univer-cli/univer-collaboration-runtime-pool only when measurements show that repeated loading is the dominant cost and the application can accept a resident process and its memory usage.

See Package catalog for the complete package list.

Footnotes

  1. A Unit is one document instance, such as a workbook or a text document. A worksheet is part of a workbook, not a separate Unit. ↩

  2. Here, Runtime means the live Univer instance and the resources used to operate on a loaded Unit, not the Node.js executable or the saved document snapshot. ↩

  3. TTL evicts an idle cached Runtime after its configured lifetime; LRU evicts the least recently used entries when capacity is limited. These policies release runtime resources; they do not delete the persisted Unit. ↩

How is this guide?

© 2026 DreamNum Co., Ltd.