Bird
Raised Fist0
Interview Prepcomputer-networkseasyAmazonGoogleMicrosoftFlipkartSwiggyRazorpayPhonePe

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

Choose your preparation mode3 modes available
🎯
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. Which of the following statements about DHCP IP address leasing is INCORRECT?
medium
A. Once a lease expires, the IP address is immediately available for reassignment
B. Clients must renew their lease before it expires to keep the same IP address
C. DHCP servers can reclaim IP addresses from clients that do not renew leases
D. Leases help prevent IP address conflicts in the network

Solution

  1. Step 1: Understand lease expiration behavior

    When a lease expires, the IP address is not immediately available; there is usually a grace period before reassignment to avoid conflicts.
  2. Step 2: Analyze other options

    Options B, C, and D are correct statements about DHCP leasing behavior.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Immediate reassignment after expiration is incorrect; DHCP uses timers to prevent conflicts.
Hint: Lease expiration ≠ instant IP reuse; timers prevent conflicts
Common Mistakes:
  • Assuming IPs are instantly reusable after lease expiry
  • Confusing lease renewal with release
  • Believing leases do not prevent conflicts
2. Why is it generally discouraged to use POST for operations that are intended to be idempotent, such as updating a user profile repeatedly with the same data?
medium
A. Because POST requests are cached by default, leading to stale data issues.
B. Because POST always deletes the resource before updating it.
C. Because POST cannot carry a request body, limiting update capabilities.
D. Because POST is not idempotent, repeated identical requests may cause unintended side effects.

Solution

  1. Step 1: Recall idempotency definition

    An idempotent method produces the same result no matter how many times it is repeated.
  2. Step 2: Analyze POST properties

    POST is not idempotent; repeated identical POSTs can create multiple resources or side effects.
  3. Step 3: Evaluate options

    Because POST is not idempotent, repeated identical requests may cause unintended side effects correctly identifies the non-idempotent nature of POST. Others are factually incorrect.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    POST is not idempotent, so using it for idempotent operations risks unintended consequences.
Hint: POST ≠ idempotent; PUT and DELETE are idempotent
Common Mistakes:
  • Thinking POST is cached by default (it is not)
  • Believing POST cannot carry a body (it can)
  • Assuming POST deletes resources before updating
3. In a network where ARP spoofing attacks are frequent, which advanced mitigation technique can be employed to detect and prevent such attacks beyond static ARP entries?
hard
A. Implementing dynamic ARP inspection (DAI) on switches to validate ARP packets against a trusted database.
B. Disabling ARP entirely and relying solely on IP addresses for communication.
C. Using DHCP snooping to assign static IP addresses to all devices.
D. Increasing the ARP cache timeout to reduce ARP traffic.

Solution

  1. Step 1: Understand advanced ARP spoofing mitigation

    Dynamic ARP Inspection (DAI) is a security feature on switches that intercepts ARP packets and verifies them against a trusted binding database.
  2. Step 2: Why not disabling ARP?

    ARP is essential for IP-to-MAC resolution; disabling it breaks local communication.
  3. Step 3: DHCP snooping is complementary but not sufficient

    DHCP snooping helps build trusted bindings but does not directly inspect ARP packets.
  4. Step 4: Increasing ARP cache timeout worsens spoofing risk

    Longer cache times mean stale or poisoned entries persist longer.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    DAI validates ARP packets to prevent spoofing effectively [OK]
Hint: DAI inspects ARP packets dynamically to prevent spoofing [OK]
Common Mistakes:
  • Thinking ARP can be disabled safely
  • Confusing DHCP snooping with ARP inspection
  • Believing longer ARP cache timeout improves security
4. If a TCP connection experiences frequent packet loss but the receiver's advertised window remains large, which adjustment should the sender prioritize to improve throughput?
hard
A. Increase retransmission timeout to avoid premature retransmissions
B. Decrease the receiver's advertised window to slow down sending rate
C. Ignore congestion signals and rely solely on sliding window flow control
D. Reduce congestion window size according to AIMD to alleviate network congestion

Solution

  1. Step 1: Analyze the scenario

    Large receiver window means flow control is not limiting sender; packet loss indicates network congestion.
  2. Step 2: Identify correct sender adjustment

    Sender should reduce congestion window per AIMD to reduce congestion and improve throughput.
  3. Step 3: Reject decreasing receiver window

    Sender cannot control receiver's advertised window; it's a receiver-side parameter.
  4. Step 4: Reject ignoring congestion or increasing timeout

    Ignoring congestion worsens loss; increasing timeout delays recovery, not throughput improvement.
  5. Final Answer:

    Option D -> Option D
  6. Quick Check:

    Congestion control adjusts sending rate; flow control limits receiver buffer usage.
Hint: When receiver window is large but loss occurs, adjust congestion window, not flow control.
Common Mistakes:
  • Confusing flow control with congestion control adjustments
  • Thinking sender can reduce receiver window
  • Believing retransmission timeout tuning solves congestion
5. If a TCP connection experiences sudden, large variations in round-trip time (RTT), how should the retransmission timeout (RTO) algorithm adapt to maintain efficient retransmissions?
hard
A. Increase the RTO variance estimate to avoid premature retransmissions, even if it delays recovery
B. Ignore RTT variations and keep RTO fixed to prevent oscillations
C. Reset the RTO to a minimal value after each retransmission to speed up recovery
D. Disable retransmissions temporarily until RTT stabilizes

Solution

  1. Step 1: Understand RTO adaptation to RTT variance

    TCP's RTO algorithm uses both RTT estimate and variance to adapt timeout dynamically.
  2. Step 2: Analyze handling of large RTT variations

    Increasing variance estimate prevents premature retransmissions caused by transient delays, trading off some delay for stability.
  3. Step 3: Evaluate options

    Increase the RTO variance estimate to avoid premature retransmissions, even if it delays recovery correctly describes the adaptive behavior. Ignore RTT variations and keep RTO fixed to prevent oscillations ignores adaptation, causing inefficiency. Reset the RTO to a minimal value after each retransmission to speed up recovery risks spurious retransmissions. Disable retransmissions temporarily until RTT stabilizes is impractical and breaks reliability.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Adaptive RTO balances responsiveness and stability under RTT fluctuations.
Hint: High RTT variance -> increase RTO variance to avoid spurious retransmits.
Common Mistakes:
  • Fixing RTO despite RTT changes
  • Resetting RTO too aggressively after retransmissions
  • Disabling retransmissions during network instability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard