Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Data Channels

Binary Data, Message Size and Backpressure

Send strings, JSON, ArrayBuffers and Blobs over RTCDataChannel, respect maxMessageSize, chunk big payloads, and use bufferedAmount and bufferedAmountLow to avoid flooding.

A data channel accepts several kinds of payload: strings, ArrayBuffer, typed arrays, DataView and Blob. That flexibility is great, but it hides two traps. First, every browser limits how large one message can be. Second, send() never blocks: if you call it in a fast loop, the data piles up in memory instead of going on the wire.

This lesson shows how to send each kind of data, how to split large payloads into chunks, and how to use the channel's built-in buffer signals so a sender never outruns the network.

What you can send

JavaScript
channel.send('plain text');                       // string, sent as UTF-8 text
channel.send(JSON.stringify({ type: 'move' }));   // JSON is just a string
channel.send(new Uint8Array([1, 2, 3]));          // typed array, sent as binary
channel.send(buffer);                             // ArrayBuffer
channel.send(blob);                               // Blob (async to read)

On the receiving side, event.data is a string for text messages. For binary messages its type depends on channel.binaryType:

  • 'arraybuffer': you get an ArrayBuffer. Best for most code.
  • 'blob': you get a Blob (the default in some browsers).

Set binaryType right after the channel exists, before any message arrives.

JS Text, JSON and binary

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When you mix text and binary, give every message a way to identify its kind. A common trick is to send small control messages as JSON strings and bulk data as binary.

Maximum message size

Each peer reports how large one message may be through pc.sctp.maxMessageSize (after the connection is set up). Browsers differ: a limit of about 256 KiB is common, and Firefox has advertised much more. The effective limit is the smaller of the two peers' values. Sending a bigger message throws a TypeError.

The safe approach is to chunk: split anything larger than, say, 16 KiB into pieces. 16 KiB works everywhere, and it keeps one large transfer from monopolizing the connection and delaying small messages on other channels.

flowchart LR
  F["Large payload 1 MiB"] --> C["Split into 16 KiB chunks"]
  C --> S["send each chunk"]
  S --> R["Receiver collects chunks"]
  R --> J["Join into one payload"]

Chunking: split on send, reassemble on receive.

Backpressure: bufferedAmount

send() copies your data into a queue and returns immediately. The property bufferedAmount tells you how many bytes are still waiting in that queue. If you send 100 MB in a loop without checking it, you use 100 MB of memory and, in some browsers, the channel closes.

Two tools let you pace yourself:

  • bufferedAmount: bytes queued right now.
  • bufferedAmountLowThreshold plus the bufferedamountlow event: the browser fires the event when the queue drains below the threshold.

The pattern is: send until bufferedAmount passes a high-water mark, stop, and continue when bufferedamountlow fires.

JS Chunked send with backpressure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sender never holds more than about 256 KiB in the queue. The number of pauses depends on how fast your machine drains it, so it is not printed.

Working with Blobs and files

A Blob (including a File from an <input type="file">) is read lazily. To send it in chunks, use blob.slice(start, end) and read each slice with await slice.arrayBuffer():

JavaScript
async function sendBlob(channel, blob) {
  const CHUNK = 16 * 1024;
  for (let offset = 0; offset < blob.size; offset += CHUNK) {
    while (channel.bufferedAmount > 256 * 1024) {
      await new Promise((r) => {
        channel.onbufferedamountlow = r;
      });
    }
    const piece = await blob.slice(offset, offset + CHUNK).arrayBuffer();
    channel.send(piece);
  }
}

This reads only 16 KiB of the file at a time, so even a multi-gigabyte file does not fill your memory. The file transfer project turns this into a working app.

Common mistakes

  • Forgetting binaryType. You receive a Blob and treat it like an ArrayBuffer.
  • Sending huge messages. One 5 MB message may throw or stall; chunk instead.
  • No backpressure. A fast loop makes bufferedAmount explode.
  • Sending a view with a larger underlying buffer. typed.buffer sends the whole buffer; send the view itself or slice() it.
  • Mixing text and binary without a header. The receiver cannot tell what it got.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does event.data have for a binary message when binaryType is 'arraybuffer'?

    With binaryType set to arraybuffer, binary messages arrive as ArrayBuffer objects; wrap them in a typed array to read bytes.
  2. 2. What does bufferedAmount tell you?

    send() queues data. bufferedAmount is the size of that queue, which you use to pace the sender.
  3. 3. When does the bufferedamountlow event fire?

    The event signals that the queue is small enough to send more.
  4. 4. Which chunk size is a safe, interoperable choice?

    16 KiB works in every browser and keeps one transfer from blocking other traffic.

Summary

  • Channels carry strings, ArrayBuffer, typed arrays and Blob; set binaryType = 'arraybuffer' on receivers.
  • One message has a size limit (pc.sctp.maxMessageSize); chunk large payloads at around 16 KiB.
  • send() queues; watch bufferedAmount and resume on bufferedamountlow.
  • Read big files slice by slice so memory stays small.

Next: Protocols and Patterns