EXERCISE
1Before HTTP or WebSockets, there is TCP. Learn how connections work and why they are expensive.
Save
TCP (Transmission Control Protocol): The way to send data reliably over networks.
Guarantees:
Almost every app uses TCP because reliability matters.
Alternative is UDP: Faster but unreliable. Used for video calls, gaming. Packets can arrive out of order or get lost.
Before any data flows, TCP requires setup.
Process:
Step 1: Client → : "SYN" (let us connect)
Step 2: Server → Client: "SYN-ACK" (agreed, let us connect)
Step 3: Client → Server: "ACK" (connection established)
Now data can flow.
Visualization:
Client Server
| |
|-------- SYN ----------->|
|<------ SYN-ACK ---------|
|-------- ACK ----------->|
| |
[Connection Ready]
Each step is a network round-trip.
Example: Client in Mumbai. Server in California. 200ms latency per trip.
Three-way handshake = 3 messages = 600ms before sending any data!
For a single HTTP request: 600ms setup + actual request/response.
This is why connection reuse matters.
When done, connection closes.
Process:
Step 1: Client → Server: "FIN" (finished, closing)
Step 2: Server → Client: "ACK" (acknowledged, connection closed)
Sometimes: Server also sends FIN, client sends ACK (four-way).
Typical: Two messages to close connection.
Critical fact: TCP connection does NOT automatically close after one request.
Connection stays open until:
This matters: You can reuse one TCP connection for multiple requests!
Without reuse (new connection per request):
Request 1: 3-way handshake + request + response + 2-way teardown
Request 2: 3-way handshake + request + response + 2-way teardown
Request 3: 3-way handshake + request + response + 2-way teardown
Overhead: 15 network messages for 3 requests.
With reuse (keep connection open):
First request: 3-way handshake + request + response
Request 2: request + response (same connection)
Request 3: request + response (same connection)
Final: 2-way teardown
Overhead: 5 network messages total. 3× faster!
Scenario: Mobile app loading profile. Needs 5 calls.
Without reuse:
With reuse:
5× reduction! This is why connection pooling exists.
Important: TCP handles reliable delivery. It does NOT care what data you send.
Analogy: TCP is like postal service. Delivers letters reliably. Does not read content.
What you send over TCP: Totally up to you.
Common choices:
TCP delivers bytes. You define what those bytes mean.
Redis uses custom protocol over TCP.
Why? Optimized for key-value operations. Faster than HTTP for its use case.
Takeaway: You can define your own protocol. Just ensure both sides understand it.
Video calls (Zoom): Use UDP. Speed matters more than perfection. Dropped frame = minor glitch.
Gaming (Fortnite): Use UDP. Old position data is worthless. Need instant updates.
DNS lookups: Often UDP. Single packet request/response. No need for connection.
Everything else: Probably TCP. Reliability worth the overhead.