skip to content

In Node.js, what does a node:dgram socket.send() callback tell a UDP metrics sender, and why connect the socket to the collector once?

level: middleimportance: nice to knowfreq 20%

answer

  1. handed off, not delivered
  2. errors go to the callback or 'error'
  3. a lookup on every send
  4. connect() fixes the destination
  5. unref() the sender

basics

~20 s

A dgram send() callback only says the datagram reached the operating system, or why it failed; nothing confirms delivery. Calling socket.connect() once resolves the collector's name once, whereas an unconnected send() to a host name runs dns.lookup() on every call.

solid answer

~40 s

A `dgram.Socket` from `dgram.createSocket('udp4')` has no connection to confirm anything with. The `send()` callback runs when Node has passed the datagram to the operating system, with an error only for local failures such as a DNS error; a datagram lost on the way produces no event at all. Without a callback, send errors are emitted as `'error'`, which crashes the process if nothing listens. On an unconnected socket, `send(msg, port, 'collector.example.com')` resolves the host with `dns.lookup()` on every call, one threadpool job per metric. `socket.connect(port, host)` resolves once and fixes the destination, so later calls are just `send(msg)`; it also restricts inbound datagrams to that peer and lets errors such as `ECONNREFUSED` surface on a later send or receive. Call `socket.unref()` so the metrics socket never keeps the process alive.

code

javascript · 19 lines
javascript
import dgram from 'node:dgram';

const socket = dgram.createSocket('udp4');
socket.on('error', (err) => {
  console.error(`metrics socket error: ${err.code}`);
});
socket.unref();

let ready = false;
socket.connect(9125, 'collector.example.com', (err) => {
  if (!err) ready = true;
});

export function sendMetric(name, value) {
  if (!ready) return;
  socket.send(`${name}=${value}\n`, (err) => {
    if (err) console.error(`metric not sent: ${err.code}`);
  });
}

go deeper

for a junior

Recall that send()'s callback means handed to the operating system, not delivered, and that a dgram socket needs an 'error' listener.

for a middle

Explain the per-send dns.lookup() on an unconnected socket, what socket.connect() changes, and why unref() matters for a background sender.

for a senior

Show the production costs: threadpool load from per-metric lookups, crashes from unheard errors, oversized datagrams silently dropped, and a fixed address after connect().

for a principal

Decide whether metrics may be lossy at all: if a team needs delivery guarantees, a fire-and-forget UDP sender is the wrong transport, whatever the client code does.

## What send() can and cannot report `node:dgram` gives Node UDP sockets. `dgram.createSocket('udp4')` (or `'udp6'`) returns a `dgram.Socket`, and `socket.send(msg[, offset, length][, port][, address][, callback])` sends one datagram. UDP has no acknowledgements, so Node can only tell you what happened locally. | Situation | What Node reports | |---|---| | Datagram handed to the operating system | `callback(null)` | | Host name could not be resolved | `callback(err)`, or `'error'` if no callback was given | | A local send failure, such as a message too large for the socket | `callback(err)`, typically with an OS code such as `EMSGSIZE` | | Datagram dropped on the network or by the collector | Nothing | | Collector port closed, on a connected socket | Possibly `ECONNREFUSED` on a later send or receive | The documentation puts it carefully: the only way to know for sure that the datagram has been **sent** is the callback. Sent is not received. The callback also tells you when it is safe to reuse the `Buffer` you passed, which matters if you recycle buffers. If you omit the callback, failures become `'error'` events on the socket. A `dgram.Socket` is an `EventEmitter`, so an `'error'` with no listener is thrown and exits the process: a metrics library without an `'error'` listener can crash the service it is measuring. ## The hidden lookup on every send Passing a host name as `address` makes Node resolve it before sending: 1. `send(msg, 9125, 'collector.example.com')` is called on an unconnected socket. 2. Node calls the socket's lookup function, `dns.lookup()` by default, which runs `getaddrinfo(3)` on libuv's threadpool. 3. Only after the lookup returns is the datagram written, at least one event-loop tick later. 4. The next `send()` repeats the whole lookup. At thousands of metrics per second that is thousands of threadpool jobs competing with `fs` and crypto work, and every metric pays the resolver's latency. A literal IP address of the socket's family is the exception: the default lookup returns it as-is without calling `dns.lookup()`. ## Connecting the socket `socket.connect(port[, address][, callback])` associates the socket with one remote address. Connecting a UDP socket performs no handshake; it records the default peer: - the host name is resolved **once**, at connect time; - later calls are `send(msg[, callback])`, and passing a port or address to a connected socket throws `ERR_SOCKET_DGRAM_IS_CONNECTED`; - the socket only receives datagrams from that peer; - errors such as `ECONNREFUSED` can surface asynchronously on a later send or receive; - `'connect'` is emitted, and the callback is called, once the association is made. The trade-off is that the address is fixed until you call `socket.disconnect()` and connect again, so a sender that must follow DNS changes needs to reconnect periodically. ## Keeping the sender from hurting the service - **`socket.unref()`.** A bound `dgram.Socket` keeps the process alive. A sender bound implicitly by its first `send()` would otherwise stop a short-lived script or a draining service from exiting. - **An `'error'` listener, always.** Log and move on; losing a metric must never crash the process. - **Small datagrams.** The IPv4 payload ceiling is 65,507 bytes, but a datagram larger than the MTU of a link on the path can be silently dropped. Batch several metrics into one datagram, kept well below a typical 1,500-byte Ethernet MTU. - **Watch the send queue.** `socket.getSendQueueSize()` and `socket.getSendQueueCount()` show how much is waiting to be sent, which helps spot a sender that is producing faster than the socket drains. - **Match the socket family to the collector.** A `'udp4'` socket asks its lookup for IPv4 addresses only, so a collector name with only IPv6 records fails to resolve on it; create a `'udp6'` socket for such a collector. - **Reuse one socket.** Creating a `dgram.Socket` per metric binds a new local port each time and multiplies the lookups; one long-lived socket per destination is the norm. - **Do not wait for callbacks to pace sends.** They report local hand-off only; they say nothing about the collector keeping up. Why UDP gives no delivery guarantee is a protocol question covered with the UDP datagram model; in Node, the practical consequence is that your code receives no signal when a datagram is lost.

  • What happens if a metric is sent before the socket is bound?
    Nothing breaks: `send()` on an unbound socket binds it to a random port on all interfaces, queues the datagram until binding completes, and emits `'listening'`. That implicit bind is why a pure sender rarely calls `bind()`. The bound socket then keeps the process alive unless you call `socket.unref()`.
  • How large can one metrics datagram safely be?
    The hard ceiling for an IPv4 payload is 65,507 bytes, but Node's documentation warns that a datagram larger than a link's MTU on the path can be silently dropped without informing the sender. Senders therefore batch several metrics into one datagram and keep it well under a typical 1,500-byte Ethernet MTU.

  • A send() callback with no error confirms the collector received the datagram.
  • A dgram socket with no 'error' listener just drops failed sends quietly.
  • Passing a host name to send() resolves it once and reuses the address.
  • Calling connect() on a UDP socket performs a handshake with the collector.
  • A bound dgram socket never keeps the Node.js process from exiting.