Hands-on journey
Learn CoAkka Runtime with Node.js
Beginner learns targets, routes and outcomes inside one Node.js process. Advanced keeps the target stable while moving the handler to a peer, uses File Lane or Stream Lane for specialized data, then reads Monitor without blocking the event loop.
Beginner · 01 / 04
Install the package and run
This lesson requires Node.js 22 or newer and npm. The official connector contains the native CoAkka Runtime for its packaged target; you do not need to clone a repository or set a library path.
1. Check the environment
node --version
npm --version2. Create a project and install the connector
mkdir coakka-node-demo
cd coakka-node-demo
npm init -y
npm install [email protected]The lesson pins [email protected] exactly.
A .mjs file uses ESM without changing
package.json. Read the version rule in the portal.
3. Paste the file into your IDE and run it
import { Buffer } from "node:buffer";
import { RuntimeHost, localRoute } from "coakka-runtime-node";
const target = "samples.echo";
const runtime = RuntimeHost.start({
systemName: "node-first-run",
nodeId: "node-first-run-1",
routes: [localRoute(target)],
});
try {
runtime.registerPayloadHandler(target, (payload) =>
Buffer.concat([Buffer.from("accepted-"), payload]),
);
const reply = await runtime.askPayload(
"node-first-run",
target,
Buffer.from("hello"),
2000,
);
console.log(Buffer.from(reply).toString("utf8"));
} finally {
await runtime.close();
}
node main.mjsExpected output
accepted-hello
RuntimeHost.start- Creates one CoAkka Runtime owner for the process lifecycle. One Node.js process may have one active host.
localRoute(target)- Places the target handler in this process; omitted network intent lets Core select Embedded.
registerPayloadHandler- Registers an application function that accepts and returns bytes.
askPayload- Sends source, target, byte payload and timeout; the Promise ends in a reply or terminal error.
await runtime.close()- Waits for CoAkka Runtime to stop and release resources before process exit.
Beginner · 02 / 04
Name the work
Replace main.mjs with this file. The
orders.quote target is the business address; the route
selects where it runs and the handler calculates the quote. The
caller does not depend on whether the handler is a JavaScript
function or later moves to another peer.
import { Buffer } from "node:buffer";
import { RuntimeHost, localRoute } from "coakka-runtime-node";
const target = "orders.quote";
function quote(payload) {
const quantity = Number.parseInt(Buffer.from(payload).toString("utf8"), 10);
if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > 100) {
return Buffer.from("invalid quantity");
}
return Buffer.from(`${quantity * 120_000} VND`);
}
const runtime = RuntimeHost.start({
systemName: "quote-demo",
nodeId: "quote-demo-1",
routes: [localRoute(target)],
});
try {
runtime.registerPayloadHandler(target, quote);
for (const quantity of ["1", "2"]) {
const reply = await runtime.askPayload(
"checkout",
target,
Buffer.from(quantity),
2000,
);
console.log(`quantity=${quantity} quote=${Buffer.from(reply).toString("utf8")}`);
}
} finally {
await runtime.close();
}
node main.mjsExpected output
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Add "3" to the input array. This remains one process so
the lesson establishes the contract before adding networking.
Beginner · 03 / 04
Read a deadletter
The first call intentionally targets orders.missing.
The connector throws DeadletterError; its
deadletter object contains Core-issued reason facts and
the original envelope. The application does not parse error text to
infer an outcome.
import { Buffer } from "node:buffer";
import {
DeadletterError,
RuntimeHost,
localRoute,
} from "coakka-runtime-node";
const target = "orders.quote";
const runtime = RuntimeHost.start({
systemName: "route-miss-demo",
nodeId: "route-miss-demo-1",
routes: [localRoute(target)],
});
try {
runtime.registerPayloadHandler(target, (payload) =>
Buffer.from(`${Number(Buffer.from(payload).toString("utf8")) * 120_000} VND`),
);
try {
await runtime.askPayload(
"checkout",
"orders.missing",
Buffer.from("2"),
2000,
);
} catch (error) {
if (!(error instanceof DeadletterError)) throw error;
console.log(
`deadletter reason=${error.deadletter.reason} target=${error.deadletter.original_envelope?.target}`,
);
}
const reply = await runtime.askPayload(
"checkout",
target,
Buffer.from("2"),
2000,
);
console.log(`quantity=2 quote=${Buffer.from(reply).toString("utf8")}`);
} finally {
await runtime.close();
}
node main.mjsExpected output
deadletter reason=2 target=orders.missing quantity=2 quote=240000 VND
Reason 2 means ROUTE_MISS. The configuration
has no route for orders.missing. The next call uses
orders.quote and receives a reply.
Look up deadletter reason codes.
Beginner · 04 / 04
Integrate the host
Keep one RuntimeHost for the application lifecycle,
register handlers during startup and await close from the shutdown
hook. requestQuote is the seam for an existing API, job
or consumer.
import { Buffer } from "node:buffer";
import { RuntimeHost, localRoute } from "coakka-runtime-node";
const target = "orders.quote";
const runtime = RuntimeHost.start({
systemName: "checkout-app",
nodeId: "checkout-app-1",
routes: [localRoute(target)],
});
function quote(payload) {
const quantity = Number(Buffer.from(payload).toString("utf8"));
return Buffer.from(`${quantity * 120_000} VND`);
}
async function requestQuote(quantity) {
const reply = await runtime.askPayload(
"checkout",
target,
Buffer.from(String(quantity)),
2000,
);
return Buffer.from(reply).toString("utf8");
}
try {
runtime.registerPayloadHandler(target, quote);
console.log("order quote:", await requestQuote(3));
} finally {
await runtime.close();
}
node main.mjsExpected output
order quote: 360000 VND
Do not create a host per request. The active host owns native runtime state, handlers and pending operations in this process.
Advanced · 05
Move the handler to a peer
The target and caller stay unchanged. The quote process opens a
NETWORK_NODE listener on loopback; checkout is
OUTBOUND_ONLY and routes to the advertised address.
This is direct distributed operation without Kubernetes.
1. Quote process
import { Buffer } from "node:buffer";
import {
RuntimeHost,
localRoute,
networkNode,
} from "coakka-runtime-node";
const target = "orders.quote";
const runtime = RuntimeHost.start({
systemName: "quote-service",
nodeId: "quote-service-1",
network: networkNode("127.0.0.1", 19321, "127.0.0.1", 19321),
routes: [localRoute(target)],
});
runtime.registerPayloadHandler(target, (payload) => {
const quantity = Number(Buffer.from(payload).toString("utf8"));
return Buffer.from(`${quantity * 120_000} VND`);
});
let requestStop;
const stopped = new Promise((resolve) => {
requestStop = resolve;
});
process.once("SIGINT", requestStop);
process.once("SIGTERM", requestStop);
console.log("quote service ready at 127.0.0.1:19321");
await stopped;
await runtime.close();
node quote-service.mjsWait for quote service ready at 127.0.0.1:19321 and keep the terminal open.
2. Checkout process
import { Buffer } from "node:buffer";
import {
RouteStrategy,
RuntimeHost,
outboundOnlyNetwork,
} from "coakka-runtime-node";
const target = "orders.quote";
const runtime = RuntimeHost.start({
systemName: "checkout",
nodeId: "checkout-1",
network: outboundOnlyNetwork(),
routes: [
{
target,
strategy: RouteStrategy.SINGLE_OWNER,
endpoints: [{ host: "127.0.0.1", port: 19321, weight: 1, flags: 0 }],
},
],
});
try {
const reply = await runtime.askPayload(
"checkout",
target,
Buffer.from("3"),
2000,
);
console.log("order quote:", Buffer.from(reply).toString("utf8"));
} finally {
await runtime.close();
}
node checkout.mjsExpected output
order quote: 360000 VND
networkNode(bind, advertise)- Opens the listener and advertises the address peers use. Loopback is only for this same-host lesson.
outboundOnlyNetwork()- Checkout makes outbound calls without opening a request listener.
SINGLE_OWNER- The target has exactly one owner endpoint in this route snapshot.
weight: 1- Endpoint weight matters to weighted strategies; it does not create retry policy.
Look up network and route fields · Learn infrastructure-independent failover, retry and discovery
Advanced · 06
Transfer a file with File Lane
File Lane transfers an immutable file by exact size and SHA-256 instead of putting file bytes in an Envelope. This loopback example uses an exact-owner grant; a real application moves that grant over its trusted control plane.
import { Buffer } from "node:buffer";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
FileLane,
FileLaneFlag,
FileTransferDirection,
} from "coakka-runtime-node";
async function waitForTerminal(lane, transferId, direction) {
let snapshot = lane.transfer(transferId, direction);
while (!snapshot.terminal) {
snapshot = await lane.waitTransfer(
transferId,
direction,
snapshot.updateSequence,
2000,
);
}
return snapshot;
}
const work = mkdtempSync(join(tmpdir(), "coakka-node-file-"));
const sourcePath = join(work, "quote.txt");
const destinationPath = join(work, "received-quote.txt");
const transferId = "file-lane-demo";
const authorizationToken = "local-demo-token";
const receiver = FileLane.openOwned(
{ flags: FileLaneFlag.RECEIVER, queueCapacity: 1 },
{ ownerInstanceId: "file-receiver-1", advertisedHost: "127.0.0.1" },
);
const sender = FileLane.open({ flags: FileLaneFlag.SENDER, queueCapacity: 1 });
try {
writeFileSync(sourcePath, "CoAkka Runtime file lane demo\n");
const digest = FileLane.sha256(sourcePath);
const grant = receiver.prepareReceiveGrant({
transferId,
authorizationToken,
destinationPath,
expectedSize: digest.size,
expectedSha256: digest.sha256,
});
sender.submitSend(grant.toSendSpec(sourcePath, 5000));
const [send, receive] = await Promise.all([
waitForTerminal(sender, transferId, FileTransferDirection.SEND),
waitForTerminal(receiver, transferId, FileTransferDirection.RECEIVE),
]);
if (!send.completed || !receive.completed) {
throw new Error(`file transfer failed: send=${send.result} receive=${receive.result}`);
}
const received = readFileSync(destinationPath);
if (!received.equals(Buffer.from("CoAkka Runtime file lane demo\n"))) {
throw new Error("received file content does not match");
}
console.log(`file lane transferred: ${received.byteLength} bytes`);
console.log("sender success:", send.completed);
console.log("receiver success:", receive.completed);
sender.forget(transferId, FileTransferDirection.SEND);
receiver.forget(transferId, FileTransferDirection.RECEIVE);
} finally {
await Promise.all([sender.close(), receiver.close()]);
rmSync(work, { recursive: true, force: true });
}
node file-lane.mjsExpected output
file lane transferred: 30 bytes sender success: true receiver success: true
Prepare the receiver before the sender. Forget retained records
only after both sides are terminal and completed. The
fixed token is for loopback teaching only; never log production tokens.
Look up the shared File Lane contract · Look up the Node.js API
Advanced · 07
Send frames with Stream Lane
Stream Lane carries one ordered, bounded frame sequence from one publisher to one subscriber. Source and consumer callbacks must be synchronous and bounded. Consumer data is borrowed only for the callback, so the example copies it immediately.
import { Buffer } from "node:buffer";
import {
StreamConsumerDecision,
StreamDirection,
StreamLane,
StreamLaneFlag,
StreamSourceSignal,
} from "coakka-runtime-node";
async function waitForTerminal(lane, sessionId, direction) {
let snapshot = lane.session(sessionId, direction);
while (!snapshot.terminal) {
snapshot = await lane.waitSession(
sessionId,
direction,
snapshot.updateSequence,
2000,
);
}
return snapshot;
}
const frames = ["temperature=21.5", "temperature=21.7", "temperature=21.6"];
const received = [];
const sessionId = "temperature-demo";
let nextFrame = 0;
const publisher = StreamLane.openOwned(
{ flags: StreamLaneFlag.PUBLISHER, capacity: 1, maxFrameBytes: 64 },
{ ownerInstanceId: "stream-publisher-1", advertisedHost: "127.0.0.1" },
);
const subscriber = StreamLane.open({
flags: StreamLaneFlag.SUBSCRIBER,
capacity: 1,
maxFrameBytes: 64,
});
try {
const grant = publisher.preparePublishGrant({
sessionId,
authorizationToken: "local-demo-token",
formatId: 1,
maxFrameBytes: 64,
source(destination) {
if (nextFrame === frames.length) return StreamSourceSignal.END;
const frame = Buffer.from(frames[nextFrame]);
destination.set(frame);
nextFrame += 1;
return { size: frame.byteLength };
},
});
subscriber.subscribe(
grant.toSubscribeSpec(256, (data, metadata) => {
received.push({ sequence: metadata.sequence, text: Buffer.from(data).toString("utf8") });
return StreamConsumerDecision.CONTINUE;
}, 5000),
);
const [publish, subscribe] = await Promise.all([
waitForTerminal(publisher, sessionId, StreamDirection.PUBLISH),
waitForTerminal(subscriber, sessionId, StreamDirection.SUBSCRIBE),
]);
if (!publish.completed || !subscribe.completed) {
throw new Error(`stream failed: publish=${publish.result} subscribe=${subscribe.result}`);
}
for (const frame of received) {
console.log(`frame ${frame.sequence}: ${frame.text}`);
}
console.log(`stream lane delivered: ${received.length} frames`);
publisher.forget(sessionId, StreamDirection.PUBLISH);
subscriber.forget(sessionId, StreamDirection.SUBSCRIBE);
} finally {
await Promise.all([subscriber.close(), publisher.close()]);
}
node stream-lane.mjsExpected output
frame 1: temperature=21.5 frame 2: temperature=21.7 frame 3: temperature=21.6 stream lane delivered: 3 frames
formatId is an opaque application contract. Core owns
ordering, flow control and session state; the application owns frame
encoding and meaning.
Look up the shared Stream Lane contract · Look up the Node.js API
Advanced · 08
Observe CoAkka Runtime with Monitor
Enable collection at startup, confirm that Core enabled it, then
read copied snapshots. awaitNext is a deadline-bounded
Promise; it does not turn the event loop into a polling loop, and no
signal is not itself an error.
import { Buffer } from "node:buffer";
import { RuntimeHost, localRoute } from "coakka-runtime-node";
const target = "orders.quote";
function printMonitor(label, view) {
console.log(
`${label}: signal=${view.signalCount} generation=${view.health.appliedGeneration} ` +
`routes=${view.stats.routeCount} queue=${view.stats.localWorkQueueDepth}/` +
`${view.stats.localWorkQueueCapacity} rejected=${view.stats.queueRejectedCount}`,
);
}
const runtime = RuntimeHost.start({
systemName: "quote-monitor",
nodeId: "quote-monitor-1",
routes: [localRoute(target)],
enableMonitor: true,
});
try {
runtime.registerPayloadHandler(target, (payload) => {
const quantity = Number(Buffer.from(payload).toString("utf8"));
return Buffer.from(`${quantity * 120_000} VND`);
});
console.log("monitor enabled:", runtime.monitor.isEnabled());
const initial = await runtime.monitor.awaitAppliedGenerationAtLeast(1, 1000);
if (initial === null) throw new Error("route generation was not visible");
printMonitor("initial", initial);
const reply = await runtime.askPayload(
"checkout",
target,
Buffer.from("3"),
2000,
);
console.log("order quote:", Buffer.from(reply).toString("utf8"));
const update = await runtime.monitor.awaitNext(250);
if (update === null) {
console.log("monitor update: no notification in 250ms; read current snapshot");
} else {
console.log("monitor update: received");
}
printMonitor("latest", update ?? runtime.monitor.snapshot());
console.log("monitor sample complete");
} finally {
await runtime.close();
}
node monitoring.mjsOne verified run
monitor enabled: true initial: signal=0 generation=1 routes=1 queue=0/4096 rejected=0 order quote: 360000 VND monitor update: received latest: signal=1 generation=1 routes=1 queue=0/4096 rejected=0 monitor sample complete
signalCount counts coalesced refresh signals, not
requests. The app owns export, dashboards and alerts; Core owns facts.
Understand the operations contract · Read effective state with Node.js