惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
量子位
宝玉的分享
宝玉的分享
爱范儿
爱范儿
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
Apple Machine Learning Research
Apple Machine Learning Research
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
aimingoo的专栏
aimingoo的专栏
Cloudbric
Cloudbric
Blog — PlanetScale
Blog — PlanetScale
Latest news
Latest news
S
Security @ Cisco Blogs
Last Week in AI
Last Week in AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Vercel News
Vercel News
W
WeLiveSecurity
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
P
Proofpoint News Feed
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Blog of Author Tim Ferriss
腾讯CDC
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
IT之家
IT之家
有赞技术团队
有赞技术团队
Microsoft Security Blog
Microsoft Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
美团技术团队
博客园 - 【当耐特】
D
DataBreaches.Net
I
InfoQ
G
GRAHAM CLULEY
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Deep Dive into Y.js CRDTs for Real-Time Multiplayer Editors
Ebendttl · 2026-05-27 · via DEV Community

This is an excerpt. The full article includes a live YATA double-linked list simulator — type into two peer editors, toggle network partitions to simulate offline-first edits, and watch Y.js automatically resolve merge conflicts in real time. Read the full interactive version →


The Local-First Wave: Why OT Is Not Enough

Building real-time collaborative software used to require a centralized server orchestrator. For decades, the industry standard was Operational Transformation (OT) — the architecture powering Google Docs.

In OT, every local edit is wrapped into an operation and sent to a central server. The server acts as the single source of truth, recalculating operation coordinates to resolve conflicts and broadcasting adjusted commands back.

The OT Bottleneck: The server must be active 100% of the time, maintaining a complex sequence history buffer. The moment a client drops offline, peer-to-peer sync becomes nearly impossible to reconcile, leading to silent document divergence.

CRDTs (Conflict-free Replicated Data Types) rethink this entirely. Instead of relying on a server to decide conflict priority, CRDT structures are mathematically designed to merge operations in any order without coordination, guaranteeing all clients converge to identical state.


The Mathematical Foundation: Join-Semilattices

To achieve absolute convergence across decentralized peers, a data structure must form a join-semilattice. In practice, your merge functions must conform to three algebraic invariants:

Property Formula Meaning
Commutativity A ⊕ B = B ⊕ A Operations merge in any sequence order
Associativity (A ⊕ B) ⊕ C = A ⊕ (B ⊕ C) Grouping doesn't affect the result
Idempotency A ⊕ A = A Receiving the same operation twice doesn't mutate state

These three properties together mean: you can merge any subset of operations, in any order, any number of times, and always reach the same final document. No coordination server required.


The YATA Engine Under the Hood

Y.js implements YATA (Yet Another Transformation Algorithm) — a highly optimized CRDT designed specifically for text editing.

Under the hood, Y.js represents a document not as a raw string array, but as a double-linked list of Item blocks. Each item contains:

  • id: A unique tuple of (clientId, lamportClock) — globally unique across all peers
  • content: The character or string chunk
  • originLeft: The ID of the item to the immediate left at creation time
  • originRight: The ID of the item to the immediate right at creation time
  • deleted: Boolean tombstone flag

These origin pointers act as a permanent spatial anchor. Even if other users concurrently insert characters between the original boundaries, YATA can deterministically sort concurrent insertions using client ID priority — ensuring all replicas converge to identical ordering.

Conflict Resolution Example

Suppose two users type simultaneously at position 5:

  • Peer A inserts "X" with originLeft = "SYS:4"
  • Peer B inserts "Y" with originLeft = "SYS:4"

Both have the same originLeft. YATA resolves this by comparing client IDs alphanumerically. If "A" < "B", Peer A's item is sorted before Peer B's — identically on both replicas, regardless of which update arrived first.


Connecting Monaco Editor

Binding Y.js to Monaco Editor is done via the y-monaco package:

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { MonacoBinding } from "y-monaco";
import * as monaco from "monaco-editor";

// 1. Initialize Y.js document
const ydoc = new Y.Doc();

// 2. Connect to WebSocket relay server
const provider = new WebsocketProvider(
  "wss://your-relay-server.com",
  "document-room-id",
  ydoc
);

// 3. Create shared Y.Text type
const ytext = ydoc.getText("monaco-content");

// 4. Bind to Monaco Editor instance
const editor = monaco.editor.create(document.getElementById("editor")!, {
  value: "",
  language: "typescript"
});

// MonacoBinding syncs ytext ↔ Monaco model bidirectionally
// It also handles cursor decorations and multi-user awareness
const binding = new MonacoBinding(
  ytext,
  editor.getModel()!,
  new Set([editor]),
  provider.awareness
);

Enter fullscreen mode Exit fullscreen mode

The MonacoBinding synchronizes Y.js document state with Monaco's internal text model bidirectionally — handling cursor decorations, selection highlights, and presence indicators automatically.


Production Relay Infrastructure

A single Y.js WebSocket server can't scale horizontally — each instance maintains its own in-memory document state. To scale, use Redis Pub/Sub as a shared synchronization backbone:

import { createServer } from "http";
import { WebSocketServer } from "ws";
import { setupWSConnection } from "y-websocket/bin/utils";
import { createClient } from "redis";

const redisPublisher = createClient({ url: process.env.REDIS_URL });
const redisSubscriber = redisPublisher.duplicate();

await redisPublisher.connect();
await redisSubscriber.connect();

const wss = new WebSocketServer({ server: createServer() });

wss.on("connection", (ws, req) => {
  // y-websocket handles CRDT sync protocol
  setupWSConnection(ws, req, {
    // Persistence callback — hook into Redis or PostgreSQL here
    persistence: {
      bindState: async (docName, ydoc) => {
        // Load existing document state from Redis
        const state = await redisPublisher.get(`ydoc:${docName}`);
        if (state) Y.applyUpdate(ydoc, Buffer.from(state, "base64"));
      },
      writeState: async (docName, ydoc) => {
        // Persist document state on every update
        const state = Y.encodeStateAsUpdate(ydoc);
        await redisPublisher.set(`ydoc:${docName}`, Buffer.from(state).toString("base64"));
      }
    }
  });
});

Enter fullscreen mode Exit fullscreen mode

With Redis Pub/Sub, any number of WebSocket server instances can participate in the same document room. An update arriving at Server A propagates to Redis, which fans it out to Servers B and C, ensuring all connected peers — regardless of which server they're on — stay synchronized.


Key Optimizations for Production

  1. Awareness Protocol: Y.js includes a built-in awareness system for sharing ephemeral state (cursor positions, user names, colors) without persisting to the CRDT document. Use this for presence, not your main Y.Doc.

  2. State Vector Sync: On reconnect, clients exchange state vectors (Y.encodeStateVector) to efficiently compute only the missing updates — avoiding full document retransmission.

  3. Subdocument Architecture: For large applications, split content across multiple Y.Doc instances (one per section/page). Load subdocuments lazily when accessed.


Engineering Takeaways

  1. OT requires centralized servers; CRDTs enable true local-first. Offline edits automatically merge on reconnect.
  2. YATA's origin pointers guarantee deterministic ordering without server coordination.
  3. y-websocket + y-monaco is the fastest path to production collaborative editing.
  4. Redis Pub/Sub enables horizontal scaling of Y.js WebSocket relay servers.
  5. State vectors make reconnection efficient — only delta updates are exchanged.

The full article includes a live YATA double-linked list simulator. You can type into both peer editors simultaneously, toggle each peer's network state to create a partition, make offline edits, then click "Resolve & Sync Partition" to watch the CRDT merge algorithm reconcile divergent histories in real time — with the underlying Item linked-list visualized beneath.

Read the full interactive article →


Written by Ebenezer Akinseinde — Software Developer & AI Automations Engineer.

Portfolio · GitHub