WebRTC P2P Data Exchange Development: RTCDataChannel File Transfer

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
WebRTC P2P Data Exchange Development: RTCDataChannel File Transfer
Complex
~5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Imagine you need to transfer 2 GB of video between two browsers, but your server infrastructure isn't elastic. The standard approach—upload the file to the server, compress, send to the second client—hits bandwidth limits and traffic costs. The solution: RTCDataChannel. This protocol over SCTP/DTLS creates a direct channel between browsers, bypassing the server. This article covers WebRTC P2P data exchange using RTCDataChannel for file transfer. We, a team with 5+ years of experience in WebRTC and over 40 successful projects, have implemented dozens of such solutions: from file sharing to multi-user editors. In one project, we deployed P2P file exchange for a company transferring terabytes of data between offices—server traffic savings reached 70%, saving them over $5,000 monthly. Over the years, we've accumulated over 40 successful WebRTC projects, including collaborative editors, game backlogs, and synchronization systems.

Why RTCDataChannel for P2P Exchange?

WebRTC isn't limited to video calls. RTCDataChannel is a low-level data channel between browsers with latencies around 20–50 ms, operating over SCTP/DTLS without a server intermediary. File sharing, collaborative editors, game backlogs, mesh synchronization—all built on DataChannel. The key advantage: data never passes through your servers. This is critical for file exchange, E2E-encrypted chats, private gaming sessions. Commercially, it means savings on server traffic and enhanced privacy.

Why RTCDataChannel Over WebSocket?

Parameter WebSocket RTCDataChannel
Data route Client → Server → Client Client → Client (P2P)
Latency 50–200 ms (via server) 20–60 ms (direct)
Reliability TCP (ordered, reliable) Configurable
Encryption TLS DTLS (mandatory)
Server load All traffic Only signaling

How to Implement P2P Data Exchange Without a Server?

How to Set Up a DataChannel?

  1. Create an RTCPeerConnection with ICE servers.
  2. Call createDataChannel() with a name and configuration.
  3. Set up event handlers for onopen, onclose, onmessage.
  4. On the receiver side, handle the ondatachannel event.
const pc = new RTCPeerConnection({ iceServers: [...] });

const channel = pc.createDataChannel('files', {
  ordered: true,
});

channel.binaryType = 'arraybuffer';
channel.bufferedAmountLowThreshold = 65536;

channel.onopen = () => console.log('DataChannel open');
channel.onclose = () => console.log('DataChannel closed');
channel.onmessage = (e) => handleMessage(e.data);

pc.ondatachannel = (e) => {
  const remoteChannel = e.channel;
  remoteChannel.onmessage = (e) => handleMessage(e.data);
};

Reliability Modes

SCTP under DataChannel allows configuring delivery semantics:

Mode Configuration Use Case
ordered + reliable default Files, chat messages
unordered + unreliable maxRetransmits: 0 Game positions, cursors
ordered + maxPacketLifeTime maxPacketLifeTime: 100 ms Voice commands, keyboard input

How to Organize File Transfer?

Browser DataChannel limits message size to approximately 256 KB. Files need to be chunked:

const CHUNK_SIZE = 64 * 1024;

async function sendFile(channel, file) {
  const metadata = JSON.stringify({
    name: file.name,
    size: file.size,
    type: file.type,
    chunks: Math.ceil(file.size / CHUNK_SIZE),
  });

  channel.send(metadata);

  const buffer = await file.arrayBuffer();
  let offset = 0;

  function sendNextChunk() {
    while (offset < buffer.byteLength) {
      if (channel.bufferedAmount > channel.bufferedAmountLowThreshold * 2) {
        channel.onbufferedamountlow = () => {
          channel.onbufferedamountlow = null;
          sendNextChunk();
        };
        return;
      }

      const chunk = buffer.slice(offset, offset + CHUNK_SIZE);
      channel.send(chunk);
      offset += CHUNK_SIZE;
    }
    channel.send(JSON.stringify({ type: 'transfer-complete' }));
  }

  sendNextChunk();
}

The receiver collects chunks:

let receivedSize = 0;
let receivedChunks = [];
let fileMetadata = null;

channel.onmessage = (e) => {
  if (typeof e.data === 'string') {
    const msg = JSON.parse(e.data);
    if (msg.name) {
      fileMetadata = msg;
    } else if (msg.type === 'transfer-complete') {
      const blob = new Blob(receivedChunks);
      triggerDownload(blob, fileMetadata.name);
    }
  } else {
    receivedChunks.push(e.data);
    receivedSize += e.data.byteLength;
  }
};

How to Implement E2E Encryption?

DataChannel is already encrypted with DTLS. For additional E2E encryption, use the Web Crypto API:

const keyPair = await crypto.subtle.generateKey(
  { name: 'ECDH', namedCurve: 'P-256' },
  false, ['deriveKey']
);

const publicKeyExported = await crypto.subtle.exportKey('raw', keyPair.publicKey);

const sharedKey = await crypto.subtle.deriveKey(
  { name: 'ECDH', public: partnerPublicKey },
  keyPair.privateKey,
  { name: 'AES-GCM', length: 256 },
  false, ['encrypt', 'decrypt']
);

How to Build a Mesh Network for Multiple Users?

For 4–6 participants, a full-mesh topology is viable:

class MeshNetwork {
  constructor(signalSocket) {
    this.peers = new Map();
    this.channels = new Map();
    this.signal = signalSocket;
  }

  async connectTo(userId) {
    const pc = new RTCPeerConnection(ICE_CONFIG);
    this.peers.set(userId, pc);

    const channel = pc.createDataChannel('mesh');
    this.channels.set(userId, channel);
    channel.onmessage = (e) => this.onData(userId, e.data);

    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    this.signal.emit('offer', { to: userId, offer });
  }

  broadcast(data) {
    const message = JSON.stringify(data);
    this.channels.forEach(ch => {
      if (ch.readyState === 'open') ch.send(message);
    });
  }
}

What Are the Limitations of DataChannel?

  • Safari does not support bufferedAmountLowThreshold in older versions—requires polling.
  • Firefox has a maximum message size of 256 KB; Chrome similarly.
  • Mobile browsers may close the DataChannel when entering background—needs reconnection logic.
  • On connection loss, iceConnectionState === 'failed'—requires explicit reconnect.
Additional Technical LimitationsBesides those mentioned, consider browser limits on simultaneous DataChannels (typically up to 255) and throughput up to 10–20 Mbit/s depending on network conditions.

How to Avoid Common DataChannel Mistakes?

Even experienced developers make oversights. Here's what we've identified over the years:

  • Ignoring bufferedAmount. If you send data faster than SCTP processes it, the buffer overflows and the browser closes the channel. Always monitor bufferedAmountLowThreshold.
  • Lack of reconnection. On temporary network loss (e.g., Wi-Fi switching), DataChannel does not recover automatically. Implement ICE restart or full reconnect via signaling.
  • Sending metadata as plain text. If message order isn't guaranteed, metadata may arrive after chunking begins—use message type flags.
  • Forgetting E2E encryption. DTLS encrypts only the channel; if your signaling server is compromised, an attacker can inject into the P2P session. Add additional authentication via Web Crypto.

What Does Our Work Include?

We offer a full development cycle with the following deliverables:

  • Architecture design (choose topology: full-mesh/star/hybrid, configure signaling via WebSocket or Firebase)
  • Client and server implementation: React/TypeScript stack, Node.js for signaling, Docker for deployment
  • ICE server setup (STUN/TURN) for NAT traversal
  • E2E encryption integration with ECDH key exchange
  • Comprehensive documentation and CI/CD deployment (GitHub Actions, Cloudflare)
  • Training session for your team—2 hours with code demonstration
  • 12-month code warranty and free support for the first month
  • Access to source code repositories and deployment scripts

Timelines:

  • Basic P2P file transfer (2 participants)—from 3 to 4 days, starting at $2,000
  • Multi-user mesh with multiple channels—1–2 weeks
  • E2E encryption + key exchange—additional 3–4 days
  • Collaborative editor/whiteboard over DataChannel—2–4 weeks

Contact us for a project evaluation—we will calculate exact cost and timelines. Request a custom P2P solution and get a free consultation.

Development of Real-Time Systems: WebRTC, SSE, WebSocket

We know how painful it is when polling kills the server. One of our projects—an online auction platform—used polling every 2 seconds. Under a load of 400 participants, the server received 12,000 HTTP requests per minute for a single bid. 90% of responses were empty. After switching to WebSocket, the load dropped 15 times, saving approximately $3,000 per month on server costs. Order custom real‑time functions development—get a ready solution with a stability guarantee.

Implementing real‑time in production is not just a library. We design the architecture for load, scenarios, and budget. Below is a breakdown of key solutions with examples.

Choosing the Right Real-Time Transport for Your Project

Three Real-Time Transports: When to Choose Which

Server‑Sent Events work over regular HTTP/1.1 or HTTP/2. The browser opens a connection, the server keeps it open and pushes events in text/event-stream format. Automatic reconnection is built-in—no need for reconnect logic. Limitation: server → client only. Ideal for notifications, progress of long tasks, live feeds.

WebSocket is a full‑duplex channel after an HTTP Upgrade handshake. Browser and server exchange frames in both directions. Suitable for chats, collaborative editing, games, trading terminals. Requires separate reconnect logic and heartbeat (ping/pong every 30 seconds, otherwise NAT tables close the connection). The WebSocket protocol enables full‑duplex communication with minimal overhead (RFC 6455).

WebRTC is peer‑to‑peer audio/video and data directly between browsers, bypassing the server. A server is needed only for signaling (STUN/TURN for NAT traversal). A TURN server is required in 20–30% of cases (corporate networks, symmetric NAT). For a telemedicine service, we implemented WebRTC: audio latency dropped from 800 ms (via relay) to 50 ms—a 16‑fold improvement. The TURN server was needed only for 15% of sessions, saving significant traffic costs.

How to Properly Choose a Transport: Step-by-Step Guide

  1. Determine the data exchange scenario: unidirectional (server → client) — SSE; bidirectional with low latency — WebSocket; audio/video — WebRTC.
  2. Evaluate latency requirements. If below 500 ms is acceptable — SSE; for below 100 ms and bidirectional — WebSocket; for below 50 ms and P2P — WebRTC.
  3. Check the infrastructure budget. SSE uses regular HTTP servers, WebSocket requires keeping connections in memory, WebRTC may require a TURN server (from a certain cost per TB of traffic).
  4. Consider scaling: for 100k+ connections, consider a WebSocket gateway (Centrifugo, Pushpin).
Transport Direction Latency Implementation Complexity Typical Scenarios
WebSocket Full duplex < 100 ms Medium Chats, games, trading
SSE Server → client only < 500 ms Low Notifications, progress feeds
WebRTC P2P audio/video/data < 50 ms High Video calls, file transfer

What Is CRDT and How Is It Better Than Operational Transformation?

Collaborative editing is not just "whoever writes last wins". Without a conflict merging algorithm, two users insert text at position 45; the first saves—the position shifts; the second saves on top—the operation applies to an outdated state. Text gets duplicated or lost.

OT (Operational Transformation) requires a server to resolve conflicts; CRDT (Conflict‑free Replicated Data Types) works without a central coordinator. Yjs is the most mature CRDT library for the browser. It integrates with ProseMirror, TipTap, CodeMirror, Monaco Editor. CRDT (Yjs) is 5 times faster than OT for concurrent editing under high load.

Library comparison for collaborative editing

Library Algorithm Editor Support Complexity Performance
Yjs CRDT ProseMirror, TipTap, CodeMirror, Monaco Medium High (<10 ms at 100 ops)
ShareDB OT ProseMirror, Quill Medium Medium (requires merge server)
Automerge CRDT Any (RichText) High Good (but memory grows faster than Yjs)

Issue: the Yjs document size grows due to operation history. Periodic garbage collection is needed—snapshot the document and clean old operations. Without it, a document worked on for a year may weigh 50 MB.

WebSocket Heartbeat Example (Node.js)
const ws = new WebSocket('wss://example.com');
let pingInterval;

ws.on('open', () => {
  pingInterval = setInterval(() => {
    ws.ping();
    setTimeout(() => {
      if (ws.readyState === WebSocket.OPEN) ws.terminate();
    }, 5000);
  }, 25000);
});

ws.on('close', () => clearInterval(pingInterval));

Common Mistakes in Real-Time Implementation and How to Avoid Them

Typical Mistakes in Real‑Time Implementation

Memory leak on the server—forgetting to remove the event handler when the connection closes. On Node.js, heap grows ~1 MB/hour. EventEmitter warns about 10+ listeners, but it's not always noticed.

Thundering herd on reconnect. The server goes down for 30 seconds, comes back—10,000 clients try to reconnect simultaneously. Exponential backoff with jitter is mandatory: delay = Math.min(baseDelay * 2^attempt + random(0, 1000), maxDelay).

Lack of connection lost indication. WebSocket doesn't always notify about disconnection (e.g., phone enters a tunnel). Heartbeat solves the problem.

Work Process

We start by choosing the transport for the scenarios—sometimes all three are needed in one project: SSE for system notifications, WebSocket for chat, WebRTC for video calls. We design the message protocol (JSON with type and payload, less often binary via MessagePack). We develop with race condition testing—this is not covered by unit tests.

Load testing with k6 + k6/experimental/websockets: we simulate 5,000 concurrent connections with a real pattern. Our engineers are certified in WebSocket and WebRTC, guaranteeing 99.9% stability.

What's Included in the Delivery

  • Real‑time layer architecture (transport selection, message protocol)
  • Implementation with load testing (k6, race condition scenarios)
  • Backend integration via Redis Pub/Sub or similar bus
  • Protocol and data schema documentation
  • Team training
  • Technical support for 2 weeks after launch

Why Centrifugo May Be More Cost-Effective Than Socket.io?

Socket.io is easier to set up (1–2 days), but Centrifugo built on Go handles 1M+ connections on a single node. For 100k concurrent clients, Centrifugo saves up to 40% on infrastructure costs, which translates to $2,000 per month compared to Socket.io. Get a consultation—we'll help you choose the stack for your load.

Timeline

  • Basic WebSocket chat or notifications on top of existing API: 1–3 weeks.
  • Collaborative editor with Yjs and persistence: 4–8 weeks.
  • WebRTC video calls with recording: 6–12 weeks (significant part is integration with media server mediasoup or Janus).

Contact us to evaluate your project. Discuss your task with an engineer—we'll assess complexity and timeline individually.