Real-Time Collaborative Editor with Git Sync
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a real-time multi-user collaborative document editor integrated with two-way Git version control.
Base your design on the following operating constraints and product questions:
- Concurrent editing & transient disconnects: Multiple authors edit the same page simultaneously and may briefly lose network connectivity before reconnecting and syncing pending work.
- Deterministic convergence: Every accepted edit requires a stable identifier together with an explicit ordering or conflict-free merge rule so all connected browsers converge on identical content.
- Git as periodic checkpoints: Repository commits represent durable milestones and external developer workflows—not the millisecond-level collaboration transport.
- Clarifying product choices to pin down up front: Define what document representation you are targeting (plain text, formatted rich text, or structured blocks), how long offline sessions must be tolerated, and what convergence or conflict UX authors expect when live edits meet concurrent changes.
Scope & Expectations
- Client representation & local edit management: Cover frontend tokenization, mapping between visual UI and underlying document offsets, buffering unacknowledged local edits, and tracking live cursors/selections.
- Merge model, streaming, & journaling: Justify your merge semantics (e.g., Operational Transformation, CRDT, or server-serialized revisions) and design the real-time transport, reconnect catch-up flow, and backend operation/session journal.
- Snapshots vs. append-only log: Analyze the storage, read-latency, and retention trade-offs between full-document blob snapshots, an append-only edit log, and hybrid compaction.
- Bidirectional Git synchronization: Show how browser milestones commit cleanly to Git branches and how external
git pushupdates merge back into active editing sessions without blocking live typing.
Step-by-step walkthrough
Clarify requirements and collaboration assumptions
Before sketching components, pin down the three open product choices up front because every downstream decision—tokenization, journaling, and repository sync—hinges on them:
- Document representation (raw text vs. rich blocks): Target technical documentation written in MDX (Markdown combined with JSX UI components like callouts or tab groups), mapped 1-to-1 to files inside a Git repository. Although the browser offers both a visual block view and a raw code view, plain MDX text is the canonical wire and storage format so Git diffs, blame history, and merges stay clean.
- Expected disconnect window: Support short connectivity gaps from a few seconds up to roughly an hour (riding through a subway tunnel, closing a laptop between rooms, or unstable Wi-Fi), letting authors keep typing locally and catch up automatically on reconnect. Multi-day disconnected editing is out of scope; we note below how the merge engine would change if multi-day offline support were mandatory.
- Convergence and conflict UX: Local typing renders immediately (0 ms network wait), co-editors see updates within 200 ms, and all browsers converge to the exact same string without file locks or merge pop-ups during live editing. Once the server acknowledges an edit, that edit is durable. Human intervention is reserved for one edge case: an external
git pushmodifying the exact same lines someone is actively editing in the browser.
Functional requirements
- Concurrent real-time editing of an MDX page, plus live presence (showing who is viewing the page and where their cursors and text selections sit).
- Fine-grained version history and one-click restore to an earlier point in time.
- Two-way Git integration: browser edits periodically become Git commits (durable milestones), and commits pushed from external Git tools flow back into live browser sessions.
- Support for images and large binary files referenced inside pages without bloating the text stream.
Non-functional requirements
- Low latency: 0 ms local echo; remote edits delivered in under 200 ms at p95 (95th percentile, meaning 95 out of 100 edits arrive within 200 ms) inside a region.
- Durability: Any edit acknowledged by the server survives a single-node crash.
- Fast failover: If the server hosting a live session crashes, clients reconnect within ~15 seconds without losing local unacknowledged keystrokes.
- Git decoupling: Slowness or downtime at the external Git host (such as GitHub or GitLab) never stalls live typing.
Back-of-the-envelope numbers
Estimating traffic and data sizes early tells us where the real bottlenecks live and immediately settles half of the snapshot-versus-log storage question.
Documents and active sessions total documents 2,000,000 MDX pages (20 KB typical, 1 MB max) open documents at peak 5,000 pages connected browsers at peak 15,000 (~3 per open page; hard cap 50 active editors/page) actively typing at once 20% of 15,000 = 3,000 concurrent typists Live operations and presence client keystroke batching at most 1 operation message every 100 ms -> ~3 ops/s per typist peak inbound edit rate 3,000 typists x 3 ops/s = 9,000 ops/s peak outbound edit messages 9,000 acks/s (to senders) + 9,000 x 2 co-editors = 18,000 broadcasts/s (27,000/s total) presence (cursors/selections) 3,000 active users x 5/s = 15,000 inbound updates/s 15,000 x 2 co-editors = 30,000 outbound messages/s (never stored) Append-only operation journal size of one stored operation ~120 B (doc_id, rev, base_rev, client_id, client_seq, author, payload) peak journal write rate 9,000 ops/s x 120 B = 1.08 MB/s (~1.1 MB/s) daily volume (avg = 1/4 peak) 2,250 ops/s x 86,400 s/day = ~194M ops/day (~23.3 GB/day) 30-day journal retention 23.3 GB/day x 30 days = ~700 GB total Periodic full-text snapshots triggers every 500 ops on a page, plus when the last editor closes the page periodic snapshot write rate (9,000 ops/s / 500) x 20 KB = 18 snapshots/s x 20 KB = 360 KB/s session-close snapshot rate ~5,000 pages / 1,200 s x 20 KB = ~4.2 closes/s x 20 KB = ~84 KB/s total peak snapshot writes 360 KB/s + 84 KB/s = ~444 KB/s (< 0.5 MB/s) vs. naive full-blob per edit 9,000 ops/s x 20 KB = 180 MB/s (~160x the op journal!) Opening a page read 1 latest snapshot (20 KB) + replay at most 500 ops (500 x 120 B = 60 KB) -> < 10 ms Git milestones triggers explicit Publish, 2 min idle, or every 15 min of continuous typing file milestone rate ~5,000 active pages / 600 s = ~8.3 file updates/s, batched per branchThree takeaways jump out from the math:
- The journal write volume is tiny (~1.1 MB/s at peak), whereas WebSocket connection management (15,000 sockets) and ephemeral cursor fan-out (30,000 messages/s) dominate network message count.
- Saving a whole 20 KB file on every edit would write 180 MB/s—about 160x more than logging 120-byte operations, proving we should not write full blobs on every keystroke.
- Git sees only a few batched commits per second across all customers, orders of magnitude below 9,000 ops/s, confirming Git belongs off the real-time path.
Choose the merge model first
We must pick how concurrent edits merge before designing tokenization, journaling, or networking, because the merge model dictates what an "edit" looks like. There are three realistic candidates:
- Serialized server operations (optimistic rebase): The server accepts an edit only if its
base_revmatches the latest server revision; otherwise the server rejects it and forces the browser to download new edits, recompute, and retry. - Operational Transformation (OT) with a central server: Browsers address characters by numeric position (offset). One server assigns sequential revision numbers (
1, 2, 3, ...) and mathematically adjusts (transforms) the offsets of any edit that was written against a slightly older revision. - Conflict-free Replicated Data Type (CRDT): Every single character ever typed gets a globally unique ID and stays in a data structure (keeping deleted characters around as invisible markers called tombstones) so edits commute in any delivery order without needing a central coordinator.
Dimension Serialized server ops Central-server OT CRDT (e.g., Yjs / RGA) ---------------------- -------------------------- -------------------------- -------------------------- How text is addressed Numeric character offsets Numeric character offsets Unique ID per character Heavy contention Slow clients bounce/retry Zero retries; transformed Zero retries; commutative Offline for days Large client rebase Works for short gaps; odd Natural fit merges on huge divergences Needs a central server Yes Yes No (peer-to-peer capable) Storage overhead Plain text only Plain text only Per-char IDs + tombstones; garbage collection is hard Change identity (doc_id, rev) total order (doc_id, rev) total order (client_id, counter) causal Git milestone mapping "Commit X == rev 18,240" "Commit X == rev 18,240" Multi-client state vectorOur choice: Operational Transformation (OT) with one central sequencer per document (the Jupiter protocol used by Google Docs and
ot.js).- Exact match for stable identity and total order: Every accepted edit gets
(doc_id, rev)with strictly increasing integers (rev = 1, 2, 3, ...). Appending to the journal is "insertrev + 1", reconnecting is "send me all ops afterrev 1204", and a Git commit maps cleanly to a single integer revision. - Zero metadata overhead for Git: Stored snapshots are pure MDX strings with no CRDT tombstones or character IDs to strip out.
- Contained math complexity: Classical peer-to-peer OT is notoriously bug-prone because it requires TP2 (Transformation Property 2, guaranteeing convergence when three peers transform edits in different orders without a central server). With a single server sequencing each document into one linear timeline, our
transformfunction only needs TP1 (Transformation Property 1: given two concurrent editsAandB, applyingAthen transformedB'produces the exact same string as applyingBthen transformedA'). - When we would switch: If product requirements changed to multi-day offline editing or peer-to-peer collaboration without a server, a CRDT like Yjs would win.
Operation format and step-by-step trace
Each operation is a compact list of steps that walks across the entire string from left to right:
retain(n) keep the next n UTF-16 code units unchanged insert(s) insert string s at the current position delete(n) remove the next n UTF-16 code units Example on "Hello world" (11 units): [retain(5), insert(","), retain(6)] -> "Hello, world" (12 units)Now trace what happens when Alice and Bob edit
"Hello world"concurrently, both starting from server revision41:Start at rev 41: "Hello world" (length 11) Alice types "," after "Hello": A = [retain(5), insert(","), retain(6)] (base_rev = 41) Bob deletes "world": B = [retain(6), delete(5)] (base_rev = 41) 1. Server receives Bob's B first (base_rev 41 == current rev 41): - Applies B directly -> "Hello " (length 6), assigns rev 42, broadcasts B. 2. Server receives Alice's A (base_rev 41 < current rev 42): - Transforms A against rev 42 (B): Alice's comma at index 5 is before Bob's deletion at index 6, and the 5 deleted characters shrink Alice's trailing retain(6) to retain(1): A' = [retain(5), insert(","), retain(1)] - Applies A' to "Hello " -> "Hello, " (length 7), assigns rev 43, acks Alice, broadcasts A'. 3. Meanwhile on Alice's browser (which already showed "Hello, world" locally): - Receives Bob's B (rev 42) while A is still unacknowledged: - Transforms B against A: Alice's inserted comma shifted "world" right by 1 character, so B' = [retain(7), delete(5)]. - Applies B' to "Hello, world" -> "Hello, " (length 7). Both browsers and server match!We verify
transformexhaustively in CI using randomized property-based testing:def converges(doc, op_a, op_b): """TP1 check: (doc + op_a) + op_b' must equal (doc + op_b) + op_a'.""" op_a_prime, op_b_prime = transform(op_a, op_b) left_path = apply(apply(doc, op_a), op_b_prime) right_path = apply(apply(doc, op_b), op_a_prime) return left_path == right_pathIf Alice and Bob both insert at the exact same offset,
transform(unsequenced_op, sequenced_op)breaks ties deterministically by placing the first argument (unsequenced_op) to the left of the second (sequenced_op). Because both the client (transforming its pending op against an arriving server op) and the server (transforming an arriving client op against an already-sequenced op) pass(unsequenced_op, sequenced_op)in that same order, every copy breaks ties identically.- Serialized server operations (optimistic rebase): The server accepts an edit only if its
API and WebSocket protocol
Real-time edits flow over a WebSocket (a persistent, bidirectional TCP connection between browser and server so either side can push messages instantly without HTTP polling overhead), while infrequent actions use standard REST HTTP endpoints.
WebSocket: wss://collab.example.com/v1/docs/{doc_id}?protocol=2 Client -> Server messages hello { client_id, auth_token, last_rev, protocol: 2 } submit { client_seq, base_rev, op, format: 2 } presence { cursor_offset, selection_end } throttled to <= 5/s, never written to disk Server -> Client messages welcome { rev, snapshot_text_or_ops_since_last_rev, participants } ack { client_seq, rev } op { rev, client_id, client_seq, author_id, op, format: 2 } presence { client_id, user, cursor_offset, selection_end } reload { reason } gap older than 30 days or protocol upgrade error { client_seq, code } INVALID_OP | FORBIDDEN | DOC_TOO_LARGE REST HTTP endpoints GET /v1/docs/{doc_id} -> { rev, text } GET /v1/docs/{doc_id}/history -> list of snapshots and Git milestones POST /v1/docs/{doc_id}/restore { rev } -> appends one new op transforming head into rev's text POST /v1/branches/{branch_id}/publish -> triggers immediate Git commit -> { commit_sha } POST /v1/assets -> { asset_id, presigned_upload_url, repo_path }Key protocol decisions:
(client_id, client_seq)is an idempotency key (a unique client-assigned ticket per edit so retrying after a dropped connection returns the original revision instead of inserting text twice).- Single ordered stream: Sending
ackandopframes over the same WebSocket guarantees a client never receivesrev 44beforerev 43. - Restore is append-only: Restoring
rev 100when the page is atrev 150does not delete revisions101..150; it computes the diff fromrev 150back torev 100and submits it asrev 151. Co-editors see the restore smoothly like any normal edit, and undo still works. - Explicit
protocolandformatfields from day one let us evolve the operation schema later without dropping active editors.
Data model and storage trade-off (snapshots vs. change stream)
Let's compare the two storage extremes mentioned in the prompt against a hybrid design:
Storage strategy Blob snapshots only Append-only op log only Hybrid: op log + snapshots -------------------- -------------------------- -------------------------- -------------------------- Write cost per edit Full 20 KB file (180 MB/s) 120 B op (~1.1 MB/s) 120 B op + ~444 KB/s snaps Opening a document 1 fast blob read (20 KB) Replay entire history 1 blob read + <= 500 ops (200k ops = 24 MB slow!) (<= 80 KB total, < 10 ms) Reconnect support Broken for OT (no ops to Natural (stream ops after Natural (stream ops after transform pending edits) client's last_rev) client's last_rev) Attribution ("blame") Coarse file diffs Exact keystroke author Exact for 30 days; Git co-authors permanently Long-term disk size Size x save count Unbounded growth Bounded (~700 GB 30-day window + Git milestones)Why the hybrid wins: OT requires the historical operation stream to transform edits from reconnecting clients, so blob snapshots alone cannot support seamless reconnects. Conversely, an unbounded operation log without snapshots makes opening a mature page slower every month. Combining a 30-day rolling operation journal, snapshots every 500 ops (stored in content-addressed object storage, meaning each blob is named by the SHA-256 hash of its text so identical snapshots share one stored file), and permanent Git commits gives fast opens, instant reconnects, and bounded database size. Never delete a page's most recent snapshot even after 30 quiet days, so idle pages still open in one read.
Relational metadata & journal (PostgreSQL, sharded by doc_id) document doc_id (PK), repo_id, branch_id, path ("guides/quickstart.mdx"), head_rev, latest_snapshot_rev, owner_server, owner_epoch doc_op PRIMARY KEY (doc_id, rev) <- enforces strict linear order & fencing UNIQUE (doc_id, client_id, client_seq) <- deduplicates client retries base_rev, author_id, op_bytes, format_ver, created_at snapshot PRIMARY KEY (doc_id, rev), blob_sha256, client_watermarks JSONB <- {client_id: highest_client_seq} so retry deduplication survives log compaction session session_id (PK), doc_id, user_id, client_id, joined_at, left_at, last_acked_rev milestone PRIMARY KEY (branch_id, commit_sha), parent_sha, source (EDITOR | EXTERNAL_PUSH), files JSONB [(doc_id, rev, file_sha256)], co_authors, created_at branch_sync branch_id (PK), last_synced_commit, sync_worker_lease asset asset_id (sha256 PK), byte_size, mime_type, repo_path, uploaded_by, created_atNotice two critical schema details:
PRIMARY KEY (doc_id, rev)is our split-brain safety fence: Even if a network hiccup causes two session servers to think they owndoc_idsimultaneously, only one SQLINSERTfor(doc_id, 105)can succeed. The loser gets a unique-key violation, realizes it lost ownership, and disconnects cleanly.- Session-data journaling (
sessiontable): Recording session joins, leaves, andlast_acked_revgives us an audit trail of who contributed to every revision range, which directly populatesCo-authored-by:trailers in outbound Git commits.
High-level architecture
Browser A Browser B [ Visual MDX Blocks <-> Plain-Text Ops ] [ Visual MDX Blocks <-> Plain-Text Ops ] [ Local state + pending ops in IndexedDB ] [ Local state + pending ops in IndexedDB ] | WebSocket | WebSocket v v +----------------------------------------------------------------------+ | Edge Gateways (TLS, JWT auth, route doc_id -> current owner server) | +----------------------------------------------------------------------+ | v +----------------------------------------------------------------------+ | Session Servers (1 active owner per open doc via lease in etcd) | | In-memory per doc: current text, head_rev, recent ops, client sockets| +----------------------------------------------------------------------+ | 1. Group-commit ops (durable BEFORE ack/broadcast) | Every 500 ops / on close v v [ Sharded PostgreSQL: doc_op + session ] [ Object Storage (S3): SHA-256 Snapshots ] | ^ | Change feed / dirty-doc poll | Read text at milestone rev v | +----------------------------------------------------------------------+ | Git Sync Workers (1 lease owner per repo branch) | +----------------------------------------------------------------------+ | Outbound fast-forward commits ^ Inbound push webhooks + 1-min poll v | [ External Git Host (GitHub / GitLab repository) ]-+ Out-of-band binary uploads: Browser --(presigned PUT)--> [ Object Storage + CDN ] (MDX text stores only "/images/diagram-3f9a.png")Two architectural invariants keep the system fast and safe:
- Single active owner per open document: A lightweight coordination service (etcd, a strongly consistent key-value store used for distributed locks and leases) assigns each open
doc_idto one session server. Because one server sequences all edits for that page in RAM, assigning revision numbers requires a simple integer counter—no slow cross-server consensus per keystroke. - Durable before visible: The session server writes
rev Nto PostgreSQL before sendingackto the author or broadcastingopto co-editors. If the server crashed after broadcasting an unpersisted edit, teammates' browsers would display text that the replacement server never knew existed, permanently diverging the copies.
- Single active owner per open document: A lightweight coordination service (etcd, a strongly consistent key-value store used for distributed locks and leases) assigns each open
Deep dive 1: Frontend tokenization and local change management
Dual visual/source views over one plain-text string
In an MDX documentation editor, writers want Notion-like visual blocks (headings, callouts, tables) and raw Markdown/JSX source access. Storing structured JSON in the database and converting to Markdown at commit time causes noisy Git diffs (reformatting whitespace or reordering JSX attributes untouched by the user). Instead, the plain MDX string is the single state:
- Tokenization with byte/character spans: The browser parses the MDX string into an AST (Abstract Syntax Tree) of blocks, tagging each block with its half-open character span
[start, end)in the raw string and maintaining an inline offset map between visible characters and raw syntax characters (for example,**bold**displays 4 visible letters while occupying 8 source characters). - Incremental re-tokenization: When a local or remote edit touches
[edit_start, edit_end), the parser restarts at the first intersecting block and shifts subsequent block spans bydelta_lengthinO(blocks)time. One subtle edge case: typing an opening code fence (```) or unclosed<Callout>tag changes how every line below it parses, so incremental parsing continues downward until block boundaries re-align with the previous tree. - Universal UTF-16 offset counting: JavaScript strings index by UTF-16 code units, where an emoji like
"👍"takes 2 UTF-16 units (a surrogate pair, two 16-bit units encoding one Unicode character) but 4 UTF-8 bytes and 1 Pythonstrcode point. Every backend service (whether written in Go, Rust, or Python) must count offsets in UTF-16 code units, reject any operation that slices a surrogate pair in half, and never auto-normalize Unicode (which silently alters string lengths).
Client change management: the one-op-in-flight state machine
If a fast writer types 10 characters per second over a 100 ms connection, sending every keystroke immediately floods the server with tiny operations to transform. Instead, each browser maintains at most one unacknowledged operation in flight (
inflight) and merges (composes) all subsequent local edits into a singlebuffer, persisting both in IndexedDB (the browser's built-in local disk database) so a tab refresh during a tunnel never loses keystrokes:class ClientDoc: def __init__(self, text, rev): self.text = text # Current text shown immediately to the user self.rev = rev # Last server revision incorporated into self.text self.inflight = None # Single op sent to server, waiting for ack self.buffer = None # Composed local ops typed while inflight is waiting def local_edit(self, op): # Apply locally right away for 0 ms typing latency self.text = apply(self.text, op) if self.inflight is None: self.inflight = op send_submit(op, base_rev=self.rev) elif self.buffer is None: self.buffer = op else: # Merge consecutive local keystrokes into one combined operation self.buffer = compose(self.buffer, op) def on_ack(self, new_rev): # Server accepted self.inflight at new_rev; flush buffer if the user kept typing self.rev = new_rev self.inflight = self.buffer self.buffer = None if self.inflight is not None: send_submit(self.inflight, base_rev=self.rev) def on_remote_op(self, remote_op, new_rev): # Shift pending local work over the arriving server op, and vice versa if self.inflight is not None: self.inflight, remote_op = transform(self.inflight, remote_op) if self.buffer is not None: self.buffer, remote_op = transform(self.buffer, remote_op) self.text = apply(self.text, remote_op) self.rev = new_revRemote cursors are transformed through incoming ops just like zero-length inserts, and local undo keeps a per-user stack of inverse operations (transformed against incoming remote edits) so pressing
Cmd+Zundoes your last change rather than deleting a paragraph your colleague just typed.- Tokenization with byte/character spans: The browser parses the MDX string into an AST (Abstract Syntax Tree) of blocks, tagging each block with its half-open character span
Deep dive 2: Backend streaming, group-commit journaling, and reconnect
Sequencing and group commit on the session server
When a
submitarrives at the owning session server, it deduplicates retries, transforms stale offsets, persists to the journal, and broadcasts:def handle_submit(doc, client_id, client_seq, base_rev, op): # 1. Idempotency check: if a retry arrives after a lost ack, return original rev existing = doc.find_sequenced(client_id, client_seq) if existing is not None: return ack(client_seq, existing.rev) # 2. Transform incoming op forward across every revision committed since base_rev for committed in doc.ops_after(base_rev): op, _ = transform(op, committed.op) # 3. Validate bounds, UTF-16 surrogate pairs, and max document size (1 MB) validate(op, doc.text) # 4. Persist to journal BEFORE mutating state or notifying clients new_rev = doc.rev + 1 journal.insert(doc.doc_id, new_rev, client_id, client_seq, base_rev, op) # 5. Update in-memory state, broadcast to co-editors, and ack sender doc.text = apply(doc.text, op) doc.rev = new_rev doc.remember(new_rev, client_id, client_seq, op) broadcast_to_others(doc, new_rev, client_id, client_seq, op) return ack(client_seq, new_rev)- Group commit for hot pages: A synchronous cross-zone database write takes ~3 ms. If we waited serially on disk for each operation, one hot page would stall at ~330 ops/s. With group commit (batching all operations sequenced in RAM while one disk write is in flight into a single multi-row
INSERTimmediately afterward), disk latency stays ~3 ms while throughput scales effortlessly past 50 concurrent typists. Acks and broadcasts go out only after the batch commits. - Why sharded PostgreSQL instead of Kafka? Apache Kafka is a fast append-only log, but standard Kafka partitions cannot atomically reject a write with "insert
(doc_id, rev 105)only if105does not exist yet." Four PostgreSQL shards easily absorb 9,000 inserts/s (~2,250 inserts/s per shard) while enforcingPRIMARY KEY (doc_id, rev)andUNIQUE (doc_id, client_id, client_seq)out of the box.
Reconnecting cleanly after a tunnel or server failover
Suppose Alice disconnects at
last_rev = 1204withinflight(client_seq = 88) and more typing inbuffer. When her Wi-Fi returns, the server is atrev 1231:1. Alice sends: hello { client_id: "alice-tab-1", last_rev: 1204 } 2. Server replies: welcome { rev: 1231, ops: [rev 1205 .. rev 1231] } 3. Alice replays [1205 .. 1231] locally BEFORE sending anything new: - If op has (client_id == "alice-tab-1", client_seq == 88): Her original submit DID reach the server before the disconnect, and only the ack was lost! Mark self.inflight = None and self.rev = op.rev WITHOUT applying op to self.text again. - For every other user's op: Run on_remote_op(op, op.rev) to transform remaining local work and advance self.text. 4. Once caught up to rev 1231, promote remaining pending work to self.inflight and send with base_rev = 1231.Step 3 prevents a classic duplicate-text bug: if Alice treated her own echoed
seq 88as a stranger's edit, she would insert her sentence a second time. If a tab stays offline longer than our 30-day journal retention (exceedingly rare), the server sendsreload, and the browser runs a client-side three-way text merge using the last-synced text stored in IndexedDB as the common base.- Group commit for hot pages: A synchronous cross-zone database write takes ~3 ms. If we waited serially on disk for each operation, one hot page would stall at ~330 ops/s. With group commit (batching all operations sequenced in RAM while one disk write is in flight into a single multi-row
Deep dive 3: Bidirectional Git integration
Git is our durable milestone store, coordinated by one Git sync worker per repository branch (guarded by a lease so our own commits never race each other).
Outbound (browser edits -> Git commits)
When a user clicks Publish, or a branch sits idle for 2 minutes (capped at 15 minutes during non-stop editing), the worker reads the current
(rev, text)of every modified page on that branch, builds a single multi-file commit withCo-authored-by:trailers queried from thesessionjournal, and performs a fast-forward branch update (an atomic Git pointer move that succeeds only if the branch tip still equalslast_synced_commit):MAX_SYNC_ATTEMPTS = 3 def commit_milestone(branch, message): for _ in range(MAX_SYNC_ATTEMPTS): dirty_docs = docs.changed_since_milestone(branch.branch_id) if not dirty_docs: return None files = [] for doc in dirty_docs: rev, text = session_servers.current(doc.doc_id) files.append((doc, rev, text)) commit = git.create_commit( repo=branch.repo, parent=branch.last_synced_commit, files=files, message=message, trailers=co_author_trailers(dirty_docs), ) if git.fast_forward(branch.repo, branch.name, commit.sha): milestones.record(branch.branch_id, commit.sha, files) branch.last_synced_commit = commit.sha return commit.sha # Someone pushed externally in the meantime: ingest their commit first, then retry ingest_new_remote_commits(branch) raise MilestoneRetryLater(branch.branch_id)Inbound (external
git pushor merged PR -> live browser sessions)When a developer pushes from their terminal, a webhook (backed up by a 1-minute branch poll in case a webhook drops) notifies the sync worker. For each changed
.mdxfile, the worker runs a three-way merge—comparing base (file atlast_synced_commit), ours (live text athead_revon the session server), and theirs (file in the new Git commit)—and injects the diff into the live session as a regular OT operation:def ingest_external_commit(branch, commit): if milestones.exists(branch.branch_id, commit.sha): return # Ignore echo webhooks triggered by our own outbound commits for path in changed_mdx_paths(branch.repo, branch.last_synced_commit, commit.sha): base = git.read_file(branch.repo, branch.last_synced_commit, path) theirs = git.read_file(branch.repo, commit.sha, path) doc = docs.by_path(branch.branch_id, path) head_rev, ours = session_servers.current(doc.doc_id) # Non-overlapping hunks merge automatically; overlapping hunks keep live "ours" merged, conflicts = three_way_merge(base, ours, theirs) op = diff_to_op(ours, merged) if not op.is_noop(): session_servers.submit( doc.doc_id, client_id="git-sync:" + commit.sha, client_seq=1, base_rev=head_rev, op=op, ) for conflict in conflicts: attach_conflict_note(doc, conflict) milestones.record_external(branch.branch_id, commit.sha) branch.last_synced_commit = commit.sha- Why keep
ourson overlapping hunks? Character-merging two different rewrites of the same sentence scrambles words into nonsense, and overwritingoursdeletes text an editor is actively typing. Keepingoursin the text while attachingtheirsas a visible margin conflict card lets a human pick cleanly. - Deterministic
(client_id="git-sync:" + commit.sha, client_seq=1)makes webhook retries idempotent, and diffing against livehead_revmeans typing never pauses during a merge. - Gate publishing, not saving: Mid-sentence MDX often has an unclosed
<Tabs>tag. Working-branch milestones accept temporarily invalid MDX so work is still backed up; merging/publishing to the production docs branch requires the MDX parser and build check to pass.
- Why keep
Scaling, failure handling, and trade-off summary
Scaling bottlenecks and mitigations
- WebSocket & presence fan-out: 4 stateless edge gateways across availability zones easily hold 15,000 sockets and relay 30,000 presence messages/s in memory without touching disk.
- Session server RAM: 5,000 active docs × (~20 KB text + ~60 KB recent ops) is ~400 MB total—3 small servers across zones provide ample N+1 headroom.
- Hot single document (all-hands doc): Above 50 concurrent active editors on one page, additional viewers receive a read-only stream batched every 250 ms so cursor and op fan-out stays bounded.
- Git host API rate limits: GitHub caps REST API writes per app installation; batching all dirty files per branch into one commit every 2–15 minutes (or pushing over native Git wire protocol from a warm bare clone) keeps API usage tiny.
Failure modes and recovery
Failure scenario Impact Recovery mechanism Session server crashes Its ~1,700 open docs lose their in-memory sequencer etcd lease expires (~10 s); new owner loads latest snapshot + <= 500ops; browsers reconnect withlast_revand flushIndexedDBpending ops; zero acknowledged edits lostZombie session server (GC pause / partition) Old and new owner both try to sequence rev NPostgreSQL PRIMARY KEY (doc_id, rev)rejects the stale owner'sINSERT; loser drops the doc and redirects socketsJournal shard unreachable Affected pages cannot persist new revisions Session server pauses acks on affected shard; clients continue typing locally into buffer+IndexedDBand display "Offline — saving locally" until shard failover completesTransform bug causes silent client drift Browser string diverges from server string Idle browsers (when inflightandbufferare empty) periodically send(rev, crc32(text)); any mismatch triggersreloadfrom server truth and pages on-callExternal Git host down or 429 rate-limited Milestone commits delayed Sync jobs retry with exponential backoff; live browser collaboration continues unaffected with a status badge ("Last synced to Git 12m ago") Summary of key trade-offs
- Central-server OT vs. CRDT: Gives linear integer revisions, zero tombstone bloat, and clean Git file parity, trading away multi-day offline and peer-to-peer support.
- Plain-text MDX ops vs. rich-tree ops: Keeps Git diffs clean and 1-to-1 with stored state, shifting incremental AST parsing and UTF-16 offset mapping work onto the browser.
- Journal commit before ack vs. memory-first ack: Adds ~3 ms per batch (via group commit) in exchange for zero lost acknowledged edits on server crash.
- Hybrid op journal + periodic snapshots + Git commits: Satisfies OT reconnects, keeps page loads under 80 KB, and bounds hot database size to a 30-day window.
Intuition & how it works
Think of a collaborative documentation editor with Git integration like co-writing on a shared whiteboard managed by one fast stenographer and a periodic photographer. Instead of sending whole files back and forth, each browser sends tiny text recipes—such as "keep 5 characters, insert a comma, keep 6 characters"—over a WebSocket (a persistent two-way network connection between browser and server). One session server acts as the stenographer for that page: it assigns every accepted edit the next sequential revision number (rev 42, 43, ...), adjusts character positions when two people type at once using Operational Transformation (OT) (a mathematical rule that shifts concurrent character offsets so every copy lands on the exact same string), and saves that 120-byte recipe into an append-only journal before confirming it. Every 500 edits, a background snapshot (a full-text photograph of the page) is saved to object storage so newly arriving editors can load the page quickly, and every few minutes a Git sync worker bundles recent page revisions into clean Git commits (permanent chapter milestones).
Why do the obvious approaches fail? Saving the whole file on every edit ("last-writer-wins") silently overwrites a colleague's work whenever two browsers save within the same second and generates ~160x more write traffic (180 MB/s vs. 1.1 MB/s). Using Git directly as the real-time transport fails because creating commits takes hundreds of milliseconds to seconds and quickly hits Git host rate limits. Conversely, keeping only an append-only edit log without periodic snapshots forces anyone opening an active page to download and replay megabytes of old keystrokes before seeing a single word.
Let's trace a tiny concrete example of Alice and Bob editing "Hello world" concurrently from rev 41:
Start at rev 41: "Hello world" (11 UTF-16 units)
Alice inserts "," at index 5: A = [retain(5), insert(","), retain(6)] (base_rev = 41)
Bob deletes "world" at index 6: B = [retain(6), delete(5)] (base_rev = 41)
1. Local echo (0 ms): Alice immediately sees "Hello, world"; Bob immediately sees "Hello ".
2. Server sequences B first -> rev 42 ("Hello "), broadcasts B to Alice.
3. Server sequences A next (base_rev 41 < 42): transforms A over B -> A' = [retain(5), insert(","), retain(1)],
applies A' -> rev 43 ("Hello, "), acks Alice, broadcasts A' to Bob.
4. Alice transforms arriving B over pending A -> B' = [retain(7), delete(5)], applies B' -> "Hello, ".
5. Two minutes after typing stops, the Git worker commits rev 43 ("Hello, ") as commit abc123 with both co-authors.
Key trade-offs
- Central-server OT vs. a CRDT: A CRDT (Conflict-free Replicated Data Type, a structure that gives every character a permanent unique ID and keeps deleted characters as invisible tombstones so edits merge in any order without a coordinator) excels at multi-day offline or peer-to-peer apps. However, when a server is already required for auth and Git—and disconnects are short—central-server OT gives a single integer revision order
(doc_id, rev)and pure plain-text files with zero tombstone cleanup overhead. - Server-side OT vs. rejecting stale base revisions: Having the server reject any edit whose
base_revis behindhead_revsimplifies server code, but on a busy page slow connections get bounced repeatedly. Runningtransformon the server eliminates client retry storms using the exact same function the browser already runs. - Operations on raw MDX text vs. operations on a structured block tree: Operating on the plain MDX string keeps snapshots and live state 100% identical to the repository file, making Git diffs minimal and clean. The trade-off is extra frontend work: maintaining a visual-to-source position map and incrementally re-parsing affected MDX blocks.
- Durable journal write before
ackvs. memory-firstack: Waiting ~3 ms for a synchronous group commit (batching concurrent edits that arrive during one disk write into the next databaseINSERT) guarantees an acknowledged edit never disappears if the session server crashes, whereas acknowledging from RAM risks permanent data loss and split state across browsers. - Snapshot frequency (every 500 ops) and journal retention (30 days): Snapshotting every 500 ops caps open-time replay at
<= 60 KBwhile writing< 0.5 MB/sat peak. Retaining 30 days of operations (~700 GB) covers all realistic reconnect gaps and keystroke attribution while relying on Git commits for permanent multi-year history. - Preserving live browser text on overlapping external Git pushes: When an external
git pushedits the exact same paragraph someone is actively rewriting in the browser, keeping the live browser text and surfacing the Git version as a side-by-side conflict card requires a human click, but avoids scrambling two sentences together character by character. - Fire-and-forget presence vs. journaled presence: Cursor and selection updates (
30,000 outbound messages/sat peak) outnumber text edits (9,000 ops/s) and lose all value a second later, so relaying them purely in memory saves more than half of all database writes.
Common mistakes
- Picking WebSockets or Kafka before picking the merge model: Without knowing whether edits use OT, CRDTs, or whole-file locks, you cannot design operation IDs, journal schemas, or reconnect catch-up rules.
- Treating Git as the live collaboration bus: Committing on every keystroke or every few seconds stalls on Git lock contention, bloats
git log, and trips GitHub/GitLab API rate limits. - Acknowledging or broadcasting before the journal write succeeds: If a session server broadcasts
rev 43from memory and immediately crashes, surviving browsers hold text that the new server never saw, breaking document convergence. - Mismatched string indexing units across languages: JavaScript strings count UTF-16 code units (
"👍"= length 2), while Python counts Unicode code points (length 1) and Rust/Go count UTF-8 bytes (length 4). Mixing units shifts every edit after an emoji onto the wrong characters. - Re-applying your own edit on reconnect: When an edit reaches the server right before Wi-Fi drops, the catch-up stream on reconnect includes that edit. Failing to match
(client_id, client_seq)againstinflightcauses the client to transform against and duplicate its own sentence. - Allowing two session servers to sequence the same page without a database fence: Lease clocks can drift during garbage-collection pauses; relying on
PRIMARY KEY (doc_id, rev)in the journal ensures a stale server's write fails immediately instead of corrupting history. - Blocking auto-saves or milestones on valid MDX syntax: Writers constantly have half-typed JSX tags mid-thought; allow working-branch milestones on broken syntax and enforce clean MDX builds only when publishing to production.
Follow-up questions
- How can you roll out a breaking change to the edit operation wire format while collaborators are actively typing in live sessions? Build explicit
protocol(on the WebSocket handshake) andformat(on every submitted and persisted operation) version fields in from day one, then ship formatv2across three zero-downtime stages. First, upgrade session servers to translate incomingv1andv2edits into a single canonical in-memory representation (v2), executetransformexclusively inv2, and down-convert outbound broadcasts for any still-connectedv1tabs. Second, ship thev2browser client; if av2editor invokes a new feature thatv1cannot express, flush pending edits on remainingv1tabs and send areloadframe so those tabs seamlessly pick up the new client bundle. Third, oncev1sockets drop to zero, record snapshots at the cutover and let legacyv1journal entries expire naturally after the 30-day retention window (having first validated the converter offline by replaying historical journals against stored snapshots). - How should embedded images or large binary files be uploaded, rendered, and committed to Git without sending raw file bytes through the real-time text operation stream? Keep binary bytes completely off the text channel: the browser computes the file's
sha256digest and callsPOST /v1/assets; if that digest already exists, the upload is skipped automatically, and otherwise the backend returns a presigned URL (a short-lived, cryptographically signed link letting the browserPUTbytes straight to object storage like S3 without routing megabytes through session servers). Inside the document, the editor inserts only a short plain-text Markdown reference—such as—into the OT log (~50 bytes), rendering a loading state for co-editors until virus scanning and CDN propagation complete. On the next Git milestone, the sync worker commits any newly referenced binary files alongside the.mdxchanges (or writes a Git LFS pointer—Git Large File Storage, which keeps large binaries outside the core Git packfile—above a configured byte threshold) so repository checkouts never see broken links, while background garbage collection purges unreferenced uploads only after the 30-day undo/restore window elapses.
Follow-up questions
- How can you roll out a breaking change to the edit operation wire format while collaborators are actively typing in live sessions?
- How should embedded images or large binary files be uploaded, rendered, and committed to Git without sending raw file bytes through the real-time text operation stream?
Similar questions
- REST API Specification for Hosted Documents
- Senior Backend Manager Screen: Career Arc, Stack Flexibility, and Startup Fit
- Translating a Static Mockup into an Accessible Card Component
- Evaluating and Deploying Database Indexes on High-Volume Tables
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor