Networking & Protocols
Interview Context
「當你在瀏覽器輸入網址後發生了什麼事?」是 system design 面試的經典開場題。對 DS/ML 工程師來說,networking 知識決定你能不能討論 model API 的 latency、real-time feature streaming、以及 dashboard 的推播架構。面試官想確認你理解 request 從 client 到 server 的完整旅程,以及每一層的 tradeoff。
What You Should Understand
- 能完整走一遍「輸入 URL 到頁面渲染」的流程:DNS → TCP → TLS → HTTP → render
- 理解 DNS 的階層式架構(root、TLD、authoritative)與 caching / TTL 機制
- 能比較 TCP 與 UDP 的差異,並說出哪些 protocol 跑在哪個之上
- 知道 HTTP/1.1 → HTTP/2 → HTTP/3 各解決了什麼問題(head-of-line blocking 的兩個層次)
- 能為不同 real-time 場景選對技術:short polling、long polling、SSE、WebSocket
- 理解 forward vs reverse proxy、L4 vs L7 load balancing 與常見 LB algorithms
What Happens When You Type a URL
The single most classic networking interview question. 完整流程如下:
- URL parsing — Browser 解析 URL 的組成:scheme(https)、domain(example.com)、path(/search)、query string(?q=cat)。
- Cache check — Browser 依序檢查 browser cache → OS cache → router cache → ISP resolver cache,找看看有沒有這個 domain 的 IP。命中就跳過 DNS 查詢。
- DNS resolution — 沒命中 cache,recursive resolver 依序問 root server → TLD server(.com)→ authoritative server,最終拿到 IP address。
- TCP handshake — Browser 和 server 用 three-way handshake(SYN → SYN-ACK → ACK)建立 TCP connection。這一步花費一個 round-trip time(RTT)。
- TLS handshake — 若是 HTTPS,再進行 TLS handshake:交換支援的加密演算法、驗證 server certificate、協商出 session key。TLS 1.3 只需 1 個額外 RTT。
- HTTP request/response — Browser 送出 HTTP GET request,server 回傳 HTML response(可能經過 load balancer、reverse proxy、application server)。
- Rendering — Browser 解析 HTML 建立 DOM tree、解析 CSS 建立 CSSOM、合成 render tree,執行 JavaScript,layout 和 paint 到螢幕上。過程中遇到的 image、CSS、JS 資源會再發出額外的 requests(通常走已建立的 connection 或 CDN)。
回答這題的層次感
好的回答不是背流程,而是能在任一步往下 zoom in:面試官說「多講一點 DNS」你就要能講 recursive vs iterative;說「多講 TLS」你就要能講 asymmetric key exchange。這一頁接下來的每個 section 就是每一步的 deep dive。
DNS Deep Dive
DNS (Domain Name System) is the internet's phonebook — it maps human-readable domain names to IP addresses.
Resolution Hierarchy
| Server | Role | Example |
|---|---|---|
| Recursive resolver | 幫 client 跑完整個查詢流程的代理(通常由 ISP 或 8.8.8.8 / 1.1.1.1 提供) | Cloudflare 1.1.1.1 |
| Root server | 回答「.com 的 TLD server 在哪」 | 全球 13 組 root server clusters |
| TLD server | 管理 top-level domain,回答「example.com 的 authoritative server 在哪」 | .com, .org, .tw |
| Authoritative server | 真正持有該 domain records 的 server,回傳最終 IP | 由 domain 擁有者或 DNS hosting 商管理 |
Recursive vs Iterative Resolution
| Mode | Who Does the Work | Flow |
|---|---|---|
| Recursive | Resolver 代勞 | Client 問 resolver 一次,resolver 自己去問 root → TLD → authoritative,最後回傳答案 |
| Iterative | 查詢者自己跑 | 每個 server 只回「你去問下一個誰」(referral),查詢者自己一路問下去 |
實務上:client → resolver 是 recursive(client 只問一次);resolver → root/TLD/authoritative 是 iterative(resolver 自己一層層問)。
Caching and TTL
每筆 DNS record 都帶 TTL (Time To Live) — cache 可以保留這筆答案幾秒。Caching 發生在多層:browser、OS、router、ISP resolver。
- TTL 長(例如 86400s):查詢快、DNS 負載低,但改 IP 後要等很久才全球生效
- TTL 短(例如 60s):failover 和 traffic switching 快,但 resolver 查詢量大增
Deployment 前常見操作:先把 TTL 調短 → 換 IP → 確認穩定後再調回長 TTL。
Common Record Types
| Record | Maps To | Purpose |
|---|---|---|
| A | IPv4 address | Domain → 32-bit IP(例如 93.184.216.34) |
| AAAA | IPv6 address | Domain → 128-bit IP |
| CNAME | Another domain | Alias:www.example.com → example.com |
| MX | Mail server | 指定收信的 mail server 與優先序 |
| NS | Name server | 指定這個 zone 的 authoritative servers |
| TXT | Arbitrary text | Domain 驗證、SPF/DKIM email 防偽 |
DNS 也是 Routing 工具
DNS 不只是查 IP — GeoDNS 可以依 client 位置回傳最近的 data center IP,weighted DNS 可以做流量分配和 canary release。這是全球性服務做 traffic routing 的第一層。
TCP vs UDP
Transport layer 的兩大 protocol,核心差異是 reliability vs speed 的 tradeoff。
TCP: Reliable, Connection-Oriented
TCP establishes a connection via the three-way handshake:
- Client → Server: SYN(我想連線,我的初始 sequence number 是 x)
- Server → Client: SYN-ACK(收到,我的初始 sequence number 是 y,ack x+1)
- Client → Server: ACK(收到,ack y+1)— connection established
之後 TCP 提供:reliability(掉包重傳)、ordering(sequence number 保證順序)、flow control(receiver 不被灌爆)、congestion control(網路塞車時降速)。
UDP: Fast, Connectionless
UDP 沒有 handshake、沒有重傳、沒有順序保證 — 就是把 datagram 丟出去。換來的是低 latency 和低 overhead,適合「遲到的資料不如不要」的場景(視訊、遊戲、DNS 查詢)。
Comparison
| Aspect | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented(3-way handshake) | Connectionless |
| Reliability | Guaranteed delivery(ACK + retransmission) | Best effort,掉了就掉了 |
| Ordering | 保證順序 | 不保證 |
| Speed / Overhead | 較慢,header 20+ bytes | 快,header 8 bytes |
| Congestion control | Yes | No |
| Use When | 資料必須完整正確 | 低延遲優先,可容忍掉包 |
Which Protocols Run on Each
| Protocol | Transport | Why |
|---|---|---|
| HTTP/1.1, HTTP/2 | TCP | 網頁內容必須完整 |
| HTTP/3 (QUIC) | UDP | QUIC 在 UDP 上自己實作 reliability,避開 TCP 限制 |
| DNS | UDP(大 response 或 zone transfer 用 TCP) | 查詢小、快,掉了重問就好 |
| TLS/SSL | TCP | 建立在 reliable stream 之上 |
| SMTP / FTP / SSH | TCP | Email、檔案、指令不能掉字 |
| Video streaming / VoIP / gaming | UDP(RTP 等) | 延遲比完整性重要 |
| NTP / DHCP | UDP | 輕量、廣播式查詢 |
Evolution of HTTP
HTTP 的演進史就是一部「消滅 head-of-line blocking」的歷史。
HTTP/1.0 → HTTP/1.1
- HTTP/1.0(1996):每個 request 開一條新 TCP connection,用完就關 — 每張圖片都要重新 handshake,極度浪費。
- HTTP/1.1(1997):引入 persistent connection(keep-alive),同一條 connection 可以連續送多個 requests。也引入 pipelining — 不等 response 就連發多個 requests,但 responses 必須按順序回來,前面的 response 慢,後面全部卡住 — 這就是 application-layer head-of-line (HOL) blocking。Pipelining 因此幾乎沒有瀏覽器啟用,實務上大家改用 6 條平行 connections hack。
HTTP/2 (2015)
- Multiplexing:一條 TCP connection 上把 requests/responses 切成帶 stream ID 的 frames 交錯傳送 — 多個 streams 並行,徹底解決 application-layer HOL blocking。
- Header compression(HPACK):headers 常常重複(cookie、user-agent),HPACK 用 static/dynamic table 壓縮,大幅減少 overhead。
- Server push、stream prioritization(實務採用有限)。
- 剩下的問題:底層還是 TCP — 一個 packet 掉了,TCP 會把整條 connection 上所有 streams 都停下來等重傳。這是 transport-layer HOL blocking。
HTTP/3 (2022): QUIC over UDP
- 改用 QUIC — 建立在 UDP 上的 transport protocol,在 user space 實作 reliability、congestion control 和 stream 概念。
- 每個 stream 獨立處理掉包:stream A 掉了 packet 只有 stream A 等重傳,其他 streams 照跑 — 解決 transport-layer HOL blocking。
- TLS 1.3 內建在 QUIC handshake 裡:transport + encryption 一次完成,新連線 1-RTT,回訪 client 可以 0-RTT 直接帶資料。
- Connection migration:connection 用 connection ID 而非 (IP, port) 四元組識別 — 手機從 Wi-Fi 切到 4G 不用重新建連線。
Comparison Table
| Feature | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Connections per origin | 多條(~6) | 1 條 multiplexed | 1 條 multiplexed |
| Multiplexing | No(pipelining 失敗) | Yes(streams/frames) | Yes(QUIC streams) |
| HOL blocking | Application + transport 層都有 | 解決 application 層,transport 層仍在 | 兩層都解決 |
| Header compression | No(plain text) | HPACK | QPACK |
| Encryption | Optional(TLS 外掛) | 實務上必須 TLS | 內建 TLS 1.3 |
| Handshake RTT(新連線) | TCP 1 + TLS 1-2 | TCP 1 + TLS 1-2 | 1(0-RTT resumption) |
HTTPS & TLS
HTTPS = HTTP over TLS。TLS 同時解決三件事:encryption(別人看不到內容)、authentication(確認對方真的是 example.com)、integrity(內容沒被竄改)。
Symmetric vs Asymmetric Encryption
| Type | Keys | Speed | Role in TLS |
|---|---|---|---|
| Asymmetric(RSA, ECDHE) | Public/private key pair | 慢(約 symmetric 的百倍以上) | 只用在 handshake:驗證身分 + 安全地協商出 session key |
| Symmetric(AES-GCM, ChaCha20) | 雙方共享同一把 session key | 快 | 之後所有 application data 都用它加密 |
直覺:asymmetric 像掛號信確認對方身分並交換保險箱密碼,之後大量資料都走快速的保險箱(symmetric)。
TLS Handshake Steps (TLS 1.2 conceptual)
- ClientHello — Client 送出支援的 TLS version、cipher suites、random number。
- ServerHello + Certificate — Server 選定 cipher suite,回傳自己的 certificate(內含 server public key)。
- Certificate verification — Client 用內建的 CA root certificates 驗證 certificate chain 的簽章、有效期、domain 是否吻合。
- Key exchange — Client 產生 pre-master secret,用 server public key 加密送出(RSA),或雙方用 ECDHE 交換參數各自算出 shared secret(有 forward secrecy,現代標準)。
- Session keys derived — 雙方由 shared secret + randoms 導出 symmetric session keys。
- Finished — 雙方交換用 session key 加密的 Finished message,確認 handshake 沒被竄改,之後全部改用 symmetric encryption。
TLS 1.3 把步驟壓縮成 1-RTT(client 第一個訊息就帶上 key exchange 參數),並移除了不安全的舊 cipher suites。
Certificates and the CA Chain
| Component | Role |
|---|---|
| Server certificate | 綁定 domain 與 public key,由 intermediate CA 簽發 |
| Intermediate CA | 由 root CA 簽發,實際負責簽 server certificates(root 保持離線以策安全) |
| Root CA | 自簽,預先內建在 OS / browser 的 trust store 裡 |
驗證邏輯:server cert 的簽章能被 intermediate CA 的 public key 驗證 → intermediate 的簽章能被 root CA 驗證 → root 在我的 trust store 裡 → 信任成立。任何一環失敗,browser 就跳 certificate warning。
面試常見誤區
「HTTPS 用 asymmetric encryption 加密所有資料」是錯的 — asymmetric 太慢,只用於 handshake 階段的身分驗證和 key exchange。實際的資料傳輸永遠是 symmetric encryption。分不清這點會被視為不理解 TLS。
Real-Time Communication
Server 有新資料時怎麼讓 client 知道?四種模式,成本與即時性各不相同。
| Technique | How It Works | Direction | Latency | Overhead | Best For |
|---|---|---|---|---|---|
| Short polling | Client 每隔 N 秒發一次 request 問「有新資料嗎」 | Client pull | 最差(取決於間隔) | 高(大量空手而回的 requests) | 更新頻率低、即時性要求低 |
| Long polling | Client 發 request,server hold 住直到有資料才回,client 立刻再發下一個 | Client pull(模擬 push) | 好 | 中(連線反覆重建) | 需要即時但無法用 WebSocket 的舊環境 |
| SSE (Server-Sent Events) | 一條長期的 HTTP connection,server 持續推 event stream | Server → client 單向 | 好 | 低 | Server 單向推播:通知、dashboard、LLM token streaming |
| WebSocket | HTTP Upgrade handshake 後變成全雙工的持久 TCP connection | 雙向 | 最好 | 低(但 server 要管理 connection state) | 雙向互動:聊天、協作編輯、遊戲、交易 |
How to Choose
| Scenario | Choice | Why |
|---|---|---|
| 營運 dashboard 每 30 秒更新 | Short polling | 簡單、stateless、夠用 |
| 即時通知 / alert feed | SSE | 只需要 server → client 單向,SSE 是純 HTTP,自帶 auto-reconnect |
| 聊天室 / 協作白板 | WebSocket | 雙向低延遲,client 也要頻繁送訊息 |
| LLM 回應逐 token 顯示 | SSE | 單向 streaming 的標準解(OpenAI/Anthropic API 都用 SSE) |
| 股票/交易報價牆 | WebSocket | 高頻雙向(訂閱管理 + 推送) |
面試決策口訣
先問兩個問題:(1)需要 server 主動推嗎?不需要 → polling。(2)需要 client 也高頻送資料嗎?不需要 → SSE;需要 → WebSocket。WebSocket 功能最強但成本最高 — stateful connections 讓 load balancing、failover、水平擴展都變複雜,不要無腦選它。
Proxies & Load Balancing
Forward vs Reverse Proxy
| Aspect | Forward Proxy | Reverse Proxy |
|---|---|---|
| Sits in front of | Clients | Servers |
| Hides | Client 的身分(server 只看到 proxy IP) | Server 架構(client 只看到 proxy) |
| Typical uses | 企業上網管控、內容過濾、匿名化、cache | Load balancing、TLS termination、caching、compression、WAF |
| Examples | Squid、企業 gateway | Nginx、HAProxy、Envoy、CDN edge |
記法:forward proxy 替 client 出面,reverse proxy 替 server 擋在前面。Load balancer 本質上就是一種專職分流的 reverse proxy;API gateway 則是在 reverse proxy 上再加 authentication、rate limiting、routing 等 API 管理功能。
L4 vs L7 Load Balancing
| Aspect | L4 (Transport Layer) | L7 (Application Layer) |
|---|---|---|
| Sees | IP + port(TCP/UDP packets) | 完整 HTTP request(path、headers、cookies) |
| Routing granularity | 只能按 connection 分流 | 可按 URL path、header、cookie 做 content-based routing |
| Performance | 快,幾乎不解析內容 | 較慢,要 terminate 並解析 HTTP |
| TLS termination | No(pass-through) | Yes(常見部署點) |
| Example decision | 「這條 connection 給 server 3」 | 「/api/predict 給 model service,/static 給 CDN」 |
Common Load Balancing Algorithms
| Algorithm | How | Best For | Weakness |
|---|---|---|---|
| Round robin | 依序輪流分配 | Servers 同質、requests 成本相近 | 不管 server 當下負載 |
| Weighted round robin | 按 server 容量加權輪流 | 機器規格不一 | 權重要手動維護 |
| Least connections | 送給目前 active connections 最少的 server | Request 處理時間差異大(如 ML inference) | 需要追蹤 connection 狀態 |
| IP hash | Hash client IP 決定 server | 需要 session affinity(sticky sessions) | 流量分布可能不均;NAT 後大量 clients 同 IP |
| Consistent hashing | Server 排在 hash ring 上,key 順時針找節點 | Cache clusters、分散式儲存 — 加減節點只搬動約 1/N 的 keys | 實作較複雜;需 virtual nodes 平衡負載 |
Consistent Hashing 為什麼重要
一般 hash(key mod N)在加減一台機器時幾乎所有 keys 都要重新分配 — 對 cache cluster 是災難(cache 全滅 → database 被打爆)。Consistent hashing 只影響環上相鄰的一小段,是分散式 cache(Memcached/Redis cluster)與 DynamoDB/Cassandra 類系統的基石。
Common HTTP Status Codes & Ports
Status Codes
| Code | Meaning | 常見情境 |
|---|---|---|
| 200 OK | 成功 | 正常回應 |
| 201 Created | 資源已建立 | POST 建立成功 |
| 301 / 302 | Permanent / temporary redirect | 網址搬家、HTTP → HTTPS 導向 |
| 304 Not Modified | 快取仍有效 | Conditional GET,省下傳輸 |
| 400 Bad Request | Client 請求格式錯誤 | JSON 格式錯、缺參數 |
| 401 Unauthorized | 未通過認證 | Token 缺失或過期 |
| 403 Forbidden | 已認證但無權限 | 權限不足 |
| 404 Not Found | 資源不存在 | 路徑錯誤 |
| 429 Too Many Requests | 被 rate limit | 超過 API 配額 |
| 500 Internal Server Error | Server 端錯誤 | Unhandled exception |
| 502 Bad Gateway | Proxy 收到 upstream 的無效回應 | 後端 crash、部署中 |
| 503 Service Unavailable | 服務暫時不可用 | 過載、維護中 |
| 504 Gateway Timeout | Upstream 逾時未回 | 後端太慢(例如 model inference 超時) |
記法:4xx 是 client 的錯(改 request 才會好),5xx 是 server 的錯(retry 可能有用 — 搭配 exponential backoff)。
Common Ports
| Port | Protocol / Service | Transport |
|---|---|---|
| 22 | SSH | TCP |
| 25 | SMTP | TCP |
| 53 | DNS | UDP(大查詢/zone transfer 用 TCP) |
| 80 | HTTP | TCP |
| 123 | NTP | UDP |
| 443 | HTTPS(HTTP/3 走 UDP 443) | TCP / UDP |
| 3306 | MySQL | TCP |
| 5432 | PostgreSQL | TCP |
| 6379 | Redis | TCP |
| 9092 | Kafka | TCP |
| 27017 | MongoDB | TCP |
Real-World Use Cases
Case 1: 即時詐欺偵測告警 — WebSocket 還是 SSE?
你負責信用卡詐欺偵測系統的 alert console:model 偵測到可疑交易後,風控人員的 dashboard 要在一秒內看到告警並可以按「凍結交易」。
分析:告警推送本身是 server → client 單向,SSE 就夠;但「凍結交易」的操作是 client → server。操作頻率低的話,SSE(推播)+ 一般 REST API(操作)是最簡單的組合 — stateless、走純 HTTP、proxy/LB 友善、自帶重連。若之後演變成高頻雙向互動(例如即時協作標注、逐筆確認),才升級成 WebSocket,並要處理 sticky sessions 或用 pub/sub backplane(Redis)讓多台 server 共享 connection 狀態。
Interview follow-ups:
- SSE connection 斷線後怎麼保證告警不漏接?(Last-Event-ID + server 端 replay buffer)
- 10 萬個併發 dashboard connections,server 端怎麼擴展?(Connection 是 stateful — LB 用 least connections、事件經 Kafka/Redis pub/sub 廣播到各 gateway node)
- 為什麼不用 short polling 每秒問一次?(99% 的 requests 空手而回,且最壞延遲 = polling 間隔)
Case 2: ML Model API 的 HTTPS 與 Latency 預算
你的房價預測 model 部署成 REST API,SLA 要求 p99 latency 低於 100ms。內部 service 呼叫時發現光是 connection 建立就吃掉數十毫秒。
分析:一次全新的 HTTPS request 要付 DNS + TCP handshake(1 RTT)+ TLS handshake(TLS 1.2 要 2 RTT,TLS 1.3 只要 1 RTT)才開始傳資料。跨 region 的 RTT 若是 30ms,光建連線就 60-90ms — 預算直接爆掉。解法:(1)connection pooling / keep-alive — client 重用連線,把 handshake 成本攤提到千百個 requests 上;(2)升級 TLS 1.3(省 1 RTT)或 HTTP/2(一條連線 multiplex 所有請求);(3)服務就近部署,縮短 RTT 本身;(4)內部流量可用 gRPC(HTTP/2 + protobuf)減少 serialization 開銷。
Interview follow-ups:
- Load balancer 做 TLS termination 的好處和風險?(後端省 CPU、憑證集中管理;但 LB 到後端若走明文,內網需另行保護或用 mTLS)
- 為什麼 p99 比 mean latency 更重要?(尾端延遲決定 SLA 與使用者體感;retry 與 timeout 策略都看 tail)
- 如果 model server 偶爾回 504,client 該怎麼辦?(Timeout + exponential backoff retry + circuit breaker,且只 retry idempotent requests)
Case 3: 推薦系統的 CDN 與 DNS-Based Routing
你的推薦系統服務全球用戶:台灣用戶抱怨首頁推薦載入慢。追查發現所有 requests 都打到美國的 origin server。
分析:分兩層處理。靜態資源(商品圖、JS bundle)交給 CDN — 用戶請求被導到最近的 edge node,cache hit 直接回傳,RTT 從 150ms 降到 10ms。動態的推薦 API 則用 GeoDNS:同一個 domain,DNS 依 resolver 位置回傳最近 region 的 IP(台灣用戶拿到東京 data center 的 A record)。搭配短 TTL,region 故障時能快速把流量切走。個人化推薦結果不能整頁 cache,但 candidate embeddings、熱門榜單這類半靜態資料可以放 edge cache 或 regional Redis,只把最後的 ranking 留在 region 內計算。
Interview follow-ups:
- GeoDNS 判斷位置的盲點?(看的是 resolver 的 IP 不是用戶的 IP — 用戶用 8.8.8.8 時可能誤判;EDNS Client Subnet 可緩解)
- CDN cache 個人化內容的策略?(不 cache 整頁;切分 cacheable 片段 + client-side 組裝,或用 cache key 加上 segment 維度)
- DNS failover 為什麼不夠即時?(各層 cache 尊重 TTL 的程度不一,總有殘留流量 — 關鍵服務還要搭配 anycast 或 LB health check)
Hands-on: Networking in Python
TCP Client and Server with socket
import socket
# --- Server: listen, accept, echo back ---
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("0.0.0.0", 9000)) # bind to port 9000
server.listen(5) # backlog of pending connections
conn, addr = server.accept() # blocks until 3-way handshake completes
data = conn.recv(1024) # read up to 1024 bytes
conn.sendall(b"ACK: " + data) # reliable, ordered send
conn.close()
# --- Client: connect and send ---
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 9000)) # triggers SYN / SYN-ACK / ACK
client.sendall(b"feature_vector_123")
reply = client.recv(1024) # blocks until server responds
client.close()
DNS Lookup
import socket
# Simple forward lookup (A record) using the OS resolver
ip = socket.gethostbyname("example.com") # "93.184.216.34"
# Full resolution: all address families, includes AAAA if available
infos = socket.getaddrinfo("example.com", 443, proto=socket.IPPROTO_TCP)
# With dnspython: query specific record types and inspect TTL
import dns.resolver
answers = dns.resolver.resolve("example.com", "A")
ttl = answers.rrset.ttl # cache lifetime in seconds
records = [rdata.address for rdata in answers]
mx_answers = dns.resolver.resolve("example.com", "MX")
mail_hosts = [(r.preference, str(r.exchange)) for r in mx_answers]
Consuming an SSE Stream with httpx
import httpx
# Server-Sent Events: one long-lived HTTP response, events separated by blank lines
# Typical for LLM token streaming and real-time alert feeds
with httpx.stream("GET", "https://api.example.com/alerts/stream",
headers={"Accept": "text/event-stream"},
timeout=None) as response:
for line in response.iter_lines():
if line.startswith("data: "):
event_payload = line[len("data: "):] # one pushed event
# process alert / token here
SSE Endpoint on the Server Side (FastAPI)
import asyncio
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def alert_stream():
# Generator yielding SSE-formatted events as alerts arrive
while True:
alert = await get_next_alert() # e.g. from a Redis pub/sub queue
payload = json.dumps({"txn_id": alert.txn_id, "score": alert.score})
yield "data: " + payload + "\n\n" # SSE frame: "data: ...\n\n"
@app.get("/alerts/stream")
async def stream_alerts():
return StreamingResponse(alert_stream(), media_type="text/event-stream")
Timeouts, Retries, and Connection Reuse for a Model API Client
import httpx
# Connection pooling: reuse TCP + TLS across requests (avoids handshake cost)
client = httpx.Client(
base_url="https://model-api.internal",
timeout=httpx.Timeout(connect=1.0, read=0.2, write=0.5, pool=1.0),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
)
def predict_with_retry(features, max_retries=2):
# Retry only on transient 5xx; backoff doubles each attempt
for attempt in range(max_retries + 1):
try:
resp = client.post("/predict", json={"features": features})
if resp.status_code == 200:
return resp.json()
if resp.status_code in (502, 503, 504) and attempt < max_retries:
continue # transient upstream failure
resp.raise_for_status() # 4xx: do not retry, fix the request
except httpx.ReadTimeout:
if attempt == max_retries:
raise
Interview Signals
What interviewers listen for:
- 你能把「輸入 URL 之後」講成有層次的流程,並在任一步 zoom in(DNS 階層、handshake 細節、render pipeline)
- 你分得清兩層 head-of-line blocking — HTTP/2 解決 application 層、HTTP/3 才解決 transport 層
- 你知道 TLS 中 asymmetric 只負責 handshake,資料傳輸走 symmetric encryption
- 你選 real-time 技術時會先問「單向還是雙向、頻率多高」,而不是無腦 WebSocket
- 你能把 networking 決策接回 business 需求:latency 預算、SLA、failover、成本
Practice
Flashcards
Flashcards (1/10)
輸入 URL 到頁面顯示,中間經過哪些步驟?
(1)解析 URL(2)逐層查 cache(browser/OS/router/ISP)(3)DNS resolution:resolver → root → TLD → authoritative 拿到 IP(4)TCP 3-way handshake(5)TLS handshake(HTTPS)(6)送 HTTP request、收 response(7)Browser 解析 HTML/CSS/JS,建 DOM → render tree → paint。
Quiz
DNS resolution 中,回答「.com 的 server 在哪裡」的是誰?