24. Servers: Domains and Peers
Everything so far ran one VM: on a board, in gogovm, or inside another
program. One VM runs its actors on one thread, which suits a board and
is the reason an actor costs so little. A server has many cores, and
servers talk to each other. This chapter is about the runtime for that:
gogopeer, a server process that runs several VMs, its domains,
each on a core of its own, and connects directly to the other
gogopeer processes of a cluster.
It builds on chapter 4 (actors, Call), chapter 5 (links, monitors,
exit reasons) and chapter 20 (remote PIDs and what a message may hold).
Status: experimental. The server runtime is tested on macOS and Linux, on up to three physical hosts, with fault injection and short soak runs (24.9), but it is new: its wire protocol and options may still change, and it is not a production-readiness or capacity guarantee. Boards and the star of chapter 20 are a separate profile and are not affected by anything here.
24.1 What a domain is
A domain is one gogo VM inside a server process, owned by one OS
thread. It has everything a VM has: its actors with their heaps and
mailboxes, its timers, its ports, its names. Only that thread ever
touches them. A gogopeer process runs 1 to 32 domains, so up to 32
cores run gogo code at once:
gogopeer process (one PeerID)
┌──────────────────────────────────────────────────────────────────┐
│ domain 1 domain 2 domain 3 │
│ thread gogo-d1 thread gogo-d2 thread gogo-d3 │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ VM: actors, │ │ VM: actors, │ │ VM: actors, │ │
│ │ heaps, │◄─►│ heaps, │◄─►│ heaps, │ in-memory │
│ │ timers, │ │ timers, │ │ timers, │ channels │
│ │ ports │ │ ports │ │ ports │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ └────── bounded queues ─────────────┘ │
│ │ │
│ I/O thread gogo-io: every socket, TLS or HMAC, framing, credit │
│ blocking pool gogo-blocking: host name lookups │
└─────────────────────────┼────────────────────────────────────────┘
│ one authenticated TCP connection per peer
other gogopeer processes
Four rules follow from “one VM, one thread”, and the rest of the chapter leans on them:
- Actors never move. An actor lives and dies in the domain that
created it.
actor.Spawnalways creates in the caller’s own domain; to start work in another domain, ask an actor there (aCallto its door, below, or a factory, 24.5). - Domains talk only by messages. A message to an actor in another
domain is encoded by the sender’s thread into a host buffer and
decoded by the receiver’s thread, exactly as if it crossed the
network, even when both domains are in one process. So it obeys the
rules of a remote message (20.4): no pointers, maps or func values, at
most 4096 bytes encoded.
Send,Call/Reply,Monitor,Link,Killand==work on a PID in another domain as on a remote PID in chapter 20, with the same results whether that domain is in this process or on another host. - Domains are isolated. Each has its own memory limit
(
--memory-mb), its own actor table (--max-actors) and its own CPU share (--cpu-limit). A domain whose main actor crashes fails alone; the other domains keep running (24.5). - A domain restarts as a new instance. A domain can be rebuilt (a drain and a fresh start of its program, 24.6). The new instance has a new boot: PIDs of the old one never reach it, nothing is replayed into it, and it starts with no names and no state of its own.
Why fixed domains, and not one VM on many threads. The VM keeps
every actor’s heap, the mailboxes, the off-heap Bytes table, the
modules, the timers and the ports in plain single-threaded structures.
That is what keeps it small enough for a board and an idle actor at
about 150 bytes. Letting several threads run the actors of one VM
would put a lock or an atomic on each of those paths, in every build,
for every board. Running several independent VMs instead uses the cores
and leaves the VM as it is. The price is explicit placement: you decide
which domain an actor lives in, a message between domains is encoded
and copied like a network message, and one busy actor never runs faster
than one core. Split hot state across actors and domains, the way you
would split it across boards.
Each domain runs its own main: the process is started with a list of
--domain ID:IMAGE pairs, usually the same image several times with
different settings. The main actor of a domain is its door: the
actor other domains reach first, by the domain’s address alone.
24.2 Addresses: peers, boots and PIDs
A PID on a server names its actor exactly, in three parts:
| Part | Fields | Where it comes from |
|---|---|---|
| the process: a peer | PeerID, PeerBoot | PeerID: 128 bits, created once and kept in the process’s state directory. PeerBoot: random, new every time the process starts |
| the domain | DomainID, DomainBoot | DomainID: the number you give --domain (any uint32). DomainBoot: 1 at start, 2 after the first rebuild, … |
| the actor | ActorID | slot and incarnation: incarnation << 16 | slot; the door is ActorID 0 |
println shows all of it as <pid PEERID/PEERBOOT/DOMAIN:DOMAINBOOT/ACTORID>.
Run in domain 1, println(actor.Self()), the door of domain 2 and a
freshly spawned actor print
<pid 05231e4a4ea740b56aeb0bcd399f908b/3651975d0dd1eef6d9571905ef371d58/1:1/0>
<pid 05231e4a4ea740b56aeb0bcd399f908b/3651975d0dd1eef6d9571905ef371d58/2:1/0>
<pid 05231e4a4ea740b56aeb0bcd399f908b/3651975d0dd1eef6d9571905ef371d58/1:1/131073>
(slot 1 in its second use: 2 << 16 | 1). The boots are what make
restarts safe. A PID taken before a process restart has the old
PeerBoot, one taken before a domain rebuild the old DomainBoot, and one
of an actor that exited an old incarnation; none of them can reach
whatever lives there now. Sending to such a PID drops the message, a
Call fails with errors.NoConnection, and a monitor or link fires
with actor.NoConnection, exactly as for a lost board (20.5). After a
restart, look the door up again.
This full address is the wide identity. A board, gogovm and the
star of chapter 20 use the compact identity: a PID is a small slot
number, and a remote PID is a slot in a table of proxies that its node
fills (20.9). Compact PIDs keep a board’s memory small; wide PIDs need
no table at all for remote actors, so a server can hold PIDs of any
number of actors on any number of hosts, at 56 bytes per PID value while
it is alive. The program’s target (chapter 12, Targets) decides which
one the compiler builds: host, the default, is the server, wide; a
board target is compact.
gogo build . -o app.ggb # target host: wide, for gogopeer
gogo build --target sticks3 . -o app.ggb # a board: compact
gogopeer refuses a compact image (domain 1 image does not require wide_identity), and a wide image does not run on a board. gogo run
does not run a server program yet: it runs host programs in gogovm,
which has the compact identity, and says so (gogo/peer needs the server runtime, which 'gogo run' does not use yet); start such a program with
gogopeer, as below. Using gogo/peer or gogo/resolve in a program for
a board is a compile error (gogo/peer is not available on target sticks3 (host only)). The two kinds of process do not
talk to each other either: a board joins the star of chapter 20; servers
join each other as peers.
The program sees its own address through sys.Config: peer.id,
peer.boot, domain.id and domain.boot, set by the server (your
own settings cannot shadow them).
24.3 One process, two domains
The example program, 24-counter, plays one
of two roles in each domain, chosen with a setting. A store keeps a
running total and answers Add and Stop Calls on its door; a
client finds a store, adds 1, 2 and 3, and stops it:
// Add asks the store to add N to its total; the reply is the new total.
type Add struct{ N int }
// Stop ends the store: its main returns, and with it the domain.
type Stop struct{}
func store() {
// Be told when the domain stops (stage 0: the first to hear).
if _, err := peer.WatchDrain(0); err != nil {
println("cannot watch the drain:", err.Error())
return
}
total := 0
peer.SetReady(true)
println("store ready")
for {
switch m := actor.Receive().(type) {
case actor.Request:
switch body := m.Body.(type) {
case Add:
total += body.N
actor.Reply(m, total)
case Stop:
actor.Reply(m, total)
println("store stopped, total", total)
return
}
case peer.Drain:
// The process is stopping or this domain is being rebuilt.
// Nothing to finish here: acknowledge and end.
println("store draining, total", total)
peer.DrainDone(m.Watch)
return
}
}
}
The store is the Call server of chapter 4 with three additions from
gogo/peer: SetReady(true) tells everyone the domain is ready for
work, and WatchDrain with the peer.Drain case lets it take part in
a graceful stop (both in 24.6). The client:
func client() {
self, _ := sys.Config("peer.id")
target := setting("target.peer", self) // default: this process
domain, _ := strconv.Atoi(setting("target.domain", "1"))
var door actor.PID
var err error
if name, ok := sys.Config("target.name"); ok {
door, err = peer.ResolveReady(name, uint32(domain), 10000)
} else {
door, err = peer.WaitReady(target, uint32(domain), 10000)
}
if err != nil {
println("no store:", err.Error())
return
}
for i := 1; i <= 3; i++ {
total, err := actor.Call(door, Add{N: i}, 5000)
if err != nil {
println("call failed:", err.Error())
return
}
println("added", i, "total", total.(int))
}
if st, err := peer.Status(target, uint32(domain)); err == nil {
println("store domain", st.Domain, "boot", st.DomainBoot, "ready", st.Ready, "local", st.Local)
}
actor.Call(door, Stop{}, 5000)
}
peer.WaitReady(peerID, domain, timeoutMs) waits until that domain is
reachable and has said it is ready, and returns its door. With this
process’s own PeerID it finds a domain of the same process; with
another PeerID, one in another process, on this host or another. The
calls after it are plain actor.Calls. (peer.Door(peerID, domain, timeoutMs) returns the door without waiting for readiness.)
Build the tools and the program. The server binaries are built from source (chapter 2.2), in the repository’s root:
make gogo-cmd peer-server # build/gogo and build/gogopeer
demo=$HOME/peer-demo # any directory of yours
mkdir -p $demo
build/gogo build docs/book/examples/24-counter -o $demo/counter.ggb
Give the process an identity and a configuration. A gogopeer needs
a state directory (mode 0700; it keeps the PeerID and a lock so that
two processes cannot share it), a cluster ID shared by every process of
the cluster, and a security mode. Here it is experimental-hmac: every
process holds the same 32-byte key and proves it on every connection
(authenticated, not encrypted; mutual TLS is in 24.4).
mkdir -m 700 $demo/state-a
openssl rand -hex 32 > $demo/cluster.psk && chmod 600 $demo/cluster.psk
build/gogopeer --init-peer-id $demo/state-a # prints the new PeerID
cat > $demo/a.conf <<EOF
cluster=$(openssl rand -hex 16)
state-dir=$demo/state-a
listen=127.0.0.1:4371
advertise=127.0.0.1:4371
security=experimental-hmac
psk-file=$demo/cluster.psk
EOF
chmod 600 $demo/a.conf
Every path in the file is absolute, and the files must belong to you and
not be writable by others (the server refuses them otherwise, naming the
field). listen and advertise are needed even by a process that talks
to no other: they are where peers would reach it.
Run two domains of the same image. Domain 1 is a store (the default role); domain 2 is a client, by a per-domain setting:
build/gogopeer --peer-config $demo/a.conf \
--domain 1:$demo/counter.ggb --domain 2:$demo/counter.ggb --set 2:role=client
[domain 1/1] store ready
[domain 2/1] added 1 total 1
[domain 2/1] added 2 total 3
[domain 2/1] added 3 total 6
[domain 2/1] store domain 1 boot 1 ready true local true
[domain 1/1] store stopped, total 6
Each line a program prints is prefixed with [domain ID/BOOT]. On
standard error the server reports each domain as it ends, and a last
line when it stops:
server domain=1 boot=1 state=done error=0 placement_errno=0 steps=9 cpu_ns=252833 probe_ack=0 mem_peak=768548 lifecycle=stopped drain_timeout=0 drain_pending=0
server domain=2 boot=1 state=done error=0 placement_errno=0 steps=12 cpu_ns=309042 probe_ack=0 mem_peak=768744 lifecycle=stopped drain_timeout=0 drain_pending=0
server drain_done=1 drain_timeout=0 unflushed_frames=0 unflushed_wire_bytes=0 leave_sent=0 leave_received=0 leave_tombstones=0 leave_unrecorded=0 app_drain=1 app_drain_timeout=0 app_drain_pending=0
A domain ends as gogovm ends a program: when its actors are done. When
every domain has ended, the process exits, with status 0, or 1 if a
domain failed (2 for a bad option or configuration). A real server
keeps its main actors alive and is stopped with a signal (24.6).
The two domains never shared a heap: the Add values and the totals
were encoded into host buffers between the two threads, and no socket
was used (the local_frames counter of 24.7 counts them).
24.4 Two processes, two hosts
Now put the store and the client in two processes. Each process has its
own state directory, and in the default static mode each lists the
others with peer=PEERID@ADDRESS:
mkdir -m 700 $demo/state-b
A=$(build/gogopeer --init-peer-id $demo/state-a)
B=$(build/gogopeer --init-peer-id $demo/state-b)
sed -e "s/4371/4372/g" -e "s/state-a/state-b/" $demo/a.conf > $demo/b.conf
echo "peer=$B@127.0.0.1:4372" >> $demo/a.conf
echo "peer=$A@127.0.0.1:4371" >> $demo/b.conf
chmod 600 $demo/b.conf
--init-peer-id prints the existing PeerID once the directory has one.
Start the store in one terminal and the client in another; the client
now names the store’s process with target.peer:
build/gogopeer --peer-config $demo/a.conf --domain 1:$demo/counter.ggb
build/gogopeer --peer-config $demo/b.conf --domain 2:$demo/counter.ggb \
--set 2:role=client --set 2:target.peer=$A
The first prints
[domain 1/1] store ready
[domain 1/1] store stopped, total 6
and the second
[domain 2/1] added 1 total 1
[domain 2/1] added 2 total 3
[domain 2/1] added 3 total 6
[domain 2/1] store domain 1 boot 1 ready true local false
The program did not change: the same WaitReady and Call, and the
store is now local false. The two processes hold one authenticated TCP
connection, which carries every domain of both (the process with the
lower PeerID dials, and redials with backoff if the connection drops).
On two real hosts, use each host’s address for advertise and the
peer= lines, listen=0.0.0.0:4371 if you like, and copy the cluster
ID and the key file to both. Addresses are numeric IPv4.
Mutual TLS. experimental-hmac proves membership but does not
encrypt, and anyone with the key can claim any PeerID. For anything but
a trusted network, use certificates: make peer-server-tls (OpenSSL 3
headers needed) builds build/gogopeer-tls, the same server with TLS,
which takes every option of gogopeer. Each process gets a
certificate from a CA of your cluster that names exactly its cluster
and PeerID, in one URI subject-alternative name
urn:gogo:peer:CLUSTER:PEERID. With OpenSSL 3 (not the LibreSSL
openssl of macOS), a test CA and the two certificates:
make peer-server-tls
peer_tls=$PWD/build/gogopeer-tls
mkdir -m 700 $demo/tls && cd $demo/tls
cluster=$(sed -n 's/^cluster=//p' $demo/a.conf)
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc \
-keyout ca.key -out ca.pem -days 365 -subj /CN=example-cluster-ca
for n in a b; do
id=$($peer_tls --init-peer-id $demo/state-$n)
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc \
-keyout $n.key -out $n.csr -subj /CN=peer-$n \
-addext "subjectAltName=URI:urn:gogo:peer:$cluster:$id" \
-addext "extendedKeyUsage=serverAuth,clientAuth"
openssl x509 -req -in $n.csr -CA ca.pem -CAkey ca.key -days 365 \
-copy_extensions copy -out $n.pem
done
chmod 600 *.key
cd - # back to the repository root
and in each configuration the security lines become (for process b, b.pem and b.key):
security=mutual-tls
tls-cert-file=/home/you/peer-demo/tls/a.pem
tls-key-file=/home/you/peer-demo/tls/a.key
tls-ca-file=/home/you/peer-demo/tls/ca.pem
The same two commands, with build/gogopeer-tls, print the same lines.
Connections use TLS 1.3, both sides check the other’s certificate
against the CA, and the certificate’s PeerID must be the one the
connection claims. Credentials are read at start; to rotate them,
install new files and restart (keeping the state directory).
Discovery. With mutual TLS, processes can find each other from a
seed instead of a full peer= list. The first process bootstraps the
cluster, the others join through any running member; every pair then
connects directly (a seed is only a source of addresses, never a relay):
# a.conf (TLS lines as above, no peer= lines)
discovery=bootstrap
peer-name=store-a
allow-peer-cidr=127.0.0.0/8
# b.conf
discovery=join
seed=127.0.0.1:4371
peer-name=client-b
allow-peer-cidr=127.0.0.0/8
allow-peer-cidr limits the addresses a process accepts and dials;
peer-name is a human name that peer.Resolve and peer.ResolveReady
look up. The client can now find the store by name:
build/gogopeer-tls --peer-config $demo/b.conf --domain 2:$demo/counter.ggb \
--set 2:role=client --set 2:target.name=store-a
A name is not an identity: two processes that claim one name make
Resolve fail with errors.Exists, and the PeerID stays the only exact
address. Discovery needs mutual TLS; HMAC supports the static list only.
24.5 What crosses between domains, and what fails
Between domains, local or remote, the rules are those of chapter 20’s remote PIDs (20.4 to 20.6), whether the other domain is in this process or on another host:
| Situation | Send | Call | Monitor / Link |
|---|---|---|---|
| target alive | delivered, in order per sender and receiver | the reply | the target’s own exit reason |
| no reply in time | errors.Timeout; a late reply is dropped | ||
| target actor already gone, its domain alive | dropped | errors.NoConnection | NoProc |
| peer unreachable, connection lost, target domain stopped or rebuilt, a PID of an old boot | dropped | errors.NoConnection | NoConnection, once |
| a queue toward that domain is full | the whole connection (or local domain pair) is cut: as the row above | ||
| message not encodable or over 4096 bytes | the sender exits BadMsg |
Delivery is at most once: nothing is ever replayed after a failure.
Sends never block: a sender that outruns its receiver does not wait,
the connection to that peer (or the pair of local domains) is cut instead
and every Call and watch on it fails with NoConnection (fail-close).
More than 64 frames (or 256 KiB) queued to one remote domain faster than
it takes them is enough, so pace long streams: a Call every few dozen
Sends, as in 21.3. A Ref cannot be sent back into the domain that made
it (it ends that peer session).
A Call that ended in Timeout or NoConnection may or may not have
run on the other side. For work with side effects, give each request an
idempotency key and ask the owner before retrying with the same key;
PEER_SERVER.md
spells the pattern out.
A failing domain. 24-isolation runs two domains of one image; in domain 1 the main actor crashes at once, in domain 2 it spawns three workers:
func main() {
domain, _ := sys.Config("domain.id")
if role, _ := sys.Config("role"); role == "crash" {
var m map[string]int
m["boom"] = 1 // a nil map: this domain's main Actor crashes
return
}
done := make([]actor.PID, 0)
for i := 1; i <= 3; i++ {
n := i
w := actor.Spawn(func() {
d, _ := sys.Config("domain.id")
println("worker", n, "runs in domain", d)
})
actor.Monitor(w)
done = append(done, w)
}
for range done {
actor.Receive() // one DownMsg per worker
}
println("domain", domain, "finished")
}
build/gogo build docs/book/examples/24-isolation -o $demo/iso.ggb
build/gogopeer --peer-config $demo/a.conf --domain 1:$demo/iso.ggb --domain 2:$demo/iso.ggb \
--set 1:role=crash
[domain 1/1] gogo: actor <pid 0> crashed: nil in maps.set
server domain=1 boot=1 state=failed error=-36 placement_errno=0 steps=1 ...
[domain 2/1] worker 1 runs in domain 2
[domain 2/1] worker 2 runs in domain 2
[domain 2/1] worker 3 runs in domain 2
[domain 2/1] domain 2 finished
server domain=2 boot=1 state=done error=0 placement_errno=0 steps=4 ...
Domain 2 is not disturbed, every worker ran in its creator’s domain, and the exit status is 1 because a domain failed. A domain’s main actor is its door: when it crashes, the domain counts as failed. Supervise the real work under it (chapter 5) and keep main simple.
Placing actors in other domains. Spawn stays in its domain. To
create an actor in another domain, that domain runs a factory
(peer.StartFactory) that publishes named entry functions;
peer.ChooseFactory picks a domain among candidates by key hash, load
or affinity, and peer.Create asks that factory to spawn and returns
the new PID. Only an entry name and an encodable argument travel; the
function itself is already in the target’s image. A Create that timed
out reports Uncertain, since the child may exist. See
examples/peer_factory and the
factory contract.
Public names. peer.Register(name, pid) publishes an actor of this
domain; peer.Whereis(peerID, domain, name, timeoutMs) and
peer.WhereisName(peerName, ...) look it up from anywhere. Private
actor.Register names stay private to their domain. In a wide image
gogo/node works too, as a thin layer over these: node.Whereis("store-a/1", "echo", 1000) names a domain as name/domain or PeerID/domain, while
node.Listen and node.Connect return errors.Unsupported, since the
server makes the connections.
24.6 Running a server: readiness, drains and restarts
Readiness. Every domain starts not ready on every boot. A domain
says it is ready with peer.SetReady(true) once it can do its work;
peer.WaitReady and peer.ResolveReady wait for that, and peers see
it in peer.Status. Ready is advice, not a lock: it does not stop
requests from arriving, and it does not make anything exclusive.
Drains. Stopping a server, or rebuilding one of its domains, first
drains the applications: the domain withdraws its Ready (and peers see
that), stops admitting new participants, and tells each actor that
called peer.WatchDrain(stage) with a peer.Drain message, stage 0
first, then 1, 2, 3, each stage once every participant of the lower
ones called peer.DrainDone (or exited). A typical split is: the front
door that admits requests at 0, request workers at 1, storage flushes at
2. Requests that still arrive during the drain reach the application,
which should refuse new work (peer.Draining() tells it) and finish
what it accepted. The whole drain has one deadline, app-drain-ms in
the configuration (default 5000): at the deadline the VM is torn down
whatever its actors are doing.
Signals.
| Signal | Effect |
|---|---|
SIGINT, SIGTERM | stop: drain every domain, stop the VMs, send what was already queued, tell the peers it is leaving, exit |
SIGHUP | rolling rebuild: one domain at a time, drain it, start its program again with the next DomainBoot, and wait (up to app-drain-ms) until it calls SetReady(true) before the next |
SIGUSR1 | with --rebuild-on-usr1 ID: the same rebuild for domain ID only |
With the store of 24.3 running alone, a SIGHUP and then a SIGTERM
print
build/gogopeer --peer-config $demo/a.conf --domain 1:$demo/counter.ggb &
kill -HUP %1 # once it printed "store ready"
kill -TERM %1 # once it printed "store ready" again
[domain 1/1] store ready
[domain 1/1] store draining, total 0
server rebuild domain=1 old_boot=1 boot=2
[domain 1/2] store ready
server rebuild_ready domain=1 boot=2
[domain 1/2] store draining, total 0
server drain_done=1 ... app_drain=1 app_drain_timeout=0 app_drain_pending=0
(program lines on standard output, server lines on standard error).
The rebuilt domain is boot 2: a new instance with an empty total, no
names, no readiness, and a new door. Anything that held a PID of boot 1
gets NoConnection and must look the door up again. A rebuild that
does not reach Ready in time stops the rolling rebuild
(server rebuild_failed domain=N boot=B reason=not-ready), and the
process exits with status 1 when it is finally stopped. A restart of the
whole process is a new PeerBoot, with the same rule for every PID of
every domain. Applications that must survive restarts keep their state
in storage or in another domain, and key their requests (24.5).
24.7 Limits, budgets and statistics
Each domain is sized by options that apply to every domain:
| Option | Default | Meaning |
|---|---|---|
--memory-mb N | 64 | VM memory of each domain: actors, heaps, mailboxes, the actor table, pending Calls and watches |
--max-actors N | 16384 | live actors per domain, 1..64512 (actor and port PIDs share 65536 slots; 1024 are ports). Each slot costs 24 bytes of the domain’s memory whether used or not; a Spawn past the table ends the spawning actor with SystemLimit |
--cpu-limit ID:PCT | 100 | CPU time of domain ID, 1..100% of one core, measured per 100 ms window (a soft quota) |
--budget N | 32 | scheduler passes between two checks of the control inbox, 1..4096 |
--config ID:FILE, --set ID:KEY=VALUE | settings of domain ID for sys.Config, at most 128 | |
--cpu ID:CPU, --numa ID:NODE | the OS’s | Linux only: pin domain ID’s thread to a CPU or to a NUMA node’s CPUs (elsewhere the domain fails to start) |
--blocking-threads N, --blocking-queue N, --blocking-bytes N | 4, 256, 1 MiB | the pool of host threads for lookups (24.8) |
Every host buffer that carries traffic (each domain’s inbox, the queue
to the I/O thread, socket buffers inside the process, TLS sessions,
discovery, the blocking pool) is charged to one budget tree before it
is allocated. The defaults suit most servers; --limit KEY=VALUE
changes one, and --print-limits shows the result:
build/gogopeer --limit process-bytes=96m --print-limits
process-bytes=100663296
process-control-bytes=auto
total-bytes=0
domain-rx-items=256
domain-rx-bytes=2097152
bridge-tx-items=256
bridge-tx-bytes=2097152
channel-items=64
channel-bytes=262144
...
max-calls=1024
max-watches=4096
process-bytes caps all host buffers together (unlimited by default),
and total-bytes checks at start that it plus every domain’s
--memory-mb fits what you have. The network queues, and a finite
process-bytes, keep one eighth for control traffic (heartbeats,
credit, leaving), so a flood of data cannot starve the connection
itself. When a queue or the process cap
refuses a frame, the connection (or local domain pair) is cut, as in
24.5. Kernel socket buffers and OpenSSL’s own memory are outside the
tree; the reference shows how
to plan for them.
--stats-ms N prints one block of statistics on standard error every N
milliseconds. From a process of two idle domains:
server domain=1 boot=1 state=idle error=0 placement_errno=0 steps=5 cpu_ns=165125 probe_ack=2 mem_peak=399908 lifecycle=running drain_timeout=0 drain_pending=0
server io_probe_ack=2 active=0 rx_frames=0 tx_bytes=0 tx_held_bytes=0 tx_connection_peak=0 tx_refused_connection=0 tx_refused_shared=0
server local_channels=1 local_frames=0 local_bytes=0 local_rejected=0
server queue_frames=0 queue_bytes=0 queue_channels=0 channel_rejected=0 queue_rejected=0 budget_rejected=0 fenced_full=0 fenced_nomem=0 credit_requests=0 credit_grants=0 credit_received=0 credit_waiting=0 credit_buffers=0 late_replies=0
server budget node=process parent=- used=0 peak=0 limit=100663296 control=12582912 items=0 peak_items=0 item_limit=unlimited refused_data=0 refused_control=0
server budget node=domain.1.rx parent=process used=0 peak=0 limit=2097152 control=0 items=0 peak_items=0 item_limit=256 refused_data=0 refused_control=0
...
A domain line says what its thread does (state: runnable, idle,
throttled by its CPU limit, done, failed), how much VM memory it
reached (mem_peak) and where its drain is (lifecycle). probe_ack
and io_probe_ack grow while the domain’s thread and the I/O thread
answer. Worth watching: fenced_full or budget_rejected growing
(senders outrun a receiver or a budget: connections are being cut),
credit_waiting staying high (a slow receiver), late_replies growing
(replies arriving after their Calls timed out), a state=failed, and
drain_timeout=1 at the end. Every line and field is listed in the
reference.
24.8 Diagnostics and blocking work
What a program can see. peer.Status(peerID, domain) reports one
domain: its PeerBoot and DomainBoot, name, Ready, Local and
Draining. peer.Domains(cursor, limit) and peer.Peers(cursor, limit) page through every domain and peer this process is connected
to (start at 0, up to 64 a page, next == -1 at the end; a page is an
observation, not a snapshot). peer.Subscribe() sends the caller
peer.Events (DomainUp, DomainDown, DomainChanged) from then on.
Why a peer is not connected. peer.Diagnostics(cursor, limit), and
--peer-diag all with --stats-ms, list what the I/O thread knows:
each configured or discovered peer with its state (backoff,
dialing, active, …) and last result, the connections still in
their handshake, and conflicts. The common one is two processes using
one PeerID, for instance a state directory copied to a second host: the
first stays connected, the other is refused again and again, and a
server diag kind=conflict role=peer-id ... line says so. Never copy a
state directory to another live host; give every process its own
(--init-peer-id). The diagnostics only observe: nothing in them evicts
or prefers a process.
Blocking work. A domain’s thread must never block, or every actor
of the domain stops with it. Host name lookups (getaddrinfo) can take
seconds, so the server runs them on a small pool of other threads
(gogo-blocking), and gogo/resolve (chapter 10.3) waits for the
answer in an ordinary Receive, while the rest of the domain runs on.
24-resolve:
func main() {
// Each Lookup waits in an ordinary Receive: the domain's other
// Actors keep running meanwhile.
for _, name := range []string{"localhost", ""} {
ip, err := resolve.Lookup(name, 5000)
if err != nil {
println("\""+name+"\" ->", err.Error())
} else {
println(name, "->", dotted(ip))
}
}
}
build/gogo build docs/book/examples/24-resolve -o $demo/resolve.ggb
build/gogopeer --peer-config $demo/a.conf --domain 1:$demo/resolve.ggb
[domain 1/1] localhost -> 127.0.0.1
[domain 1/1] "" -> bad argument
A full pool, or one domain asking for more than its share, gets
errors.Busy at once instead of a queue without end; a lookup past its
timeout gets errors.Timeout, and its late answer is dropped. Under
gogo run the same program prints unsupported for localhost: the
host VM and the boards have no resolve port (boards use gogo/dns).
24.9 Sizing: one domain, many, or many processes
| You have | Use |
|---|---|
| work that fits one core | one domain. Everything is a local Send, nothing is encoded |
| independent work that needs more cores (sessions, tenants, shards of a key space) | one process with a domain per core, each owning its part; route requests by key to the right domain’s door or factory |
| actors that talk to each other a lot | keep them in one domain: a local message is a copy, a message to another domain is an encode, a queue, a wakeup and a decode |
| a failure or upgrade unit bigger than a domain, or more than 32 domains | several processes on one host; each restarts on its own |
| more than one machine, or a failure that must not take every domain | processes on several hosts |
Numbers measured on the test machines (they are measurements, not guarantees; the reference has the details):
- Actors. An idle actor costs about 168 bytes of VM memory (144 for
the actor, 24 for its slot in the table that
--max-actorspreallocates) and about 172 bytes of resident memory. A domain holds at most 64512 live actors and a process 32 domains, so about 2.06 million actors per process; one Linux host held 784 million idle actors in 380 processes. Actors use no threads, file descriptors or mappings. - Domains. One thread and one VM each; an empty domain is about 0.36 MiB of VM memory with the default table (16384 slots x 24 bytes of it). A process also has one I/O thread, the blocking pool (4 threads) and a controller.
- Throughput. Work that stays inside its domain scales with the
domains: 12.5x at 16 domains on a 16-core desktop, 20x at 24 on a
24-core server. Traffic between domains does not: one lock guards the
cross-domain queues and falls off beyond 4 to 8 busy domains, and one
I/O thread carries every socket of a process (about 45 to 75 thousand
remote Calls a second on loopback on the desktop, several times less
on an older server CPU). On a two-socket host, keep domains that talk
to each other on one node with
--numa. - Many concurrent remote sends. Each queued frame reserves about
4.2 KB; 16 domains with 16 Calls each in flight fill the default
256-item queue to the I/O thread, so raise
--limit bridge-tx-itemsbeyond that.
Tested on macOS 15 (Apple M3 Ultra, kqueue), Linux 6.17 (Ryzen 9 9950X) and Linux 6.12 (a two-socket Xeon E5-2650 v4 server), both with epoll: unit, sanitizer and multi-process tests on each, two and three physical hosts (static and discovery, HMAC and TLS), network fault injection on Linux, and soak runs of up to 90 minutes. Not tested: four or more hosts, WAN links, IPv6 or NAT, more than 8 processes or 16 domains per process under message load. The tested environment lists every run.
24.10 gogoserver: the host of the star
gogoserver (make server) is the host for chapter 20’s star: it runs
compact images, the server node of the star among them, each in a
domain of its own, with the options of 24.7 that are not about peers
(--max-actors up to 61440 there). Its domains are ordinary VMs with
the host’s real sockets; they do not message each other by PID. Use
gogopeer when servers must talk to each other by PID.
24.11 Further reading
- docs/peer-runtime.md: the reference. Every
gogo/peerfunction and error, every option, configuration key,--limitkey and statistics field, the capacity and memory costs, kernel socket buffers, upgrades, the tested environment and the known limits. - runtime/server/PEER_SERVER.md: the guide to the server’s parts in the order they were built: TLS provisioning, discovery, names and readiness, diagnostics, services, events, factories, local channels, flow control, the lifecycle, budgets, performance and the soak test.
- Known issues: the server runtime’s open limitations, with workarounds.
- docs/design.md, section 5.14: why the server runtime is built from fixed domains, and the design records in docs/plans/.