
Network communication choices affect latency, reliability, and application behavior. Interviewers ask this to test whether you understand transport-layer trade-offs and can connect them to real systems.
Explain the differences between TCP and UDP. In your answer, address:
You do not need to derive packet formats from memory, but you should be able to compare the protocols clearly, describe the main mechanisms behind reliability and speed, and discuss practical trade-offs such as overhead, congestion handling, and message loss.
TCP is connection-oriented, meaning endpoints establish a session before exchanging application data. UDP is connectionless, so packets can be sent immediately without a handshake, which reduces startup latency.
import socket
# TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# UDP
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
TCP provides reliable delivery using acknowledgments, sequence numbers, retransmissions, and error detection. UDP does not guarantee delivery, so lost packets are not automatically resent unless the application implements its own recovery logic.
TCP delivers bytes in order and uses flow control so a fast sender does not overwhelm a slow receiver. UDP preserves packet boundaries but does not guarantee ordering, duplication avoidance, or receiver pacing.
TCP adds overhead from connection setup, acknowledgments, congestion control, and retransmissions. UDP has a smaller header and less protocol work, making it attractive for time-sensitive traffic where occasional loss is acceptable.
TCP is a good fit when correctness matters more than minimal delay, such as web pages, file transfer, and email. UDP is often used for DNS, live voice/video, gaming, and telemetry where low latency matters and the application can tolerate or handle loss.