Bird
Raised Fist0
Interview Prepcomputer-networkseasyAmazonGoogleMicrosoftFlipkartSwiggyRazorpayPhonePe

TCP vs UDP - When to Use Each (Reliability vs Speed)

Choose your preparation mode3 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
🎯
TCP vs UDP - When to Use Each (Reliability vs Speed)
easyNETWORKSAmazonGoogleMicrosoft

Imagine streaming a live sports event where delays ruin the experience, versus sending an important email where every bit must be correct.

💡 Beginners often confuse TCP and UDP as just 'slow vs fast' without understanding the trade-offs in reliability, ordering, and connection overhead. Think of TCP as a phone call where both parties confirm messages, ensuring everything arrives correctly and in order, while UDP is like sending postcards without expecting confirmation, which is faster but less reliable.
📋
Interview Question

Explain the differences between TCP and UDP, and when to use each protocol considering reliability and speed requirements.

Connection-oriented vs connectionless communicationReliability mechanisms like acknowledgments and retransmissionsUse cases favoring speed over reliability and vice versa
💡
Scenario & Trace
ScenarioA user sends an email using an email client.
The email client uses TCP to establish a connection → data packets are sent with sequence numbers → acknowledgments confirm receipt → retransmissions occur if packets are lost → email is delivered reliably and in order.
ScenarioA user watches a live video stream on a mobile device.
The streaming app uses UDP to send video packets → packets are sent continuously without waiting for acknowledgments → some packets may be lost or arrive out of order → video plays with minimal delay, prioritizing speed over perfect accuracy.
ScenarioA DNS query is made to resolve a domain name.
The client sends a DNS request over UDP → the server responds quickly → if no response is received, the client retries → the lightweight UDP protocol reduces latency for fast lookups.
  • What happens if a UDP packet is lost during a live video stream?
  • How does TCP handle network congestion and packet loss?
  • What if an application requires both speed and reliability?
  • What happens when a TCP connection is abruptly closed?
⚠️
Common Mistakes
Assuming UDP is always unreliable and unusable

Interviewer thinks candidate lacks understanding of UDP's valid use cases

Explain that UDP is suitable for applications prioritizing speed and can tolerate some loss, like live streaming or DNS

Confusing TCP's connection setup with application-level connections

Interviewer doubts candidate's grasp of transport layer concepts

Clarify TCP's three-way handshake is a transport layer mechanism independent of application protocols

Thinking TCP guarantees zero packet loss

Interviewer notes candidate's unrealistic expectations of TCP

Explain TCP ensures reliable delivery through retransmissions but cannot prevent all network failures

Believing UDP has no error detection

Interviewer suspects candidate missed UDP's checksum feature

Mention UDP includes a checksum for basic error detection but no retransmission

🧠
Basic Definition - What It Is
💡 This level covers the fundamental differences and is essential for any networking interview. It helps you quickly explain the core concepts and when to use each protocol.

Intuition

TCP is reliable and connection-oriented; UDP is fast and connectionless.

Explanation

TCP (Transmission Control Protocol) establishes a connection between sender and receiver before data transfer, ensuring reliable and ordered delivery through acknowledgments and retransmissions. UDP (User Datagram Protocol) sends packets without establishing a connection, offering faster transmission but no guarantee of delivery or order. TCP is used when accuracy is critical, while UDP suits applications needing speed and can tolerate some data loss.

Memory Hook

💡 Think of TCP as a phone call where both parties confirm messages, and UDP as sending postcards without confirmation.

Illustrative Code

Interview Questions

What is the main difference between TCP and UDP?
  • TCP is connection-oriented; UDP is connectionless
  • TCP guarantees reliable, ordered delivery; UDP does not
  • UDP is faster due to less overhead
Depth Level
Interview Time30 seconds
Depthbasic

Covers fundamental definitions and use cases; sufficient for screening rounds. No algorithmic complexity applies as this is conceptual knowledge.

Interview Target: Minimum floor - never go below this

Knowing only this will help pass initial screening but not detailed technical interviews.

🧠
Mechanism Depth - How It Works
💡 This level explains internal mechanisms and trade-offs expected in product company interviews. It helps you demonstrate deeper understanding of TCP and UDP protocols.

Intuition

TCP manages reliability through connection setup, flow control, and retransmissions; UDP sends packets independently without overhead.

Explanation

TCP uses a three-way handshake to establish a connection, assigns sequence numbers to packets, and requires acknowledgments to confirm receipt. It implements flow control to avoid overwhelming the receiver and congestion control to adapt to network conditions. Lost packets are retransmitted, ensuring data integrity and order. UDP skips connection setup and reliability features, sending datagrams independently, which reduces latency but risks packet loss or disorder. Applications using UDP often implement their own error handling if needed.

Memory Hook

💡 TCP is like a courier service that tracks every package and confirms delivery; UDP is like dropping flyers from a plane without tracking.

Illustrative Code

Interview Questions

How does TCP ensure reliable data transfer?
  • Three-way handshake for connection setup
  • Sequence numbers and acknowledgments for ordering and confirmation
  • Retransmission of lost packets
  • Flow and congestion control mechanisms
Why might an application choose UDP despite its unreliability?
  • Lower latency due to no connection overhead
  • Suitable for real-time applications like video or voice streaming
  • Application can tolerate some data loss
  • Simpler protocol with less processing
Depth Level
Interview Time2-3 minutes
Depthintermediate

Demonstrates understanding of protocol internals and trade-offs; expected in on-site interviews. No algorithmic complexity applies as this is conceptual knowledge.

Interview Target: Target level for FAANG on-sites

Mastering this level distinguishes you from most candidates.

📊
Explanation Depth Levels
💡 Choose your explanation depth based on interview stage and role requirements.
LevelInterview TimeSuitable ForRisk
Basic Definition30sScreening call, quick conceptual questionsToo shallow for detailed technical interviews
Mechanism Depth2-3 minutesOn-site interviews, product companiesRequires good understanding; missing details may lose points
💼
Interview Strategy
💡 Use this guide to structure your explanation clearly and confidently before interviews. Start simple, then add details and examples.

How to Present

Start with a clear definition of TCP and UDPGive a relatable example or analogyExplain the internal mechanisms and trade-offsDiscuss edge cases and when to choose each protocol

Time Allocation

Definition: 30s → Example: 1min → Mechanism: 2min → Edge cases: 30s. Total ~4min

What the Interviewer Tests

Your ability to differentiate protocols, explain mechanisms, and apply knowledge to real-world scenarios.

Common Follow-ups

  • What happens if a UDP packet is lost? → It is simply dropped; no retransmission by UDP itself.
  • How does TCP handle congestion? → Through congestion control algorithms like slow start and congestion avoidance.
💡 These common follow-ups test deeper understanding beyond definitions.
🔍
Pattern Recognition

When to Use

Asked when discussing transport layer protocols, network communication trade-offs, or application design choices.

Signature Phrases

'Explain the difference between TCP and UDP''When would you use UDP over TCP?''What happens when packets are lost in TCP vs UDP?'

NOT This Pattern When

Similar Problems

Practice

(1/5)
1. Trace the sequence of DNS queries when a browser requests 'www.example.com' and the local DNS cache is empty. Which of the following correctly describes the order of servers queried?
easy
A. Local resolver -> Recursive DNS server -> Root DNS server -> TLD DNS server -> Authoritative DNS server
B. Local resolver -> TLD DNS server -> Root DNS server -> Recursive DNS server -> Authoritative DNS server
C. Local resolver -> Root DNS server -> Recursive DNS server -> TLD DNS server -> Authoritative DNS server
D. Local resolver -> Recursive DNS server -> Authoritative DNS server -> Root DNS server -> TLD DNS server

Solution

  1. Step 1: Start at local resolver

    The browser asks the local resolver, which forwards to the recursive DNS server if cache is empty.
  2. Step 2: Recursive DNS server queries root server

    The recursive server queries the root DNS server to find the TLD server for '.com'.
  3. Step 3: Recursive server queries TLD server

    Root server directs to TLD server, which is then queried for 'example.com'.
  4. Step 4: Recursive server queries authoritative server

    TLD server directs to authoritative DNS server for 'example.com', which returns the IP.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Order matches DNS resolution hierarchy and recursive query flow -> correct
Hint: Recursive DNS server queries root -> TLD -> authoritative servers in order.
Common Mistakes:
  • Misplacing root server query after authoritative server
  • Confusing order of recursive and root server queries
  • Assuming local resolver queries root server directly
2. Trace the sequence of events when a client using HTTP Long Polling requests real-time updates from a server.
easy
A. Client sends a request; server responds with a stream of events over a single connection
B. Client opens a persistent connection; server pushes updates continuously without client requests
C. Client sends a request; server responds immediately with current data; client waits before sending another request
D. Client sends a request; server holds it open until data is available; server responds; client immediately sends a new request

Solution

  1. Step 1: Understand Long Polling mechanics

    Client sends an HTTP request that the server holds open until new data is available.
  2. Step 2: Server response and client behavior

    Once data is sent, the connection closes, and the client immediately sends a new request to wait for further updates.
  3. Step 3: Evaluate other options

    Client opens a persistent connection; server pushes updates continuously without client requests describes WebSocket behavior. Client sends a request; server responds immediately with current data; client waits before sending another request misses the 'hold open' aspect, responding immediately regardless of data availability. Client sends a request; server responds with a stream of events over a single connection describes SSE.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Long Polling = request held open until data -> response -> new request
Hint: Long Polling = held-open request until data, then reconnect
Common Mistakes:
  • Confusing Long Polling with SSE or WebSocket persistent connections
  • Assuming server pushes data without client requests in Long Polling
  • Believing Long Polling responses are immediate regardless of data
3. What is a key limitation of Port Address Translation (PAT) when many internal hosts simultaneously initiate outbound connections to the internet?
medium
A. PAT cannot translate destination IP addresses, so inbound connections are impossible
B. PAT requires a unique public IP per internal host, increasing IP address consumption
C. PAT can run out of available source ports, limiting the number of simultaneous connections
D. PAT causes all internal hosts to share the same source port, causing packet collisions

Solution

  1. Step 1: Recall PAT function

    PAT maps multiple internal IP:port pairs to a single public IP with unique source ports.
  2. Step 2: Identify limitation

    Since TCP/UDP ports are 16-bit, only ~65,000 ports are available per public IP, limiting simultaneous connections.
  3. Step 3: Analyze options

    PAT can run out of available source ports, limiting the number of simultaneous connections correctly identifies port exhaustion. PAT requires a unique public IP per internal host, increasing IP address consumption is false; PAT uses one public IP for many hosts. PAT cannot translate destination IP addresses, so inbound connections are impossible is unrelated to PAT's outbound translation. PAT causes all internal hosts to share the same source port, causing packet collisions is false; PAT assigns unique ports to avoid collisions.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    PAT port exhaustion limits simultaneous connections [OK]
Hint: PAT multiplexes ports but port space is finite
Common Mistakes:
  • Thinking PAT needs multiple public IPs
  • Confusing PAT with DNAT limitations
  • Believing PAT uses the same source port for all hosts
4. Why might the TCP three-way handshake introduce latency, and when could this be a disadvantage?
medium
A. Because it requires multiple round-trip times before data transfer, causing delay in time-sensitive applications
B. Because it encrypts all packets during handshake, increasing processing time
C. Because it uses UDP packets which are slower than TCP packets
D. Because it requires the server to send data before the client can send any

Solution

  1. Step 1: Identify handshake latency cause

    The handshake requires at least one full round-trip time (RTT) before data can be sent, introducing delay.
  2. Step 2: Analyze options

    Because it requires multiple round-trip times before data transfer, causing delay in time-sensitive applications correctly states the latency due to multiple RTTs, which can be problematic for real-time or low-latency applications. Because it encrypts all packets during handshake, increasing processing time is incorrect; encryption is separate from handshake. Because it uses UDP packets which are slower than TCP packets is false; handshake uses TCP packets, not UDP. Because it requires the server to send data before the client can send any is incorrect; the client sends data after handshake completes.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Handshake latency = multiple RTTs before data flow.
Hint: Handshake latency = waiting for multiple packet exchanges before data
Common Mistakes:
  • Confusing handshake with encryption overhead
  • Thinking handshake uses UDP packets
  • Believing server sends data first
5. If a CDN edge server uses a stale-while-revalidate caching strategy, what happens when a user requests content whose TTL has expired but the stale content is still served?
hard
A. User receives stale content immediately while edge server fetches fresh content asynchronously
B. User request is blocked until fresh content is fetched from the origin server
C. Edge server returns an error indicating content is expired
D. User is redirected to the origin server to get fresh content

Solution

  1. Step 1: Define stale-while-revalidate

    This strategy serves stale content immediately after TTL expiry while asynchronously fetching fresh content.
  2. Step 2: User experience

    User gets content without delay, improving perceived performance.
  3. Step 3: Background refresh

    Edge server updates cache with fresh content once fetched.
  4. Step 4: Analyze other options

    User request is blocked until fresh content is fetched from the origin server is incorrect because user is not blocked. Edge server returns an error indicating content is expired is false; no error is returned. User is redirected to the origin server to get fresh content is wrong; user is not redirected to origin.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Stale-while-revalidate balances freshness and latency by serving stale content immediately.
Hint: Stale-while-revalidate = serve stale now, refresh in background
Common Mistakes:
  • Assuming user waits for fresh content
  • Thinking stale content causes errors
  • Believing user is redirected to origin on expiry