← Back to Node.js, page 5

nodejs-0086 · Medium mid

How does UDP differ from TCP, and how do you send and receive datagrams with the dgram module?

UDP sends independent packets (datagrams) with no connection, no delivery guarantee, no ordering and no retransmission, but with very low overhead and preserved message boundaries. In Node, dgram.createSocket('udp4') gives a socket that you bind, send(msg, port, host) on, and read with the 'message' event.

Full answer

TCP gives a reliable ordered byte stream. UDP gives much less, and that is the point:

  • No connection set-up. A sender just sends a packet to an address and port.
  • Message boundaries are kept: one send is one message at the receiver (if it arrives).
  • No guarantees: packets can be lost, duplicated or reordered. Nothing tells you.
  • Size limit: a datagram should fit the path MTU (about 1,200 to 1,472 bytes to be safe). Larger packets get fragmented, and the loss of a fragment loses the whole message. The hard limit is about 65,507 bytes.
  • No congestion control built in, so applications must be polite.

Good uses: DNS queries, real-time audio and video, game state, metrics (StatsD), service discovery, logging at high volume where a lost line is acceptable. Not for payments or files, unless a protocol on top adds acknowledgements and retries (as QUIC and some game protocols do).

Node API:

  • const socket = dgram.createSocket('udp4') (or 'udp6').
  • socket.bind(port, address): needed to receive. A socket that only sends is bound automatically to a random port.
  • socket.on('message', (msg, rinfo)): msg is a Buffer and rinfo has address, port and size.
  • socket.send(msg, port, address, callback). With a connected socket (socket.connect) you can omit the address.
  • Broadcast (setBroadcast(true)) and multicast (addMembership) exist for local networks.
  • socket.close() when done. Remember to handle 'error'.

Because there are no acknowledgements, a sender cannot know whether the message arrived. If you need that, add sequence numbers and ACK messages, or use TCP.

javascript
const dgram = require('node:dgram');

const server = dgram.createSocket('udp4');
const received = [];

server.on('message', (message, remote) => {
  const text = message.toString();
  received.push(text);
  // Reply to the sender's address and port.
  server.send('ack:' + text, remote.port, remote.address);
});

server.on('listening', () => {
  const { port } = server.address();
  const client = dgram.createSocket('udp4');

  const replies = [];
  client.on('message', (message) => {
    replies.push(message.toString());
    if (replies.length === 3) {
      console.log('server received (each send is one message):', received);
      console.log('client received:', replies);
      console.log('message boundaries are kept: 3 sends -> 3 messages');
      client.close();
      server.close();
    }
  });

  // Send one at a time on localhost so the order stays stable in this demo.
  let i = 0;
  const sendNext = () => {
    client.send(Buffer.from('ping ' + ++i), port, '127.0.0.1', () => {
      if (i < 3) setTimeout(sendNext, 5);
    });
  };
  sendNext();
});

server.bind(0, '127.0.0.1');

On a real network, packets may be lost or arrive out of order. On localhost they almost never are, so the demo sends one packet at a time to keep the output identical on every run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): server received (each send is one message): [ 'ping 1', 'ping 2', 'ping 3' ] client received: [ 'ack:ping 1', 'ack:ping 2', 'ack:ping 3' ] message boundaries are kept: 3 sends -> 3 messages

Key points

  • UDP is connectionless and unreliable, but keeps message boundaries.
  • Keep datagrams small, below the MTU.
  • Use it where speed matters more than every packet.
  • Reliability needs your own protocol.

Common mistakes

  • Using UDP and assuming delivery.
  • Sending datagrams larger than the MTU.
  • Forgetting to bind before expecting messages.
  • Not closing sockets, which keeps the process alive.

Follow-ups

  • How would you add reliability on top of UDP?
  • What is multicast and when is it used?
  • Why does DNS use UDP first and TCP as a fallback?

Tips

  • Compare TCP and UDP in a table-like sentence.
  • Say 'message boundaries are kept'.
  • Mention size limits.