Split View: 개발자를 위한 네트워크 기초 완전 정복: TCP/IP, HTTP, DNS, TLS부터 gRPC, WebSocket까지
개발자를 위한 네트워크 기초 완전 정복: TCP/IP, HTTP, DNS, TLS부터 gRPC, WebSocket까지
- 1. 왜 개발자에게 네트워크 지식이 필수인가
- 2. TCP vs UDP 심화
- 3. IP, 서브넷, 라우팅
- 4. DNS 완전 정복
- 5. HTTP 진화: 1.0 에서 1.1, 2, 3까지
- 6. HTTPS와 TLS 1.3
- 7. REST vs GraphQL vs gRPC vs WebSocket
- 8. CDN과 로드 밸런싱
- 9. 실전 디버깅 도구
- 10. 면접 예상 질문 15선
- 11. 퀴즈
- 12. 참고 자료
1. 왜 개발자에게 네트워크 지식이 필수인가
면접에서 빠지지 않는 단골 주제
개발자 면접에서 "브라우저에 URL을 입력하면 무슨 일이 일어나는가?" 라는 질문은 거의 단골입니다. 이 질문 하나에 DNS, TCP, TLS, HTTP, 라우팅, 로드 밸런싱, 렌더링까지 전부 들어갑니다. 네트워크를 모르면 이 질문에 대한 깊이 있는 답변이 불가능합니다.
디버깅과 성능 최적화의 핵심
API가 느린데 원인을 모르겠다면? 네트워크 레벨에서 봐야 합니다. DNS 해석에 500ms가 걸리는지, TCP 연결 수립에 시간이 걸리는지, TLS 핸드셰이크가 병목인지, 아니면 서버 응답 자체가 느린지. 네트워크를 이해하면 curl -w 하나로 어디가 병목인지 즉시 파악할 수 있습니다.
아키텍처 설계의 기반
마이크로서비스 간 통신에 REST를 쓸지 gRPC를 쓸지, WebSocket이 필요한지 SSE로 충분한지, CDN을 어디에 배치할지 — 이 모든 판단의 기반이 네트워크 지식입니다.
OSI 7계층 vs TCP/IP 4계층 비교
실무에서는 OSI 7계층보다 TCP/IP 4계층을 더 자주 사용합니다. 아래 비교표를 참고하세요.
| TCP/IP 4계층 | OSI 7계층 | 프로토콜 예시 | 역할 |
|---|---|---|---|
| 응용 계층 (Application) | 응용 (7), 표현 (6), 세션 (5) | HTTP, FTP, SMTP, DNS, gRPC | 사용자 데이터 처리 |
| 전송 계층 (Transport) | 전송 (4) | TCP, UDP | 포트 기반 프로세스 간 통신 |
| 인터넷 계층 (Internet) | 네트워크 (3) | IP, ICMP, ARP | IP 주소 기반 라우팅 |
| 네트워크 접근 계층 (Network Access) | 데이터링크 (2), 물리 (1) | Ethernet, Wi-Fi | 물리적 데이터 전송 |
면접 팁: "OSI 7계층을 설명하세요"라는 질문이 나오면, TCP/IP 4계층과의 매핑까지 함께 설명하면 차별화됩니다.
2. TCP vs UDP 심화
TCP: 신뢰성 있는 연결 지향 프로토콜
TCP(Transmission Control Protocol)는 데이터의 순서 보장, 손실 복구, 흐름 제어를 제공하는 프로토콜입니다.
3-Way Handshake (연결 수립)
클라이언트 서버
|--- SYN (seq=x) -------->|
|<-- SYN-ACK (seq=y, ack=x+1) ---|
|--- ACK (ack=y+1) ------>|
| 연결 수립 완료 |
- SYN: 클라이언트가 서버에 연결 요청 (시퀀스 번호 x 전송)
- SYN-ACK: 서버가 요청을 수락하고 자신의 시퀀스 번호 y와 함께 응답
- ACK: 클라이언트가 확인 응답을 보내고 연결 수립 완료
4-Way Termination (연결 종료)
클라이언트 서버
|--- FIN ----------------->|
|<-- ACK ------------------|
|<-- FIN ------------------|
|--- ACK ----------------->|
| TIME_WAIT (2MSL) |
연결 종료 시 4단계가 필요한 이유는 양방향 스트림을 각각 독립적으로 종료하기 때문입니다. TIME_WAIT 상태는 지연된 패킷이 새 연결에 영향을 주지 않도록 보호하는 역할을 합니다.
흐름 제어 (Flow Control) — Sliding Window
수신자의 버퍼가 넘치지 않도록 **윈도우 크기(Window Size)**를 통해 한 번에 보낼 수 있는 데이터 양을 조절합니다.
Sender Window:
[Sent & ACKed] [Sent, Not ACKed] [Can Send] [Cannot Send]
|<--- Window Size --->|
수신자는 ACK에 자신의 수신 윈도우(rwnd) 값을 포함하여 송신자에게 알려줍니다.
혼잡 제어 (Congestion Control)
네트워크 혼잡을 감지하고 전송 속도를 조절하는 메커니즘입니다.
- Slow Start: cwnd(congestion window)를 1 MSS에서 시작하여 지수적으로 증가
- Congestion Avoidance (AIMD): ssthresh 도달 후 선형적으로 증가, 패킷 손실 시 절반으로 감소
- Fast Retransmit: 3개의 중복 ACK 수신 시 타임아웃 전에 재전송
- Fast Recovery: Fast Retransmit 이후 Slow Start가 아닌 Congestion Avoidance로 진입
cwnd
^
| /\
| / \ /\
| / \ / \ /
| / \ / \ /
| / X \/
| / ssthresh
| /
| / Slow Start
|/__________________ time
Nagle 알고리즘과 TCP_NODELAY
Nagle 알고리즘은 작은 패킷을 모아서 한 번에 전송하여 네트워크 효율을 높입니다. 하지만 실시간 애플리케이션(게임, 트레이딩)에서는 지연이 문제가 됩니다.
// Nagle 알고리즘 비활성화
int flag = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
UDP: 비연결형 프로토콜
UDP(User Datagram Protocol)는 연결 설정 없이 데이터그램을 전송합니다. 신뢰성은 없지만, 오버헤드가 적고 빠릅니다.
UDP 사용 사례:
- DNS 질의: 단일 요청-응답, 빠른 응답이 중요
- 온라인 게임: 약간의 패킷 손실보다 낮은 지연이 중요
- 실시간 스트리밍: 음성/영상에서 재전송은 의미 없음
- QUIC (HTTP/3): UDP 위에 신뢰성을 자체 구현
TCP vs UDP 비교표
| 특성 | TCP | UDP |
|---|---|---|
| 연결 방식 | 연결 지향 (3-Way Handshake) | 비연결형 |
| 신뢰성 | 보장 (재전송, 순서 보장) | 비보장 |
| 순서 보장 | 있음 | 없음 |
| 흐름/혼잡 제어 | 있음 | 없음 |
| 헤더 크기 | 20바이트 | 8바이트 |
| 속도 | 상대적으로 느림 | 빠름 |
| 사용 사례 | HTTP, FTP, SMTP, SSH | DNS, 게임, 스트리밍, QUIC |
3. IP, 서브넷, 라우팅
IPv4 vs IPv6 비교
| 특성 | IPv4 | IPv6 |
|---|---|---|
| 주소 길이 | 32비트 (4옥텟) | 128비트 (8그룹) |
| 주소 예시 | 192.168.1.1 | 2001:0db8:85a3::8a2e:0370:7334 |
| 주소 개수 | 약 43억 개 | 사실상 무한 |
| NAT 필요 | 필수적 | 불필요 |
| IPsec | 선택 | 기본 내장 |
| 헤더 | 가변 길이 | 고정 40바이트 |
CIDR 표기법과 서브넷 마스크
CIDR(Classless Inter-Domain Routing)은 IP 주소 뒤에 슬래시와 프리픽스 길이를 붙여 네트워크를 표현합니다.
192.168.1.0/24
├── 네트워크 부분: 192.168.1 (24비트)
└── 호스트 부분: 0~255 (8비트, 256개 주소 중 사용 가능 254개)
10.0.0.0/16
├── 네트워크 부분: 10.0 (16비트)
└── 호스트 부분: 0.0~255.255 (16비트, 65,536개 주소)
자주 사용하는 CIDR:
| CIDR | 서브넷 마스크 | 사용 가능 호스트 | 용도 |
|---|---|---|---|
| /32 | 255.255.255.255 | 1 | 단일 호스트 |
| /24 | 255.255.255.0 | 254 | 일반적인 서브넷 |
| /16 | 255.255.0.0 | 65,534 | 대규모 네트워크 |
| /8 | 255.0.0.0 | 16,777,214 | 클래스 A |
NAT(Network Address Translation)
사설 IP 주소를 공인 IP 주소로 변환하는 기술입니다.
사설 네트워크 NAT 라우터 인터넷
[192.168.1.10] ---+
[192.168.1.11] ---+--- [NAT] --- [203.0.113.1] --- [서버]
[192.168.1.12] ---+
사설 IP 대역 (RFC 1918):
10.0.0.0/8(10.0.0.0 ~ 10.255.255.255)172.16.0.0/12(172.16.0.0 ~ 172.31.255.255)192.168.0.0/16(192.168.0.0 ~ 192.168.255.255)
Docker/K8s 네트워킹과의 연결
Docker 네트워킹:
bridge: 기본 네트워크, 컨테이너 간 통신host: 호스트 네트워크 직접 사용overlay: 다중 호스트 간 컨테이너 통신 (Docker Swarm)none: 네트워크 비활성화
Kubernetes 네트워킹 원칙:
- 모든 Pod는 고유한 IP를 가진다
- 모든 Pod는 NAT 없이 다른 Pod와 통신할 수 있다
- 모든 Node의 에이전트는 모든 Pod와 통신할 수 있다
K8s 클러스터
┌─────────────────────────────────────┐
│ Node 1 Node 2 │
│ ┌─────────┐ ┌─────────┐ │
│ │ Pod A │ │ Pod C │ │
│ │ 10.1.1.2│◄────────►│ 10.1.2.3│ │
│ ├─────────┤ ├─────────┤ │
│ │ Pod B │ │ Pod D │ │
│ │ 10.1.1.3│ │ 10.1.2.4│ │
│ └─────────┘ └─────────┘ │
│ CNI Plugin (Calico/Flannel) │
└─────────────────────────────────────┘
Kubernetes에서는 CNI(Container Network Interface) 플러그인(Calico, Flannel, Cilium 등)이 Pod 간 네트워킹을 담당합니다. Service 리소스는 L4 로드 밸런서 역할을 하며, Ingress는 L7 라우팅을 제공합니다.
4. DNS 완전 정복
DNS 질의 과정
DNS(Domain Name System)는 도메인 이름(예: www.example.com)을 IP 주소로 변환하는 분산 데이터베이스 시스템입니다.
사용자 → 로컬 DNS 캐시 → 재귀적 리졸버 → 루트 서버 → TLD 서버 → 권한 서버
↓ ↓ ↓
"." 루트 ".com" TLD "example.com"
→ IP: 93.184.216.34
재귀적 질의 (Recursive Query):
- 클라이언트가 재귀적 리졸버에게 최종 답을 요청
- 리졸버가 루트 → TLD → 권한 서버를 차례로 질의하여 IP를 반환
반복적 질의 (Iterative Query):
- 각 서버가 다음에 질의할 서버를 알려주는 방식
- 리졸버가 직접 각 서버에 순차적으로 질의
DNS 레코드 종류
| 레코드 | 용도 | 예시 |
|---|---|---|
| A | 도메인 → IPv4 주소 | example.com → 93.184.216.34 |
| AAAA | 도메인 → IPv6 주소 | example.com → 2606:2800:220:1:... |
| CNAME | 도메인 → 다른 도메인 (별칭) | www.example.com → example.com |
| MX | 메일 서버 지정 | example.com → mail.example.com (priority 10) |
| TXT | 텍스트 정보 (SPF, DKIM 등) | v=spf1 include:_spf.google.com ~all |
| NS | 네임서버 지정 | example.com → ns1.example.com |
| SOA | 도메인 권한 시작점 | 시리얼, 리프레시, 만료 등 관리 정보 |
| SRV | 서비스 위치 정보 | 포트, 가중치 포함 서비스 디스커버리 |
| PTR | IP → 도메인 (역방향) | 34.216.184.93 → example.com |
TTL과 캐싱 전략
TTL(Time To Live)은 DNS 레코드가 캐시에 유지되는 시간(초)입니다.
| TTL 값 | 적합한 상황 |
|---|---|
| 60초 (1분) | 인프라 마이그레이션 직전, 빠른 전환 필요 |
| 300초 (5분) | 일반적인 웹 서비스 |
| 3600초 (1시간) | 변경이 드문 서비스 |
| 86400초 (1일) | 거의 변경되지 않는 레코드 |
실전 팁: DNS 마이그레이션 전에 TTL을 먼저 낮추고(예: 60초), 충분한 시간이 지난 후 IP를 변경하면 전환 시 다운타임을 최소화할 수 있습니다.
DNS over HTTPS (DoH) / DNS over TLS (DoT)
기존 DNS는 평문(UDP 53번 포트)으로 전송되어 도청 및 변조에 취약합니다.
| 특성 | 전통적 DNS | DoH | DoT |
|---|---|---|---|
| 프로토콜 | UDP/53 | HTTPS/443 | TLS/853 |
| 암호화 | 없음 | TLS | TLS |
| 프라이버시 | 낮음 | 높음 | 높음 |
| 방화벽 우회 | 쉽게 차단 | HTTPS와 구분 어려움 | 전용 포트로 차단 가능 |
dig/nslookup 실전 명령어
# A 레코드 조회
dig example.com A
# 특정 DNS 서버로 조회
dig @8.8.8.8 example.com
# 전체 질의 과정 추적
dig +trace example.com
# 간략한 결과만 출력
dig +short example.com
# MX 레코드 조회
dig example.com MX
# 역방향 DNS 조회
dig -x 8.8.8.8
# nslookup 사용
nslookup example.com
nslookup -type=MX example.com 8.8.8.8
# DNS 캐시 클리어 (macOS)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
5. HTTP 진화: 1.0 에서 1.1, 2, 3까지
HTTP/1.0: 요청마다 새 연결
초기 HTTP는 매 요청마다 TCP 연결을 새로 수립했습니다. HTML 페이지 하나에 이미지 10개가 있으면 TCP 연결을 11번 맺어야 했습니다.
[TCP 연결] → [요청] → [응답] → [TCP 종료]
[TCP 연결] → [요청] → [응답] → [TCP 종료]
... 반복
HTTP/1.1: Keep-Alive와 파이프라이닝
주요 개선사항:
- Persistent Connection (Keep-Alive): 하나의 TCP 연결에서 여러 요청/응답 처리
- Pipelining: 응답을 기다리지 않고 여러 요청을 연속 전송 (하지만 HOL blocking 문제)
- Host 헤더: 하나의 IP에서 여러 도메인 호스팅 가능 (가상 호스팅)
- Chunked Transfer Encoding: 응답 크기를 모르는 상태에서 스트리밍 전송
[TCP 연결] → [요청1] → [응답1] → [요청2] → [응답2] → ... → [TCP 종료]
HOL(Head-of-Line) Blocking 문제: 첫 번째 응답이 느리면 뒤의 모든 요청이 대기해야 합니다.
HTTP/2: 멀티플렉싱 혁명
단일 TCP 연결
┌──────────────────────────────────┐
│ Stream 1: GET /index.html │
│ Stream 3: GET /style.css │ ← 동시에 처리
│ Stream 5: GET /script.js │
│ Stream 7: GET /image.png │
└──────────────────────────────────┘
핵심 기능:
-
멀티플렉싱(Multiplexing): 하나의 TCP 연결에서 여러 스트림을 동시에 처리. HTTP/1.1의 HOL blocking을 해결합니다.
-
Header Compression (HPACK): 반복되는 헤더를 정적/동적 테이블로 압축하여 헤더 오버헤드를 크게 줄입니다.
-
Server Push: 서버가 클라이언트의 요청 없이 리소스를 미리 전송합니다.
-
Binary Framing: 텍스트 기반이 아닌 바이너리 프레임으로 전송하여 파싱 효율 향상.
-
Stream Priority: 스트림 간 우선순위를 설정하여 중요한 리소스를 먼저 전송.
HTTP/3: QUIC (UDP 기반)
HTTP/3는 TCP 대신 UDP 기반의 QUIC 프로토콜을 사용합니다.
HTTP/2 스택 HTTP/3 스택
┌──────────┐ ┌──────────┐
│ HTTP/2 │ │ HTTP/3 │
├──────────┤ ├──────────┤
│ TLS 1.2+│ │ QUIC │ ← TLS 1.3 내장
├──────────┤ ├──────────┤
│ TCP │ │ UDP │
├──────────┤ ├──────────┤
│ IP │ │ IP │
└──────────┘ └──────────┘
HTTP/3의 핵심 장점:
- 0-RTT 연결: 이전에 연결한 서버에 대해 첫 패킷부터 데이터 전송 가능
- HOL Blocking 완전 제거: 각 스트림이 독립적으로 관리되므로 하나의 스트림 손실이 다른 스트림에 영향을 주지 않음
- Connection Migration: 네트워크가 변경되어도(Wi-Fi에서 셀룰러) 연결이 유지됨
HTTP 버전 비교표
| 특성 | HTTP/1.0 | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|---|
| 전송 프로토콜 | TCP | TCP | TCP | QUIC (UDP) |
| 연결 방식 | 요청당 연결 | Keep-Alive | 멀티플렉싱 | 멀티플렉싱 |
| HOL Blocking | TCP + HTTP | TCP + HTTP | TCP 수준만 | 없음 |
| 헤더 압축 | 없음 | 없음 | HPACK | QPACK |
| 서버 푸시 | 없음 | 없음 | 지원 | 지원 |
| 암호화 | 선택 | 선택 | 사실상 필수 | 필수 (TLS 1.3) |
| 연결 수립 | 1-RTT (TCP) | 1-RTT (TCP) | 1-RTT (TCP+TLS) | 0-RTT 가능 |
언제 무엇을 사용하는가?
- HTTP/1.1: 레거시 시스템, 단순 API
- HTTP/2: 대부분의 웹사이트와 API (현재 기본)
- HTTP/3: 모바일 환경, 글로벌 서비스, 낮은 지연이 중요한 경우
6. HTTPS와 TLS 1.3
대칭 vs 비대칭 암호화
| 구분 | 대칭 암호화 | 비대칭 암호화 |
|---|---|---|
| 키 | 동일한 키로 암호화/복호화 | 공개키로 암호화, 개인키로 복호화 |
| 속도 | 빠름 | 느림 |
| 알고리즘 | AES, ChaCha20 | RSA, ECDSA, Ed25519 |
| 용도 | 데이터 암호화 | 키 교환, 디지털 서명 |
TLS는 비대칭 암호화로 세션 키를 교환한 후, 대칭 암호화로 실제 데이터를 암호화합니다.
TLS 1.2 vs TLS 1.3 핸드셰이크
TLS 1.2 (2-RTT):
클라이언트 서버
|--- ClientHello ----------------->| RTT 1
|<-- ServerHello, Certificate -----|
|<-- ServerKeyExchange, Done ------|
|--- ClientKeyExchange, Finished ->| RTT 2
|<-- Finished ---------------------|
|===== 암호화 통신 시작 ===========|
TLS 1.3 (1-RTT, 0-RTT 가능):
클라이언트 서버
|--- ClientHello + KeyShare ------>| RTT 1
|<-- ServerHello + KeyShare -------|
|<-- EncryptedExtensions, Cert ----|
|<-- Finished ---------------------|
|--- Finished -------------------->|
|===== 암호화 통신 시작 ===========|
TLS 1.3의 핵심 개선:
| 특성 | TLS 1.2 | TLS 1.3 |
|---|---|---|
| 핸드셰이크 RTT | 2-RTT | 1-RTT (0-RTT 가능) |
| 키 교환 | RSA 또는 ECDHE | ECDHE만 (전방 비밀성 필수) |
| 암호 스위트 | 많은 옵션 (일부 취약) | 5개만 (모두 AEAD) |
| 0-RTT | 미지원 | 지원 (재방문 시) |
인증서와 CA
인증서 체인:
┌────────────────────┐
│ Root CA 인증서 │ ← 브라우저/OS에 내장
├────────────────────┤
│ Intermediate CA │ ← Root CA가 서명
├────────────────────┤
│ 서버 인증서 │ ← Intermediate CA가 서명
└────────────────────┘
- Let's Encrypt: 무료 DV(Domain Validation) 인증서, 90일 유효, 자동 갱신 (certbot)
- OV/EV 인증서: 조직 검증/확장 검증으로 더 높은 신뢰 수준
OCSP Stapling
기존 OCSP는 브라우저가 직접 CA에 인증서 유효성을 확인했지만, 이는 느리고 프라이버시 문제가 있었습니다. OCSP Stapling은 서버가 CA로부터 미리 받은 응답을 클라이언트에게 전달합니다.
# Nginx OCSP Stapling 설정
server {
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
}
mTLS (상호 TLS 인증)
일반 TLS에서는 클라이언트만 서버를 인증합니다. mTLS에서는 서버도 클라이언트의 인증서를 확인합니다.
일반 TLS:
클라이언트 → 서버 인증서 검증 (단방향)
mTLS:
클라이언트 → 서버 인증서 검증
서버 → 클라이언트 인증서 검증 (양방향)
mTLS 사용 사례:
- Kubernetes 서비스 메시 (Istio, Linkerd)에서 서비스 간 통신
- Zero Trust 아키텍처에서 서비스 인증
- API 게이트웨이에서 클라이언트 인증
7. REST vs GraphQL vs gRPC vs WebSocket
REST (Representational State Transfer)
REST는 HTTP 메서드(GET, POST, PUT, DELETE)와 리소스 URI를 기반으로 한 아키텍처 스타일입니다.
Richardson 성숙도 모델:
| 레벨 | 설명 | 예시 |
|---|---|---|
| Level 0 | 단일 URI, 단일 메서드 | POST /api (RPC 스타일) |
| Level 1 | 리소스별 URI | /users, /orders |
| Level 2 | HTTP 메서드 활용 | GET /users, POST /users |
| Level 3 | HATEOAS (하이퍼미디어) | 응답에 관련 링크 포함 |
HATEOAS 예시:
{
"id": 1,
"name": "John",
"links": [
{ "rel": "self", "href": "/users/1" },
{ "rel": "orders", "href": "/users/1/orders" },
{ "rel": "update", "href": "/users/1", "method": "PUT" }
]
}
GraphQL
GraphQL은 클라이언트가 필요한 데이터만 정확히 요청할 수 있는 쿼리 언어입니다.
# 클라이언트가 필요한 필드만 요청
query {
user(id: 1) {
name
email
orders(last: 5) {
id
total
items {
name
price
}
}
}
}
장점:
- Overfetching / Underfetching 해결
- 단일 엔드포인트
- 강력한 타입 시스템
단점:
- N+1 문제 (DataLoader로 해결)
- 캐싱이 어려움 (URL 기반 캐시 불가)
- 복잡한 쿼리로 인한 서버 부하
gRPC
gRPC는 Google이 개발한 HTTP/2 기반의 고성능 RPC 프레임워크입니다. Protocol Buffers를 사용하여 바이너리 직렬화를 수행합니다.
// user.proto
syntax = "proto3";
service UserService {
rpc GetUser (GetUserRequest) returns (User);
rpc ListUsers (ListUsersRequest) returns (stream User);
rpc CreateUsers (stream CreateUserRequest) returns (CreateUsersResponse);
rpc Chat (stream ChatMessage) returns (stream ChatMessage);
}
message GetUserRequest {
int32 id = 1;
}
message User {
int32 id = 1;
string name = 2;
string email = 3;
}
gRPC 4가지 통신 패턴:
| 패턴 | 설명 | 사용 사례 |
|---|---|---|
| Unary | 1 요청 → 1 응답 | 일반 API 호출 |
| Server Streaming | 1 요청 → N 응답 | 대량 데이터 조회 |
| Client Streaming | N 요청 → 1 응답 | 파일 업로드 |
| Bidirectional Streaming | N 요청 ↔ N 응답 | 채팅, 실시간 게임 |
WebSocket
WebSocket은 HTTP 업그레이드를 통해 전이중 양방향 통신을 제공합니다.
HTTP 업그레이드:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
→ 이후 양방향 프레임 기반 통신
사용 사례:
- 실시간 채팅
- 주식/암호화폐 실시간 시세
- 온라인 게임
- 협업 도구 (Google Docs 등)
SSE (Server-Sent Events)
SSE는 서버에서 클라이언트로의 단방향 실시간 스트리밍입니다. WebSocket보다 간단하며, HTTP 위에서 동작합니다.
// 서버 (Node.js)
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
})
setInterval(() => {
res.write('data: ' + JSON.stringify(data) + '\n\n')
}, 1000)
// 클라이언트
const eventSource = new EventSource('/events')
eventSource.onmessage = (event) => {
console.log(JSON.parse(event.data))
}
통신 방식 비교표
| 특성 | REST | GraphQL | gRPC | WebSocket | SSE |
|---|---|---|---|---|---|
| 프로토콜 | HTTP/1.1+ | HTTP/1.1+ | HTTP/2 | TCP (HTTP 업그레이드) | HTTP/1.1+ |
| 데이터 형식 | JSON/XML | JSON | Protobuf (바이너리) | 자유 형식 | 텍스트 |
| 방향 | 요청-응답 | 요청-응답 | 양방향 스트리밍 | 양방향 | 서버→클라이언트 |
| 성능 | 보통 | 보통 | 높음 | 높음 | 보통 |
| 브라우저 지원 | 완벽 | 완벽 | 제한적 (gRPC-Web) | 완벽 | 완벽 |
| 사용 시점 | 공개 API, CRUD | 복잡한 데이터 관계 | 내부 마이크로서비스 | 양방향 실시간 | 단방향 알림 |
8. CDN과 로드 밸런싱
CDN 동작 원리
CDN(Content Delivery Network)은 전 세계에 분산된 엣지 서버에 콘텐츠를 캐싱하여 사용자에게 가장 가까운 서버에서 콘텐츠를 제공합니다.
사용자 (서울) → 엣지 서버 (서울) → [캐시 히트] → 즉시 응답
[캐시 미스] → 오리진 서버 (미국) → 캐시 저장 → 응답
핵심 기술:
- Anycast: 동일한 IP를 여러 엣지 서버가 공유하고, BGP 라우팅으로 가장 가까운 서버로 라우팅
- Edge Caching: Cache-Control 헤더를 기반으로 콘텐츠를 캐싱
- Cache-Control 헤더:
public, max-age=31536000, immutable(1년 캐시, 불변 콘텐츠)
Cache-Control 주요 지시어:
| 지시어 | 설명 |
|---|---|
public | CDN 및 중간 프록시에서 캐시 가능 |
private | 브라우저에서만 캐시 |
no-cache | 캐시하되 매번 서버에 유효성 검증 |
no-store | 어떤 캐시도 저장하지 않음 |
max-age=N | N초 동안 캐시 유효 |
s-maxage=N | CDN/프록시에서 N초 동안 캐시 유효 |
immutable | 캐시 기간 내 재검증하지 않음 |
CDN 비교
| 특성 | Cloudflare | AWS CloudFront | Fastly | Akamai |
|---|---|---|---|---|
| PoP 수 | 310+ | 600+ | 100+ | 4,000+ |
| 무료 플랜 | 있음 | 없음 | 없음 | 없음 |
| DDoS 보호 | 기본 내장 | AWS Shield | 기본 | 기본 |
| Edge Computing | Workers | Lambda@Edge | Compute@Edge | EdgeWorkers |
| 실시간 퍼지 | 즉시 | 수 초 | 150ms | 5초 |
| 강점 | 가성비, 보안 | AWS 생태계 | 실시간 퍼지 | 엔터프라이즈 |
로드 밸런서: L4 vs L7
| 특성 | L4 (Transport) | L7 (Application) |
|---|---|---|
| 동작 계층 | TCP/UDP | HTTP/HTTPS |
| 라우팅 기준 | IP, 포트 | URL, 헤더, 쿠키 |
| SSL 종료 | 불가 (패스스루) | 가능 |
| 성능 | 더 빠름 | 더 유연함 |
| WebSocket | 지원 | 지원 |
| 예시 | AWS NLB, Nginx (stream) | AWS ALB, Nginx (http) |
로드 밸런싱 알고리즘
| 알고리즘 | 설명 | 적합한 경우 |
|---|---|---|
| Round Robin | 순서대로 분배 | 서버 성능이 동일한 경우 |
| Weighted Round Robin | 가중치에 따라 분배 | 서버 성능이 다른 경우 |
| Least Connections | 연결 수가 가장 적은 서버로 | 요청 처리 시간이 다양한 경우 |
| IP Hash | 클라이언트 IP 기반 고정 서버 | 세션 유지가 필요한 경우 |
| Consistent Hashing | 해시 링 기반 분배 | 서버 추가/제거 시 최소 재분배 |
Consistent Hashing의 장점:
해시 링:
0 ─── Server A ─── Server B ─── Server C ─── 2^32
↑ ↑ ↑
Key1, Key4 Key2, Key5 Key3, Key6
Server D 추가 시:
0 ─── Server A ── Server D ── Server B ─── Server C ─── 2^32
↑ ↑ ↑ ↑
Key1, Key4 Key2 Key5 Key3, Key6
→ Server D와 Server B 사이의 키만 재분배 (전체 아님)
주요 로드 밸런서 제품
# Nginx L7 로드 밸런서 설정 예시
upstream backend {
least_conn;
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
server backend3.example.com:8080 weight=1;
server backend4.example.com:8080 backup;
}
server {
listen 443 ssl;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
9. 실전 디버깅 도구
curl — HTTP 요청의 스위스 아미 나이프
# 기본 GET 요청
curl https://api.example.com/users
# 상세 정보 출력 (TLS 핸드셰이크 포함)
curl -v https://api.example.com/users
# POST 요청 (JSON)
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'
# 응답 시간 분석 (핵심!)
curl -w "\n
DNS 조회: %{time_namelookup}s\n
TCP 연결: %{time_connect}s\n
TLS 핸드셰이크: %{time_appconnect}s\n
첫 바이트: %{time_starttransfer}s\n
총 시간: %{time_total}s\n" \
-o /dev/null -s https://api.example.com/users
# HTTP/2로 요청
curl --http2 https://api.example.com/users
# 헤더만 출력
curl -I https://api.example.com/users
tcpdump — 패킷 캡처
# 특정 포트의 TCP 패킷 캡처
sudo tcpdump -i eth0 port 80 -n
# 특정 호스트와의 통신 캡처
sudo tcpdump host 192.168.1.100
# 패킷을 파일로 저장 (Wireshark에서 분석)
sudo tcpdump -i eth0 -w capture.pcap port 443
# SYN 패킷만 캡처 (연결 시작 추적)
sudo tcpdump 'tcp[tcpflags] & (tcp-syn) != 0'
# HTTP 요청만 캡처
sudo tcpdump -A 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
netstat / ss / lsof — 연결 상태 확인
# 열린 포트 확인 (ss가 netstat보다 빠름)
ss -tulnp
# 특정 포트 사용 프로세스 확인
ss -tulnp | grep :8080
lsof -i :8080
# TIME_WAIT 상태 연결 수 확인
ss -s
ss -tan state time-wait | wc -l
# ESTABLISHED 연결 목록
ss -tan state established
traceroute / mtr — 경로 추적
# 기본 경로 추적
traceroute example.com
# TCP 기반 traceroute (ICMP가 차단된 경우)
traceroute -T -p 443 example.com
# mtr (traceroute + ping 결합, 실시간 모니터링)
mtr example.com
# 특정 횟수만 실행
mtr -c 10 --report example.com
Chrome DevTools Network 탭 활용
주요 분석 포인트:
- Waterfall 차트: 각 요청의 DNS, TCP, TLS, TTFB(Time To First Byte) 시간 확인
- Size vs Transferred: 압축 효과 확인 (gzip, br)
- Initiator: 어떤 리소스가 해당 요청을 트리거했는지
- Timing 탭: Queued, Stalled, DNS, Initial Connection, SSL, TTFB, Content Download 세분화
- Throttling: Slow 3G, Fast 3G 등으로 느린 네트워크 시뮬레이션
10. 면접 예상 질문 15선
기본 개념
Q1. "브라우저에 URL을 입력하면 어떤 일이 일어나는지 설명해주세요."
- URL 파싱 (프로토콜, 도메인, 경로)
- DNS 조회 (브라우저 캐시 → OS 캐시 → 리졸버 → 루트 → TLD → 권한 서버)
- TCP 3-Way Handshake
- TLS 핸드셰이크 (HTTPS인 경우)
- HTTP 요청 전송
- 서버 처리 및 HTTP 응답
- 브라우저 렌더링 (HTML 파싱, DOM 구성, CSSOM, Layout, Paint)
Q2. "TCP와 UDP의 차이를 설명하고, 각각 언제 사용하나요?"
TCP는 신뢰성 있는 연결 지향 프로토콜로 데이터 순서 보장과 재전송을 제공합니다. 웹, 이메일, 파일 전송에 사용합니다. UDP는 비연결형으로 빠르지만 신뢰성이 없습니다. DNS, 실시간 스트리밍, 게임에 사용합니다.
Q3. "HTTP/2와 HTTP/3의 주요 차이점은?"
HTTP/2는 TCP 위에서 멀티플렉싱을 지원하지만 TCP 수준의 HOL blocking이 남아있습니다. HTTP/3는 UDP 기반 QUIC를 사용하여 HOL blocking을 완전히 제거하고, 0-RTT 연결과 Connection Migration을 지원합니다.
심화 질문
Q4. "TCP 3-Way Handshake를 SYN Flood 공격과 연관지어 설명해주세요."
SYN Flood는 대량의 SYN 패킷을 보내 서버의 반개방(half-open) 연결 테이블을 가득 채우는 DoS 공격입니다. 방어 방법으로 SYN Cookies, SYN Proxy, Rate Limiting이 있습니다.
Q5. "CORS란 무엇이고, 왜 필요한가요?"
Cross-Origin Resource Sharing는 브라우저의 동일 출처 정책(Same-Origin Policy)을 안전하게 완화하는 메커니즘입니다. 서버가 Access-Control-Allow-Origin 헤더로 허용할 출처를 명시합니다.
Q6. "DNS의 TTL 값이 낮으면 어떤 장단점이 있나요?"
장점: DNS 변경 시 빠른 전파, 장애 복구 시 빠른 전환. 단점: DNS 서버 부하 증가, 질의 빈도 증가로 인한 지연.
Q7. "TLS 1.3이 1.2보다 빠른 이유는?"
TLS 1.3은 핸드셰이크를 1-RTT로 줄이고 (1.2는 2-RTT), 0-RTT 재개를 지원합니다. 또한 취약한 암호 스위트를 제거하고 키 교환을 단순화했습니다.
Q8. "REST API에서 멱등성(Idempotency)이란?"
동일한 요청을 여러 번 수행해도 결과가 같은 것입니다. GET, PUT, DELETE는 멱등적이고, POST는 그렇지 않습니다. 결제 API에서 중복 요청을 방지하기 위해 Idempotency Key를 사용합니다.
설계/실무 질문
Q9. "WebSocket과 SSE를 비교하고 언제 각각을 사용하나요?"
WebSocket은 양방향, SSE는 서버에서 클라이언트로의 단방향입니다. 채팅이나 게임은 WebSocket, 알림이나 실시간 피드는 SSE가 적합합니다.
Q10. "CDN을 사용하면 어떤 이점이 있나요?"
지연 시간 감소(지리적 근접), 오리진 서버 부하 감소, DDoS 방어, 글로벌 가용성 향상, 대역폭 비용 절감.
Q11. "L4 vs L7 로드 밸런서의 차이는?"
L4는 TCP/UDP 수준에서 IP와 포트 기반으로 라우팅하여 빠르지만 제한적입니다. L7은 HTTP 헤더, URL, 쿠키 기반으로 라우팅하여 더 유연하지만 오버헤드가 있습니다.
Q12. "마이크로서비스 간 통신에 gRPC를 쓰면 어떤 장점이 있나요?"
HTTP/2 기반 멀티플렉싱, Protobuf 바이너리 직렬화로 높은 성능, 강력한 타입 시스템, 양방향 스트리밍, 다중 언어 지원, K8s 환경에서 서비스 메시와 잘 통합됩니다.
Q13. "Consistent Hashing이란 무엇이고, 왜 사용하나요?"
서버 추가/제거 시 전체 키를 재분배하지 않고 해시 링에서 인접한 키만 이동시키는 기법입니다. 분산 캐시(Memcached, Redis Cluster)와 로드 밸런서에서 사용합니다.
Q14. "NAT가 필요한 이유와 동작 방식을 설명하세요."
IPv4 주소 부족으로 사설 IP를 사용하고, NAT를 통해 공인 IP로 변환합니다. 출발지/목적지 IP와 포트를 변환하며, 사설 네트워크의 보안을 높여줍니다.
Q15. "HTTP Keep-Alive와 WebSocket의 차이는?"
Keep-Alive는 TCP 연결을 유지하지만 여전히 요청-응답 모델입니다. WebSocket은 프로토콜 업그레이드 후 양방향 전이중 통신이 가능합니다.
11. 퀴즈
지금까지 배운 내용을 점검해봅시다.
Q1. TCP 3-Way Handshake의 세 단계를 순서대로 말하세요.
정답: SYN → SYN-ACK → ACK
- 클라이언트가 SYN 패킷을 서버에 전송 (시퀀스 번호 포함)
- 서버가 SYN-ACK 패킷으로 응답 (자신의 시퀀스 번호 + 클라이언트 시퀀스 번호 확인)
- 클라이언트가 ACK 패킷을 보내고 연결 수립 완료
이 과정에서 양쪽 모두 시퀀스 번호를 교환하여 이후 데이터 순서를 추적할 수 있게 됩니다.
Q2. HTTP/2의 멀티플렉싱이 해결하는 HTTP/1.1의 문제는 무엇인가요?
정답: HOL(Head-of-Line) Blocking
HTTP/1.1에서는 하나의 연결에서 요청이 순서대로 처리되므로, 앞선 응답이 느리면 뒤의 모든 요청이 대기해야 합니다. HTTP/2는 하나의 TCP 연결에서 여러 스트림을 동시에 처리(멀티플렉싱)하여 이 문제를 해결합니다. 다만 TCP 수준의 HOL blocking은 여전히 존재하며, 이는 HTTP/3(QUIC)에서 완전히 해결됩니다.
Q3. DNS 레코드 중 CNAME과 A 레코드의 차이는 무엇인가요?
정답:
- A 레코드: 도메인을 IPv4 주소에 직접 매핑합니다. (예: example.com → 93.184.216.34)
- CNAME 레코드: 도메인을 다른 도메인에 매핑하는 별칭입니다. (예: www.example.com → example.com)
CNAME은 체이닝이 가능하지만, 루트 도메인(Zone Apex)에는 사용할 수 없습니다. AWS Route 53의 ALIAS 레코드나 Cloudflare의 CNAME flattening으로 이 제한을 우회할 수 있습니다.
Q4. TLS 1.3에서 0-RTT가 가능한 원리를 간단히 설명하세요.
정답:
이전 TLS 세션에서 교환한 PSK(Pre-Shared Key)를 기반으로 재방문 시 ClientHello와 함께 첫 패킷에 암호화된 데이터를 포함할 수 있습니다. 서버는 저장된 PSK로 즉시 복호화하여 핸드셰이크 완료 전에 데이터를 처리합니다. 다만 0-RTT 데이터는 재전송 공격(Replay Attack)에 취약하므로 멱등적 요청에만 사용해야 합니다.
Q5. Consistent Hashing에서 서버가 추가되었을 때 왜 전체 키 재분배가 발생하지 않나요?
정답:
Consistent Hashing은 해시 링 구조를 사용합니다. 각 서버와 키가 해시 링 위의 특정 위치에 매핑되며, 각 키는 시계 방향으로 가장 가까운 서버에 할당됩니다. 서버가 추가되면 그 서버와 이전 서버 사이에 있는 키만 새 서버로 이동합니다. 전체 키 중 K/N개(K: 전체 키 수, N: 서버 수)만 재분배되므로 영향이 최소화됩니다. 가상 노드(Virtual Node)를 사용하면 부하 분산을 더욱 균등하게 할 수 있습니다.
12. 참고 자료
공식 문서 및 RFC
- RFC 793 - Transmission Control Protocol
- RFC 768 - User Datagram Protocol
- RFC 9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC 9114 - HTTP/3
- RFC 8446 - TLS 1.3
- RFC 7540 - HTTP/2
- RFC 1035 - Domain Names - Implementation and Specification
서적
- Computer Networking: A Top-Down Approach (Kurose, Ross) - 네트워크 기초 교과서
- TCP/IP Illustrated, Volume 1 (W. Richard Stevens) - TCP/IP 바이블
- High Performance Browser Networking (Ilya Grigorik) - 무료 온라인 서적, 웹 성능 최적화
온라인 자료
- MDN Web Docs - HTTP - HTTP 가이드
- Cloudflare Learning Center - 네트워크 개념 시각적 설명
- Julia Evans - Networking Zines - 네트워킹 개념을 만화로 쉽게 설명
- gRPC Official Documentation - gRPC 공식 문서
- Beej's Guide to Network Programming - 네트워크 프로그래밍 가이드
- DNS 101 - How DNS Works - DNS 동작 원리 시각화
- Wireshark User's Guide - Wireshark 사용법
네트워크는 개발자의 기본 소양입니다. 이 글에서 다룬 내용을 한 번에 다 외울 필요는 없습니다. 실무에서 API 성능 문제를 디버깅하거나, 시스템 설계를 논의하거나, 면접을 준비할 때 이 글을 다시 찾아보세요. 각 프로토콜의 "왜"를 이해하면, 새로운 기술이 나와도 빠르게 적응할 수 있습니다.
Networking Fundamentals Every Developer Must Know: TCP/IP, HTTP, DNS, TLS to gRPC and WebSocket
- 1. Why Networking Knowledge Is Essential for Developers
- 2. TCP vs UDP Deep Dive
- 3. IP, Subnets, and Routing
- 4. DNS Mastery
- 5. HTTP Evolution: From 1.0 to 1.1, 2, and 3
- 6. HTTPS and TLS 1.3
- 7. REST vs GraphQL vs gRPC vs WebSocket
- 8. CDN and Load Balancing
- 9. Practical Debugging Tools
- 10. Top 15 Interview Questions
- 11. Quiz
- 12. References
1. Why Networking Knowledge Is Essential for Developers
A Staple Interview Question
In developer interviews, the question "What happens when you type a URL into the browser?" comes up constantly. This single question covers DNS, TCP, TLS, HTTP, routing, load balancing, and rendering. Without networking knowledge, you cannot provide a deep answer.
The Core of Debugging and Performance Optimization
When your API is slow but you do not know why, you need to look at the network level. Is DNS resolution taking 500ms? Is TCP connection establishment the bottleneck? Is the TLS handshake slowing things down, or is the server response itself slow? Understanding networking lets you pinpoint bottlenecks instantly with a single curl -w command.
The Foundation of Architecture Design
Should you use REST or gRPC for microservice communication? Do you need WebSocket or is SSE sufficient? Where should the CDN be placed? All these decisions are grounded in networking knowledge.
OSI 7-Layer vs TCP/IP 4-Layer Comparison
In practice, the TCP/IP 4-layer model is used far more often than the OSI 7-layer model. Here is a comparison.
| TCP/IP 4-Layer | OSI 7-Layer | Protocol Examples | Role |
|---|---|---|---|
| Application | Application (7), Presentation (6), Session (5) | HTTP, FTP, SMTP, DNS, gRPC | User data processing |
| Transport | Transport (4) | TCP, UDP | Port-based inter-process communication |
| Internet | Network (3) | IP, ICMP, ARP | IP address-based routing |
| Network Access | Data Link (2), Physical (1) | Ethernet, Wi-Fi | Physical data transmission |
Interview tip: When asked to explain the OSI 7-layer model, also map it to the TCP/IP 4-layer model. This demonstrates deeper understanding.
2. TCP vs UDP Deep Dive
TCP: Reliable Connection-Oriented Protocol
TCP (Transmission Control Protocol) provides ordered delivery, loss recovery, and flow control.
3-Way Handshake (Connection Establishment)
Client Server
|--- SYN (seq=x) ------------>|
|<-- SYN-ACK (seq=y, ack=x+1) ---|
|--- ACK (ack=y+1) ---------->|
| Connection Established |
- SYN: Client sends a connection request with sequence number x
- SYN-ACK: Server acknowledges and responds with its own sequence number y
- ACK: Client confirms, and the connection is established
4-Way Termination (Connection Teardown)
Client Server
|--- FIN ------------------>|
|<-- ACK -------------------|
|<-- FIN -------------------|
|--- ACK ------------------>|
| TIME_WAIT (2MSL) |
Four steps are needed because each direction of the bidirectional stream must be terminated independently. The TIME_WAIT state protects against delayed packets affecting new connections.
Flow Control — Sliding Window
The receiver controls how much data the sender can transmit at once through the Window Size, preventing buffer overflow.
Sender Window:
[Sent & ACKed] [Sent, Not ACKed] [Can Send] [Cannot Send]
|<--- Window Size --->|
The receiver includes its receive window (rwnd) value in ACK packets to inform the sender.
Congestion Control
Mechanisms for detecting network congestion and adjusting transmission speed.
- Slow Start: cwnd (congestion window) starts at 1 MSS and grows exponentially
- Congestion Avoidance (AIMD): Linear increase after reaching ssthresh, halves on packet loss
- Fast Retransmit: Retransmits before timeout upon receiving 3 duplicate ACKs
- Fast Recovery: Enters Congestion Avoidance instead of Slow Start after Fast Retransmit
cwnd
^
| /\
| / \ /\
| / \ / \ /
| / \ / \ /
| / X \/
| / ssthresh
| /
| / Slow Start
|/__________________ time
Nagle's Algorithm and TCP_NODELAY
Nagle's Algorithm batches small packets together to improve network efficiency. However, in real-time applications (games, trading), the added latency becomes problematic.
// Disable Nagle's Algorithm
int flag = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
UDP: Connectionless Protocol
UDP (User Datagram Protocol) sends datagrams without establishing a connection. It lacks reliability but has minimal overhead and is fast.
UDP Use Cases:
- DNS queries: Single request-response, fast response matters
- Online gaming: Low latency matters more than occasional packet loss
- Real-time streaming: Retransmission is meaningless for audio/video
- QUIC (HTTP/3): Builds reliability on top of UDP
TCP vs UDP Comparison
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (3-Way Handshake) | Connectionless |
| Reliability | Guaranteed (retransmission, ordering) | Not guaranteed |
| Ordering | Yes | No |
| Flow/Congestion Control | Yes | No |
| Header Size | 20 bytes | 8 bytes |
| Speed | Relatively slower | Fast |
| Use Cases | HTTP, FTP, SMTP, SSH | DNS, Gaming, Streaming, QUIC |
3. IP, Subnets, and Routing
IPv4 vs IPv6 Comparison
| Property | IPv4 | IPv6 |
|---|---|---|
| Address Length | 32 bits (4 octets) | 128 bits (8 groups) |
| Address Example | 192.168.1.1 | 2001:0db8:85a3::8a2e:0370:7334 |
| Address Count | About 4.3 billion | Practically unlimited |
| NAT Required | Essential | Not needed |
| IPsec | Optional | Built-in |
| Header | Variable length | Fixed 40 bytes |
CIDR Notation and Subnet Masks
CIDR (Classless Inter-Domain Routing) represents networks by appending a slash and prefix length to the IP address.
192.168.1.0/24
├── Network portion: 192.168.1 (24 bits)
└── Host portion: 0-255 (8 bits, 256 addresses, 254 usable)
10.0.0.0/16
├── Network portion: 10.0 (16 bits)
└── Host portion: 0.0-255.255 (16 bits, 65,536 addresses)
Commonly Used CIDRs:
| CIDR | Subnet Mask | Usable Hosts | Purpose |
|---|---|---|---|
| /32 | 255.255.255.255 | 1 | Single host |
| /24 | 255.255.255.0 | 254 | Typical subnet |
| /16 | 255.255.0.0 | 65,534 | Large network |
| /8 | 255.0.0.0 | 16,777,214 | Class A |
NAT (Network Address Translation)
NAT translates private IP addresses to public IP addresses.
Private Network NAT Router Internet
[192.168.1.10] ---+
[192.168.1.11] ---+--- [NAT] --- [203.0.113.1] --- [Server]
[192.168.1.12] ---+
Private IP Ranges (RFC 1918):
10.0.0.0/8(10.0.0.0 to 10.255.255.255)172.16.0.0/12(172.16.0.0 to 172.31.255.255)192.168.0.0/16(192.168.0.0 to 192.168.255.255)
Connection to Docker/K8s Networking
Docker Networking:
bridge: Default network for container-to-container communicationhost: Shares the host network directlyoverlay: Multi-host container communication (Docker Swarm)none: Networking disabled
Kubernetes Networking Principles:
- Every Pod gets a unique IP address
- Every Pod can communicate with any other Pod without NAT
- Agents on every Node can communicate with all Pods
K8s Cluster
+-------------------------------------+
| Node 1 Node 2 |
| +---------+ +---------+ |
| | Pod A | | Pod C | |
| | 10.1.1.2|<-------->| 10.1.2.3| |
| +---------+ +---------+ |
| | Pod B | | Pod D | |
| | 10.1.1.3| | 10.1.2.4| |
| +---------+ +---------+ |
| CNI Plugin (Calico/Flannel) |
+-------------------------------------+
In Kubernetes, CNI (Container Network Interface) plugins (Calico, Flannel, Cilium, etc.) handle Pod-to-Pod networking. Service resources act as L4 load balancers, while Ingress provides L7 routing.
4. DNS Mastery
DNS Query Process
DNS (Domain Name System) is a distributed database system that converts domain names (e.g., www.example.com) into IP addresses.
User -> Local DNS Cache -> Recursive Resolver -> Root Server -> TLD Server -> Authoritative Server
| | |
"." root ".com" TLD "example.com"
-> IP: 93.184.216.34
Recursive Query:
- The client asks the recursive resolver for the final answer
- The resolver queries Root, TLD, and Authoritative servers sequentially and returns the IP
Iterative Query:
- Each server tells the resolver where to query next
- The resolver queries each server sequentially on its own
DNS Record Types
| Record | Purpose | Example |
|---|---|---|
| A | Domain to IPv4 address | example.com -> 93.184.216.34 |
| AAAA | Domain to IPv6 address | example.com -> 2606:2800:220:1:... |
| CNAME | Domain to another domain (alias) | www.example.com -> example.com |
| MX | Mail server designation | example.com -> mail.example.com (priority 10) |
| TXT | Text information (SPF, DKIM, etc.) | v=spf1 include:_spf.google.com ~all |
| NS | Nameserver designation | example.com -> ns1.example.com |
| SOA | Start of Authority for domain | Serial, refresh, expiry, and admin info |
| SRV | Service location info | Service discovery with port and weight |
| PTR | IP to domain (reverse) | 34.216.184.93 -> example.com |
TTL and Caching Strategies
TTL (Time To Live) is the duration in seconds that a DNS record is cached.
| TTL Value | Suitable Scenario |
|---|---|
| 60s (1 min) | Right before infrastructure migration, fast switchover needed |
| 300s (5 min) | General web services |
| 3600s (1 hour) | Services that rarely change |
| 86400s (1 day) | Records that almost never change |
Practical tip: Before DNS migration, lower the TTL first (e.g., to 60 seconds), wait for the old TTL to expire, then change the IP. This minimizes downtime during the transition.
DNS over HTTPS (DoH) / DNS over TLS (DoT)
Traditional DNS is transmitted in plaintext (UDP port 53), making it vulnerable to eavesdropping and tampering.
| Property | Traditional DNS | DoH | DoT |
|---|---|---|---|
| Protocol | UDP/53 | HTTPS/443 | TLS/853 |
| Encryption | None | TLS | TLS |
| Privacy | Low | High | High |
| Firewall Bypass | Easily blocked | Hard to distinguish from HTTPS | Dedicated port, can be blocked |
dig/nslookup Practical Commands
# A record lookup
dig example.com A
# Query specific DNS server
dig @8.8.8.8 example.com
# Trace the entire query process
dig +trace example.com
# Brief output only
dig +short example.com
# MX record lookup
dig example.com MX
# Reverse DNS lookup
dig -x 8.8.8.8
# nslookup usage
nslookup example.com
nslookup -type=MX example.com 8.8.8.8
# Clear DNS cache (macOS)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
5. HTTP Evolution: From 1.0 to 1.1, 2, and 3
HTTP/1.0: A New Connection Per Request
Early HTTP established a new TCP connection for every single request. If an HTML page had 10 images, you needed 11 TCP connections.
[TCP Connect] -> [Request] -> [Response] -> [TCP Close]
[TCP Connect] -> [Request] -> [Response] -> [TCP Close]
... repeat
HTTP/1.1: Keep-Alive and Pipelining
Key improvements:
- Persistent Connection (Keep-Alive): Multiple requests/responses over a single TCP connection
- Pipelining: Send multiple requests without waiting for responses (but HOL blocking issue)
- Host Header: Multiple domains on a single IP (virtual hosting)
- Chunked Transfer Encoding: Streaming transmission when response size is unknown
[TCP Connect] -> [Req1] -> [Res1] -> [Req2] -> [Res2] -> ... -> [TCP Close]
HOL (Head-of-Line) Blocking Problem: If the first response is slow, all subsequent requests must wait.
HTTP/2: The Multiplexing Revolution
Single TCP Connection
+----------------------------------+
| Stream 1: GET /index.html |
| Stream 3: GET /style.css | <- Processed simultaneously
| Stream 5: GET /script.js |
| Stream 7: GET /image.png |
+----------------------------------+
Core Features:
-
Multiplexing: Multiple streams processed simultaneously over a single TCP connection. Solves HTTP/1.1 HOL blocking.
-
Header Compression (HPACK): Compresses repeated headers using static/dynamic tables, greatly reducing header overhead.
-
Server Push: Server proactively sends resources before the client requests them.
-
Binary Framing: Transmits binary frames instead of text, improving parsing efficiency.
-
Stream Priority: Sets priorities between streams to deliver important resources first.
HTTP/3: QUIC (UDP-Based)
HTTP/3 uses the QUIC protocol based on UDP instead of TCP.
HTTP/2 Stack HTTP/3 Stack
+----------+ +----------+
| HTTP/2 | | HTTP/3 |
+----------+ +----------+
| TLS 1.2+ | | QUIC | <- TLS 1.3 built-in
+----------+ +----------+
| TCP | | UDP |
+----------+ +----------+
| IP | | IP |
+----------+ +----------+
Key Advantages of HTTP/3:
- 0-RTT Connection: Can send data from the first packet for previously connected servers
- Complete HOL Blocking Elimination: Each stream is independent, so loss in one stream does not affect others
- Connection Migration: Connection persists even when network changes (Wi-Fi to cellular)
HTTP Version Comparison
| Property | HTTP/1.0 | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|---|
| Transport Protocol | TCP | TCP | TCP | QUIC (UDP) |
| Connection Model | Connection per request | Keep-Alive | Multiplexing | Multiplexing |
| HOL Blocking | TCP + HTTP | TCP + HTTP | TCP level only | None |
| Header Compression | None | None | HPACK | QPACK |
| Server Push | None | None | Supported | Supported |
| Encryption | Optional | Optional | Practically required | Required (TLS 1.3) |
| Connection Setup | 1-RTT (TCP) | 1-RTT (TCP) | 1-RTT (TCP+TLS) | 0-RTT possible |
When to use what?
- HTTP/1.1: Legacy systems, simple APIs
- HTTP/2: Most websites and APIs (current default)
- HTTP/3: Mobile environments, global services, low latency requirements
6. HTTPS and TLS 1.3
Symmetric vs Asymmetric Encryption
| Category | Symmetric Encryption | Asymmetric Encryption |
|---|---|---|
| Keys | Same key for encryption/decryption | Public key encrypts, private key decrypts |
| Speed | Fast | Slow |
| Algorithms | AES, ChaCha20 | RSA, ECDSA, Ed25519 |
| Purpose | Data encryption | Key exchange, digital signatures |
TLS exchanges session keys using asymmetric encryption, then encrypts actual data with symmetric encryption.
TLS 1.2 vs TLS 1.3 Handshake
TLS 1.2 (2-RTT):
Client Server
|--- ClientHello ----------------->| RTT 1
|<-- ServerHello, Certificate -----|
|<-- ServerKeyExchange, Done ------|
|--- ClientKeyExchange, Finished ->| RTT 2
|<-- Finished ---------------------|
|===== Encrypted Communication ====|
TLS 1.3 (1-RTT, 0-RTT possible):
Client Server
|--- ClientHello + KeyShare ------>| RTT 1
|<-- ServerHello + KeyShare -------|
|<-- EncryptedExtensions, Cert ----|
|<-- Finished ---------------------|
|--- Finished -------------------->|
|===== Encrypted Communication ====|
Key Improvements in TLS 1.3:
| Property | TLS 1.2 | TLS 1.3 |
|---|---|---|
| Handshake RTT | 2-RTT | 1-RTT (0-RTT possible) |
| Key Exchange | RSA or ECDHE | ECDHE only (forward secrecy mandatory) |
| Cipher Suites | Many options (some vulnerable) | Only 5 (all AEAD) |
| 0-RTT | Not supported | Supported (return visits) |
Certificates and CAs
Certificate Chain:
+--------------------+
| Root CA Cert | <- Embedded in browser/OS
+--------------------+
| Intermediate CA | <- Signed by Root CA
+--------------------+
| Server Cert | <- Signed by Intermediate CA
+--------------------+
- Let's Encrypt: Free DV (Domain Validation) certificates, 90-day validity, auto-renewal (certbot)
- OV/EV Certificates: Organization Validation/Extended Validation for higher trust levels
OCSP Stapling
Traditional OCSP required the browser to check certificate validity directly with the CA, which was slow and had privacy issues. OCSP Stapling lets the server deliver a pre-fetched CA response to the client.
# Nginx OCSP Stapling configuration
server {
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
}
mTLS (Mutual TLS Authentication)
In standard TLS, only the client verifies the server. In mTLS, the server also verifies the client's certificate.
Standard TLS:
Client -> Verifies server certificate (one-way)
mTLS:
Client -> Verifies server certificate
Server -> Verifies client certificate (two-way)
mTLS Use Cases:
- Kubernetes service meshes (Istio, Linkerd) for inter-service communication
- Service authentication in Zero Trust architectures
- Client authentication at API gateways
7. REST vs GraphQL vs gRPC vs WebSocket
REST (Representational State Transfer)
REST is an architectural style based on HTTP methods (GET, POST, PUT, DELETE) and resource URIs.
Richardson Maturity Model:
| Level | Description | Example |
|---|---|---|
| Level 0 | Single URI, single method | POST /api (RPC style) |
| Level 1 | URIs per resource | /users, /orders |
| Level 2 | HTTP methods utilized | GET /users, POST /users |
| Level 3 | HATEOAS (Hypermedia) | Related links included in responses |
HATEOAS Example:
{
"id": 1,
"name": "John",
"links": [
{ "rel": "self", "href": "/users/1" },
{ "rel": "orders", "href": "/users/1/orders" },
{ "rel": "update", "href": "/users/1", "method": "PUT" }
]
}
GraphQL
GraphQL is a query language that lets clients request exactly the data they need.
# Client requests only needed fields
query {
user(id: 1) {
name
email
orders(last: 5) {
id
total
items {
name
price
}
}
}
}
Advantages:
- Solves overfetching and underfetching
- Single endpoint
- Strong type system
Disadvantages:
- N+1 problem (solved with DataLoader)
- Caching is difficult (URL-based caching not possible)
- Complex queries can burden the server
gRPC
gRPC is a high-performance RPC framework developed by Google, based on HTTP/2. It uses Protocol Buffers for binary serialization.
// user.proto
syntax = "proto3";
service UserService {
rpc GetUser (GetUserRequest) returns (User);
rpc ListUsers (ListUsersRequest) returns (stream User);
rpc CreateUsers (stream CreateUserRequest) returns (CreateUsersResponse);
rpc Chat (stream ChatMessage) returns (stream ChatMessage);
}
message GetUserRequest {
int32 id = 1;
}
message User {
int32 id = 1;
string name = 2;
string email = 3;
}
gRPC 4 Communication Patterns:
| Pattern | Description | Use Case |
|---|---|---|
| Unary | 1 request -> 1 response | Standard API calls |
| Server Streaming | 1 request -> N responses | Large data retrieval |
| Client Streaming | N requests -> 1 response | File uploads |
| Bidirectional Streaming | N requests, N responses (bidirectional) | Chat, real-time gaming |
WebSocket
WebSocket provides full-duplex bidirectional communication through an HTTP upgrade.
HTTP Upgrade:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-> Full-duplex frame-based communication follows
Use Cases:
- Real-time chat
- Stock/crypto live prices
- Online gaming
- Collaboration tools (Google Docs, etc.)
SSE (Server-Sent Events)
SSE provides unidirectional real-time streaming from server to client. It is simpler than WebSocket and runs over HTTP.
// Server (Node.js)
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
})
setInterval(() => {
res.write('data: ' + JSON.stringify(data) + '\n\n')
}, 1000)
// Client
const eventSource = new EventSource('/events')
eventSource.onmessage = (event) => {
console.log(JSON.parse(event.data))
}
Communication Method Comparison
| Property | REST | GraphQL | gRPC | WebSocket | SSE |
|---|---|---|---|---|---|
| Protocol | HTTP/1.1+ | HTTP/1.1+ | HTTP/2 | TCP (HTTP Upgrade) | HTTP/1.1+ |
| Data Format | JSON/XML | JSON | Protobuf (binary) | Free-form | Text |
| Direction | Request-Response | Request-Response | Bidirectional Streaming | Bidirectional | Server to Client |
| Performance | Moderate | Moderate | High | High | Moderate |
| Browser Support | Full | Full | Limited (gRPC-Web) | Full | Full |
| When to Use | Public APIs, CRUD | Complex data relationships | Internal microservices | Bidirectional real-time | Unidirectional notifications |
8. CDN and Load Balancing
How CDNs Work
A CDN (Content Delivery Network) caches content on globally distributed edge servers and serves it from the location closest to the user.
User (Seoul) -> Edge Server (Seoul) -> [Cache Hit] -> Immediate response
[Cache Miss] -> Origin Server (US) -> Cache stored -> Response
Core Technologies:
- Anycast: Multiple edge servers share the same IP, and BGP routing directs traffic to the nearest one
- Edge Caching: Caches content based on Cache-Control headers
- Cache-Control Header:
public, max-age=31536000, immutable(1-year cache, immutable content)
Key Cache-Control Directives:
| Directive | Description |
|---|---|
public | Cacheable by CDNs and intermediate proxies |
private | Cacheable only by the browser |
no-cache | Cache but validate with server every time |
no-store | Do not cache at all |
max-age=N | Cache valid for N seconds |
s-maxage=N | Cache valid for N seconds on CDN/proxies |
immutable | Do not revalidate within cache period |
CDN Comparison
| Property | Cloudflare | AWS CloudFront | Fastly | Akamai |
|---|---|---|---|---|
| PoP Count | 310+ | 600+ | 100+ | 4,000+ |
| Free Tier | Yes | No | No | No |
| DDoS Protection | Built-in | AWS Shield | Built-in | Built-in |
| Edge Computing | Workers | Lambda@Edge | Compute@Edge | EdgeWorkers |
| Real-time Purge | Instant | Seconds | 150ms | 5 seconds |
| Strength | Value, Security | AWS ecosystem | Real-time purge | Enterprise |
Load Balancer: L4 vs L7
| Property | L4 (Transport) | L7 (Application) |
|---|---|---|
| OSI Layer | TCP/UDP | HTTP/HTTPS |
| Routing Criteria | IP, Port | URL, Headers, Cookies |
| SSL Termination | Not possible (passthrough) | Possible |
| Performance | Faster | More flexible |
| WebSocket | Supported | Supported |
| Examples | AWS NLB, Nginx (stream) | AWS ALB, Nginx (http) |
Load Balancing Algorithms
| Algorithm | Description | Best For |
|---|---|---|
| Round Robin | Distributes sequentially | Servers with equal capacity |
| Weighted Round Robin | Distributes by weight | Servers with different capacities |
| Least Connections | Routes to server with fewest connections | Variable request processing times |
| IP Hash | Fixed server based on client IP | When session persistence is needed |
| Consistent Hashing | Hash ring-based distribution | Minimal redistribution when adding/removing servers |
Advantages of Consistent Hashing:
Hash Ring:
0 --- Server A --- Server B --- Server C --- 2^32
^ ^ ^
Key1, Key4 Key2, Key5 Key3, Key6
When Server D is added:
0 --- Server A -- Server D -- Server B --- Server C --- 2^32
^ ^ ^ ^
Key1, Key4 Key2 Key5 Key3, Key6
-> Only keys between Server D and Server B are redistributed (not all)
Major Load Balancer Products
# Nginx L7 Load Balancer Configuration Example
upstream backend {
least_conn;
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
server backend3.example.com:8080 weight=1;
server backend4.example.com:8080 backup;
}
server {
listen 443 ssl;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
9. Practical Debugging Tools
curl — The Swiss Army Knife of HTTP Requests
# Basic GET request
curl https://api.example.com/users
# Verbose output (including TLS handshake)
curl -v https://api.example.com/users
# POST request (JSON)
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'
# Response timing analysis (essential!)
curl -w "\n
DNS Lookup: %{time_namelookup}s\n
TCP Connect: %{time_connect}s\n
TLS Handshake: %{time_appconnect}s\n
First Byte: %{time_starttransfer}s\n
Total Time: %{time_total}s\n" \
-o /dev/null -s https://api.example.com/users
# Request with HTTP/2
curl --http2 https://api.example.com/users
# Headers only
curl -I https://api.example.com/users
tcpdump — Packet Capture
# Capture TCP packets on specific port
sudo tcpdump -i eth0 port 80 -n
# Capture communication with specific host
sudo tcpdump host 192.168.1.100
# Save packets to file (analyze in Wireshark)
sudo tcpdump -i eth0 -w capture.pcap port 443
# Capture only SYN packets (track connection starts)
sudo tcpdump 'tcp[tcpflags] & (tcp-syn) != 0'
# Capture HTTP requests only
sudo tcpdump -A 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
netstat / ss / lsof — Connection State
# Check open ports (ss is faster than netstat)
ss -tulnp
# Find process using specific port
ss -tulnp | grep :8080
lsof -i :8080
# Check TIME_WAIT connection count
ss -s
ss -tan state time-wait | wc -l
# List ESTABLISHED connections
ss -tan state established
traceroute / mtr — Route Tracing
# Basic route tracing
traceroute example.com
# TCP-based traceroute (when ICMP is blocked)
traceroute -T -p 443 example.com
# mtr (traceroute + ping combined, real-time monitoring)
mtr example.com
# Run specific number of times
mtr -c 10 --report example.com
Chrome DevTools Network Tab
Key Analysis Points:
- Waterfall Chart: Check DNS, TCP, TLS, TTFB (Time To First Byte) timing for each request
- Size vs Transferred: Verify compression effectiveness (gzip, br)
- Initiator: Which resource triggered the request
- Timing Tab: Breakdown of Queued, Stalled, DNS, Initial Connection, SSL, TTFB, Content Download
- Throttling: Simulate slow networks with Slow 3G, Fast 3G, etc.
10. Top 15 Interview Questions
Basic Concepts
Q1. "What happens when you type a URL into the browser?"
- URL parsing (protocol, domain, path)
- DNS lookup (browser cache, OS cache, resolver, root, TLD, authoritative server)
- TCP 3-Way Handshake
- TLS handshake (if HTTPS)
- HTTP request sent
- Server processing and HTTP response
- Browser rendering (HTML parsing, DOM construction, CSSOM, Layout, Paint)
Q2. "Explain the difference between TCP and UDP, and when to use each."
TCP is a reliable connection-oriented protocol that provides ordered delivery and retransmission. Used for web, email, and file transfer. UDP is connectionless, fast but unreliable. Used for DNS, real-time streaming, and gaming.
Q3. "What are the main differences between HTTP/2 and HTTP/3?"
HTTP/2 supports multiplexing over TCP but still has TCP-level HOL blocking. HTTP/3 uses UDP-based QUIC to completely eliminate HOL blocking, and supports 0-RTT connections and Connection Migration.
Advanced Questions
Q4. "Explain TCP 3-Way Handshake in relation to SYN Flood attacks."
SYN Flood sends massive SYN packets to fill the server's half-open connection table, causing a DoS attack. Defenses include SYN Cookies, SYN Proxy, and Rate Limiting.
Q5. "What is CORS and why is it needed?"
Cross-Origin Resource Sharing is a mechanism that safely relaxes the browser's Same-Origin Policy. The server specifies allowed origins via the Access-Control-Allow-Origin header.
Q6. "What are the pros and cons of a low DNS TTL value?"
Advantages: Fast propagation on DNS changes, quick failover during outages. Disadvantages: Increased DNS server load, more queries resulting in higher latency.
Q7. "Why is TLS 1.3 faster than TLS 1.2?"
TLS 1.3 reduces the handshake to 1-RTT (vs 2-RTT for 1.2) and supports 0-RTT resumption. It also removes vulnerable cipher suites and simplifies key exchange.
Q8. "What is idempotency in REST APIs?"
Performing the same request multiple times produces the same result. GET, PUT, DELETE are idempotent; POST is not. Idempotency Keys are used in payment APIs to prevent duplicate requests.
Design/Practical Questions
Q9. "Compare WebSocket and SSE, and when to use each."
WebSocket is bidirectional; SSE is server-to-client only. Chat or gaming needs WebSocket; notifications or live feeds suit SSE.
Q10. "What benefits does using a CDN provide?"
Reduced latency (geographic proximity), reduced origin server load, DDoS protection, improved global availability, and bandwidth cost savings.
Q11. "What is the difference between L4 and L7 load balancers?"
L4 routes at the TCP/UDP level based on IP and port — fast but limited. L7 routes based on HTTP headers, URLs, and cookies — more flexible but with more overhead.
Q12. "What advantages does gRPC offer for microservice communication?"
HTTP/2-based multiplexing, Protobuf binary serialization for high performance, strong type system, bidirectional streaming, multi-language support, and good integration with Kubernetes service meshes.
Q13. "What is Consistent Hashing and why is it used?"
Instead of redistributing all keys when servers are added/removed, only adjacent keys on the hash ring are moved. Used in distributed caches (Memcached, Redis Cluster) and load balancers.
Q14. "Explain why NAT is needed and how it works."
Due to IPv4 address exhaustion, private IPs are used internally, and NAT translates them to public IPs. It modifies source/destination IPs and ports, also enhancing private network security.
Q15. "What is the difference between HTTP Keep-Alive and WebSocket?"
Keep-Alive maintains the TCP connection but still uses the request-response model. WebSocket, after protocol upgrade, enables full-duplex bidirectional communication.
11. Quiz
Let us review what we have learned.
Q1. Name the three stages of the TCP 3-Way Handshake in order.
Answer: SYN, SYN-ACK, ACK
- The client sends a SYN packet to the server (with a sequence number)
- The server responds with a SYN-ACK packet (its own sequence number plus acknowledgment of the client's sequence number)
- The client sends an ACK packet, and the connection is established
During this process, both sides exchange sequence numbers to track data ordering for subsequent communication.
Q2. What HTTP/1.1 problem does HTTP/2 multiplexing solve?
Answer: HOL (Head-of-Line) Blocking
In HTTP/1.1, requests on a single connection are processed sequentially, so if the first response is slow, all subsequent requests must wait. HTTP/2 processes multiple streams simultaneously over a single TCP connection (multiplexing) to solve this. However, TCP-level HOL blocking still exists and is fully resolved only in HTTP/3 (QUIC).
Q3. What is the difference between CNAME and A records in DNS?
Answer:
- A Record: Directly maps a domain to an IPv4 address. (e.g., example.com to 93.184.216.34)
- CNAME Record: Maps a domain as an alias to another domain. (e.g., www.example.com to example.com)
CNAME supports chaining but cannot be used at the root domain (Zone Apex). AWS Route 53's ALIAS record or Cloudflare's CNAME flattening work around this limitation.
Q4. Briefly explain how 0-RTT is possible in TLS 1.3.
Answer:
Based on the PSK (Pre-Shared Key) exchanged during a previous TLS session, encrypted data can be included in the first packet alongside the ClientHello on return visits. The server decrypts it immediately using the stored PSK, processing data before the handshake completes. However, 0-RTT data is vulnerable to replay attacks and should only be used for idempotent requests.
Q5. Why does adding a server in Consistent Hashing not cause full key redistribution?
Answer:
Consistent Hashing uses a hash ring structure. Each server and key is mapped to a specific position on the hash ring, and each key is assigned to the nearest server in the clockwise direction. When a server is added, only keys between that server and the previous server are moved to the new server. Only K/N keys (K: total keys, N: servers) are redistributed, minimizing impact. Virtual nodes can be used for even more balanced load distribution.
12. References
Official Documentation and RFCs
- RFC 793 - Transmission Control Protocol
- RFC 768 - User Datagram Protocol
- RFC 9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC 9114 - HTTP/3
- RFC 8446 - TLS 1.3
- RFC 7540 - HTTP/2
- RFC 1035 - Domain Names - Implementation and Specification
Books
- Computer Networking: A Top-Down Approach (Kurose, Ross) - Networking fundamentals textbook
- TCP/IP Illustrated, Volume 1 (W. Richard Stevens) - The TCP/IP bible
- High Performance Browser Networking (Ilya Grigorik) - Free online book on web performance optimization
Online Resources
- MDN Web Docs - HTTP - HTTP guide
- Cloudflare Learning Center - Visual explanations of networking concepts
- Julia Evans - Networking Zines - Networking concepts explained through comics
- gRPC Official Documentation - gRPC official docs
- Beej's Guide to Network Programming - Network programming guide
- DNS 101 - How DNS Works - DNS visualization
- Wireshark User's Guide - Wireshark usage guide
Networking is a fundamental skill for developers. You do not need to memorize everything in this article at once. Revisit it when debugging API performance issues, discussing system design, or preparing for interviews. Once you understand the "why" behind each protocol, you can quickly adapt when new technologies emerge.