
Java Collaborative Editing: Block Versioning, CRDT, and Handling Concurrent Document Edits
This article details how to build real-time collaborative editing in Java using Spring Boot, covering block-level versioning to reduce conflicts, conditional database updates for concurrency control, WebSocket broadcast after transaction commit, reconnection with operation replay, CRDT integration via Yjs for character-level editing, multi-instance deployment with Redis and message brokers, permission validation, and history version recovery without rollback.
Reading font
Core Problem: Concurrent Edits on the Same Document
When two users simultaneously modify the same document — e.g., user A changes "项目预计月底上线" to "项目预计下个月上线" while user B changes it to "项目预计月底正式上线" — a naive last-write-wins approach loses one user's changes. Collaborative editing must handle concurrent modifications, conflict merging, message ordering, disconnection recovery, and history versioning, not just data updates.
Why Not Sync the Entire Document via WebSocket?
Sending the full document on every keystroke causes three problems:
Content overwrite: Late-arriving requests overwrite earlier saves.
Traffic amplification: A 100 KB document sent per character by 10 users generates massive unnecessary traffic.
Message reordering: Rapid keystrokes may arrive out of order, causing newer content to be replaced by older content.
Instead, clients should send discrete edit operations, e.g.:
{
"operationId": "op-8d21",
"documentId": "10086",
"blockId": "paragraph-001",
"type": "UPDATE_BLOCK",
"baseVersion": 12,
"content": "修改后的段落内容"
}Block-Level Editing: Reducing Conflict Scope
Split documents into independent blocks (heading, paragraph, image, code, table). Users editing different blocks don't conflict. Example document structure:
{
"documentId": "10086",
"blocks": [
{ "id": "block-001", "type": "HEADING", "content": "项目开发计划", "version": 1 },
{ "id": "block-002", "type": "PARAGRAPH", "content": "项目预计月底上线", "version": 5 },
{ "id": "block-003", "type": "PARAGRAPH", "content": "测试环境已经准备完成", "version": 3 }
]
}Database schema separates document-level and block-level versions:
CREATE TABLE document (
id BIGINT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
revision BIGINT NOT NULL DEFAULT 0,
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL
);
CREATE TABLE document_block (
id VARCHAR(64) PRIMARY KEY,
document_id BIGINT NOT NULL,
block_type VARCHAR(32) NOT NULL,
content TEXT NOT NULL,
sort_order BIGINT NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
updated_at DATETIME(3) NOT NULL,
INDEX idx_document_order (document_id, sort_order, id)
);document.revisionis a global modification sequence for sync and recovery; document_block.version detects concurrent edits on the same block. Merging them would cause false conflicts when users edit different blocks.
Spring Boot Implementation: Edit Operations and Version Conflict Detection
Client request includes a unique operationId and the baseVersion of the block:
public record EditOperation(
String operationId,
Long documentId,
String blockId,
long baseVersion,
String content
) {}MyBatis conditional update checks version:
UPDATE document_block
SET content = #{content},
version = version + 1,
updated_at = NOW(3)
WHERE document_id = #{documentId}
AND id = #{blockId}
AND version = #{baseVersion};If affected rows = 1, the edit succeeded; if 0, the block was modified by another user (conflict).
An document_operation table stores every operation for history and replay:
CREATE TABLE document_operation (
document_id BIGINT NOT NULL,
revision BIGINT NOT NULL,
operation_id VARCHAR(64) NOT NULL,
operator_id BIGINT NOT NULL,
block_id VARCHAR(64) NOT NULL,
block_version BIGINT NOT NULL,
operation_type VARCHAR(32) NOT NULL,
payload JSON NOT NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (document_id, revision),
UNIQUE KEY uk_document_operation (document_id, operation_id)
);Core service logic (transactional):
@Service
public class CollaborativeEditService {
private final DocumentMapper documentMapper;
private final DocumentBlockMapper blockMapper;
private final DocumentOperationMapper operationMapper;
private final DocumentPermissionService permissionService;
@Transactional
public OperationResult edit(Long userId, EditOperation command) {
permissionService.requireEdit(userId, command.documentId());
Document document = documentMapper.lockById(command.documentId()); // SELECT ... FOR UPDATE
if (document == null) throw new DocumentNotFoundException();
// Idempotency: reject duplicate operationId
OperationResult existing = operationMapper.findResult(command.documentId(), command.operationId());
if (existing != null) return existing;
int affected = blockMapper.updateByVersion(
command.documentId(), command.blockId(), command.baseVersion(), command.content()
);
if (affected != 1) throw new DocumentConflictException(command.blockId());
long revision = document.getRevision() + 1;
long blockVersion = command.baseVersion() + 1;
documentMapper.updateRevision(command.documentId(), revision);
OperationResult result = new OperationResult(
command.operationId(), command.documentId(), command.blockId(),
revision, blockVersion, command.content()
);
operationMapper.insert(userId, result);
return result;
}
}
public record OperationResult(
String operationId,
Long documentId,
String blockId,
long revision,
long blockVersion,
String content
) {}Row lock on the document ensures global revision ordering per document; different documents don't block each other. This works for medium-scale systems; high-frequency editing may need batching, sharding, or CRDT.
WebSocket Broadcast After Database Commit
Broadcast must happen after transaction commit; otherwise clients may see changes that later roll back. Controller calls service, then broadcasts:
@Controller
public class CollaborationController {
private final CollaborativeEditService editService;
private final SimpMessagingTemplate messagingTemplate;
private final CurrentUserService currentUserService;
@MessageMapping("/document/{documentId}/edit")
public void edit(@DestinationVariable Long documentId, EditOperation command, Principal principal) {
if (!documentId.equals(command.documentId())) throw new IllegalArgumentException("文档编号不一致");
Long userId = currentUserService.requireUserId(principal);
OperationResult result = editService.edit(userId, command);
messagingTemplate.convertAndSend("/topic/document/" + documentId, result);
}
}Risk: process crash after commit but before broadcast. For reliability, use document_operation as an event source; a background publisher reads unpublished operations, sends to message broker with retries; clients deduplicate via revision and operationId.
Reconnection: Incremental Operation Replay
Client tracks last applied revision (e.g., 105). After disconnect, server advanced to 120. Client requests missing ops:
GET /api/documents/10086/operations?afterRevision=105Server returns ordered operations:
SELECT * FROM document_operation
WHERE document_id = #{documentId} AND revision > #{afterRevision}
ORDER BY revision LIMIT 500;Client applies sequentially. Must handle out-of-order WebSocket messages: buffer later revisions, actively fetch gaps. Local edits during disconnect are queued; after sync, replay with original operationId and blockVersion. If conflict, server rejects; client shows latest content and preserves draft for manual merge. Subscription should be established before fetching history to avoid missing new messages in the gap.
Character-Level Editing Requires CRDT / OT
Block versioning prevents silent overwrites but cannot auto-merge simultaneous edits within the same block. Example: original "ABCDE"; user A inserts "X" after "A" → "AXBCDE"; user B deletes "C" (original index 2). If operations use character indices, B's delete targets wrong position after A's insert.
This requires Operational Transformation (OT) or Conflict-free Replicated Data Types (CRDT). For Java teams, don't implement from scratch; use Yjs on the client (with Tiptap/ProseMirror). Yjs provides shared types, incremental updates, offline merge, and editor integrations. Java backend persists and forwards Yjs binary updates:
CREATE TABLE document_crdt_update (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
document_id BIGINT NOT NULL,
update_id VARCHAR(64) NOT NULL,
operator_id BIGINT NOT NULL,
update_data MEDIUMBLOB NOT NULL,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_document_update (document_id, update_id),
INDEX idx_document_update (document_id, id)
);Client-side Yjs usage:
import * as Y from 'yjs';
const doc = new Y.Doc();
const text = doc.getText('content');
text.insert(0, '项目开发计划');
doc.on('update', (update, origin) => {
if (origin === 'remote') return;
sendDocumentUpdate(update);
});function receiveDocumentUpdate(update) {
Y.applyUpdate(doc, update, 'remote');
}Java only stores/forwards binary updates; for snapshot generation, state vector handling, or content validation, add a separate Node.js service compatible with Yjs, keeping Java for core business logic.
Multi-Instance Deployment: Online State and Permissions
With multiple Spring Boot instances, local maps can't share presence. Architecture:
Web / App
|
WebSocket Gateway
|
Spring Boot Cluster
|
+-- Redis: online status, heartbeats, temporary sessions
+-- Message Broker: cross-instance edit events
+-- MySQL: documents, permissions, operation history
+-- Object Storage: historical document snapshotsRedis holds ephemeral state (cursors, editing blocks) with TTL; loss is acceptable. Persistent edits must go to MySQL. Permissions (OWNER, EDITOR, COMMENTER, VIEWER) validated on edit request and WebSocket subscribe. Revoking permission must invalidate existing subscriptions, not just check on connect.
History Version Recovery: Append, Don't Rollback
Restoring revision 300 at revision 500 by deleting later ops breaks clients holding revision 500. Instead, create a new revision (501) from the snapshot at 300:
CREATE TABLE document_snapshot (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
document_id BIGINT NOT NULL,
revision BIGINT NOT NULL,
snapshot_url VARCHAR(500) NOT NULL,
content_hash CHAR(64) NOT NULL,
created_by BIGINT NOT NULL,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_document_snapshot (document_id, revision)
);Snapshots generated periodically (by operation count, time, or user action). For CRDT, restoration is trickier: generate explicit restore operation or start a new document epoch, handling pending local edits.
Choosing the Right Architecture
Block-level (Spring Boot + WebSocket + MySQL + Redis + versioning): internal knowledge bases, project docs, business forms. Provides concurrency protection, reconnection, audit.
CRDT/OT (Yjs + Tiptap/ProseMirror + Java backend): rich-text editors like Tencent Docs needing simultaneous sentence editing, live cursors, offline auto-merge.
Don't over-engineer. The real challenge is business consistency : WebSocket connected ≠ message delivered ≠ persisted ≠ synced. A production system must solve atomic commit, duplicate handling, conflict detection, message compensation, permissions, and version management together.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.