What is the difference between TCP and UDP for embedded devices?
Short answer: TCP provides a reliable, ordered, connection-oriented byte stream with retransmission, flow control and congestion control, at the cost of RAM for buffers and state, and higher latency when packets are lost. UDP sends independent datagrams with no delivery or ordering guarantee and no connection, so it is lighter and has lower, more predictable latency, but the application must handle loss if it matters.
| TCP | UDP | |
|---|---|---|
| Connection | 3-way handshake, teardown | none |
| Reliability and ordering | yes | no |
| Message boundaries | no (byte stream) | yes (datagrams) |
| Flow/congestion control | yes | no |
| Overhead | 20+ byte header, ACKs, state per connection, buffers | 8-byte header |
| Latency under loss | retransmission delays (head-of-line blocking) | none, data is just lost |
| Multicast/broadcast | no | yes |
| Embedded protocols | MQTT, HTTP(S), Modbus TCP, FTP | CoAP, DNS, DHCP, SNTP, mDNS, syslog, RTP, QUIC |
Choosing
- Use TCP for commands and data that must arrive intact and in order (configuration, firmware updates, MQTT telemetry).
- Use UDP for real-time streams where late data is useless (audio, control loops, sensor streams), discovery (mDNS), and very constrained devices (CoAP with its own lightweight reliability), or when you need broadcast/multicast.
Embedded resource notes: each TCP connection needs a TCB plus send/receive buffers (several KB in lwIP); MCUs often limit simultaneous connections. TLS on top of TCP adds tens of KB of RAM (mbedTLS); DTLS is TLS for UDP.
Interview follow-up: "How would you make UDP reliable?" Sequence numbers, ACKs, retransmission timers and duplicate detection (CoAP confirmable messages, or QUIC, which builds a reliable, encrypted transport on UDP).