Several instances without an owner
Ownership gives each document one instance that accepts its edits. Some deployments can't route a client to that instance: one socket per browser tab carries every document, behind a load balancer that isn't sticky per document. Folio also runs without an owner:
- every instance keeps its own copy of the documents it serves (rooms, REST pushes, pulls);
- storage is the authority: a write lands only if it's the next version (
DocStorage.append's next-version check), so two instances can never both write version n; - each instance's commits are fanned out over a pub/sub bus to the others, which apply them to their copies without writing anything (
applyCommitted); - a copy that falls behind (a lost or late message) catches up from storage.
What you provide
A DocStorage that refuses a racing write with VersionConflictError.append(docId, from, steps) must refuse unless from is the next version it holds, in the same transaction as the insert: a unique (doc_id, version) key in SQL, then turn the unique violation into new VersionConflictError(docId, from). Any other error is a failed write (the client retries later). Snapshots must be idempotent by version: ignore a snapshot older than the stored one (... WHERE snapshot_version <= $version). Implement head (version without loading) and logSince(docId, from) (the log tail): a lagging instance uses them instead of loading the whole document. MemoryStorage follows this contract and is what the tests use.
A pub/sub bus, any that delivers one publisher's messages on a channel in order: Redis pub/sub, NATS, Postgres LISTEN/NOTIFY, a cloud topic. PubSub is two methods:
interface PubSub {
publish(channel: string, message: string): void | number | Promise<void | number>;
subscribe(channel: string, fn: (message: string) => void): (() => void) | Promise<() => void>;
}Delivery may be at most once. Folio recovers from lost messages (below).
Wiring
import { CollabRooms, fanOutCommits, PersistentDocumentServer } from '@nextgensoftwares/folio-server-node';
const docs = new PersistentDocumentServer(schema, storage, { pushPolicy });
const stop = await fanOutCommits(docs, bus, { instance: myInstanceId });
const rooms = new CollabRooms(docs); // attach your own sockets: rooms.attach(docId, conn)fanOutCommits publishes every change committed on this instance and applies every other instance's change to the documents loaded here. If you'd rather send changes yourself, for example inside your own change notices, use the two halves:
onCommitted(docs, (change) => …): every local commit (room pushes, REST pushes, server edits), never a replicated one. The change hasdocId,from,version,steps,clientIDs,at,epochandchecksum, plus who made it:userId(the pusher's, fromroleOfor the room connection; a server edit'suser.id) andvia('room','rest'or'edit'). Use them for app hooks that need the user, such as a document's status or per-user edit history.docs.applyCommitted(docId, committedSteps(change))on the other instances. It returnsapplied,duplicate,unloaded,caught-up,gapormismatch.
Commit listeners (docs.onCommit((docId, from, steps, origin, meta) => …)) see both kinds, with origin set to 'local' or 'replica'. Fan out only local ones. meta is { userId?, via? }; on a replicated change it's what the committing instance sent.
How races and losses resolve
- Two instances write the same version. Storage takes one. The other instance gets
VersionConflictErrorand catches its copy up from storage. A push that takes rebasing (CollabClientandSyncClientask by default) is then retried once, mapped over what the other instance wrote, and accepted; others are answered as behind (room members receive the missing steps at once and resend, a REST push gets 409). Nobody waits for aretryAfterMs. - A fan-out message is lost or late. The next message for that document doesn't follow on (
gap), so the copy catches up from storage. If a client pushes there first, the write conflicts and the copy catches up the same way. If nothing happens on that document at all, the periodic check (reconcileMs, 5 s by default) compares the copy with storage's head version. Pulls served in the meantime are stale but consistent, and clients catch up when the copy does. - A copy that doesn't fit (another epoch, or a checksum mismatch after applying) is caught up from storage, or reloaded when the log no longer reaches back to it.
What stays per instance
- History (
RoomOptions.history) is recorded once, by the instance that committed the change. Rooms skip recording replicated steps. Share the history storage between instances. - Presence (cursors, selections) reaches only the members of the same instance's room, unless you fan it out too (below).
maxMemberscounts one instance's members.- Snapshots and periodic checkpoints may be written by every instance: storage keeps the newest snapshot by version, and steps are only dropped below a snapshot's version, so none are lost. To leave them to one instance, pass
snapshots: falseto the others. Their in-memory step tail is then trimmed byretentionas steps arrive. - Epochs. If your documents have lineages (
Manifest.epoch), overrideepochOf(docId)on your server class. Changes carry it, and a copy with another epoch catches up from storage instead of applying them. - Checksums. Every change carries the committing copy's checksum after the steps. A receiving copy that ends up with another one catches up from storage.
Presence across instances
import { fanOutPresence } from '@nextgensoftwares/folio-server-node';
const stopPresence = await fanOutPresence(rooms, bus, { instance: myInstanceId });Each instance publishes what its rooms' members show of themselves (only their visible presence: hidden readers stay hidden) and shows the other instances' members to its own as remote peers. Clients can't tell them from local ones: carets, typing, follow and the people list work the same. Each instance keeps the other instances' members per document, so someone who joins here sees at once who is already in the document elsewhere. A member who reconnects to another instance moves there; the old instance's late leave doesn't remove them.
An instance heartbeats every heartbeatMs (10 s). One not heard from for ttlMs (30 s) is gone, with all its members (a crash); one that stops says so, and its members disappear at once. The default channel is folio:presence. maxMembers still counts one instance's members.
The push policy holds everywhere
pushPolicy: (docId) => PushPolicy | undefined (a ServerOptions field) checks every client push after the pusher's role: room pushes, REST pushes and rebased pushes, on every instance. A returned string refuses the push as forbidden with that message. Server edits (edit) are trusted and skip it.
pushPolicy is synchronous. Checks that need I/O (a database lookup of media the user may place, say) go in beforePush:
const docs = new PersistentDocumentServer(schema, storage, {
beforePush: async (docId, { steps, clientID, userId, role, version }) =>
(await mediaRefused(docId, userId, steps)) ? 'You can’t place that image here' : null,
});It runs on the same paths (room pushes after their parts are reassembled, REST pushes, and pushes the server rebases, on the steps as the client sent them) and skips server edits and replicated changes. A string refuses the push as forbidden (REST 422; in a room, a refused ack with the message). A throw or a rejection fails it as retryable: REST answers 503, the room acks retryAfterMs, and nothing is applied.
It runs before the document's write queue, so a slow check doesn't hold up other writers. Order is still safe: a client has one push in flight, and a resend after an ack timeout carries the same base version, so whichever lands second is refused as behind (or rebased) by the version check. A check slower than the client's ack timeout (5 s for rooms) runs again on the resend. Keep it fast or cache its answers.
Both apply. beforePush runs first, then the role policy and pushPolicy when the push is validated in the queue. Rooms refuse viewers and commenters before either; on REST a viewer's push reaches beforePush (its role says so) and is then refused by the role policy.