Hands-on journey
Learn CoAkka Runtime with Bun
Beginner learns targets, routes and outcomes inside one Bun 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. Blocking lane loops stay off the main event loop.
Beginner · 01 / 04
Install the package and run
This lesson requires Bun 1.3.14 or newer. 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
bun --version2. Create a project and install the connector
mkdir coakka-bun-demo
cd coakka-bun-demo
bun init -y
bun add [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 { BunRuntimeHost, localRoute } from "coakka-runtime-bun";
const target = "samples.echo";
const runtime = BunRuntimeHost.start({
systemName: "bun-first-run",
nodeId: "bun-first-run-1",
routes: [localRoute(target)],
});
try {
runtime.registerPayloadHandler(target, (payload) =>
Buffer.concat([Buffer.from("accepted-"), payload]),
);
const reply = await runtime.askPayload(
"bun-first-run",
target,
Buffer.from("hello"),
2000,
);
console.log(Buffer.from(reply).toString("utf8"));
} finally {
await runtime.close();
}
bun run main.mjsExpected output
accepted-hello
BunRuntimeHost.start- Creates one CoAkka Runtime owner for the process lifecycle. One Bun 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 { BunRuntimeHost, localRoute } from "coakka-runtime-bun";
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 = BunRuntimeHost.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();
}
bun run 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,
BunRuntimeHost,
localRoute,
} from "coakka-runtime-bun";
const target = "orders.quote";
const runtime = BunRuntimeHost.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();
}
bun run main.mjsExpected output
deadletter reason=2 target=orders.missing quantity=2 quote=240000 VND
The reason code is contract data, not text for an app to reinterpret. Look up shared Deadletter fields and checklists.
Beginner · 04 / 04
Integrate the host
Keep one BunRuntimeHost 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 { BunRuntimeHost, localRoute } from "coakka-runtime-bun";
const target = "orders.quote";
const runtime = BunRuntimeHost.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();
}
bun run 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_BUN 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 {
BunRuntimeHost,
localRoute,
networkNode,
} from "coakka-runtime-bun";
const target = "orders.quote";
const runtime = BunRuntimeHost.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();
bun run 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,
BunRuntimeHost,
outboundOnlyNetwork,
} from "coakka-runtime-bun";
const target = "orders.quote";
const runtime = BunRuntimeHost.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();
}
bun run checkout.mjsExpected output
order quote: 360000 VND
networkBun(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-bun";
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-bun-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 });
}
bun run 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.
Bun note. This CLI sample
deliberately dedicates the process to the transfer. In an HTTP
server or event-loop application, run the waitTransfer
loop in a Worker or dedicated process; never share a lane owner across Workers.
Advanced · 07
Send frames with Stream Lane
Stream Lane carries one ordered, bounded frame sequence from one
publisher to one subscriber. Bun uses its own mailbox surface: the
publisher calls push/end and the subscriber
calls poll. This is not Node.js's callback API.
import { Buffer } from "node:buffer";
import {
StreamDirection,
StreamLane,
StreamLaneFlag,
} from "coakka-runtime-bun";
const frames = ["temperature=21.5", "temperature=21.7", "temperature=21.6"];
const received = [];
const sessionId = "temperature-demo";
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,
mailboxFrames: 4,
});
for (const text of frames) {
if (!publisher.push(sessionId, Buffer.from(text))) {
throw new Error("publisher mailbox is full");
}
}
if (!publisher.end(sessionId)) {
throw new Error("publisher mailbox cannot accept the end marker");
}
subscriber.subscribe(grant.toSubscribeSpec(256, { mailboxFrames: 4 }));
for (let turn = 0; turn < 5000; turn += 1) {
let frame;
while ((frame = subscriber.poll(sessionId)) !== null) {
received.push({
sequence: frame.metadata.sequence,
text: Buffer.from(frame.bytes).toString("utf8"),
});
}
const publish = publisher.session(sessionId, StreamDirection.PUBLISH);
const subscribe = subscriber.session(sessionId, StreamDirection.SUBSCRIBE);
if (publish.terminal && subscribe.terminal) {
if (!publish.succeeded || !subscribe.succeeded) {
throw new Error(`stream failed: publish=${publish.result} subscribe=${subscribe.result}`);
}
break;
}
Bun.sleepSync(1);
}
let frame;
while ((frame = subscriber.poll(sessionId)) !== null) {
received.push({
sequence: frame.metadata.sequence,
text: Buffer.from(frame.bytes).toString("utf8"),
});
}
if (received.length !== frames.length) {
throw new Error(`expected ${frames.length} frames, received ${received.length}`);
}
for (const item of received) {
console.log(`frame ${item.sequence}: ${item.text}`);
}
console.log(`stream lane delivered: ${received.length} frames`);
publisher.forget(sessionId, StreamDirection.PUBLISH);
subscriber.forget(sessionId, StreamDirection.SUBSCRIBE);
} finally {
subscriber.close();
publisher.close();
}
bun run 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.
Worker rule. poll,
waitSession and mailbox loops can block the event loop.
The CLI sample intentionally uses the main thread; a server must
run this loop in a Worker or dedicated process and keep each lane owner local to it.
Look up the shared Stream Lane contract · Look up the Bun 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 { BunRuntimeHost, localRoute } from "coakka-runtime-bun";
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 = BunRuntimeHost.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();
}
bun run 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 Bun