← Back to Node.js, page 5

nodejs-0087 · Medium mid

TCP has no message boundaries. How do you frame messages with a length prefix and handle partial chunks?

Because TCP is a byte stream, data events can contain half a message or several messages. Add a length header (for example 4 bytes, big-endian) before each message. The receiver keeps a buffer, reads the length, waits until enough bytes have arrived, emits the message and continues. Check the length against a maximum.

Full answer

When a client writes 'hello' and 'world' separately, the server may see 'helloworld' in one chunk, or 'hel' and 'loworld' in two. The operating system and the network decide. So the application protocol must mark where each message starts and ends.

Common methods:

  • Delimiter: end every message with a newline (\n). Simple, good for text, but the payload must not contain the delimiter (escape it, or use JSON lines).
  • Fixed length: every message has the same size. Wasteful and inflexible.
  • Length prefix: a header that holds the payload length, then the payload. Works for binary data of any content. Used by many databases and RPC protocols.

Decoder algorithm for a 4-byte big-endian length:

  1. Append each new chunk to a buffer of pending bytes.
  2. While the buffer has at least 4 bytes, read the length. If the buffer holds fewer than 4 + length bytes, stop and wait for more data.
  3. Otherwise cut out the payload, emit it, and remove 4 + length bytes from the buffer.
  4. Repeat, because one chunk may complete several messages.

Safety: validate the length. A hostile client can send 0xFFFFFFFF and make you wait for, or allocate, 4 GB. Set a maximum and destroy the connection when it is exceeded. Also set an idle timeout.

Implement the decoder as a Transform stream in object mode, so it fits pipelines and gets backpressure for free.

javascript
const net = require('node:net');
const { Transform } = require('node:stream');

const MAX_MESSAGE = 1024;

// Turns a stream of bytes into a stream of message strings.
class FrameDecoder extends Transform {
  constructor() {
    super({ readableObjectMode: true });
    this.pending = Buffer.alloc(0);
  }
  _transform(chunk, encoding, callback) {
    this.pending = Buffer.concat([this.pending, chunk]);
    while (this.pending.length >= 4) {
      const length = this.pending.readUInt32BE(0);
      if (length > MAX_MESSAGE) return callback(new Error('message too large: ' + length));
      if (this.pending.length < 4 + length) break;           // wait for more bytes
      this.push(this.pending.subarray(4, 4 + length).toString('utf8'));
      this.pending = this.pending.subarray(4 + length);
    }
    callback();
  }
}

function encode(text) {
  const payload = Buffer.from(text, 'utf8');
  const header = Buffer.alloc(4);
  header.writeUInt32BE(payload.length);
  return Buffer.concat([header, payload]);
}

// 1. Feed the decoder with awkward chunk boundaries.
const wire = Buffer.concat([encode('hello'), encode('नमस्ते'), encode('last')]);
const decoder = new FrameDecoder();
const messages = [];
decoder.on('data', (m) => messages.push(m));

let offset = 0;
for (const size of [1, 3, 2, 10, 5, 100]) {
  decoder.write(wire.subarray(offset, offset + size));
  offset += size;
}
decoder.end(wire.subarray(offset));
console.log('decoded from odd chunks:', messages);

// 2. The same decoder on a real TCP connection. The client sends all three frames in one write.
const server = net.createServer((socket) => {
  const framed = socket.pipe(new FrameDecoder());
  framed.on('data', (m) => console.log('server got message:', m));
  framed.on('error', (err) => {
    console.log('server rejects the connection:', err.message);
    socket.destroy();
    server.close();
  });
});
server.listen(0, '127.0.0.1', () => {
  const client = net.connect(server.address().port, '127.0.0.1', () => {
    client.write(Buffer.concat([encode('one'), encode('two'), encode('three')]));
    const evil = Buffer.alloc(4);
    evil.writeUInt32BE(0xffffffff); // a hostile length (error on purpose)
    setTimeout(() => client.end(evil), 20);
  });
  client.on('error', () => {});
  client.on('close', () => {});
});

The last four bytes are a hostile length value (error on purpose). The decoder refuses it instead of waiting for 4 GB of data. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): decoded from odd chunks: [ 'hello', 'नमस्ते', 'last' ] server got message: one server got message: two server got message: three server rejects the connection: message too large: 4294967295

Key points

  • TCP delivers a byte stream, not messages.
  • A length prefix works for any binary payload.
  • The decoder buffers partial data and can emit several messages per chunk.
  • Enforce a maximum length.

Common mistakes

  • Assuming one data event is one message.
  • Trusting the length field without a maximum.
  • Converting each chunk to a string before the frame is complete, which breaks multi-byte characters.
  • Using string concatenation on a growing buffer for large streams.

Follow-ups

  • How would you frame messages in a text protocol?
  • How does HTTP mark the end of a body?
  • How would you add a message type and version to the header?

Tips

  • Describe the three framing methods in one line each.
  • Say 'partial reads' and 'several messages per chunk'.
  • Always mention the maximum length.