There's a pattern in the P2P database space that nobody talks about: The "minimal core" trap.
You pick a distributed database because it looks lightweight — a 3-line setup, a clean README. Then reality hits: authentication is a separate module, conflict resolution breaks after disconnections, encryption requires custom wiring. Offline persistence that doesn't corrupt? Good luck. What looked minimal becomes a fragile assembly of add-ons, each with its own quirks, version issues, and undocumented edge cases.
I lived this for years building real peer-to-peer applications in JavaScript, and it's why I built GenosDB — a complete P2P graph database that works from line one.
The Ecosystem Today: Great Ideas, Painful Realities
There are great projects out there, and they deserve credit for pushing the space forward. But they each carry trade-offs that hit hard in production:
GunDB pioneered P2P databases in JavaScript. But its core carries years of accumulated technical debt. Storage is built on localStorage — a synchronous API with a 5MB cap that blocks the main thread. Conflict resolution uses wall-clock timestamps (HAM), which drift across devices in ways that are hard to debug. The sync protocol becomes unpredictable after prolonged disconnections, with no clean mechanism to replay missed operations. Cryptography is a custom implementation (SEA) rather than leveraging browser-native standards. And to build anything real, you stack modules — SEA for auth, RAD for storage, custom relays for signaling — each with its own learning curve and failure modes. What looks minimal quickly becomes a fragile assembly.
OrbitDB is architecturally strong — Merkle-CRDTs, append-only logs, well-structured codebase. But it requires IPFS and Libp2p as dependencies. That's not just adding a database to your project — it's adopting an entire distributed networking stack with its own daemon, configuration, and operational complexity. For many JavaScript developers who just need P2P data sync in a web app, it's a heavyweight commitment.
Both projects inspired me. But neither gave me what I needed: a complete, production-ready P2P graph database that works from the first line of code, using modern web standards, with zero external infrastructure.
GenosDB: Everything Works from Line One
import { gdb } from "https://cdn.jsdelivr.net/npm/genosdb@latest/dist/index.min.js";
const db = await gdb("myapp", { rtc: true });
Two lines. Here's what's already running:
Storage: OPFS, Not localStorage
GenosDB uses the Origin Private File System (see Async Engine details) — a modern, sandboxed file system API. All I/O runs in a dedicated Web Worker, so the main thread is never blocked. The worker implements a tiered fallback strategy:
- Synchronous OPFS (lowest latency, atomic writes)
- Asynchronous OPFS (stream-based, still fast)
- IndexedDB (universal fallback)
This means GenosDB automatically uses the best storage available in any browser — with no size limits, no main-thread blocking, and per-file write queues that prevent corruption from concurrent operations.
Sync: Hybrid Delta Protocol
Most P2P databases either send everything (wasteful) or try diffs that break after disconnections. GenosDB uses a dual-mode sync engine:
- Delta sync (primary): Every mutation is logged in a capped operation log (oplog). When a peer reconnects, only the missed operations are serialized with MessagePack, compressed with Pako, and sent over. Minimal bandwidth, minimal latency.
- Full-state fallback (automatic): If a peer has been offline too long and the oplog can't cover the gap, the system automatically sends the entire compressed graph state. The receiving peer reconciles, resets its clock, and is immediately ready for future delta syncs.
No manual intervention. No broken states. Just eventual consistency that actually works.
Conflict Resolution: Hybrid Logical Clocks
Wall-clock timestamps are unreliable in distributed systems. GenosDB uses Hybrid Logical Clocks (HLC) — the standard approach for causal ordering. Every operation gets a unique, partially-ordered timestamp that doesn't depend on synchronized device clocks. Conflicts resolve deterministically with last-write-wins semantics.
Networking: Decentralized Signaling via Nostr
GenosDB's P2P module (GenosRTC) uses Nostr relays for WebRTC signaling. It ships with a built-in list of stable relays that stays automatically updated — so it works instantly with zero configuration. Developers can optionally provide their own relay list for private networks or specific infrastructure needs.
The relay management is intelligent:
- Connects instantly to built-in stable relays (zero startup delay)
- In parallel, loads additional relays from local cache and community sources like
nostr.watch - Automatically detects and drops unhealthy relays (PoW requirements, timeouts, restrictive policies)
- Supports custom relay URLs:
gdb("app", { rtc: { relayUrls: ["wss://my-relay.com"] } })
Once signaling completes, all data flows directly peer-to-peer through WebRTC data channels. No server touches your data.
Cross-Tab Sync
Multiple tabs of the same app stay in sync via BroadcastChannel. No race conditions, no stale data between tabs.
Serialization: MessagePack + Pako
All data — both on disk and over the wire — is serialized with MessagePack (compact binary, faster than JSON) and compressed with Pako (zlib). This dramatically reduces storage footprint and network payloads compared to JSON-based approaches.
The API
import { gdb } from "https://cdn.jsdelivr.net/npm/genosdb@latest/dist/index.min.js";
const db = await gdb("myapp", { rtc: true });
// Create — returns a SHA-256 content-addressable ID
const id = await db.put({ name: "Alice", role: "admin" })
// Read
const node = await db.get(id)
// Read with real-time subscription
db.get(id, (node) => {
console.log("Node changed:", node)
})
// Update
await db.put({ name: "Alice", role: "superadmin" }, id)
// Delete (also cleans up all edges)
await db.remove(id)
// Graph relationships
await db.link(userId, projectId)
// Reactive query with MongoDB-style filters
db.map({ where: { role: { $in: ["admin", "superadmin"] } } }, (node, id, action) => {
// action: 'initial' | 'added' | 'updated' | 'removed'
console.log(action, id, node)
})
// Graph traversal — follow edges recursively
db.map({
where: { type: "department" },
$edge: { where: { active: true } }
}, (node, id) => {
// Returns all active descendants of department nodes
})
// Sorting and pagination
db.map({
where: { type: "post" },
field: "created",
order: "desc",
$limit: 10,
$after: lastCursorId
}, callback)
Middleware: Intercept P2P Operations
// Block remove operations from peers
db.use(async (operations) => {
return operations.filter(op => op.type !== 'remove')
})
// Custom validation before applying remote data
db.use(async (operations) => {
return operations.filter(op => isValid(op))
})
Process, validate, transform, or reject incoming P2P data before it touches your local database.
Beyond Data: Audio, Video, and File Streaming
GenosDB isn't just a database — its P2P layer supports direct communication between peers:
// Named data channels
const chat = db.room.channel("chat")
chat.send({ text: "Hello!" })
chat.on("message", (msg, peerId) => { ... })
// Audio/video streaming
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true })
db.room.addStream(stream)
db.room.on("peer:stream", (stream, peerId) => { ... })
// Peer lifecycle
db.room.on("peer:join", (peerId) => { ... })
db.room.on("peer:leave", (peerId) => { ... })
Build collaborative apps, real-time games, video calls, or file sharing — all P2P, all from the same database instance.
Opt-In Modules: First-Party, Tested Together
When your app grows, activate what you need. These aren't community add-ons — they're first-party modules with the same maintainer and release cycle:
const db = await gdb("myapp", {
rtc: true,
sm: { superAdmins: ["addr"] }, // Security: RBAC + WebAuthn + Mnemonic recovery
nlq: true, // Natural Language Queries
geo: true, // Geospatial ($near, $bbox)
rx: true, // Radix tree ($startsWith, prefix search)
ii: true, // Inverted index (full-text search)
audit: true // Oplog auditing with custom prompts
})
Security Manager: Zero-Trust by Default
The Security Manager module deserves special attention. It's not bolted on — it's integrated into the sync pipeline:
- WebAuthn: Authenticate with biometrics or hardware keys. Silent session resume on page reload.
- Mnemonic phrases (BIP39): User-friendly account creation and recovery.
- Cryptographic identity: Ethereum-style key pairs. All P2P operations are signed and verified by peers.
-
RBAC hierarchy:
superadmin > admin > manager > user > guest(fully customizable). -
Granular permissions:
read,write,link,publish,delete,deleteAny,assignRole. -
Encrypted storage:
db.sm.put()/db.sm.get()for end-to-end encrypted, user-scoped data. - Role expiration: Assign roles with optional TTL.
Cellular Mesh: A Novel Architecture for Scaling P2P Networks
This is one of the innovations I'm most proud of, because it didn't exist before GenosDB.
The fundamental problem with browser-based P2P networks is that they use flat mesh topology — every peer connects to every other peer. This works fine with 10 peers. At 100, it collapses. At 1,000, it's impossible. The connection count grows O(N²), and browsers have hard limits on simultaneous WebRTC connections.
I spent months researching and testing different approaches to solve this. The result is Cellular Mesh — a novel overlay protocol that organizes peers into logical cells with designated bridge nodes for inter-cell communication:
cell-0 ←→ cell-1 ←→ cell-2 ←→ cell-3
│ │ │ │
peers peers peers peers
Each peer only connects to others in its cell. Bridge nodes at cell boundaries relay messages between cells. This reduces connection complexity from O(N²) to O(N) — making it possible to scale a browser-based P2P network to thousands of simultaneous peers.
The protocol includes:
- Dynamic cell sizing that adapts automatically as the network grows or shrinks
- Health-scored bridge selection — bridges are chosen based on connection quality, not randomly
- TTL-based message propagation calculated from the actual topology
- Automatic deduplication to prevent message storms
- Heartbeat-based cleanup of inactive peers
To my knowledge, no other browser-based P2P database or WebRTC framework implements anything like this. It was born from the real need of scaling OVGrid — a planetary-scale virtual world where potentially thousands of users need to share state simultaneously.
Enable it with one flag: { rtc: { cells: true } }
Live Examples
Every example runs in the browser with zero backend:
- Collaborative Whiteboard — P2P drawing canvas
- Real-Time Video Room — P2P video streaming
- Collaborative Rich-Text Editor — Live typing, remote cursors, RBAC, version history
- Secure Decentralized Notes — End-to-end encrypted, P2P shared notes
- Location Sharing — Live map with Leaflet + GenosRTC
- IoT Thermostat — Reactive P2P device control
- Cellular Mesh Monitor (3D) — Three.js visualization of the mesh topology
Get Started
npm install genosdb
import { gdb } from "https://cdn.jsdelivr.net/npm/genosdb@latest/dist/index.min.js";
const db = await gdb("my-app", { rtc: true });
Or use it directly from a CDN:
<script type="module">
import { gdb } from "https://cdn.jsdelivr.net/npm/genosdb@latest/dist/index.min.js"
const db = await gdb("my-app", { rtc: true })
</script>
Two lines. Full P2P graph database. No assembly. No infrastructure. No vendor lock-in.
Docs: github.com/estebanrfp/gdb
Explore More
- GenosDB Cellular Mesh: Solving P2P Network Scalability — the novel topology for massive-scale P2P
- GenosDB: Zero-Trust Security for Distributed Systems — how the security model works
- Technical Features of GenosDB — complete feature overview
- Most Popular P2P Distributed Databases — how GenosDB compares
I'm estebanrfp — Full Stack Developer, dWEB R&D. I build distributed systems in pure JavaScript because the web should be free, resilient, and owned by the people who use it.
This article is part of the official documentation of GenosDB (GDB).
GenosDB is a distributed, modular, peer-to-peer graph database built with a Zero-Trust Security Model, created by Esteban Fuster Pozzi (estebanrfp).
📄 Whitepaper | overview of GenosDB design and architecture
🛠 Roadmap | planned features and future updates
💡 Examples | code snippets and usage demos
📖 Documentation | full reference guide
🔍 API Reference | detailed API methods
📚 Wiki | additional notes and guides
💬 GitHub Discussions | community questions and feedback
🗂 Repository | Minified production-ready files
📦 Install via npm | quick setup instructions
Top comments (0)