How I Would Build a Document Versioning System
Whenever I get a new feature request, especially "Version History," the immediate temptation is to build something complex like Git. Diffs, branches, merge conflicts. it sounds like a cool engineering challenge, right?
But as an Softwar Engineer, my main focus is always: Simple, reliable, and maintainable.
Today, I’m going to share how I would design a practical document versioning system. My goal isn't to show off complexity, but to build a system that works flawlessly in production and is easy for future developers to understand and extend.
1. Architecture: Keep "Now" and "History" Strictly Separate
The biggest mistake beginners make is trying to manage the current document state and the version history in the same data structure. I always keep them strictly separate.
I would use two tables:
documents: Stores the current, mutable state. This is what the user is actively editing right now.document_versions: Stores immutable snapshots. Once written, a version is never updated or deleted.
-- The current, editable document
CREATE TABLE documents (
id UUID PRIMARY KEY,
title TEXT,
content TEXT,
updated_at TIMESTAMP,
created_at TIMESTAMP
);
-- The immutable history
CREATE TABLE document_versions (
id UUID PRIMARY KEY,
document_id UUID REFERENCES documents(id),
version INT,
content TEXT,
content_hash TEXT, -- Crucial for preventing duplicates!
created_at TIMESTAMP,
created_by UUID,
change_type TEXT -- 'AUTO_SAVE', 'MANUAL_SAVE', 'RESTORE', 'PUBLISH'
);
2. The Auto-Save Dilemma: Why Debounce and Throttle Fail
When should the system automatically create a version? Most developers immediately reach for debouncing or throttling. Both are flawed for version history.
Why Debounce Fails: Debounce waits for the user to stop typing before saving. Imagine a user types continuously for 30 minutes. Because they never pause long enough for the debounce timer to fire, no version is ever saved. If the browser crashes, 30 minutes of work is lost.
Why Throttle is Sub-optimal: Throttle saves every X seconds while typing. It prevents data loss, but it might save a version when the user has only added a single space, or it might capture an incomplete thought mid-sentence. The history gets cluttered with junk.
My Strategy: Interval + Dirty Flag This is the industry standard (used by Notion, Google Docs, etc.). I keep an isDirty flag.
let isDirty = false;
// Mark as dirty when the user types
editor.onChange(() => {
isDirty = true;
});
// Check every 10 minutes
setInterval(() => {
if (!isDirty) return; // Do nothing if no changes were made
createVersion('AUTO_SAVE');
isDirty = false;
}, 10 * 60 * 1000); // 10 minutes
Why this approach: It guarantees periodic checkpoints without creating unnecessary versions for static documents. I combine this with immediate saves on manual "Save" clicks, "Publish" actions, and beforeunload (tab close) events for a bulletproof setup.
3. Preventing Duplicate Versions: The Hash Trick
What happens if the 10-minute auto-save timer fires, but the user hasn't actually changed the text since the last save? I don't want to clutter the database with identical snapshots.
Instead of doing an expensive string comparison on the entire document, I use a SHA-256 hash.
const newHash = sha256(currentContent);
const lastVersionHash = getLastVersion().content_hash;
if (newHash === lastVersionHash) {
return; // Content hasn't changed, skip saving!
}
// Proceed to save the new version
This makes duplicate detection lightning-fast and keeps the version history perfectly clean.
4. The "Restore" Trap: Never Rewrite History
When a user decides to revert to an older version, how should the system handle it?
The Bad Way (Rewriting History): If the user is on Version 5 and restores Version 2, some systems delete V3, V4, and V5, and overwrite the current document. This completely destroys the audit trail.
The Good Way (Linear Progression): I treat a "restore" as just another edit. If the user is on V5 and restores V2, the system copies the content of V2 into the current document and creates a new Version 6.
v1 -> v2 -> v3 -> v4 -> v5
↑
User restores v2
↓
v1 -> v2 -> v3 -> v4 -> v5 -> v6 (Content matches v2)
History remains strictly linear, immutable, and fully auditable.
5. Storage Strategy: Full Snapshots vs. Diffs
Should I store the entire markdown text for every version, or just the "diffs" (changes) like Git does?
For an project, I always store the full text.
Markdown files are incredibly small (usually just a few Kilobytes). Storing full snapshots provides massive benefits:
Easy to implement: No complex diff/patch algorithms required.
Easy to restore: Just copy the
contentcolumn.Easy to debug: I can query the database and read any version in plain text.
Diff-based storage is reserved for systems handling massive enterprise documents or millions of versions. I follow the KISS (Keep It Simple, Stupid) principle here.
6. UI and Retention Policy
The UI: I wouldn't clutter the main editor with version history. I’d put it in a side sheet or drawer. Each entry should clearly display:
Version Number (e.g.,
v15)Timestamp (e.g.,
Today at 10:20 AM)Change Type (e.g.,
Auto Saved,Manual Save,Restored from v2)
I’d also allow users to preview the version and compare it side-by-side with the current version (using libraries like diff-match-patch or jsdiff).
Retention Policy: I wouldn't keep infinite auto-saves; the database will bloat. I’d implement a simple retention policy:
Keep all manual saves and publishes forever.
Keep auto-saves for the last 30 days.
After 30 days, thin out auto-saves to one snapshot per day or week.
Final Thoughts
Building a versioning system doesn't require a computer science degree in distributed systems. By focusing on the fundamentals, I can build a robust feature in a fraction of the time:
Separate the current document from immutable version snapshots.
Use a Dirty Flag + Interval for auto-saving, avoiding debounce/throttle pitfalls.
Use SHA-256 hashing to prevent duplicate versions.
Always create a new version when restoring, preserving linear history.
Store full content snapshots, not diffs.
This design is production-friendly, easy to test, and provides a fantastic user experience. More importantly, it leaves the door open: if the app eventually scales to the point where diffs are needed, I can swap out the storage layer without changing the core application logic.
Keep it simple, keep it reliable, and just ship it!
Comments
Join the discussionNo comments yet. Be the first to comment.