Chuyển đến nội dung chính

Lesson 4: Networking Fundamentals for System Design

DNS and how it works. TCP vs UDP. HTTP/HTTPS, HTTP/2, HTTP/3. WebSocket and Server-Sent Events. REST vs RPC vs GraphQL. Latency numbers every programmer should know.

🏗️ Architecture — Lesson 4 Lesson 4: Networking Fundamentals for System Design

System Architecture: From Zero to Hero

Part 1: System Design Foundation

xdev.asia

Introduction

Every distributed system communicates via a network. Understanding networking fundamentals helps you make the right design decisions: which protocol to choose, where to optimize latency, and how to predict bottlenecks.


1. DNS (Domain Name System)

1.1 What is DNS?

DNS is the "phone book" of the Internet — converting domain names into IP addresses.

Browser: "Tôi muốn truy cập xdev.asia"
DNS:     "xdev.asia → 104.21.35.123"
Browser: → Kết nối đến 104.21.35.123

1.2 DNS Resolution Process

Browser ──► Local DNS Cache
            │ miss
            ▼
        OS DNS Cache
            │ miss
            ▼
        ISP DNS Resolver ──► Root DNS Server
                             │ ".asia"
                             ▼
                         TLD DNS Server (.asia)
                             │ "xdev.asia"
                             ▼
                         Authoritative DNS
                             │
                             ▼
                         IP: 104.21.35.123

1.3 DNS Record Types

RecordDescriptionExample
ADomain → IPv4xdev.asia → 104.21.35.123
AAAADomain → IPv6xdev.asia → 2606:4700::6812
CNAMEDomain → Domainwww.xdev.asia → xdev.asia
MXMail serverxdev.asia → mail.xdev.asia
NSName serverxdev.asia → ns1.cloudflare.com
TXTText recordsSPF, DKIM for email

1.4 DNS in System Design

DNS-based Load Balancing:

xdev.asia → 10.0.1.1  (Server US)
          → 10.0.2.1  (Server EU)
          → 10.0.3.1  (Server Asia)

Strategies:
  - Round Robin: Trả lần lượt từng IP
  - Weighted: Server khỏe hơn nhận nhiều traffic hơn
  - Geo-based: Trả IP gần user nhất
  - Latency-based: Trả IP có latency thấp nhất

2. TCP vs UDP

2.1 TCP (Transmission Control Protocol)

TCP 3-way Handshake:

Client          Server
  │── SYN ────────►│     1. Client gửi SYN
  │◄── SYN-ACK ───│     2. Server trả SYN-ACK
  │── ACK ────────►│     3. Client confirm
  │                │     → Connection established
  │◄─── Data ─────►│     4. Truyền data

Features:

  • Reliable: Ensures data arrives in the correct order
  • Flow control & Congestion control
  • Overhead is higher than UDP

2.2 UDP (User Datagram Protocol)

UDP: Fire and Forget

Client          Server
  │── Data ───────►│     Gửi data, không cần handshake
  │── Data ───────►│     Không đảm bảo đến nơi
  │── Data ───────►│     Không đảm bảo thứ tự

2.3 Comparison

CriteriaTCPUDP
ReliabilityGuaranteed deliveryBest effort
OrderOrder GuaranteedNo guarantee
SpeedSlower (handshake)Faster
Use casesHTTP, Email, File transferVideo calling, Gaming, DNS
ConnectionConnection-orientedConnectionless
OverheadCaoLow

3. HTTP/HTTPS and Evolution

3.1 HTTP/1.1

Client ──► Server: GET /page1
Client ◄── Server: Response page1
Client ──► Server: GET /style.css    ← Phải đợi response trước
Client ◄── Server: Response style.css
Client ──► Server: GET /script.js
Client ◄── Server: Response script.js

Vấn đề: Head-of-line blocking
  → Mỗi lần chỉ 1 request trên 1 connection
  → Browsers mở 6-8 connections song song (workaround)

3.2 HTTP/2

Client ──► Server: Stream 1: GET /page1     ┐
Client ──► Server: Stream 2: GET /style.css  │ Multiplexing!
Client ──► Server: Stream 3: GET /script.js  ┘ Cùng 1 connection

Server Push:
  Client request /page1
  Server trả /page1 + push /style.css, /script.js
  → Client có sẵn resources trước khi cần

Main improvements:

  • Multiplexing: Multiple requests on 1 connection
  • Header compression (HPACK)
  • Server Push
  • Binary protocol (instead of text)

3.3 HTTP/3 (QUIC)

HTTP/1.1: TCP + TLS         → 3 roundtrips to start
HTTP/2:   TCP + TLS         → 3 roundtrips to start
HTTP/3:   QUIC (over UDP)   → 1 roundtrip (0-RTT resumption)

Improvement:

  • Built on UDP (faster than TCP handshake)
  • 0-RTT connection resumption
  • No more Head-of-line blocking at the transport layer
  • Built-in encryption

4. WebSocket & Server-Sent Events

4.1 Polling vs Long Polling vs WebSocket vs SSE

Polling:
  Client: "Có tin nhắn mới không?" (mỗi 5 giây)
  Server: "Không" / "Có"
  → Lãng phí bandwidth

Long Polling:
  Client: "Có tin nhắn mới không?" (hold connection)
  Server: ... đợi ... "Có tin nhắn mới!" → return
  Client: Nhận xong → gửi request mới ngay
  → Tốt hơn polling, vẫn overhead

WebSocket:
  Client ◄──── Full-duplex connection ────► Server
  → Cả hai bên gửi data bất kỳ lúc nào
  → Ideal cho chat, gaming, real-time

SSE (Server-Sent Events):
  Server ────► Client (one-way stream)
  → Server push updates liên tục
  → Ideal cho notifications, live feeds

4.2 When to use what?

Use casesRecommended
Chat applicationsWebSockets
Live sports scoresSSE
Stock tickerWebSocket or SSE
Social media feedLong Polling or SSE
Online gamingWebSockets
NotificationsSSE
File upload progressSSE
Collaborative editingWebSockets

5. API Paradigms: REST vs RPC vs GraphQL

5.1 REST (Representational State Transfer)

GET    /users/123          → Lấy user 123
POST   /users              → Tạo user mới
PUT    /users/123          → Update user 123
DELETE /users/123          → Xóa user 123
GET    /users/123/orders   → Lấy orders của user 123

Advantages: Simple, standard, cacheable, widely supported Disadvantages: Over-fetching, under-fetching, multiple roundtrips

5.2 RPC (Remote Procedure Call)

POST /getUserById          { "userId": 123 }
POST /createUser           { "name": "John", "email": "..." }
POST /transferMoney        { "from": 1, "to": 2, "amount": 100 }

Modern RPC: gRPC

service UserService {
  rpc GetUser (GetUserRequest) returns (User);
  rpc CreateUser (CreateUserRequest) returns (User);
}

Advantages: Performance (binary protocol), type-safe, bi-directional streaming Disadvantages: Not browser-friendly, requires genetic code, learning curve

5.3 GraphQL

query {
  user(id: 123) {
    name
    email
    orders(last: 5) {
      id
      total
      items {
        name
        price
      }
    }
  }
}

Advantage: Client chooses exactly the data needed, 1 endpoint, no over-fetching Disadvantages: Complexity, caching is more difficult, N+1 query problem

5.4 When to use what?

ParadigmBest for
RESTPublic APIs, CRUD operations, simple interactions
gRPCInternal microservices communication, high performance
GraphQLComplex data relationships, mobile apps, BFF

6. Summary

TopicKey Takeaway
DNSInternet "directory", can be used for load balancing
TCPReliable, ordered — used for HTTP, database
UDPFast, unreliable — used for video, gaming
HTTP/2Multiplexing, server push — current standard
HTTP/3QUIC over UDP — future standard
WebSocketsFull-duplex real-time communication
RESTStandard for public APIs
gRPCHigh-performance internal communication
GraphQLFlexible data fetching for complex UIs

Exercises

  1. DNS Design: Design DNS strategy for applications with users in Vietnam, Singapore and Japan. Servers located in Singapore and Tokyo.

  2. Protocol Choice: For each scenario, choose the appropriate protocol:

    • (a) Live video streaming platform
    • (b) Banking API for mobile app
    • (c) Internal microservice communication (10K RPS)
    • (d) Real-time collaborative document editing
  3. API Design: Design API for e-commerce system using REST. List endpoints for: Products, Orders, Cart, Users.