Why I Built GenosDB: The P2P Database That Works Out of the Box
Source: Dev.to
The “Minimal Core” Trap in P2P Databases
You pick a library because it looks lightweight. The README shows a 3‑line setup. You think: perfect, this is all I need. Then reality hits.
- You need authentication → a separate module.
- You need conflict resolution that actually works → another module.
- Encryption? → another module.
- Offline persistence that doesn’t corrupt? → good luck.
Suddenly your “lightweight” database is a patchwork of add‑ons, each with its own quirks, version issues, and undocumented edge cases.
I lived this for years building real P2P applications, and it’s why I built GenosDB.
Existing Projects & Their Trade‑offs
| Project | Strengths | Pain Points |
|---|---|---|
| GunDB | Pioneered P2P databases in JavaScript. | • Core built on localStorage (synchronous, 5 MB cap, blocks main thread).• Conflict resolution uses wall‑clock timestamps (HAM) → drift & hard debugging. • Sync protocol becomes unpredictable after long disconnections; no clean replay mechanism. • Cryptography is a custom implementation (SEA) instead of browser‑native standards. • Real‑world use requires stacking modules (SEA for auth, RAD for storage, custom relays for signaling) → steep learning curve and fragile assembly. |
| OrbitDB | Architecturally strong: Merkle‑CRDTs, append‑only logs, clean codebase. | • Requires IPFS + Libp2p as dependencies → you’re adopting an entire distributed networking stack with its own daemon, configuration, and operational complexity. • For many JS developers who just need P2P data sync in a web app, this is 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.
Introducing GenosDB
import { gdb } from "genosdb";
const db = await gdb("myapp", { rtc: true });
Two lines. Here’s what’s already running under the hood.
Storage – OPFS + IndexedDB
GenosDB uses the Origin Private File System (OPFS) – a modern, sandboxed file‑system API. All I/O runs in a dedicated Web Worker, so the main thread is never blocked.
| Tier | Description |
|---|---|
| Synchronous OPFS | Lowest latency, atomic writes |
| Asynchronous OPFS | Stream‑based, still fast |
| IndexedDB | Universal fallback |
Result: GenosDB automatically picks the best storage available in any browser – no size limits, no main‑thread blocking, and per‑file write queues that prevent corruption from concurrent operations.
Sync Engine – Dual‑Mode
| Mode | How it works |
|---|---|
| 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.
Causal Ordering – 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.
P2P Signaling – GenosRTC + Nostr Relays
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.
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 ever touches your data.
Multi‑Tab Sync
Multiple tabs of the same app stay in sync via BroadcastChannel. No race conditions, no stale data between tabs.
Compact Serialization
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.
Quick‑Start API
import { gdb } from "genosdb";
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
console.log("Descendant:", id, node);
}
);
TL;DR
- Minimal core libraries often become fragile patchworks.
- GenosDB gives you a complete, production‑ready P2P graph database out of the box.
- It leverages modern web APIs (OPFS, Web Workers, WebRTC, BroadcastChannel) and proven techniques (HLC, MessagePack, Pako).
- Zero external infrastructure, two‑line setup, and a clean, ergonomic API.
Give it a try and see how “lightweight” can truly mean lightweight.
Sorting and Pagination
db.map({
where: { type: "post" },
field: "created",
order: "desc",
$limit: 10,
$after: lastCursorId
}, callback);
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.
GenosDB + P2P Layer
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 Events
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.
Modular First‑Party Features
When your app grows, activate only what you need. These are first‑party modules (same maintainer, same 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
});
The SM (Security & Management) Module
- WebAuthn – biometric or hardware‑key authentication; silent session resume on reload.
- Mnemonic phrases (BIP‑39) – user‑friendly account creation & recovery.
- Cryptographic identity – Ethereum‑style key pairs; all P2P ops are signed & verified.
- 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.
This is one of the innovations I’m most proud of; it didn’t exist before GenosDB.
Cellular Mesh – Scalable Browser‑Based P2P
The classic flat mesh topology (every peer ↔ every other peer) collapses beyond ~10 peers (O(N²) connections).
GenosDB introduces Cellular Mesh, an overlay protocol that groups peers into logical cells with bridge nodes for inter‑cell communication:
cell‑0 ←→ cell‑1 ←→ cell‑2 ←→ cell‑3
│ │ │ │
peers peers peers peers
- Only intra‑cell connections – each peer talks to peers in its own cell.
- Bridge nodes relay messages between cells, reducing connection complexity from O(N²) → O(N).
Cellular Mesh Features
| Feature | Description |
|---|---|
| Dynamic cell sizing | Cells grow/shrink automatically as the network changes. |
| Health‑scored bridge selection | Bridges are chosen based on connection quality, not randomly. |
| TTL‑based propagation | Message TTL is calculated from the actual topology. |
| Automatic deduplication | Prevents message storms. |
| Heartbeat cleanup | Removes inactive peers. |
To the best of my knowledge, no other browser‑based P2P database or WebRTC framework implements anything like this. It was born from scaling OVGrid, a planetary‑scale virtual world.
Enable Cellular Mesh with a single flag:
{ rtc: { cells: true } }
Live Browser‑Only Examples
| Example | Description |
|---|---|
| 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 |
Installation
npm
npm install genosdb
import { gdb } from "genosdb";
const db = await gdb("my-app", { rtc: true });
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.
Resources
- Docs: https://github.com/estebanrfp/gdb
- Whitepaper – Overview of GenosDB design & architecture
- Roadmap – Planned features & future updates
- Examples – Code snippets & usage demos
- API Reference – Detailed method docs
- Wiki – Additional notes & guides
- GitHub Discussions – Community Q&A
- Repository – Minified production‑ready files
- Website – https://genosdb.org
About the Author
I’m Esteban Fuster Pozzi (@estebanrfp), a Full‑Stack Developer focused on 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).