Files
skills/public/realtime-realtime-sync.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

813 lines
31 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>realtime-realtime-sync</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/realtime-realtime-sync.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/realtime-realtime-sync">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/realtime-realtime-sync.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>realtime-realtime-sync</h1><p class="lede">Scope: Conflict resolution, CRDTs, operational transformation, and eventual consistency patterns Lines: 398 Last Updated: 2025-10-18</p><h1>Real-time Data Synchronization</h1>
<p><strong>Scope</strong>: Conflict resolution, CRDTs, operational transformation, and eventual consistency patterns <strong>Lines</strong>: 398 <strong>Last Updated</strong>: 2025-10-18</p>
<h2>When to Use This Skill</h2>
<p>Use real-time sync patterns when you need:</p>
<ul><li><strong>Collaborative editing</strong>: Multiple users editing the same document simultaneously</li><li><strong>Offline-first apps</strong>: Apps that work offline and sync when reconnected</li><li><strong>Conflict resolution</strong>: Merging concurrent updates without data loss</li><li><strong>Eventual consistency</strong>: Distributed data that converges to same state</li><li><strong>Real-time collaboration</strong>: Shared whiteboards, multiplayer games, collaborative design</li></ul>
<p><strong>Don&#x27;t use</strong> when:</p>
<ul><li>Single user editing with simple save/load (use optimistic updates)</li><li>No concurrent edits possible (use last-write-wins)</li><li>Strong consistency required (use pessimistic locking)</li><li>Data is immutable/append-only (use event sourcing)</li></ul>
<h2>Core Concepts</h2>
<h3>Conflict Resolution Strategies</h3>
<pre><code>1. Last-Write-Wins (LWW)
- Simplest approach
- Use timestamp or sequence number
- Data loss possible
2. Operational Transformation (OT)
- Transform operations based on concurrent ops
- Complex but preserves intent
- Used in Google Docs
3. Conflict-Free Replicated Data Types (CRDTs)
- Mathematical guarantees of convergence
- No conflict resolution needed
- Used in distributed systems
4. Three-Way Merge
- Compare: base, local, remote
- Identify conflicts explicitly
- User resolves ambiguities</code></pre>
<h3>Synchronization Patterns</h3>
<pre><code>Client A Server Client B
| | |
|-- Update A ----&gt;| |
| |-- Broadcast --&gt;|
| | |
|&lt;-- Update B ----|&lt;-- Update B ---|
| | |
|-- Resolve -----&gt;| |
|&lt;-- Merged ------|-- Merged -----&gt;|</code></pre>
<h2>Patterns</h2>
<h3>1. Last-Write-Wins (LWW) with Vector Clocks</h3>
<pre><code class="lang-typescript">// Simple LWW with timestamps
interface VersionedData&lt;T&gt; {
data: T;
version: number;
timestamp: number;
clientId: string;
}
class LWWStore&lt;T&gt; {
private data: VersionedData&lt;T&gt; | null = null;
update(newData: T, clientId: string): VersionedData&lt;T&gt; {
const version = (this.data?.version ?? 0) + 1;
const timestamp = Date.now();
this.data = {
data: newData,
version,
timestamp,
clientId,
};
return this.data;
}
merge(remote: VersionedData&lt;T&gt;): boolean {
if (!this.data) {
this.data = remote;
return true;
}
// Resolve conflicts with LWW
if (remote.timestamp &gt; this.data.timestamp) {
this.data = remote;
return true;
} else if (remote.timestamp === this.data.timestamp) {
// Tie-break with clientId for determinism
if (remote.clientId &gt; this.data.clientId) {
this.data = remote;
return true;
}
}
return false; // No update
}
get(): T | null {
return this.data?.data ?? null;
}
}
// Usage
const store = new LWWStore&lt;string&gt;();
store.update(&#x27;Hello&#x27;, &#x27;client-1&#x27;);
// Simulate remote update
const remoteData = {
data: &#x27;World&#x27;,
version: 2,
timestamp: Date.now() + 1000,
clientId: &#x27;client-2&#x27;,
};
const updated = store.merge(remoteData);
console.log(updated); // true
console.log(store.get()); // &#x27;World&#x27;</code></pre>
<h3>2. CRDT: Last-Write-Wins Register</h3>
<pre><code class="lang-typescript">// LWW-Register CRDT
interface LWWRegister&lt;T&gt; {
value: T;
timestamp: number;
clientId: string;
}
class LWWRegisterCRDT&lt;T&gt; {
private register: LWWRegister&lt;T&gt;;
constructor(initialValue: T, clientId: string) {
this.register = {
value: initialValue,
timestamp: Date.now(),
clientId,
};
}
set(value: T, clientId: string): LWWRegister&lt;T&gt; {
this.register = {
value,
timestamp: Date.now(),
clientId,
};
return this.register;
}
merge(other: LWWRegister&lt;T&gt;): boolean {
if (other.timestamp &gt; this.register.timestamp ||
(other.timestamp === this.register.timestamp &amp;&amp;
other.clientId &gt; this.register.clientId)) {
this.register = other;
return true;
}
return false;
}
get(): T {
return this.register.value;
}
getState(): LWWRegister&lt;T&gt; {
return { ...this.register };
}
}</code></pre>
<h3>3. CRDT: Grow-Only Set (G-Set)</h3>
<pre><code class="lang-typescript">// G-Set: Elements can only be added, never removed
class GSet&lt;T&gt; {
private elements: Set&lt;T&gt; = new Set();
add(element: T): boolean {
if (this.elements.has(element)) {
return false;
}
this.elements.add(element);
return true;
}
has(element: T): boolean {
return this.elements.has(element);
}
merge(other: GSet&lt;T&gt;): void {
other.elements.forEach((element) =&gt; {
this.elements.add(element);
});
}
toArray(): T[] {
return Array.from(this.elements);
}
getState(): T[] {
return this.toArray();
}
}
// Usage
const set1 = new GSet&lt;string&gt;();
set1.add(&#x27;a&#x27;);
set1.add(&#x27;b&#x27;);
const set2 = new GSet&lt;string&gt;();
set2.add(&#x27;b&#x27;);
set2.add(&#x27;c&#x27;);
set1.merge(set2);
console.log(set1.toArray()); // [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;]</code></pre>
<h3>4. CRDT: Two-Phase Set (2P-Set)</h3>
<pre><code class="lang-typescript">// 2P-Set: Elements can be added and removed (but only once each)
class TwoPhaseSet&lt;T&gt; {
private addSet: Set&lt;T&gt; = new Set();
private removeSet: Set&lt;T&gt; = new Set();
add(element: T): boolean {
if (this.removeSet.has(element)) {
return false; // Cannot re-add removed element
}
this.addSet.add(element);
return true;
}
remove(element: T): boolean {
if (!this.addSet.has(element)) {
return false; // Cannot remove non-existent element
}
this.removeSet.add(element);
return true;
}
has(element: T): boolean {
return this.addSet.has(element) &amp;&amp; !this.removeSet.has(element);
}
merge(other: TwoPhaseSet&lt;T&gt;): void {
other.addSet.forEach((element) =&gt; this.addSet.add(element));
other.removeSet.forEach((element) =&gt; this.removeSet.add(element));
}
toArray(): T[] {
return Array.from(this.addSet).filter((element) =&gt; !this.removeSet.has(element));
}
getState() {
return {
added: Array.from(this.addSet),
removed: Array.from(this.removeSet),
};
}
}</code></pre>
<h3>5. CRDT: Counter (G-Counter and PN-Counter)</h3>
<pre><code class="lang-typescript">// G-Counter: Grow-only counter (increment only)
class GCounter {
private counts: Map&lt;string, number&gt; = new Map();
increment(clientId: string, amount: number = 1): void {
const current = this.counts.get(clientId) ?? 0;
this.counts.set(clientId, current + amount);
}
value(): number {
let total = 0;
this.counts.forEach((count) =&gt; {
total += count;
});
return total;
}
merge(other: GCounter): void {
other.counts.forEach((count, clientId) =&gt; {
const current = this.counts.get(clientId) ?? 0;
this.counts.set(clientId, Math.max(current, count));
});
}
getState(): Map&lt;string, number&gt; {
return new Map(this.counts);
}
}
// PN-Counter: Positive-Negative counter (increment and decrement)
class PNCounter {
private increments: GCounter = new GCounter();
private decrements: GCounter = new GCounter();
increment(clientId: string, amount: number = 1): void {
this.increments.increment(clientId, amount);
}
decrement(clientId: string, amount: number = 1): void {
this.decrements.increment(clientId, amount);
}
value(): number {
return this.increments.value() - this.decrements.value();
}
merge(other: PNCounter): void {
this.increments.merge(other.increments);
this.decrements.merge(other.decrements);
}
}
// Usage
const counter = new PNCounter();
counter.increment(&#x27;client-1&#x27;, 5);
counter.decrement(&#x27;client-1&#x27;, 2);
console.log(counter.value()); // 3</code></pre>
<h3>6. Operational Transformation (Simple Text)</h3>
<pre><code class="lang-typescript">// Simple OT for text insertion and deletion
interface Operation {
type: &#x27;insert&#x27; | &#x27;delete&#x27;;
position: number;
content?: string;
length?: number;
}
class OperationalTransform {
static transform(op1: Operation, op2: Operation): Operation {
if (op1.type === &#x27;insert&#x27; &amp;&amp; op2.type === &#x27;insert&#x27;) {
if (op1.position &lt; op2.position) {
// op2 happens after op1&#x27;s insertion
return {
...op2,
position: op2.position + (op1.content?.length ?? 0),
};
} else if (op1.position &gt; op2.position) {
// op2 happens before op1, no transformation needed
return op2;
} else {
// Same position, use arbitrary tie-breaker
return {
...op2,
position: op2.position + (op1.content?.length ?? 0),
};
}
}
if (op1.type === &#x27;delete&#x27; &amp;&amp; op2.type === &#x27;insert&#x27;) {
if (op2.position &lt;= op1.position) {
// op2 before deletion
return op2;
} else if (op2.position &gt;= op1.position + (op1.length ?? 0)) {
// op2 after deletion
return {
...op2,
position: op2.position - (op1.length ?? 0),
};
} else {
// op2 inside deletion range
return {
...op2,
position: op1.position,
};
}
}
if (op1.type === &#x27;insert&#x27; &amp;&amp; op2.type === &#x27;delete&#x27;) {
if (op2.position &lt; op1.position) {
// op2 before insertion
return op2;
} else if (op2.position &gt;= op1.position + (op1.content?.length ?? 0)) {
// op2 after insertion
return {
...op2,
position: op2.position + (op1.content?.length ?? 0),
};
} else {
// op2 inside insertion
return {
...op2,
position: op1.position,
length: (op2.length ?? 0) + (op1.content?.length ?? 0),
};
}
}
if (op1.type === &#x27;delete&#x27; &amp;&amp; op2.type === &#x27;delete&#x27;) {
if (op2.position &lt; op1.position) {
return op2;
} else if (op2.position &gt;= op1.position + (op1.length ?? 0)) {
return {
...op2,
position: op2.position - (op1.length ?? 0),
};
} else {
// Overlapping deletes
return {
...op2,
position: op1.position,
length: Math.max(0, (op2.length ?? 0) - (op1.length ?? 0)),
};
}
}
return op2;
}
static apply(text: string, op: Operation): string {
if (op.type === &#x27;insert&#x27;) {
return text.slice(0, op.position) + op.content + text.slice(op.position);
} else if (op.type === &#x27;delete&#x27;) {
return text.slice(0, op.position) + text.slice(op.position + (op.length ?? 0));
}
return text;
}
}
// Usage
let text = &#x27;Hello World&#x27;;
const op1: Operation = { type: &#x27;insert&#x27;, position: 5, content: &#x27;,&#x27; };
const op2: Operation = { type: &#x27;delete&#x27;, position: 6, length: 5 };
// Client A applies op1
let textA = OperationalTransform.apply(text, op1); // &quot;Hello, World&quot;
// Client B applies op2 (concurrently)
let textB = OperationalTransform.apply(text, op2); // &quot;Hello &quot;
// Transform op2 against op1 for Client A
const op2Transformed = OperationalTransform.transform(op1, op2);
textA = OperationalTransform.apply(textA, op2Transformed); // &quot;Hello,&quot;
// Transform op1 against op2 for Client B
const op1Transformed = OperationalTransform.transform(op2, op1);
textB = OperationalTransform.apply(textB, op1Transformed); // &quot;Hello,&quot;
console.log(textA === textB); // true - convergence!</code></pre>
<h3>7. Sync Manager with WebSocket</h3>
<pre><code class="lang-typescript">interface SyncMessage {
type: &#x27;update&#x27; | &#x27;sync_request&#x27; | &#x27;sync_response&#x27;;
clientId: string;
data?: any;
version?: number;
}
class SyncManager&lt;T&gt; {
private ws: WebSocket;
private clientId: string;
private crdt: LWWRegisterCRDT&lt;T&gt;;
private onUpdate: (data: T) =&gt; void;
constructor(
url: string,
initialData: T,
onUpdate: (data: T) =&gt; void
) {
this.clientId = this.generateClientId();
this.crdt = new LWWRegisterCRDT(initialData, this.clientId);
this.onUpdate = onUpdate;
this.ws = new WebSocket(url);
this.setupWebSocket();
}
private setupWebSocket() {
this.ws.onopen = () =&gt; {
console.log(&#x27;Connected to sync server&#x27;);
this.requestSync();
};
this.ws.onmessage = (event) =&gt; {
const message: SyncMessage = JSON.parse(event.data);
this.handleMessage(message);
};
}
private handleMessage(message: SyncMessage) {
switch (message.type) {
case &#x27;update&#x27;:
if (message.data &amp;&amp; message.clientId !== this.clientId) {
const updated = this.crdt.merge(message.data);
if (updated) {
this.onUpdate(this.crdt.get());
}
}
break;
case &#x27;sync_response&#x27;:
if (message.data) {
this.crdt.merge(message.data);
this.onUpdate(this.crdt.get());
}
break;
}
}
update(data: T) {
this.crdt.set(data, this.clientId);
this.broadcast();
this.onUpdate(this.crdt.get());
}
private broadcast() {
const message: SyncMessage = {
type: &#x27;update&#x27;,
clientId: this.clientId,
data: this.crdt.getState(),
};
this.ws.send(JSON.stringify(message));
}
private requestSync() {
const message: SyncMessage = {
type: &#x27;sync_request&#x27;,
clientId: this.clientId,
};
this.ws.send(JSON.stringify(message));
}
private generateClientId(): string {
return `client_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
}
// Usage
const syncManager = new SyncManager(
&#x27;wss://sync.example.com&#x27;,
&#x27;Initial data&#x27;,
(data) =&gt; {
console.log(&#x27;Data updated:&#x27;, data);
}
);
syncManager.update(&#x27;New data&#x27;);</code></pre>
<h2>Quick Reference</h2>
<h3>CRDT Types</h3>
<pre><code class="lang-typescript">// LWW-Register: Single value, last write wins
const register = new LWWRegisterCRDT(&#x27;initial&#x27;, &#x27;client-1&#x27;);
// G-Set: Grow-only set (add only)
const gset = new GSet&lt;string&gt;();
// 2P-Set: Add and remove (once each)
const tpset = new TwoPhaseSet&lt;string&gt;();
// G-Counter: Increment-only counter
const gcounter = new GCounter();
// PN-Counter: Increment and decrement counter
const pncounter = new PNCounter();</code></pre>
<h3>Conflict Resolution Strategies</h3>
<pre><code class="lang-typescript">// Last-Write-Wins: Use timestamp
if (remote.timestamp &gt; local.timestamp) {
local = remote;
}
// Version Vector: Use vector clock
if (isGreaterThan(remote.vector, local.vector)) {
local = remote;
}
// Three-Way Merge: Compare base, local, remote
const merged = merge(base, local, remote);</code></pre>
<h3>State Synchronization</h3>
<pre><code class="lang-typescript">// Full state sync
send({ type: &#x27;full_sync&#x27;, state: crdt.getState() });
// Delta sync (changes only)
send({ type: &#x27;delta_sync&#x27;, delta: crdt.getDelta() });
// Operational sync (operations)
send({ type: &#x27;operation&#x27;, op: { type: &#x27;insert&#x27;, ... } });</code></pre>
<h2>Anti-Patterns</h2>
<h3>❌ Using Timestamps Without Tie-Breakers</h3>
<pre><code class="lang-typescript">// Wrong: Ties cause non-deterministic results
if (remote.timestamp &gt; local.timestamp) {
local = remote;
}
// What if timestamps are equal?</code></pre>
<p><strong>Why it&#x27;s bad</strong>: Different clients may choose different values for concurrent updates</p>
<p><strong>Better approach</strong>:</p>
<pre><code class="lang-typescript">if (remote.timestamp &gt; local.timestamp ||
(remote.timestamp === local.timestamp &amp;&amp; remote.clientId &gt; local.clientId)) {
local = remote;
}</code></pre>
<h3>❌ Sending Full State on Every Update</h3>
<pre><code class="lang-typescript">// Wrong: Inefficient for large documents
socket.send(JSON.stringify({ type: &#x27;update&#x27;, data: fullDocument }));</code></pre>
<p><strong>Why it&#x27;s bad</strong>: Wastes bandwidth, especially for small changes</p>
<p><strong>Better approach</strong>:</p>
<pre><code class="lang-typescript">// Send operations or deltas
socket.send(JSON.stringify({ type: &#x27;operation&#x27;, op: { type: &#x27;insert&#x27;, position: 5, content: &#x27;x&#x27; } }));</code></pre>
<h3>❌ No Conflict Detection</h3>
<pre><code class="lang-typescript">// Wrong: Blindly overwrite
function update(data) {
this.data = data; // No version checking
}</code></pre>
<p><strong>Why it&#x27;s bad</strong>: Lost updates when concurrent modifications occur</p>
<p><strong>Better approach</strong>:</p>
<pre><code class="lang-typescript">function update(data, version) {
if (version &lt;= this.version) {
throw new Error(&#x27;Conflict detected&#x27;);
}
this.data = data;
this.version = version;
}</code></pre>
<h3>❌ Synchronous Merge Operations</h3>
<pre><code class="lang-typescript">// Wrong: Blocking merge for large data
await merge(largeDocument); // Blocks UI</code></pre>
<p><strong>Why it&#x27;s bad</strong>: UI freezes during merge</p>
<p><strong>Better approach</strong>:</p>
<pre><code class="lang-typescript">// Merge in Web Worker or use incremental merging
worker.postMessage({ type: &#x27;merge&#x27;, data: largeDocument });</code></pre>
<h2>Related Skills</h2>
<ul><li><strong>websocket-implementation.md</strong>: WebSocket protocol for sync communication</li><li><strong>server-sent-events.md</strong>: SSE for server-to-client sync updates</li><li><strong>pubsub-patterns.md</strong>: Server-side message routing for collaborative features</li><li><strong>network-resilience-patterns.md</strong>: Handling network failures during sync</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-18 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/realtime-realtime-sync.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>