Skip to content
Published on

Networking Fundamentals Every Developer Must Know: TCP/IP, HTTP, DNS, TLS to gRPC and WebSocket

Authors

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-LayerOSI 7-LayerProtocol ExamplesRole
ApplicationApplication (7), Presentation (6), Session (5)HTTP, FTP, SMTP, DNS, gRPCUser data processing
TransportTransport (4)TCP, UDPPort-based inter-process communication
InternetNetwork (3)IP, ICMP, ARPIP address-based routing
Network AccessData Link (2), Physical (1)Ethernet, Wi-FiPhysical 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   |
  1. SYN: Client sends a connection request with sequence number x
  2. SYN-ACK: Server acknowledges and responds with its own sequence number y
  3. 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

PropertyTCPUDP
ConnectionConnection-oriented (3-Way Handshake)Connectionless
ReliabilityGuaranteed (retransmission, ordering)Not guaranteed
OrderingYesNo
Flow/Congestion ControlYesNo
Header Size20 bytes8 bytes
SpeedRelatively slowerFast
Use CasesHTTP, FTP, SMTP, SSHDNS, Gaming, Streaming, QUIC

3. IP, Subnets, and Routing

IPv4 vs IPv6 Comparison

PropertyIPv4IPv6
Address Length32 bits (4 octets)128 bits (8 groups)
Address Example192.168.1.12001:0db8:85a3::8a2e:0370:7334
Address CountAbout 4.3 billionPractically unlimited
NAT RequiredEssentialNot needed
IPsecOptionalBuilt-in
HeaderVariable lengthFixed 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:

CIDRSubnet MaskUsable HostsPurpose
/32255.255.255.2551Single host
/24255.255.255.0254Typical subnet
/16255.255.0.065,534Large network
/8255.0.0.016,777,214Class 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 communication
  • host: Shares the host network directly
  • overlay: Multi-host container communication (Docker Swarm)
  • none: Networking disabled

Kubernetes Networking Principles:

  1. Every Pod gets a unique IP address
  2. Every Pod can communicate with any other Pod without NAT
  3. 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

RecordPurposeExample
ADomain to IPv4 addressexample.com -> 93.184.216.34
AAAADomain to IPv6 addressexample.com -> 2606:2800:220:1:...
CNAMEDomain to another domain (alias)www.example.com -> example.com
MXMail server designationexample.com -> mail.example.com (priority 10)
TXTText information (SPF, DKIM, etc.)v=spf1 include:_spf.google.com ~all
NSNameserver designationexample.com -> ns1.example.com
SOAStart of Authority for domainSerial, refresh, expiry, and admin info
SRVService location infoService discovery with port and weight
PTRIP 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 ValueSuitable 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.

PropertyTraditional DNSDoHDoT
ProtocolUDP/53HTTPS/443TLS/853
EncryptionNoneTLSTLS
PrivacyLowHighHigh
Firewall BypassEasily blockedHard to distinguish from HTTPSDedicated 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:

  1. Multiplexing: Multiple streams processed simultaneously over a single TCP connection. Solves HTTP/1.1 HOL blocking.

  2. Header Compression (HPACK): Compresses repeated headers using static/dynamic tables, greatly reducing header overhead.

  3. Server Push: Server proactively sends resources before the client requests them.

  4. Binary Framing: Transmits binary frames instead of text, improving parsing efficiency.

  5. 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

PropertyHTTP/1.0HTTP/1.1HTTP/2HTTP/3
Transport ProtocolTCPTCPTCPQUIC (UDP)
Connection ModelConnection per requestKeep-AliveMultiplexingMultiplexing
HOL BlockingTCP + HTTPTCP + HTTPTCP level onlyNone
Header CompressionNoneNoneHPACKQPACK
Server PushNoneNoneSupportedSupported
EncryptionOptionalOptionalPractically requiredRequired (TLS 1.3)
Connection Setup1-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

CategorySymmetric EncryptionAsymmetric Encryption
KeysSame key for encryption/decryptionPublic key encrypts, private key decrypts
SpeedFastSlow
AlgorithmsAES, ChaCha20RSA, ECDSA, Ed25519
PurposeData encryptionKey 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:

PropertyTLS 1.2TLS 1.3
Handshake RTT2-RTT1-RTT (0-RTT possible)
Key ExchangeRSA or ECDHEECDHE only (forward secrecy mandatory)
Cipher SuitesMany options (some vulnerable)Only 5 (all AEAD)
0-RTTNot supportedSupported (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:

LevelDescriptionExample
Level 0Single URI, single methodPOST /api (RPC style)
Level 1URIs per resource/users, /orders
Level 2HTTP methods utilizedGET /users, POST /users
Level 3HATEOAS (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:

PatternDescriptionUse Case
Unary1 request -> 1 responseStandard API calls
Server Streaming1 request -> N responsesLarge data retrieval
Client StreamingN requests -> 1 responseFile uploads
Bidirectional StreamingN 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

PropertyRESTGraphQLgRPCWebSocketSSE
ProtocolHTTP/1.1+HTTP/1.1+HTTP/2TCP (HTTP Upgrade)HTTP/1.1+
Data FormatJSON/XMLJSONProtobuf (binary)Free-formText
DirectionRequest-ResponseRequest-ResponseBidirectional StreamingBidirectionalServer to Client
PerformanceModerateModerateHighHighModerate
Browser SupportFullFullLimited (gRPC-Web)FullFull
When to UsePublic APIs, CRUDComplex data relationshipsInternal microservicesBidirectional real-timeUnidirectional 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:

DirectiveDescription
publicCacheable by CDNs and intermediate proxies
privateCacheable only by the browser
no-cacheCache but validate with server every time
no-storeDo not cache at all
max-age=NCache valid for N seconds
s-maxage=NCache valid for N seconds on CDN/proxies
immutableDo not revalidate within cache period

CDN Comparison

PropertyCloudflareAWS CloudFrontFastlyAkamai
PoP Count310+600+100+4,000+
Free TierYesNoNoNo
DDoS ProtectionBuilt-inAWS ShieldBuilt-inBuilt-in
Edge ComputingWorkersLambda@EdgeCompute@EdgeEdgeWorkers
Real-time PurgeInstantSeconds150ms5 seconds
StrengthValue, SecurityAWS ecosystemReal-time purgeEnterprise

Load Balancer: L4 vs L7

PropertyL4 (Transport)L7 (Application)
OSI LayerTCP/UDPHTTP/HTTPS
Routing CriteriaIP, PortURL, Headers, Cookies
SSL TerminationNot possible (passthrough)Possible
PerformanceFasterMore flexible
WebSocketSupportedSupported
ExamplesAWS NLB, Nginx (stream)AWS ALB, Nginx (http)

Load Balancing Algorithms

AlgorithmDescriptionBest For
Round RobinDistributes sequentiallyServers with equal capacity
Weighted Round RobinDistributes by weightServers with different capacities
Least ConnectionsRoutes to server with fewest connectionsVariable request processing times
IP HashFixed server based on client IPWhen session persistence is needed
Consistent HashingHash ring-based distributionMinimal 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:

  1. Waterfall Chart: Check DNS, TCP, TLS, TTFB (Time To First Byte) timing for each request
  2. Size vs Transferred: Verify compression effectiveness (gzip, br)
  3. Initiator: Which resource triggered the request
  4. Timing Tab: Breakdown of Queued, Stalled, DNS, Initial Connection, SSL, TTFB, Content Download
  5. 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?"

  1. URL parsing (protocol, domain, path)
  2. DNS lookup (browser cache, OS cache, resolver, root, TLD, authoritative server)
  3. TCP 3-Way Handshake
  4. TLS handshake (if HTTPS)
  5. HTTP request sent
  6. Server processing and HTTP response
  7. 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

  1. The client sends a SYN packet to the server (with a sequence number)
  2. The server responds with a SYN-ACK packet (its own sequence number plus acknowledgment of the client's sequence number)
  3. 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

  1. RFC 793 - Transmission Control Protocol
  2. RFC 768 - User Datagram Protocol
  3. RFC 9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
  4. RFC 9114 - HTTP/3
  5. RFC 8446 - TLS 1.3
  6. RFC 7540 - HTTP/2
  7. RFC 1035 - Domain Names - Implementation and Specification

Books

  1. Computer Networking: A Top-Down Approach (Kurose, Ross) - Networking fundamentals textbook
  2. TCP/IP Illustrated, Volume 1 (W. Richard Stevens) - The TCP/IP bible
  3. High Performance Browser Networking (Ilya Grigorik) - Free online book on web performance optimization

Online Resources

  1. MDN Web Docs - HTTP - HTTP guide
  2. Cloudflare Learning Center - Visual explanations of networking concepts
  3. Julia Evans - Networking Zines - Networking concepts explained through comics
  4. gRPC Official Documentation - gRPC official docs
  5. Beej's Guide to Network Programming - Network programming guide
  6. DNS 101 - How DNS Works - DNS visualization
  7. 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.