Collaboration server
How @nextgensoftwares/folio-server-node stores documents, keeps memory in check and stays correct when the host runs it at scale. The protocol and the client side are in Collaboration and Real networks; the API is on the server-node and sync pages.
Every change to a document goes through one authority path (MemoryDocumentServer.submit in @nextgensoftwares/folio-sync): version check → validatePush (steps apply, checksum, mass-delete guard, role policy) → the committed hook (persistence) → apply in memory → broadcast. REST pushes, collab pushes and server edits all take it, so they are validated, persisted and broadcast identically.
The storage contract
A host plugs its database in through DocStorage. Every method may return a value or a Promise, so synchronous stores (files, SQLite) and asynchronous ones (Postgres, Mongo, a key-value service) implement the same interface, and storage written for earlier versions (synchronous methods) keeps working.
| method | contract |
|---|---|
load(docId) | the last snapshot plus the step log after it ({ snapshot: { version, doc }, log, logFrom, layout?, meta? }), or undefined |
create(docId, doc, meta?) | a document at version 0; refuse if it exists |
append(docId, from, steps) | durable before it resolves. Refuse (throw or reject) unless from is the next version the store holds: a conditional insert, never an overwrite |
snapshot(docId, version, docJson, keepFrom) | replace the snapshot atomically; steps older than keepFrom may then be dropped |
list({ after?, limit? }) | ids in ascending order; a store may ignore the paging and return all (the server pages what it gets) |
head?(docId) | version and title without loading the document (listings) |
saveLayout?, close? | page hints; shutdown |
Durability and the acknowledgement. The server acknowledges, applies and broadcasts a push only after append resolves. The order inside submit is: validate and compute the result without touching memory, await append, then commit to memory and broadcast. A failed append (the database is down, a constraint fired) therefore leaves the in-memory document, its version and the log exactly as they were; the push is refused with retryAfterMs (REST: 503 + Retry-After: 1, collab: an ack with retryAfterMs), and the client retries on its backoff schedule. No client ever sees an edit that isn't stored.
One write at a time per document. While an append is in flight, later pushes to the same document queue behind it, in arrival order (up to maxQueuedPushes, 64; beyond that they are answered retryAfterMs at once). A queued push based on the version before the append is answered "behind" (409 / ok: false) like any concurrent push: the client pulls, rebases and pushes again. Other documents are never blocked. With a synchronous store (the default MemoryStorage) nothing is queued and nothing is asynchronous.
In SQL, one table holds the log and one the snapshots:
create table folio_steps (
doc_id text not null, version bigint not null,
client_id text not null, accepted_at timestamptz not null, step jsonb not null,
primary key (doc_id, version) -- continuity: a gap or a second writer fails
);
create table folio_snapshots (doc_id text primary key, version bigint not null, doc jsonb not null);append is one multi-row INSERT in a transaction (the primary key refuses an overlap; check from = max(version) + 1 in the same statement to refuse a gap); snapshot is an upsert plus DELETE ... WHERE version < keepFrom.
Lazy load and memory
Nothing loads when the server starts. A document loads from storage on its first access (a manifest, a pull, a push, a collab connection, a server edit), after the request is authorized, and concurrent first accesses share one load (open(docId)). Idle documents leave memory again:
- after
evictIdleMs(10 minutes) without access, or beyondmaxLoadedDocs(least recently used first); - never while a collab room holds the document, a write is pending, or steps are not yet in a snapshot (it is snapshotted first, then unloaded).
The next access reloads it (snapshot + replay of the log tail). GET /docs pages through storage (?after=&limit=, 1,000 per page, X-Folio-Next gives the next cursor) and describes unloaded documents through head when the storage has it.
Ownership and deployment
A document's authority must be in one place: two processes accepting pushes for the same document would both apply "version 42". There are two ways to run more than one instance: with an owner per document (below), or without an owner, with storage as the authority and every instance's commits fanned out to the others.
One instance (the default): no configuration. Every document is owned by the process; scale vertically, and use idle eviction to bound memory.
Several instances behind a load balancer, with ownership:
const app = createFolioServer({
schema, storage, // a shared database implementing claim + fenced writes
ownership: new StoreOwnership(redisLeaseStore), // or MemoryOwnership in one process
instance: { id: `${host}-${process.pid}`, url: `https://${host}.internal:8787` },
leaseMs: 30_000,
});- The first instance to access a document acquires its lease (
DocOwnership.acquire) and claims storage with the lease's fencing token before loading it. Only it accepts edits (and serves the document). - Any other instance answers
421 Misdirected RequestwithX-Folio-Owner: <owner url>and{ error: 'not-owner', owner, hint }, and refuses the collab upgrade the same way. HTTP clients retry 421 with backoff (isRetryable); a smart load balancer or a host's client can follow the hint. - Leases are renewed every third of
leaseMs. An instance that can't renew (crashed, partitioned, paused) loses the lease; another one acquires it with a higher token after it expires (failover takes up toleaseMs). - On losing a lease an instance stops at once: the document is dropped from memory, its collab sockets close with code
4409(clients reconnect and land on the new owner), queued pushes fail and are retried by their clients. - Fencing makes this safe even when an old owner doesn't notice in time (a GC pause, a clock jump): every storage write carries the token, storage keeps the highest token it has seen per document and refuses anything older (
StaleTokenError). The new owner'sclaimraises the token before it loads, so nothing the old owner writes afterwards can land. Together with the continuity check (frommust be the next version), no step is lost or written twice. Idle documents release their lease, so another instance can pick them up without waiting.
Routing. Sticky routing by document id (hash /docs/:id/... to an instance, e.g. nginx hash $doc_id consistent) makes almost every request hit the owner; ownership is then the safety net for rebalancing and failures. Without stickiness, requests that hit a non-owner get 421 and the hint; the load balancer (or a small proxy) can redirect on it.
Implementing DocOwnership. Use StoreOwnership over a LeaseStore (a compare-and-set record per document) or write your own with the same contract: acquire grants a lease only when none is live, with a token higher than every token granted before (keep the record on release so tokens never repeat; persist it); renew extends a live lease with the same token or returns null; release expires it early. Redis: one key per document holding {owner, hint, token, expiresAt}, swapped with a Lua compare-and-set. SQL: UPDATE folio_leases SET owner = $me, token = token + 1, expires_at = now() + $ttl WHERE doc_id = $1 AND (expires_at < now() OR owner = $me) RETURNING token.
Fencing in SQL. Keep fence bigint on the document row and make every write conditional, in the same transaction:
update folio_docs set fence = $token where doc_id = $1 and fence <= $token; -- 0 rows: stale, roll back
insert into folio_steps (doc_id, version, ...) values ...; -- primary key: continuityclaim is the first statement alone. Fencing must fail closed: if the current token can't be read, is corrupt, or is missing for a document that had one, refuse the write (the client retries); tokens only move forward.
FileStorage fences with a fence.json per document (plus a write-once fenced marker, so a vanished record is detected rather than restarted at 0) under an exclusive lock file per document (withFileLock: O_EXCL create with the holder's id, heartbeat, stale locks broken only under a guard lock, release only by the holder). That is mutual exclusion for processes on one host with a local filesystem. Network filesystems (NFS and the like) don't reliably provide atomic O_EXCL and rename, so FileStorage ownership is single-host: for instances on several hosts, implement DocStorage and the lease store over Postgres, MySQL or Redis as above. MemoryStorage fences within one process.
Server-side edits
Hosts change live documents on the server (a publish workflow, an AI edit, a migration, an admin fix) with edit, never by overwriting storage:
import { replaceBlock, setBlockAttrs } from '@nextgensoftwares/folio-sync/server';
await app.documents.edit('book-42', (tr, doc) => {
replaceBlock(tr, 'chapter-3-intro', { type: 'paragraph', attrs: { id: 'chapter-3-intro' }, content: [{ type: 'text', text: 'Revised intro' }] });
setBlockAttrs(tr, 'title', { textAlign: 'center' });
}, { origin: 'publish', user: { id: 'publish', name: 'Publishing', color: '#0f766e' } });fn gets a prosemirror-transform Transform of the current document (with the server's schema) and adds steps; returning false or adding none changes nothing. The steps then take exactly the path of a client push: they are queued behind writes in flight, version-checked, validated (validatePush), appended to storage (fenced, on the owner only), applied and broadcast. Live clients receive them as steps and rebase their unconfirmed edits over them, as with any collaborator; REST clients get them on their next pull. Steps are recorded under origin ('server' by default), which is what history and blame show, with user as its display name.
Helpers address blocks by their id attribute, which survives other people's edits: replaceBlock, setBlockAttrs, insertBlocks (an index, or before / after an id), deleteBlocks, replaceDocument (one replace step: clients keep their unconfirmed edits where they still map), and findBlock. Server edits may delete most of a document by default (confirm: true); pass confirm: false to keep the mass-delete guard.
Over HTTP, with allowEdits: true: POST /docs/:id/edit with { ops, version?, confirm? } (replaceBlock, setBlockAttrs, insertBlocks, deleteBlocks, replaceDocument, or raw steps at version). It runs authorize(req, id, 'edit') before anything else (give that action to trusted services only), validates the shape and the content against the schema (400; 422 for node types the schema lacks), applies all operations as one edit or none, and attributes it to editOrigin(req, id) (default 'server'; the body can't choose an author). A version that is no longer current gets 409, so a service can read, decide and write without overwriting anyone.
Retention and sizing
Every accepted edit is a step in the log, and a long-lived document would grow without bound. After each snapshot the server keeps only the newest steps that fit the retention policy, in memory and in the log:
createFolioServer({
schema, storage,
retention: {
keepSteps: 20_000, // default
keepBytes: 8 * 1024 ** 2, // default
keepDays: 30, // also drop steps older than this (default: no age limit)
checkpointEvery: 30_000, // a periodic checkpoint every N steps (default 0: none)
keepCheckpoints: 10, // periodic checkpoints kept (named ones always)
},
});- A step is kept only while it fits every cap; trimming happens at the next snapshot (every
snapshotEverysteps orsnapshotIdleMsidle). The olderretainSteps/retainStepBytesoptions are aliases ofkeepSteps/keepBytes. - A client further behind than the oldest kept step can't catch up with steps: REST pulls get
410andSyncClientstops withstate: 'diverged', reason: 'gone'; collab clients get thegoneerror. Both keep their unsaved edits in the outbox; the host reopens the document from the snapshot. - Checkpoints are snapshots kept as version history:
checkpoint(docId, name?)keeps a named one ("Sent to the printer") forever,checkpointEverywrites periodic ones and keeps the newestkeepCheckpoints. Storages that implementcheckpoint/checkpoints/readCheckpoint/dropCheckpointkeep them (MemoryStorage,FileStorage:checkpoints/<version>.json). The collab plugin'sHistoryStore(timeline, diffs, blame) is separate and has its own compaction. await documents.storageStats(docId)reports the snapshot bytes, log steps and bytes, the oldest version clients can catch up from, checkpoints, what is held in memory, the average stored bytes per step and the growth per 1,000 edits.
Measured sizes
node tools/collab-sizing.mjs (after pnpm build) pushes real edits through PersistentDocumentServer into a FileStorage log on a ~300-page book (15 chapters, 1,440 top-level blocks, ~95k words, tables and figures) and measures the bytes on disk. Each log line is the step JSON plus ~50 bytes of version, author and time. Gzip is measured on segments of 1,000 lines, as a store that compresses closed log segments would keep them (FileStorage does not compress; Postgres' TOAST does not compress rows this small).
| edit | stored bytes/step | step JSON | gzip (1k-step segments) |
|---|---|---|---|
| typing (one character) | 147 | 96 | 14 |
| delete (one character) | 98 | 47 | 13 |
| paste (3 paragraphs, ~1,200 characters) | 2,417 | 2,368 | 303 |
| bold over a range | 120 | 70 | 14 |
| typing in a table cell | 147 | 96 | 14 |
| add a table row (4 cells) | 2,922 | 2,873 | 134 |
| insert an image block | 596 | 546 | 48 |
The snapshot of the book is 614 KB (140 KB gzip). Step JSON carries every attribute, defaults included (snapshots and chunks use the compact wire format), which is why structural steps (table rows, images) are larger than their content.
Example: a 300-page book edited by 5 people for a semester (15 weeks × 5 working days; each person-day ≈ 4,000 typed characters, 800 deletions, 8 pastes, 40 formatting changes, 200 characters in tables, 2 table rows, 2 images = 5,052 steps, 144 bytes on average): 1.89 million steps.
| policy | storage for the book |
|---|---|
| keep every step (no retention) | 273 MB (27 MB with gzip segments) |
| default retention (20,000 steps / 8 MB) | 3.5 MB |
| default + a checkpoint per working day, newest 10 kept | 9.6 MB |
| default + a named checkpoint per week, all 15 kept | 12.7 MB |
| log growth per 1,000 edits (this mix) | 144 KB (14 KB gzip) |
So: retention bounds a document's storage to about one snapshot plus keepBytes, whatever its age; full version history is a choice of checkpoints (one snapshot each), not of the step log. With the default policy a client can be about 20,000 steps (≈ one working day of five people) behind and still catch up with steps; beyond that it reopens.