
On February 26, 2025, Slack experienced a global outage that disrupted messaging, calls, and integrations for millions of users. Discord suffered a similar disruption on January 26, 2022, preventing users from sending messages or accessing the platform entirely. According to reports from ThousandEyes and The Verge, both incidents lasted several hours and left teams unable to work effectively.
These outages highlight a core vulnerability in applications that rely fully on a remote server: When the servers go down, everything stops. Productivity stalls, communication breaks, and users are left waiting for someone else's infrastructure to recover. Even when these services are operational, you face the constant challenge of building complex conflict-resolution systems, managing operational transforms for real-time edits, and scaling server costs with every session.. In contrast, DefraDB offers peer-to-peer capabilities that allow data to be shared directly between nodes, enabling operations to continue without having to worry about a remote server being unavailable.
In this article, you'll learn about the technical components that make DefraDB's P2P capabilities possible. We will explore how nodes establish secure connections and discover each other across networks, examine the cryptographic protocols that protect data in transit, and walk through the sync mechanisms based on conflict-free replicated data type (CRDT) that resolve conflicts automatically. You will learn through two use cases how to architect applications that maintain full functionality offline and sync seamlessly when connectivity returns.
Why P2P Matters in Edge-First (and Local-First) Apps
Monolithic databases force your applications into a dependency bottleneck where every interaction requires server approval, creating single points of failure that can paralyze entire systems. Beyond reliability concerns, this architecture surrenders your user data to third-party infrastructure, where privacy becomes a matter of trust rather than technical certainty. P2P architecture changes this by allowing each device to act as an edge-first data store and participate in synchronization. Rather than always relying on a central server, data can flow directly between peers. With DefraDB, applications remain functional offline because data is stored and managed on the device itself, while also giving developers the option to replicate that data to additional peers. These peers might include other devices owned by the same user, such as a phone, tablet, or laptop, or a cloud-hosted DefraDB node that provides availability if the user’s device goes offline. This flexibility lets developers choose the replication strategy that best fits their application, balancing edge-first functionality with reliability. When connectivity returns, DefraDB takes care of peer discovery, synchronization, and update propagation automatically, without requiring manual coordination. This lets you avoid building complex replication and communication layers yourself, so you can focus on application logic instead of infrastructure. Users benefit from a seamless experience across devices, even in environments with limited or intermittent connectivity.
How Peer-to-Peer Sync Works in DefraDB
To understand how DefraDB enables edge-first, peer-to-peer applications, it's helpful to look at what happens under the hood when multiple devices begin exchanging data. Instead of relying on a central server to coordinate state, DefraDB treats each device as a node or an equal participant in the network. Each node runs a full database instance locally and maintains its own data using CRDT. These are mathematical structures that allow updates to be applied in any order while still ensuring all devices eventually reach the same final state. This approach removes the usual complexity of handling merge conflicts in distributed systems.
Nodes form secure connections using libp2p, a modular networking stack designed for peer-to-peer communication. Libp2p manages complex tasks like the complexity of NAT traversal. It also handles connection multiplexing and provides transport security. When two nodes connect, they perform cryptographic handshakes to negotiate encryption keys and verify each other's identities. This process creates a secure channel that protects all data exchanged between them. By relying on libp2p, DefraDB abstracts away low-level networking details and can focus on synchronizing data reliably and maintaining consistency across nodes.
The actual sync process in DefraDB involves exchanging lightweight diffs based on a Merkle-CRDT data model, which combines Merkle trees for cryptographic integrity with CRDTs to enable conflict-free updates. Each change is represented as a delta that includes cryptographic hashes and proofs, allowing it to be independently verified and applied without relying on a central coordinator. These deltas are organized in a directed acyclic graph (DAG), which encodes causal relationships between operations and provides a deterministic way to merge concurrent updates. Synchronization is encrypted and bidirectional, meaning nodes can send and receive updates at the same time without needing coordination. The DAG structure also preserves causal ordering, so operations are applied in a logically consistent way. And since the system is designed for eventual consistency, nodes can stay offline for long periods and still participate in sync when they reconnect. This makes the network resilient to intermittent connectivity and temporary partitions.
Core Components of DefraDB's P2P Stack
DefraDB's peer-to-peer capabilities rely on four fundamental components that work together to create secure, reliable communication between nodes. Each component solves a specific aspect of distributed networking, from establishing trust between unknown peers to efficiently synchronizing data changes across unreliable connections.
Identity and Authentication
Identity and authentication determine how nodes recognize and verify each other within DefraDB's peer-to-peer network. Each node generates a unique public/private key pair that serves as its cryptographic identity, enabling self-sovereign operation without depending on external certificate authorities or identity providers. These key pairs serve multiple purposes beyond simple identification. Nodes use their private keys to sign documents and data changes, creating tamper-evident records that other peers can verify using the corresponding public key.
When establishing connections, identity key pairs enable secure peer-to-peer encryption similar to Transport Layer Security (TLS), but without centralized certificate authorities, ensuring that communication channels remain private. The actual end-to-end encryption of CRDT data uses symmetric encryption keys, but access to these keys is authorized through the identity key-pair system. This creates a web of trust where peers can verify the authenticity of changes using cryptographic signatures from remote nodes.
Discovery
Discovery mechanisms allow nodes to find and connect with each other across different network topologies. For local network scenarios, DefraDB can use multicast DNS (mDNS) to automatically discover peers on the same network segment, though this capability depends on the deployment environment since some platforms, like browsers, typically cannot access mDNS. For internet-wide communication, nodes have several options, including relay nodes that facilitate connections between peers behind NATs, WebRTC for browser-based applications, or direct IP/DNS connections when nodes have publicly accessible addresses. Peer addresses can be shared manually between applications or discovered through known bootstrap nodes that help new peers join the network.
Secure Transport
Secure transport ensures that all communication between nodes remains encrypted and tamper-proof. DefraDB uses libp2p's security protocols, including Noise and TLS 1.3, to create encrypted channels that protect data in transit. No information is ever transmitted in clear text, and cryptographic signatures remain verifiable on both ends of a connection even when data passes through relay nodes. This transport security works seamlessly with the identity system to create authenticated, encrypted connections between any two peers regardless of their network topology.
Document Sync
Document sync represents the core of DefraDB's collaborative capabilities, where changes flow between nodes as Merkle-CRDT deltas rather than full document overwrites. Each modification is encoded as a compact, cryptographically verifiable delta that contains only the changed information, dramatically reducing bandwidth requirements and sync times. The synchronization operates at the field level with causal ordering, ensuring that changes maintain their logical relationships even when they arrive out of sequence. When peers go offline, changes queue locally until reconnection, at which point the sync process automatically reconciles all pending modifications without requiring manual conflict resolution in most cases.
How Two Apps Can Communicate Over P2P (Edge or Remote)
DefraDB supports peer-to-peer communication both on local networks and across the public internet. On a local area network (LAN), nodes automatically discover each other using mDNS, enabling seamless synchronization once schemas and permissions align. This allows applications such as mobile devices or IoT edge devices to sync messages or shared state in real time without relying on internet connectivity or cloud infrastructure. Across different networks, peers establish connections manually by adding each other's libp2p multiaddr, often requiring port forwarding, NAT traversal, or relay nodes. Regardless of the connection method, DefraDB uses the same secure, conflict-free CRDT protocol, ensuring data sync even if peers disconnect temporarily.
A practical example involves running two DefraDB instances in a Docker Compose setup with a shared network. Each instance requires a unique cryptographic key ring secret to establish its identity in the P2P network and enable secure communication channels.
To set up the environment file, you would create a .env file and generate the keyring secrets:
These secrets are passed to each container as environment variables to define the keyring secret that will be used to access the keyring. Below is a typical Docker Compose configuration illustrating how two nodes are configured to expose HTTP and P2P ports, mount persistent data volumes, and assign static IPs on a user-defined bridge network:
When one of the nodes is started, in this case node1, the logs will reflect successful initialization of the P2P service and readiness to accept connections:
To establish connections, you would also need the peer ID. This unique cryptographic identifier can be retrieved using docker exec defradb_node1 /defradb client p2p info, which in this case retrieves the peer info for node1, and this can be shared with other nodes to facilitate secure peer connections. The peer info is a JSON object, typically including the node’s ID and its network addresses, for example:
When two nodes are running and are already connected, whether on the same Docker network or on different networks, data replication can be configured to ensure data is shared seamlessly. Ensuring both nodes have matching schemas, such as the DeviceData schema shown in the schema-addition operation below, is key to enabling consistent data validation and synchronization:
The following command configures the database to automatically replicate data from node1 to node2; it requires the target node's peer information as a JSON object:
Once replication is established, data flows automatically between nodes. The images below demonstrate how the same CRDT protocol works across any network topology.
Data is created on node1, and the successful document creation response is shown in the image below:
Since node1 has been set to replicate data to node2, the image below shows the seamless synchronization of data between the two nodes:
The logs below show the process of establishing a connection, receiving data, and synchronizing data between the two nodes:
The system's eventual consistency ensures that peers receive all updates in real time or upon reconnection, even after extended offline periods, making collaboration resilient to network instability common in distributed environments.
If you want to do communication across the public internet, DefraDB nodes must handle NAT traversal and public reachability. This typically involves port forwarding or NAT punching to expose each peer's listening address or routing through a relay node using libp2p's circuit relay protocol. A remote peer can manually initiate a connection by adding the target node's multiaddr, and once a connection is established, synchronization proceeds securely using the same CRDT protocol. Importantly, peers that go offline will still receive all missed updates upon reconnection, preserving eventual consistency without requiring a constant connection.
Security Model: How Communications Stay Safe
DefraDB improves security by replacing traditional username-and-password authentication with cryptographic identities. As mentioned, each node generates a unique public/private key pair that serves as its identity, reducing the risk of impersonation since the possibility of an attacker forging a valid private key is considered highly unlikely (or even computationally infeasible). All communication between nodes is signed by the sender and verified by the receiver using public key cryptography, allowing peers to detect tampering or message injection attempts. Document changes are also signed and verified, ensuring that only updates from recognized peers are accepted. This model makes writes tamper-evident and scoped to trusted participants, strengthening the integrity of shared data without relying on centralized access control.
All communication streams between DefraDB nodes are encrypted over the wire using transport-level encryption provided by libp2p. This encryption is not end-to-end in the application-layer sense, where only the sender and final recipient can decrypt the data. Instead, each hop in the peer-to-peer connection is individually secured, ensuring that no data travels in clear text. This prevents intermediaries on the network path from reading or modifying the content of any message in transit. When combined with cryptographic signatures on every message, this layered security model provides strong protection against threats like man-in-the-middle attacks, data injection, and message spoofing. Even if attackers intercept network traffic, they cannot decrypt the payload, forge valid signatures, or impersonate trusted peers.
Offline Support and Reconnection Behavior
DefraDB's CRDT-based architecture is designed with offline support as a core capability rather than an afterthought. When a device loses connectivity, all data changes are stored locally using CRDT state representations. Users can continue creating and editing documents without disruption. Because CRDTs are designed to track operations in a causally ordered and mergeable format, these offline updates can be automatically reconciled when the node reconnects to the network. This approach avoids typical merge conflicts and reduces the need for manual resolution. While application-level conflicts may still arise depending on the schema, the underlying synchronization of CRDT deltas remains deterministic and reliable.
Upon reconnection, DefraDB automatically initiates synchronization by exchanging Merkle-CRDT diffs with connected peers, transmitting only the changes that occurred during the offline period. This process respects causal ordering, ensuring that operations are applied in their logical sequence regardless of when they physically arrive over the network. The system's eventual consistency guarantees mean that all connected nodes will converge to the same final state, even if they experienced different offline periods or received updates in different orders. This seamless reconnection behavior enables use cases like field workers collecting data in remote locations, collaborative editing sessions that survive network interruptions, and mobile applications that sync effortlessly as users move between WiFi networks and cellular coverage.
Sync Topologies Supported
DefraDB's flexible P2P architecture supports multiple synchronization topologies, allowing developers to optimize data flow for their specific use case rather than forcing all applications into a one-size-fits-all model. The system emphasizes targeted synchronization, where peers can exchange only the data they explicitly subscribe to, such as specific collections or documents, rather than replicating the entire database. Relevance is determined through replication configurations, including collection-level sync settings in active replication or document-level pub/sub subscriptions in passive replication, all governed by shared schema definitions and access permissions.
One-to-one synchronization enables direct peer relationships where two nodes maintain a shared state, making it ideal for user-to-user scenarios like messaging applications or shared document editing, where there is a need for efficient content delivery and reduced latency. Star topologies allow multiple edge devices to synchronize with a central hub node, ideal for IoT deployments where sensors report to a local gateway or mobile devices sync with a desktop workstation. Mesh networks support multipeer environments where every node can potentially sync with every other node, enabling fully distributed collaborative systems without any central coordination point. This flexibility means applications can start with simple peer-to-peer connections and evolve into complex distributed networks as requirements grow, all while using the same underlying CRDT synchronization protocol. Whether building ad hoc networks that form spontaneously or structured systems with well-defined hierarchies, DefraDB's P2P capabilities adapt to support the optimal topology for each use case.
Conclusion
Through this exploration of DefraDB's peer-to-peer communication system, you've seen how CRDT-based synchronization maintains consistency across devices without requiring central coordination or manual conflict resolution. You also learned how nodes use cryptographic key pairs for identity and authentication, how secure communication is established over libp2p, and how peer discovery can occur both on the edge and in internet-connected environments.
Most importantly, you now understand how DefraDB's P2P architecture shifts control back to users and developers, providing the technical foundation to build resilient distributed applications without implementing your own networking stack, conflict-resolution logic, or security protocols. Whether building collaborative tools or deploying IoT devices at the edge or mobile applications, you can create systems that work reliably in any environment while eliminating the single points of failure that plague centralized architectures.