Hands-on learning

Learn CoAkka Runtime with Go

CoAkka Runtime is a distributed application runtime. Start Embedded to learn targets, routes and outcomes in one Go process; Advanced moves the handler to a peer, selects File Lane or Stream Lane for specialized data, then observes the result with Monitor.

Beginner · 01 / 04

Set up and get a first reply

1. Set up the environment

Run these checks in your IDE terminal. Use Go 1.22.12 or later and a C compiler for cgo. On native Windows ARM64, use Go 1.25.5 and a matching ARM64 C compiler. Use your compiler's command in place of cc if it has a different name.

Terminal
go version
go env CGO_ENABLED
cc --version

Once go env CGO_ENABLED prints 1, create a module and install the released Go package.

Terminal
mkdir coakka-go-demo
cd coakka-go-demo
go mod init example.com/coakka-go-demo
go get github.com/phuong-tran/coakka-runtime-go/[email protected]
Read the version

In v3.3.2, 3.3 identifies the Core generation and 2 is the Go connector revision on that Core. A Go-only fix can advance the final number while keeping Core 3.3.

Look up the Go package and version in the portal

The connector is installed from the official published Go module. View release v3.3.2 on pkg.go.dev (optional)

2. Configure CoAkka Runtime in one process

In Embedded mode, the caller and handler live in the same Go application. CoAkka Runtime delivers the request within that process without opening a network port. Build your application logic here and move the work to a peer when you need to.

SystemName
go-first-run names the example system.
NodeID
go-first-run-node identifies this CoAkka Runtime instance. Give each instance its own ID when running several.
Routes
LocalRouteDefault(target) places samples.echo in this process. Register the handler on the same target.
Network
EmbeddedNetwork() selects single-process delivery.
runtimeLibPath
The "" argument to StartRuntimeHost lets the connector find the CoAkka Runtime library supplied by the package.

AskPayload takes the caller name, target, payload, wait budget and delivery hint. The example sends hello, waits up to 2*time.Second and follows the declared route using DeliveryHintRouterDefault. Look up each request parameter

3. Run and check

Create main.go in the new directory. Paste the full file into your IDE, then run the command below.

main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

func run() (err error) {
	const target = "samples.echo"
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "go-first-run",
		NodeID:     "go-first-run-node",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.EmbeddedNetwork(),
	}, "")
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()

	if err := host.RegisterPayloadHandler(target, func(input []byte) []byte {
		return append([]byte("accepted-"), input...)
	}); err != nil {
		return err
	}

	reply, err := host.AskPayload("first-run", target, []byte("hello"),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	if err != nil {
		return err
	}
	if string(reply) != "accepted-hello" {
		return fmt.Errorf("unexpected reply: %q", reply)
	}
	fmt.Println(string(reply))
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly .

Expected output

accepted-hello

If the build reports a cgo error, check Go, the compiler and the target architecture. The macOS sample explains how to choose the Xcode SDK if the linker reports an architecture error.

View the Go sample on GitHub (optional)

Beginner · 02 / 04

Name the work

Replace main.go with this file and run it again. The target orders.quote names the work. The route says where to send it. The handler calculates a sample price of 120,000 VND per item.

main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

func quote(input []byte) []byte {
	quantity, err := strconv.Atoi(string(input))
	if err != nil || quantity < 1 || quantity > 100 {
		return []byte("invalid quantity")
	}
	return []byte(fmt.Sprintf("%d VND", quantity*120_000))
}

func run() (err error) {
	const target = "orders.quote"
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-demo",
		NodeID:     "quote-demo-node",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.EmbeddedNetwork(),
	}, "")
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()
	if err := host.RegisterPayloadHandler(target, quote); err != nil {
		return err
	}

	for _, quantity := range []string{"1", "2"} {
		reply, err := host.AskPayload("checkout", target, []byte(quantity),
			2*time.Second, coakka.DeliveryHintRouterDefault)
		if err != nil {
			return err
		}
		fmt.Printf("quantity=%s quote=%s\n", quantity, reply)
	}
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly .

Expected output

quantity=1 quote=120000 VND
quantity=2 quote=240000 VND

Try adding "3" to the quantities. Check that the quote is 360000 VND.

Beginner · 03 / 04

Call the wrong target

Paste this file and run it again. The first call deliberately goes to orders.missing. Read the reason in the deadletter and the original target in its envelope. The program then sends a new call to orders.quote.

main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

func quote(input []byte) []byte {
	quantity, err := strconv.Atoi(string(input))
	if err != nil || quantity < 1 || quantity > 100 {
		return []byte("invalid quantity")
	}
	return []byte(fmt.Sprintf("%d VND", quantity*120_000))
}

func run() (err error) {
	const target = "orders.quote"
	const missingTarget = "orders.missing"
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-demo",
		NodeID:     "quote-demo-node",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.EmbeddedNetwork(),
	}, "")
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()
	if err := host.RegisterPayloadHandler(target, quote); err != nil {
		return err
	}

	_, err = host.AskPayload("checkout", missingTarget, []byte("2"),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	var failure *coakka.DeadletterError
	if !errors.As(err, &failure) || failure.Deadletter == nil {
		return fmt.Errorf("expected a deadletter for %q, got %v", missingTarget, err)
	}
	deadletter := failure.Deadletter
	if deadletter.Reason != coakka.DeadletterReasonRouteMiss ||
		deadletter.OriginalEnvelope == nil ||
		deadletter.OriginalEnvelope.Target != missingTarget {
		return fmt.Errorf("unexpected delivery failure: %w", err)
	}
	fmt.Printf("%s target=%s\n", deadletter.Reason, deadletter.OriginalEnvelope.Target)

	reply, err := host.AskPayload("checkout", target, []byte("2"),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	if err != nil {
		return err
	}
	fmt.Printf("quantity=2 quote=%s\n", reply)
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly .

Expected output

ROUTE_MISS target=orders.missing
quantity=2 quote=240000 VND

If you see a different error, compare the registered route with the target used by each call. This exercise covers a missing route.

Beginner · 04 / 04

Use it in your application

This file extracts requestQuote so the order flow can call it. In your own application, keep one CoAkka Runtime host for the application lifetime, put your pricing rules in quote and handle errors at the call site.

main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const target = "orders.quote"

func quote(input []byte) []byte {
	quantity, err := strconv.Atoi(string(input))
	if err != nil || quantity < 1 || quantity > 100 {
		return []byte("invalid quantity")
	}
	return []byte(fmt.Sprintf("%d VND", quantity*120_000))
}

func requestQuote(host *coakka.RuntimeHost, quantity int) (string, error) {
	reply, err := host.AskPayload("checkout", target, []byte(strconv.Itoa(quantity)),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	if err != nil {
		return "", fmt.Errorf("request order quote: %w", err)
	}
	return string(reply), nil
}

func run() (err error) {
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-demo",
		NodeID:     "quote-demo-node",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.EmbeddedNetwork(),
	}, "")
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()
	if err := host.RegisterPayloadHandler(target, quote); err != nil {
		return err
	}

	price, err := requestQuote(host, 3)
	if err != nil {
		return err
	}
	fmt.Println("order quote:", price)
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly .

Expected output

order quote: 360000 VND

Change the quantity in requestQuote and run again. The close in run shows how the code that starts the host owns its cleanup.

Open the portal integration checklist · Read the full source on GitHub (optional)

Advanced · 05

Move the handler to a second process

Keep the orders.quote target and send quantity 3 as before. This time the quote service owns the handler. Checkout calls it at 127.0.0.1:19301 on the same machine.

In the module from episode 1, use your IDE to create quote-service and checkout directories. Run both commands from the module root.

NetworkNode takes two host and port pairs. Pricing listens on the first pair. Peers use the advertised pair. Checkout uses OutboundOnlyNetwork() and routes to that advertised endpoint. Look up each network field

1. Start the quote service

Paste this file into quote-service/main.go. This process opens the loopback listener and registers the quote handler.

quote-service/main.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/signal"
	"strconv"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const (
	target   = "orders.quote"
	loopback = "127.0.0.1"
	port     = 19301
)

func quote(input []byte) []byte {
	quantity, err := strconv.Atoi(string(input))
	if err != nil || quantity < 1 || quantity > 100 {
		return []byte("invalid quantity")
	}
	return []byte(fmt.Sprintf("%d VND", quantity*120_000))
}

func run() (err error) {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-demo",
		NodeID:     "pricing",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.NetworkNode(loopback, port, loopback, port),
	}, "")
	if err != nil {
		return fmt.Errorf("start quote service: %w", err)
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()

	if err := host.RegisterPayloadHandler(target, quote); err != nil {
		return fmt.Errorf("register quote handler: %w", err)
	}
	fmt.Printf("quote service ready at %s:%d\n", loopback, port)
	<-ctx.Done()
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal 1
go run -mod=readonly ./quote-service

Wait for quote service ready at 127.0.0.1:19301 and leave this terminal running.

2. Call from checkout

Paste this file into checkout/main.go. Checkout makes outbound calls. Its route points to the quote service.

checkout/main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const target = "orders.quote"

func run() (err error) {
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-demo",
		NodeID:     "checkout",
		Routes: []coakka.RouteSpec{{
			Target:   target,
			Strategy: coakka.RouteStrategySingleOwner,
			Endpoints: []coakka.EndpointSpec{{
				Host:   "127.0.0.1",
				Port:   19301,
				Weight: 1,
			}},
		}},
		Network: coakka.OutboundOnlyNetwork(),
	}, "")
	if err != nil {
		return fmt.Errorf("start checkout: %w", err)
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()

	reply, err := host.AskPayload("checkout", target, []byte("3"),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	if err != nil {
		var failure *coakka.DeadletterError
		if errors.As(err, &failure) && failure != nil && failure.Deadletter != nil {
			return fmt.Errorf("request order quote (%s): %w", failure.Deadletter.Reason, err)
		}
		return fmt.Errorf("request order quote: %w", err)
	}
	fmt.Println("order quote:", string(reply))
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal 2
go run -mod=readonly ./checkout

Expected output

order quote: 360000 VND

Press Ctrl+C in terminal 1 and run checkout again. The call reports an error. If you see TRANSPORT_SEND_FAILED, check the quote service and the address in the route. Restart the service, wait for its ready line and retry. If port 19301 is busy, choose a free port and use it in both files.

Look up network modes in the portal · Read the source on GitHub (optional)

Advanced · 06

Transfer one file with File Lane

Use File Lane when the source is one immutable file and the receiver needs its exact byte count and SHA-256. This loopback example keeps sender and receiver in one process to expose the contract. File Lane is still an independent resource from a CoAkka Runtime host, and file bytes do not belong in message payloads.

In the module from episode 1, create file-lane/main.go and paste the complete file below.

file-lane/main.go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const fileTransferID = "catalog-2026-11-05"

func waitForTransfer(
	lane *coakka.FileLane,
	direction coakka.FileTransferDirection,
) (coakka.FileTransferSnapshot, error) {
	var afterSequence uint64
	for {
		snapshot, err := lane.WaitTransfer(
			fileTransferID,
			direction,
			afterSequence,
			5_000,
		)
		if err != nil {
			return coakka.FileTransferSnapshot{}, err
		}
		if snapshot.Terminal() {
			return snapshot, nil
		}
		afterSequence = snapshot.UpdateSequence
	}
}

func run() (err error) {
	workDir, err := os.MkdirTemp("", "coakka-file-lane-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(workDir)

	sourcePath := filepath.Join(workDir, "catalog.txt")
	destinationPath := filepath.Join(workDir, "received-catalog.txt")
	source := []byte("sku=coffee-beans price=240000\n")
	if err := os.WriteFile(sourcePath, source, 0o600); err != nil {
		return err
	}

	digest, err := coakka.FileSHA256(sourcePath, "")
	if err != nil {
		return err
	}

	lane, err := coakka.OpenFileLane(coakka.DefaultFileLaneConfig(), "")
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, lane.Close()) }()

	port, err := lane.BoundPort()
	if err != nil {
		return err
	}
	receive := coakka.FileReceiveSpec{
		TransferID:         fileTransferID,
		AuthorizationToken: "local-file-demo-token",
		DestinationPath:    destinationPath,
		ExpectedSize:       digest.Size,
		ExpectedSHA256:     digest.SHA256,
	}
	if err := lane.PrepareReceive(receive); err != nil {
		return err
	}

	send := coakka.FileSendSpec{
		TransferID:         fileTransferID,
		AuthorizationToken: receive.AuthorizationToken,
		RemoteHost:         "127.0.0.1",
		RemotePort:         port,
		SourcePath:         sourcePath,
		ExpectedSize:       digest.Size,
		ExpectedSHA256:     digest.SHA256,
		TimeoutMillis:      5_000,
	}
	if err := lane.SubmitSend(send); err != nil {
		return err
	}

	sender, err := waitForTransfer(lane, coakka.FileTransferSend)
	if err != nil {
		return err
	}
	receiver, err := waitForTransfer(lane, coakka.FileTransferReceive)
	if err != nil {
		return err
	}
	if !sender.Succeeded() || !receiver.Succeeded() {
		return fmt.Errorf("file transfer failed: send=%v receive=%v", sender.Result, receiver.Result)
	}

	received, err := os.ReadFile(destinationPath)
	if err != nil {
		return err
	}
	if !bytes.Equal(received, source) {
		return errors.New("received file differs from source")
	}

	fmt.Printf("file lane transferred: %d bytes\n", len(received))
	fmt.Printf("sender success: %t\n", sender.Succeeded())
	fmt.Printf("receiver success: %t\n", receiver.Succeeded())

	if err := lane.Forget(fileTransferID, coakka.FileTransferSend); err != nil {
		return err
	}
	return lane.Forget(fileTransferID, coakka.FileTransferReceive)
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly ./file-lane

Expected output

file lane transferred: 30 bytes
sender success: true
receiver success: true
FileSHA256
Computes the exact size and SHA-256 content identity before opening a transfer.
PrepareReceive
The receiver admits one transfer, token, destination and content identity before the sender starts.
SubmitSend
The sender uses the same content identity and the port opened by the receiver.
WaitTransfer
Reads copied snapshots until both sides are terminal and report Succeeded().
Forget / Close
Release a retained record only after recording its outcome; the owner closes the lane last.

The fixed token is only for this local loopback lesson. A real app control plane issues an unguessable token to the exact peer and never writes it to logs. Read the shared File Lane contract and parameters · Look up the Go API

Advanced · 07

Send frames with Stream Lane

Use Stream Lane for one ordered, bounded sequence of binary frames from one publisher to one subscriber. This loopback example sends three temperature readings. It is not file transfer, fan-out or a WebSocket protocol.

Create stream-lane/main.go in the same module and paste the complete file below.

stream-lane/main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"sync"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const (
	streamSessionID = "temperature-demo"
	streamFormatID  = 1
	maxFrameBytes   = 64
)

type receivedFrame struct {
	sequence uint64
	value    string
}

func waitForSession(
	lane *coakka.StreamLane,
	direction coakka.StreamDirection,
) (coakka.StreamSessionSnapshot, error) {
	var afterSequence uint64
	for {
		snapshot, err := lane.WaitSession(
			streamSessionID,
			direction,
			afterSequence,
			5_000,
		)
		if err != nil {
			return coakka.StreamSessionSnapshot{}, err
		}
		if snapshot.Terminal() {
			return snapshot, nil
		}
		afterSequence = snapshot.UpdateSequence
	}
}

func run() (err error) {
	config := coakka.DefaultStreamLaneConfig()
	config.MaxFrameBytes = maxFrameBytes
	config.MaxWindowBytes = 4 * maxFrameBytes
	lane, err := coakka.OpenStreamLane(config, "")
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, lane.Close()) }()

	port, err := lane.BoundPort()
	if err != nil {
		return err
	}

	frames := [][]byte{
		[]byte("temperature=21.5"),
		[]byte("temperature=21.7"),
		[]byte("temperature=21.6"),
	}
	var sourceMu sync.Mutex
	nextFrame := 0
	source := func(destination []byte) coakka.StreamSourceResult {
		sourceMu.Lock()
		defer sourceMu.Unlock()
		if nextFrame == len(frames) {
			return coakka.StreamSourceResult{Status: coakka.StreamSourceEnd}
		}
		size := copy(destination, frames[nextFrame])
		nextFrame++
		return coakka.StreamSourceResult{
			Status: coakka.StreamSourceFrame,
			Size:   size,
		}
	}

	if err := lane.PreparePublish(coakka.StreamPublishSpec{
		SessionID:          streamSessionID,
		AuthorizationToken: "local-stream-demo-token",
		FormatID:           streamFormatID,
		MaxFrameBytes:      maxFrameBytes,
		Source:             source,
	}); err != nil {
		return err
	}

	received := make(chan receivedFrame, len(frames))
	consumer := func(
		frame []byte,
		metadata coakka.StreamFrameMetadata,
	) coakka.StreamConsumerDecision {
		// The callback slice is borrowed. Converting it to string copies the bytes.
		received <- receivedFrame{sequence: metadata.Sequence, value: string(frame)}
		return coakka.StreamConsumerContinue
	}
	if err := lane.Subscribe(coakka.StreamSubscribeSpec{
		SessionID:          streamSessionID,
		AuthorizationToken: "local-stream-demo-token",
		RemoteHost:         "127.0.0.1",
		RemotePort:         port,
		FormatID:           streamFormatID,
		MaxFrameBytes:      maxFrameBytes,
		InitialWindowBytes: 4 * maxFrameBytes,
		TimeoutMillis:      5_000,
		Consumer:           consumer,
	}); err != nil {
		return err
	}

	publisher, err := waitForSession(lane, coakka.StreamPublish)
	if err != nil {
		return err
	}
	subscriber, err := waitForSession(lane, coakka.StreamSubscribe)
	if err != nil {
		return err
	}
	if !publisher.Succeeded() || !subscriber.Succeeded() {
		return fmt.Errorf("stream failed: publish=%v subscribe=%v", publisher.Result, subscriber.Result)
	}

	close(received)
	for frame := range received {
		fmt.Printf("frame %d: %s\n", frame.sequence, frame.value)
	}
	fmt.Printf("stream lane delivered: %d frames\n", subscriber.Frames)

	if err := lane.Forget(streamSessionID, coakka.StreamPublish); err != nil {
		return err
	}
	return lane.Forget(streamSessionID, coakka.StreamSubscribe)
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly ./stream-lane

Expected output

frame 1: temperature=21.5
frame 2: temperature=21.7
frame 3: temperature=21.6
stream lane delivered: 3 frames
MaxFrameBytes
Bounds each frame at 64 bytes; the 256-byte window bounds memory and in-flight data.
PreparePublish
The publisher registers the session, token, format and source callback before the subscriber connects.
Subscribe
The subscriber uses the exact session, token, format, endpoint and consumer callback.
Callback bytes
The slice is borrowed only during the callback. The example converts it to string to copy before retaining it.
WaitSession
Observe publish and subscribe independently until terminal, then Forget and Close.

The application owns the meaning of FormatID and its frame policy. Core owns ordering, flow control, session state and outcomes. Read the shared Stream Lane contract and parameters · Look up the Go API

Advanced · 08

Observe CoAkka Runtime with Monitor

Enable extra monitor collection for one Embedded instance, confirm the setting accepted by Core, then read health and counters as copied Go values. Core owns the facts and update signals; the application decides when to read and where to export, display or alert.

In the module from episode 1, create monitoring/main.go and paste the complete file below. host.Monitor borrows the host lifetime, so every read and wait must finish before host.Close().

monitoring/main.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

const target = "orders.quote"

func quote(input []byte) []byte {
	quantity, err := strconv.Atoi(string(input))
	if err != nil || quantity < 1 || quantity > 100 {
		return []byte("invalid quantity")
	}
	return []byte(fmt.Sprintf("%d VND", quantity*120_000))
}

func printMonitor(label string, view coakka.MonitorSnapshot) {
	fmt.Printf("%s: signal=%d generation=%d routes=%d queue=%d/%d rejected=%d\n",
		label,
		view.SignalCount,
		view.Health.AppliedGeneration,
		view.Stats.RouteCount,
		view.Stats.LocalWorkQueueDepth,
		view.Stats.LocalWorkQueueCapacity,
		view.Stats.QueueRejectedCount,
	)
}

func run() (err error) {
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "quote-monitor",
		NodeID:     "quote-monitor-1",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault(target)},
		Network:    coakka.EmbeddedNetwork(),
		Monitor:    &coakka.RuntimeMonitorOptions{Enabled: true},
	}, "")
	if err != nil {
		return fmt.Errorf("start monitored host: %w", err)
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()

	if err := host.RegisterPayloadHandler(target, quote); err != nil {
		return fmt.Errorf("register quote handler: %w", err)
	}

	enabled, err := host.Monitor.IsEnabled()
	if err != nil {
		return fmt.Errorf("read monitor setting: %w", err)
	}
	if !enabled {
		return errors.New("Core did not enable monitor collection")
	}
	fmt.Println("monitor enabled:", enabled)

	initial, err := host.Monitor.AwaitAppliedGenerationAtLeast(1, time.Second)
	if err != nil {
		return fmt.Errorf("wait for route generation: %w", err)
	}
	if initial == nil {
		return errors.New("route generation was not visible before the deadline")
	}
	printMonitor("initial", *initial)

	reply, err := host.AskPayload("checkout", target, []byte("3"),
		2*time.Second, coakka.DeliveryHintRouterDefault)
	if err != nil {
		return fmt.Errorf("request order quote: %w", err)
	}
	fmt.Println("order quote:", string(reply))

	latest, err := host.Monitor.AwaitNext(250 * time.Millisecond)
	if err != nil {
		return fmt.Errorf("wait for monitor update: %w", err)
	}
	if latest == nil {
		current, snapshotErr := host.Monitor.Snapshot(0)
		if snapshotErr != nil {
			return fmt.Errorf("read current monitor snapshot: %w", snapshotErr)
		}
		latest = &current
		fmt.Println("monitor update: no notification in 250ms; read current snapshot")
	} else {
		fmt.Println("monitor update: received")
	}
	printMonitor("latest", *latest)
	fmt.Println("monitor sample complete")
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Terminal
go run -mod=readonly ./monitoring

One 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

signal counts coalesced refresh signals, not requests. generation and routes identify the applied route table. Queue depth, capacity and rejection count are useful when comparing pressure over time.

AwaitNext uses a 250 ms deadline. If no signal arrives in that window, the example reads the current snapshot and still completes. No update does not mean healthy, unhealthy or stopped.

Understand the shared operations contract · Review the monitoring decision · Look up monitoring and overload fields