Giao diện
📈 SCALABILITY
Mở rộng Quy mô: Giao thức là Mạch máu của Hệ thống Phân tán
Mục tiêu Học tập
Sau khi hoàn thành module này, bạn sẽ có khả năng:
- Phân tích tác động của Layer 4/7 đến độ trễ hệ thống
- Quyết định khi nào dùng TCP, khi nào dùng UDP
- Hiểu sâu về HTTP evolution và vấn đề Head-of-Line Blocking
- Giải thích QUIC protocol hoạt động như thế nào
1. The OSI Model (Góc nhìn Kiến trúc sư)
NOTE
🎓 Giáo sư Tom: Chúng ta sẽ KHÔNG liệt kê 7 tầng OSI như sách giáo khoa. Thay vào đó, hãy tập trung vào hai tầng quan trọng nhất với System Design: Layer 4 (Transport) và Layer 7 (Application).
1.1 Layer 4 vs Layer 7: Tác động đến Latency
┌─────────────────────────────────────────────────────────────────┐
│ CLIENT REQUEST FLOW │
├─────────────────────────────────────────────────────────────────┤
│ │
│ [Client] │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ LAYER 7 (HTTP/HTTPS) │ │
│ │ • URL parsing, Headers, Cookies │ │
│ │ • SSL/TLS Termination (expensive!) │ │
│ │ • Content-based routing ("if /api/* → backend pool") │ │
│ │ • Request inspection & modification │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ LAYER 4 (TCP/UDP) │ │
│ │ • IP:Port routing only (no content awareness) │ │
│ │ • Connection tracking (SYN, ACK states) │ │
│ │ • NAT translation │ │
│ │ • Much faster (no payload inspection) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ [Backend Servers] │
│ │
└─────────────────────────────────────────────────────────────────┘Bảng so sánh chi phí xử lý:
| Aspect | Layer 4 | Layer 7 |
|---|---|---|
| Throughput | 10M+ req/s | 100K-1M req/s |
| Latency overhead | ~10-50μs | ~100-500μs |
| CPU cost | Minimal | High (TLS, parsing) |
| Content routing | ❌ Không thể | ✅ Có thể |
| SSL Termination | ❌ Pass-through | ✅ Có thể xử lý |
TIP
🔧 Kỹ sư Raizo: Trong production, chúng tôi thường dùng kiến trúc 2-tier: Layer 4 LB (như IPVS, Maglev) ở edge để chịu tải cao, sau đó route đến Layer 7 LB (như Envoy, Nginx) để xử lý intelligent routing. Đừng bao giờ để L7 LB trực tiếp chịu internet traffic!
1.2 Practical Implication: TLS Latency Tax
┌─────────────────────────────────────────────────────────────┐
│ TLS 1.2 HANDSHAKE (2-RTT) │
├─────────────────────────────────────────────────────────────┤
│ │
│ Client Server │
│ │ │ │
│ │────── ClientHello ───────────────►│ RTT 1 │
│ │ │ │
│ │◄───── ServerHello + Cert ─────────│ │
│ │ │ │
│ │────── ClientKeyExchange ─────────►│ RTT 2 │
│ │ │ │
│ │◄───── Finished ───────────────────│ │
│ │ │ │
│ │═══════ Encrypted Data ═══════════►│ Now we can talk! │
│ │
│ Total: 2 Round-Trip Times before ANY data transfer │
│ If RTT = 100ms → 200ms wasted on handshake ALONE │
│ │
└─────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────┐
│ TLS 1.3 HANDSHAKE (1-RTT) │
├─────────────────────────────────────────────────────────────┤
│ │
│ Client Server │
│ │ │ │
│ │────── ClientHello + KeyShare ────►│ RTT 1 │
│ │ │ │
│ │◄───── ServerHello + Finished ─────│ │
│ │ │ │
│ │═══════ Encrypted Data ═══════════►│ Ready! │
│ │
│ 0-RTT possible with PSK (Pre-Shared Key) for repeat visits│
│ │
└─────────────────────────────────────────────────────────────┘IMPORTANT
Triết lý HPN: Latency = Lost Revenue. Amazon phát hiện mỗi 100ms delay giảm 1% doanh thu. Google cho thấy page load tăng 0.5s làm traffic giảm 20%. TLS version không chỉ là security, nó là business decision.
2. TCP vs UDP Deep Dive
2.1 Three-way Handshake: Chi phí Ẩn giấu
┌─────────────────────────────────────────────────────────────────┐
│ TCP THREE-WAY HANDSHAKE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Client Server │
│ │ │ │
│ │ ┌─────────────────────────────────────┐ │ │
│ Step 1 │ │ SYN: seq=x │ │ │
│ │ │ "Hey, I want to talk, my number is x" │ │
│ │ └──────────────────────────────────────► │ │
│ │ │ │
│ │ ┌─────────────────────────────────────┐ │ │
│ Step 2 │ │ SYN-ACK: seq=y, ack=x+1 │ │ │
│ │ │ "OK! My number is y, I heard your x"│ │ │
│ │◄─┴─────────────────────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────────────────────────┐ │ │
│ Step 3 │ │ ACK: ack=y+1 │ │ │
│ │ │ "Great, let's talk!" │ │ │
│ │ └──────────────────────────────────────► │ │
│ │ │ │
│ │═══════════ NOW DATA CAN FLOW ═══════════════│ │
│ │
│ COST: 1.5 RTT before any application data! │
│ For a 150ms RTT (US ↔ Europe): 225ms of pure WAITING │
│ │
└─────────────────────────────────────────────────────────────────┘Tại sao cần 3-way handshake?
NOTE
🎓 Giáo sư Tom: Đây là giải pháp cho "Two Generals' Problem" - một bài toán kinh điển về đồng bộ hóa trong mạng không đáng tin cậy. Three-way handshake đảm bảo BOTH sides đều xác nhận: (1) Tôi có thể gửi đến bạn, (2) Bạn có thể gửi đến tôi, (3) Tôi biết bạn nhận được reply của tôi.
2.2 TCP: Thế mạnh và Điểm yếu
TCP Guarantees:
- Reliable Delivery: Mọi packet đều được ACK, mất packet = retransmit
- Ordered Delivery: Sequence numbers đảm bảo thứ tự
- Flow Control: Sliding window ngăn sender overwhelm receiver
- Congestion Control: Slow start, AIMD ngăn network collapse
TCP Hidden Costs:
┌─────────────────────────────────────────────────────────────────┐
│ HEAD-OF-LINE BLOCKING (TCP) │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Stream: [Packet 1] [Packet 2] [Packet 3] [Packet 4] │
│ │ │
│ ▼ │
│ ╔═══════╗ │
│ ║ LOST! ║ │
│ ╚═══════╝ │
│ │ │
│ ▼ │
│ Receiver Buffer: [Pkt 1] [WAIT...] [Pkt 3 waiting] [Pkt 4 waiting]
│ ▲ │
│ │ │
│ Cannot deliver Pkt 3, 4 to application │
│ until Pkt 2 is retransmitted! │
│ │
│ RESULT: One lost packet blocks ALL subsequent packets │
│ │
└─────────────────────────────────────────────────────────────────┘2.3 UDP: Fire and Forget
┌─────────────────────────────────────────────────────────────────┐
│ UDP CHARACTERISTICS │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Header Size: TCP = 20+ bytes || UDP = 8 bytes │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ UDP HEADER (8 bytes) │ │
│ ├─────────────────┬─────────────────┬─────────────────────┐│ │
│ │ Source Port (2) │ Dest Port (2) │ Length (2) │ Checksum││ │
│ └─────────────────┴─────────────────┴─────────────────────┘│ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
│ GUARANTEES: │
│ ✅ Delivery to correct port (if host is reachable) │
│ ✅ Data integrity (checksum) - optional in IPv4 │
│ │
│ NO GUARANTEES: │
│ ❌ Delivery at all (packet can be dropped) │
│ ❌ Order (packets may arrive out of sequence) │
│ ❌ Duplicate prevention │
│ ❌ Congestion control (YOU must implement) │
│ │
└─────────────────────────────────────────────────────────────────┘2.4 Case Study: Tại sao Game Online & Video Call dùng UDP?
Phân tích Trade-offs:
| Factor | TCP cho Gaming | UDP cho Gaming |
|---|---|---|
| Packet loss handling | Retransmit (adds latency) | Skip stale, use latest |
| Position update value | Stale data useless | Only latest matters |
| Latency tolerance | Cannot tolerate 200ms spike | Can tolerate 1-2% loss |
| Connection overhead | Handshake per connection | Fire immediately |
TIP
🔧 Kỹ sư Raizo: Nhưng UDP không có nghĩa là "không quản lý gì cả"! Các game studio xây custom reliability layer trên UDP: sequence numbers riêng, selective ACK cho critical events (player death, item pickup), nhưng skip ACK cho position updates. Đây là lý do QUIC ra đời - mang lại best of both worlds.
3. HTTP Evolution: The Real Performance Story
3.1 HTTP/1.0 → HTTP/1.1: Keep-Alive Revolution
┌─────────────────────────────────────────────────────────────────┐
│ HTTP/1.0 vs HTTP/1.1 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ HTTP/1.0 (Multiple Connections): │
│ ═══════════════════════════════ │
│ │
│ Request 1: [Handshake]──[GET /index.html]──[Response]──[CLOSE] │
│ Request 2: [Handshake]──[GET /style.css]───[Response]──[CLOSE] │
│ Request 3: [Handshake]──[GET /app.js]──────[Response]──[CLOSE] │
│ │
│ Cost: 3 × TCP Handshake + 3 × TLS Handshake = EXPENSIVE! │
│ │
│ ───────────────────────────────────────────────────────────── │
│ │
│ HTTP/1.1 (Keep-Alive - Connection Reuse): │
│ ═════════════════════════════════════════ │
│ │
│ [Handshake]──[GET /index.html]──[Response] │
│ └──[GET /style.css]────[Response] │
│ └──[GET /app.js]───────[Response]──[CLOSE after idle] │
│ │
│ Cost: 1 × TCP + 1 × TLS only! Huge win! │
│ │
└─────────────────────────────────────────────────────────────────┘Nhưng HTTP/1.1 vẫn có vấn đề nghiêm trọng:
┌─────────────────────────────────────────────────────────────────┐
│ HTTP/1.1 HEAD-OF-LINE BLOCKING │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Single Connection (FIFO Queue): │
│ │
│ Request Queue: [Req 1][Req 2][Req 3][Req 4] │
│ │ │
│ ▼ │
│ Processing: [Req 1 processing... 500ms] │
│ │ │
│ ▼ │
│ Req 2, 3, 4: BLOCKED waiting for Req 1's response! │
│ │
│ ───────────────────────────────────────────────────────────── │
│ │
│ Browser Workaround: Open 6 parallel connections per domain │
│ │
│ Connection 1: [Req 1] ─────────────► │
│ Connection 2: [Req 2] ─────────────► │
│ Connection 3: [Req 3] ─────────────► │
│ Connection 4: [Req 4] ─────────────► │
│ Connection 5: [Req 5] ─────────────► │
│ Connection 6: [Req 6] ─────────────► │
│ │
│ Problems: 6× handshake cost, connection management overhead, │
│ server-side resource exhaustion │
│ │
└─────────────────────────────────────────────────────────────────┘3.2 HTTP/2: Multiplexing & Binary Framing
┌─────────────────────────────────────────────────────────────────┐
│ HTTP/2 MULTIPLEXING MAGIC │
├─────────────────────────────────────────────────────────────────┤
│ │
│ SINGLE TCP CONNECTION with multiple streams: │
│ │
│ Frame Format: │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Length (24) │ Type (8) │ Flags (8) │ Stream ID (32) │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ Frame Payload │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ Multiplexed Streams (no HOL blocking at HTTP layer!): │
│ │
│ Time → │
│ ═══════════════════════════════════════════════════════════ │
│ │[S1:HEADER]│[S2:HEADER]│[S1:DATA]│[S3:DATA]│[S2:DATA]│ │
│ ═══════════════════════════════════════════════════════════ │
│ │
│ Stream 1 (index.html): ■─────────■ │
│ Stream 2 (style.css): ■───────────────■ │
│ Stream 3 (app.js): ■───────■ │
│ │
│ ALL streams INTERLEAVED on single connection! │
│ │
└─────────────────────────────────────────────────────────────────┘HTTP/2 Features:
| Feature | Benefit |
|---|---|
| Binary Framing | Efficient parsing (vs text parsing in HTTP/1.1) |
| Stream Multiplexing | No HTTP-level HOL blocking |
| Header Compression | HPACK reduces redundant headers by 85-90% |
| Server Push | Server proactively sends resources |
| Stream Prioritization | Critical resources first |
3.3 The Remaining Problem: TCP-level HOL Blocking
┌─────────────────────────────────────────────────────────────────┐
│ HTTP/2 STILL HAS TCP-LEVEL HOL BLOCKING! │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 3 HTTP/2 streams sharing 1 TCP connection: │
│ │
│ TCP Packets: [Pkt1:S1] [Pkt2:S2] [Pkt3:S3] [Pkt4:S1] │
│ ▲ │
│ │ │
│ PACKET LOST! │
│ │ │
│ ▼ │
│ TCP Layer: "Must wait for Pkt2 retransmit..." │
│ │ │
│ ▼ │
│ ALL STREAMS BLOCKED: │
│ │
│ Stream 1: [Waiting...] │
│ Stream 2: [Waiting for its own lost packet] │
│ Stream 3: [Waiting... even though Pkt3 arrived fine!] │
│ │
│ ⚠️ HTTP/2 solved HTTP-level HOL blocking │
│ ❌ But TCP still causes blocking at transport layer │
│ │
└─────────────────────────────────────────────────────────────────┘3.4 HTTP/3 & QUIC: The TCP Killer
QUIC Protocol: Giải quyết mọi vấn đề
┌─────────────────────────────────────────────────────────────────┐
│ QUIC STREAM INDEPENDENCE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ QUIC tách mỗi stream thành independent flow: │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Stream 0 │ │ Stream 1 │ │ Stream 2 │ │
│ │ (ctrl) │ │ (request) │ │ (request) │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ QUIC (per-stream flow control & recovery) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ UDP (simple, fast) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ If Stream 1's packet lost: │
│ • Stream 1: Waits for retransmit │
│ • Stream 0: Continues normally! ✅ │
│ • Stream 2: Continues normally! ✅ │
│ │
│ NO MORE HOL BLOCKING AT TRANSPORT LAYER! │
│ │
└─────────────────────────────────────────────────────────────────┘QUIC Key Innovations:
┌─────────────────────────────────────────────────────────────────┐
│ QUIC 0-RTT HANDSHAKE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ First Connection: │
│ ──────────────── │
│ Client Server │
│ │───── ClientHello + Key Share ──────►│ │
│ │◄───── ServerHello + Cert + Token ───│ 1-RTT │
│ │═══════════ Encrypted Data ══════════│ │
│ │
│ ───────────────────────────────────────────────────────────── │
│ │
│ Repeat Connection (0-RTT): │
│ ────────────────────────── │
│ Client Server │
│ │═══ ClientHello + Early Data ════════►│ 0-RTT! │
│ │◄════════ Response ══════════════════│ │
│ │
│ Client sends data IMMEDIATELY with first packet! │
│ Uses cached server config from previous connection. │
│ │
└─────────────────────────────────────────────────────────────────┘TIP
🔧 Kỹ sư Raizo - HPN Note: Penrift Tunnel sử dụng custom protocol trên nền UDP, tương tự triết lý của QUIC. Bằng cách bypass TCP overhead và implement own reliability layer tối ưu cho use case cụ thể, chúng tôi đạt được latency thấp hơn 30-40% so với OpenVPN/WireGuard trong điều kiện network packet loss 2-5%.
3.5 HTTP Version Comparison Matrix
| Aspect | HTTP/1.1 | HTTP/2 | HTTP/3 (QUIC) |
|---|---|---|---|
| Transport | TCP | TCP | UDP |
| Multiplexing | ❌ (workaround: 6 connections) | ✅ Single connection | ✅ Single connection |
| HOL Blocking | ❌ HTTP + TCP level | ❌ TCP level only | ✅ None! |
| Handshake | TCP + TLS separate | TCP + TLS separate | Combined (0-RTT possible) |
| Header Format | Text | Binary (HPACK) | Binary (QPACK) |
| Connection Migration | ❌ IP change = reconnect | ❌ IP change = reconnect | ✅ Connection ID survives |
IMPORTANT
Connection Migration là killer feature cho mobile: User chuyển từ WiFi sang 4G, HTTP/2 phải handshake lại, HTTP/3 tiếp tục ngay lập tức vì connection được định danh bằng Connection ID, không phải IP:Port tuple.
4. Practical Takeaways
4.1 Decision Matrix: Khi nào dùng gì?
4.2 Production Checklist
TIP
🔧 Kỹ sư Raizo's Production Checklist:
Layer 4 Optimizations:
- [ ] Enable TCP BBR congestion control (vs CUBIC)
- [ ] Tune TCP buffer sizes (net.ipv4.tcp_rmem/wmem)
- [ ] Enable TCP Fast Open cho repeat visitors
- [ ] Consider IPVS cho L4 load balancing scale
Layer 7 Optimizations:
- [ ] Upgrade to TLS 1.3 (1-RTT handshake)
- [ ] Enable HTTP/2 với proper priority tuning
- [ ] Evaluate HTTP/3 cho mobile-first apps
- [ ] Implement connection pooling cho backend calls
5. Tiếp theo
Bây giờ bạn đã hiểu về network fundamentals, hãy tiếp tục với:
Chúng ta sẽ khám phá cách điều phối traffic qua các proxy layers và thuật toán load balancing - đặc biệt là Consistent Hashing, thuật toán "tỷ đô" đứng sau mọi distributed system hiện đại.