Forwarding (experimental)
Several Node servers can share one Postgres or MySQL store, so that a browser may call any of them.
Each instance runs on one node at a time, its home: the node that holds its lease. The lease row
names the home, because each node's store sets its lease holder to the node's internal URL. A
node that cannot open an instance because another node holds its lease forwards the request to that
node, with the call protocol a browser uses, and passes the home's answer back.
It needs no message queue, since the lease row already names each instance's home.
// This node's routes as the other nodes reach them, such as http://10.0.0.7:3000/motoko.
const self = process.env.MOTOKO_SELF!;
// The same URL of every node in the cluster.
const peers = process.env.MOTOKO_PEERS!.split(",");
const store = createPostgresStore(pool, { holder: self, ttlMs: 5_000 }); // or createMysqlStore(pool, { ... })
const runtime = createAgentRuntime({ agents, host: processHost(store), models, ports });
const cluster = nodeCluster({ self, peers });
const handler = motokoHandler(runtime, { basePath: "/motoko", resolve, authorize, cluster });The handler makes no connection itself: it hands each request whose instance a peer holds to its
cluster, a MotokoCluster, which answers the home's response, or undefined for 503
lease_held. nodeCluster(options) is that function on Node's http and https, and it validates
its options, throwing a TypeError for a self that is not an http(s) URL or a connectTimeoutMs
that is not positive:
selfis the base URL of this node's routes,basePathincluded, at an address its peers can reach. The store'sholdermust be the same string.createPostgresStoreandcreateMysqlStoreboth takeholderin their options. Without it the holder ishostname:pid, which is not a URL, so no node forwards to it.peersis the list of every node'sself, or a predicate of one holder. It is required, because a forward carries the caller's credentials. A node forwards only to a holder thatpeersnames.connectTimeoutMs(default 2 000) is how long a forward waits to connect to the home.
What a node forwards
A call or a follow is forwarded when its instance's open is refused with LeaseHeldError and the
holder is a peer, is not self, and is an http or https URL. Any other refusal is answered 503
lease_held, as without cluster. A forward sends the home this request:
- The same method, to the holder's URL followed by the request's path below
basePathand its query. - Every header of the request, credentials included, except those of its connection:
Host,Connectionand the headers it names,Content-Length,Expect,Keep-Alive,Proxy-Authorization,Proxy-Authenticate,Proxy-Connection,TE,Trailer,Transfer-EncodingandUpgrade. - The call's body as the handler read it, within
maxBodyBytes. - One more header,
motoko-forwarded-by: <self>.
Each forward opens a connection of its own, so a home that is gone fails the connect before anything is sent.
A request that already carries motoko-forwarded-by is never forwarded again. The node that sent
it read this node as the home, and this node is not, so the lease moved meanwhile. It is answered
503 lease_held, and the client tries again.
The node that forwards runs resolve and authorize before it learns where the instance lives. The
home runs both again on the forwarded request.
An ask travels the same way. A deferred call's start submits with replyTo to any node, which
forwards it to the asked instance's home. When the asked run ends, that home's deliverReply sends
reply to any node with the asker's credentials, and it is forwarded to the asker's home. A
deliverReply that posts to its own node is enough:
deliverReply: async ({ to, text, isError }) => {
const asker = motokoClient(httpTransport({ baseUrl: self, headers: credentialsOf(to.scope) }));
try {
await asker.reply(to.sessionId, { toolCallId: to.toolCallId, token: to.token, text, isError });
} catch (error) {
// Refused for good: the call waits for no reply, or its session is gone. Anything else is tried again.
if (!(error instanceof MotokoError && ["reply_not_pending", "session_not_found"].includes(error.code))) throw error;
}
},credentialsOf is the app's: whatever its resolve and authorize accept for the asker's instance.
What the client gets
| The home | The answer |
|---|---|
| answers | the home's status, headers and body, as the home sent them |
accepts no connection within connectTimeoutMs | 503 lease_held, with Retry-After |
| got the request, and the connection broke | an answer that breaks off where the home's did |
The home's answer passes back whatever it is: a result, a call error, or the app's own refusal from
resolve, such as a 401 with its own body and headers. Only the headers of the connection and
Content-Length are left out. A connection that breaks before the home answers is a 502 whose body
breaks off at once. httpTransport rejects such a call with connection_closed, since it may have
run, and retries such a follow.
Retry-After is the whole seconds until the lease expires, by the node's clock, as the store read
the lease. A holder that is alive renews its lease before then, so a retry at that time may be
refused again.
A follow streams through: every event, heartbeat and ended comes from the home. When the client
goes away, the forwarding node ends its request to the home, and the home stops its reader. When the
home's stream ends without ended (the home shut down, or lost the lease), the forwarded stream ends
too. The client reconnects with Last-Event-ID, and the cursor rules resume it
exactly, on whichever node is the home by then.
What a forward costs
A forward adds one hop. The node that forwards first tries to take the lease (two statements, one
of them to name the holder), then sends the request to the home on a new connection.
bench/failover.ts in packages/cluster-tests measures it on one machine:
listSessions took 0.15 ms (median of 300) answered by the home. Through a peer it took 0.8 ms on
PGlite, and 1.3 ms and 6.5 ms in two runs on Postgres 17 in Docker. Between machines, add two
database round trips, a TCP handshake, and one request to the home. A load balancer that routes by
user, so that most calls reach the home, saves most forwards.
Failover
A home that shuts down releases its leases in runtime.close(), and the next call on any node takes
the instance over at once. A home that crashes holds its leases until they expire, ttlMs after its
last renewal. Until then, the other nodes answer that instance's calls 503 lease_held. A cluster
should shorten ttlMs from the default of 30 seconds.
bench/failover.ts measures it: the home's store stops reaching the database and its server closes,
and another node calls every 5 ms until the instance answers. With ttlMs: 1_000 (a renewal every
333 ms), 20 crashes on PGlite and 10 on Postgres 17 each took 0.69 to 1.01 seconds. Counted from the
home's last renewal instead, each took 0.97 to 1.03 seconds: the instance opened on the new home at
the first call after the lease expired. With ttlMs: 3_000, failover took 2.1 to 3.0 seconds.
A shorter TTL adds little traffic: each node's store renews all its leases in one statement every
ttlMs / 3, however many instances it holds. Its risk is that a home that cannot reach the database
for ttlMs loses its leases, and their instances close. ttlMs: 5_000 keeps a crashed home's
failover to about 5 seconds.
httpTransport retries a follow after a 503 with its own backoff, which doubles from half a second,
so a follower may reconnect up to its current wait after the takeover. Run runtime.recover() on
each node every ttlMs or so, so that work a crashed home left carries on before the next call.
Security
- A forward sends the caller's credentials to another server, so a node sends them only to a holder
that
peersnames. A holder read from the database is never trusted alone: a stale row, or a row that someone else wrote, gets nothing. - The home authenticates and authorizes every forwarded request again with its own
resolveandauthorize, and its refusal passes back unchanged. Nodes do not sign requests to each other, andmotoko-forwarded-bygrants nothing: it only stops a second forward. A client that sends it gets 503 instead of a forward. - A forward to an
httppeer is plain HTTP. Keep the peers on a private network, or give themhttpsURLs, whose certificates Node verifies. - A
lease_helderror's message names the holder, so a client can read a node's internal URL.
What is not built
- Placement by hashing: an instance's home is the node that its first call after a free lease reaches.
- Fan-out: each follow is its own stream from the home, through one node.
- Rebalancing: an instance stays on its home until the home closes it (an idle close or a shutdown) or loses its lease.