Networking Essentials
System design 面试必备的 networking 基础
Networking 是 system design 的基础:你几乎总是在设计一堆独立的 devices,通过 network 互相通信。Networking 这个领域又大又深,面试里不会考到“电压层面”的细节,但需要你能清晰地讲出 层次模型、关键协议、以及在架构里如何选型。
这章会从基础原理开始,快速覆盖 network stack 的关键层与主流协议,然后通过一个简单 web request 例子串起来,再延伸到 API 协议、实时通信、load balancing、以及常见 failure 处理。
Networking 101
Networking 的核心是 连接设备、让它们能沟通。我们一般用分层架构(OSI model / TCP/IP model)来理解网络,这让 application developer 不需要知道电信号细节,只要用下一层提供的 abstraction。
Networking Layers
面试里最常出现的三层:
- Network Layer (L3):IP 负责 routing / addressing,把 data 切成 packets 并在网络中转发。
- Transport Layer (L4):TCP / UDP / QUIC 提供 end-to-end 通信能力,负责可靠性、顺序、flow control 等。
- Application Layer (L7):DNS、HTTP、WebSocket、WebRTC 等协议,直接服务于应用层的通信需求。
Example: A Simple Web Request
当你在 browser 里输入 URL,网络大致按下面流程工作:
- DNS Resolution:把 domain name 转成 IP address。
- TCP Handshake:三次握手建立连接(SYN → SYN-ACK → ACK)。
- HTTP Request:发送 HTTP GET 请求。
- Server Processing:服务端处理请求并生成 response。
- HTTP Response:把响应返回给 client。
- TCP Teardown:四次挥手关闭连接(FIN / ACK)。
几个关键观察:
- 应用层只看到 request/response,但底层发生了更多 packets 与 handshake。
- TCP 提供可靠性与顺序保障,简化了 application 的心智负担。
- 连接是 stateful 的,频繁建连会带来额外 latency;HTTP keep-alive / HTTP2 多路复用能缓解这个问题。
Network Layer Protocols
这一层由 IP 主导,负责 routing 与 addressing。服务器通常通过 DHCP 获取 IP。你可以在 private network 中自定义 IP,但对外服务需要 public IP(由 RIR 分配、可在全球路由)。
面试里你不需要深入 BGP 细节,但要知道:internet routing 基于 public IP,流量会被送到对应 ISP / backbone 的 routers。
Transport Layer Protocols
这一层提供 end-to-end 可靠通信。主要是 TCP / UDP / QUIC:
- TCP:可靠、有序、流控、拥塞控制。
- UDP:低 overhead、低 latency,但不保证送达/顺序。
- QUIC:基于 UDP 的现代化协议(HTTP/3),更低延迟、更快建连,但面试里通常只需要知道它是 “更现代的 TCP”。
UDP: Fast but Unreliable
UDP 是 “spray and pray”。适合对 latency 极敏感且可容忍丢包的场景。
Key characteristics:
- Connectionless:不需要 handshake
- No guarantee of delivery
- No ordering guarantees
- Lower latency
典型 use cases:
- live video streaming
- online gaming
- VoIP
- DNS queries
Browser 对 UDP 的支持有限(主要通过 WebRTC)。如果需要 browser 客户端,通常要有 HTTP fallback。
TCP: Reliable but with Overhead
TCP 提供可靠、按序、error-checked 的传输,建立在 connection(stream)之上。它通过 ACK 与重传确保数据到达。
Key characteristics:
- Connection-oriented
- Reliable delivery
- Flow control
- Congestion control
TCP 是默认选择,除非你有明确的理由选 UDP。
When to Choose Each Protocol
通常默认 TCP。你可能选择 UDP 的情形:
- Low latency 极其关键(实时应用、gaming)
- 可以容忍丢包(media streaming)
- 高吞吐 telemetry/logs,偶尔丢包 OK
- 不需要 browser 支持
| Feature | UDP | TCP |
|---|---|---|
| Connection | Connectionless | Connection-oriented |
| Reliability | Best-effort | Guaranteed |
| Ordering | No | Yes |
| Flow Control | No | Yes |
| Congestion Control | No | Yes |
| Header Size | 8 bytes | 20-60 bytes |
| Speed | Faster | Slower |
| Use Cases | Streaming, gaming, VoIP | Most web apps |
Application Layer Protocols
Application layer 运行在 user space,灵活、易改;L4/L3 多在 kernel space,性能高但难改。
HTTP/HTTPS: The Web's Foundation
HTTP 是 request-response 协议,stateless。这是 system design 里很好的默认:尽量让服务 stateless。
核心概念:
- Methods:GET / POST / PUT / PATCH / DELETE
- Status Codes:200 / 201 / 301 / 302 / 401 / 403 / 404 / 429 / 500 / 502
- Headers:metadata
- Body:payload
HTTP headers 是 “flexible interface” 的好例子,比如 Accept-Encoding 与 Content-Encoding 让 server/client 自由协商 gzip / brotli。
HTTPS 在 HTTP 上增加 TLS/SSL,确保传输加密,但 不等于信任请求体。不要直接信任 request body 里的 userId,一定要 server-side validate。
REST: Simple and Flexible
REST 把 API 设计成 “resources + verbs”。常见 pattern:
GET /users/{id} -> User
PUT /users/{id} -> User
POST /users -> User
GET /users/{id}/posts -> [Post]
REST 好理解、好扩展,是面试里的默认选择。但 JSON 序列化成本高,在高吞吐系统里不是最优。
Where to use it:大多数 public APIs、CRUD 型服务。
GraphQL: Flexible Data Fetching
GraphQL 允许 client 精确指定需要的数据,解决 under-fetching 与 over-fetching:
query GetUsersWithProfilesAndGroups($limit: Int = 10, $offset: Int = 0) {
users(limit: $limit, offset: $offset) {
id
username
profile {
id
fullName
avatar
}
groups {
id
name
description
category {
id
name
icon
}
}
status {
isActive
lastActiveAt
}
}
_metadata {
totalCount
hasNextPage
}
}
GraphQL 适合 需求变化快、client 复杂 的场景,但 server 复杂度高、执行成本高。面试里如果需求明确,GraphQL 的优势不一定明显。
gRPC: Efficient Service Communication
gRPC 使用 HTTP/2 + Protocol Buffers,binary 序列化效率高,适合 internal service-to-service 通信。
message User { string id = 1; string name = 2; }
message GetUserRequest { string id = 1; }
message GetUserResponse { User user = 1; }
service UserService { rpc GetUser (GetUserRequest) returns (GetUserResponse); }
Where to use it:microservices 内部调用、性能敏感、低 latency。 Avoid for public APIs(browser/tooling 支持弱)。常见组合:internal gRPC + external REST。
Server-Sent Events (SSE)
SSE 基于 HTTP 的单向 streaming(server -> client),适合通知类实时更新,比如价格/状态推送。
WebSockets
WebSocket 提供 bidirectional realtime connection:
- Client 通过 HTTP handshake
- 升级到 WebSocket protocol
- 双向发送 binary message
- 连接保持直到显式关闭
WebRTC
WebRTC 用于 peer-to-peer,常配合 STUN/TURN:
- STUN:获取 public IP/port,解决 NAT traversal
- TURN:中继服务器,NAT 无法直连时兜底
常见流程:
- Client 连接 signaling server 交换信息
- STUN 获取 public IP/port
- 通过 signaling server 交换信息
- 建立 P2P 连接并传输数据
Load Balancing
Types of Load Balancing
Client-Side Load Balancing
- Example: Redis Cluster
- Example: DNS-based
Dedicated Load Balancers
- Layer 4 (L4):高性能、低开销,不看请求内容
- Layer 7 (L7):可基于 URL/header/cookie routing,功能强但更耗 CPU
Health Checks and Fault Tolerance
Load balancer 通过 health checks 剔除 unhealthy instances,提升可用性。
Algorithms
- Round Robin
- Random
- Least Connections
- Least Response Time
- IP Hash(session persistence)
Real-World Implementations
- Hardware: F5 BIG-IP
- Software: HAProxy, NGINX, Envoy
- Cloud: AWS ELB/ALB/NLB, GCP LB, Azure LB
Common Deep Dives and Challenges
Regionalization and Latency
- CDN:把 static content 推近用户
- Regional Partitioning:数据与服务按 region 分片
Handling Failures and Fault Modes
Timeouts & Retries
需要 exponential backoff,避免放大流量。配合 idempotency 防止重复写入。
Circuit Breaker
- 失败次数超阈值后 “trip”
- open 状态直接 fail fast
- timeout 后进入 half-open,试探恢复
好处:
- Fail Fast
- Reduce Load
- Self-Healing
- Improve UX
- Prevent cascading failures
适用场景:
- third-party APIs
- DB connections
- service-to-service calls
- 任何可能 timeout 的 network call
Wrapping Up
- Understand basics: IP addressing, DNS, TCP/IP model
- Know protocols: TCP vs UDP, HTTP/HTTPS, WebSockets, gRPC
- Master load balancing: client-side + dedicated LB
- Plan for reality: regionalization, retries, circuit breakers
如果你想自测,可以用一些 networking quiz 检查理解(面试里经常是“概念 + 选型 + trade-off”组合问法)。