Autocoder

TCP vs UDP Interview Questions with Socket Code and Numericals

Last updated 2026-11-19

TCP versus UDP is one of the most repeated networking questions, and the weak answer is a two-column table. A strong answer explains what each protocol promises, what it costs, and which real application needs which, then backs it with a number: header overhead, the largest UDP payload, or the throughput ceiling of a TCP window. This page does that and includes working Python socket code for both.

For TCP internals such as the handshake and congestion control, see TCP/IP interview questions. For the layer context see OSI model interview questions, and for the application protocols on top, HTTP and HTTPS and DNS. For the broader round, read how to crack a computer networks interview.

Header sizesTCP 20 bytes minimum, UDP 8 bytes
NumericalsThroughput = window / RTT, bandwidth-delay product, largest UDP payload
CodePython TCP echo and UDP echo servers

One-line summary to start every answer

TCP is a connection-oriented, reliable, ordered byte stream with flow and congestion control. UDP is connectionless, sends independent datagrams with no delivery, ordering or retransmission guarantee, and leaves any reliability to the application.

TCP vs UDP Interview Questions with Socket Code and Numericals: questions with worked answers

  1. 1

    What is the difference between TCP and UDP?

    easy

    TCP sets up a connection with a handshake, delivers bytes reliably and in order using acknowledgements and retransmissions, controls flow and congestion, and has a header of at least 20 bytes. UDP sends self-contained datagrams without connection setup, with no acknowledgement, ordering, retransmission or congestion control, and has an 8-byte header (source port, destination port, length, checksum). TCP is chosen when correctness matters, UDP when latency or simplicity does.

  2. 2

    Give real examples of applications using TCP and UDP.

    easy

    TCP: web (HTTP and HTTPS up to HTTP/2), email (SMTP, IMAP), file transfer (FTP, SFTP), SSH and databases, where lost or reordered data would be wrong. UDP: DNS queries, DHCP, NTP, VoIP and video calls, online games, live streaming and QUIC (HTTP/3), where a late packet is useless or the application manages reliability itself. Some protocols use both, such as DNS.

  3. 3

    Why does DNS usually use UDP?

    medium

    A DNS query and response fit in a single small datagram, so UDP avoids the cost of a TCP handshake (one extra round trip) and server state for millions of clients. If the response is truncated (the TC bit is set) because it exceeds the UDP size limit, the client retries over TCP, and zone transfers and DNS over TLS use TCP. The application simply retries if a datagram is lost. See DNS interview questions.

  4. 4

    Is UDP always faster than TCP?

    medium

    Not always. UDP has lower latency to start because there is no handshake, and less per-packet overhead, so it can be faster for short exchanges and real-time media. But for bulk transfer, TCP's congestion control and retransmission are what get good throughput over a shared network, and a naive UDP sender can flood the path and lose most of its data. Speed depends on the workload and on what reliability the application adds on top of UDP.

  5. 5

    Numerical: What is the maximum payload of a UDP datagram over IPv4?

    medium

    The IP total length field is 16 bits, so a packet is at most 65,535 bytes. Subtract the 20-byte IP header and the 8-byte UDP header: 65,535 - 20 - 8 = 65,507 bytes of data. On Ethernet with MTU 1500 the usable payload without fragmentation is 1500 - 20 - 8 = 1472 bytes, which is why applications such as DNS and games keep datagrams under about 1200 to 1400 bytes.

  6. 6

    Numerical: Compare the header overhead of sending 1 byte of data over TCP and over UDP on IPv4.

    medium

    TCP: 20 (IP) + 20 (TCP) = 40 bytes of headers for 1 byte, 41 bytes in all, and the handshake adds three more packets before data. UDP: 20 (IP) + 8 (UDP) = 28 bytes of headers, 29 in all, with no setup. For a 1460-byte payload the overheads (40 and 28 bytes) are 2.7 percent and 1.9 percent, so the gap matters mainly for small messages.

  7. 7

    Numerical: A TCP connection has a 64 KB receive window and a round-trip time of 50 ms. What is the maximum throughput?

    medium

    TCP can send at most one window per round trip: throughput = window / RTT = 65,536 bytes x 8 / 0.05 s = 524,288 / 0.05 = 10,485,760 bits per second, about 10.5 Mbps, no matter how fast the link is. To fill a 1 Gbps link at this RTT the window must be bandwidth x RTT = 10^9 x 0.05 / 8 = 6.25 MB, which needs window scaling.

  8. 8

    Numerical: What is the bandwidth-delay product of a 100 Mbps link with a 40 ms round-trip time?

    medium

    BDP = bandwidth x RTT = 100 x 10^6 bits/s x 0.04 s = 4,000,000 bits = 500,000 bytes, about 488 KiB. This is the amount of data that must be in flight to keep the pipe full. A TCP window smaller than the BDP leaves the link underused, as in the previous question. It is also the size of buffer a sender needs for retransmission.

  9. 9

    Does TCP preserve message boundaries? What about UDP?

    medium

    TCP provides a byte stream: two send() calls of 100 bytes may arrive as one read of 200 bytes, or as three smaller reads, so the application must frame messages itself using a length prefix or a delimiter. UDP preserves boundaries: each send produces one datagram, and each recvfrom returns exactly one datagram (or truncates it if the buffer is too small). Forgetting this difference is a common source of bugs in socket code.

  10. 10

    Write a minimal TCP echo server and client in Python.

    medium

    The server creates a stream socket, binds, listens and accepts one connection at a time, echoing what it reads. The client connects and sends. Note the use of sendall on the client, since send may transmit only part of the data.

    python
    # server.py
    import socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(("127.0.0.1", 9000))
        s.listen()
        conn, addr = s.accept()
        with conn:
            while data := conn.recv(1024):
                conn.sendall(data)
    
    # client.py
    import socket
    with socket.create_connection(("127.0.0.1", 9000)) as c:
        c.sendall(b"hello")
        print(c.recv(1024))
  11. 11

    Write a UDP echo server and client in Python.

    medium

    There is no listen or accept: the server binds and calls recvfrom, which returns the data and the sender's address, then replies with sendto. The client needs no connection and should set a timeout, because a lost datagram would otherwise block recvfrom forever.

    python
    # server.py
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("127.0.0.1", 9001))
    while True:
        data, addr = s.recvfrom(2048)
        s.sendto(data, addr)
    
    # client.py
    import socket
    c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    c.settimeout(2)
    c.sendto(b"hello", ("127.0.0.1", 9001))
    try:
        print(c.recvfrom(2048)[0])
    except socket.timeout:
        print("lost, retry")
  12. 12

    Why is the UDP checksum optional in IPv4 but mandatory in IPv6?

    medium

    IPv4 has its own header checksum and UDP over IPv4 allows a zero checksum meaning not computed, to save CPU in the early days. IPv6 removed the IP header checksum for faster router processing, so the UDP checksum became the only protection for the pseudo-header addresses and data, and it is mandatory (with narrow exceptions for tunnels). TCP always uses its checksum.

  13. 13

    What is head-of-line blocking in TCP, and how does QUIC address it?

    hard

    TCP delivers a single ordered stream, so if one segment is lost every later byte waits in the receive buffer until it is retransmitted, even if later data belongs to independent requests. HTTP/2 multiplexes many requests on one TCP connection, so a single loss stalls all of them. QUIC (the transport for HTTP/3) runs over UDP and implements streams itself, so loss on one stream blocks only that stream. It also merges the transport and TLS 1.3 handshakes, reaching a secure connection in one round trip, or zero for resumed ones.

  14. 14

    How do you build reliability on top of UDP?

    hard

    The application adds sequence numbers to detect loss, duplication and reordering; acknowledgements and timers to retransmit; and possibly windowing and congestion control to avoid flooding the network. Applications often choose selective reliability: a game resends only important state, a video call favours the newest frame. Protocols that do this include QUIC, RTP with RTCP feedback and TFTP. If you need everything TCP offers, just use TCP.

  15. 15

    Which transport protocol supports broadcast and multicast, and why?

    hard

    UDP does, because it is connectionless: a datagram can be addressed to a broadcast or multicast group and delivered to many receivers. TCP is a one-to-one connection with a handshake and per-connection state and acknowledgements, so it cannot be used for broadcast or multicast. This is why DHCP discovery, mDNS and IPTV use UDP.

Frequently asked questions

Which is more secure, TCP or UDP?

Neither provides security. TCP's handshake makes some spoofing harder, but is itself a target for SYN floods, while UDP's lack of a handshake makes it useful for reflection and amplification attacks. Encryption comes from TLS or DTLS above them, or from QUIC.

Can the same port number be used by TCP and UDP?

Yes. The transport protocol is part of the socket identity, so TCP port 53 and UDP port 53 are separate endpoints. DNS uses exactly that.

How many ports are there?

16-bit port numbers give 65,536 per protocol: well-known 0 to 1023, registered 1024 to 49151 and dynamic or ephemeral 49152 to 65535 by the IANA convention, while Linux uses 32768 to 60999 by default for outgoing connections.

Why does streaming video often use TCP today?

Adaptive streaming such as HLS and DASH downloads small segments over HTTP, so TCP's reliability and firewall friendliness work well and buffering hides delays. Live calls and low-latency streaming prefer UDP-based protocols.

Related guides

More in CS Fundamentals Interview Questions

See all in this section