HTTP runs on top of TCP, which guarantees delivery and correct ordering — every packet arrives, in the right sequence, or the connection reports a failure. That reliability comes at a cost: overhead and latency. UDP takes the opposite trade-off — no delivery guarantee, no ordering guarantee, no connection setup — in exchange for being fast and lightweight. Node.js's dgram module lets you send and receive UDP messages directly.
When UDP's trade-off actually makes sense
- Live video/audio streaming — a dropped frame here and there is barely noticeable; waiting for a retransmit would be far more disruptive.
- Online multiplayer games — a slightly-stale position update is fine; a laggy, TCP-buffered one is not.
- DNS lookups — small, simple request-response pairs where TCP's connection setup overhead isn't worth it.
- IoT sensor data — frequent, small readings where losing an occasional one doesn't matter.
Creating a UDP server
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`Received: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`UDP server listening on ${address.address}:${address.port}`);
});
server.bind(41234);
Sending a UDP message
const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const message = Buffer.from('sensor-reading:23.5');
client.send(message, 41234, 'localhost', (err) => {
if (err) console.error('Send failed:', err);
else console.log('Message sent');
client.close();
});
Notice there's no handshake, no "connection" being established beforehand — the client just fires the message at an address and port, and moves on. Whether it actually arrives is not something UDP itself guarantees.
Closing a socket
server.close(() => {
console.log('Server socket closed');
});
A quick contrast with TCP/HTTP
| TCP (what HTTP runs on) | UDP | |
|---|---|---|
| Delivery guaranteed | Yes | No |
| Order guaranteed | Yes | No |
| Connection setup | Required (handshake) | None |
| Speed | Slower, more overhead | Faster, minimal overhead |
| Typical use | Web pages, APIs, file transfer | Live streaming, gaming, DNS |
The practical takeaway
Most applications you build will use HTTP (and therefore TCP) without a second thought, and that's the right default. Reach for dgram specifically when you're building something where an occasional lost or out-of-order message is genuinely acceptable, and the speed and low overhead of UDP outweighs the reliability TCP would otherwise provide.