LearnThatStack Ace your next interview

Networking for Developers

Commands assume Linux Checked Oct 2026 7 code snippets

The model

  • A request goes down a stack of layers. HTTP rides on TLS, TLS on TCP, and TCP on IP. The IP address finds the machine, and the port finds the process on it.
  • Latency is the time one round trip takes, the RTT. Bandwidth is how many bits fit through per second. Most requests are small, so cutting round trips helps more than buying bandwidth.
  • A new HTTPS connection waits for DNS, the TCP handshake and TLS before any data moves. Each costs a round trip. Reusing a warm connection skips all three.
  • TCP delivers one reliable, ordered byte stream, so a lost packet stalls everything behind it. UDP sends single packets with no promise they arrive. QUIC builds reliable streams on top of it.
  • HTTP is stateless. A cookie or token tells the server who you are. The method says whether a retry is safe, because a resend can repeat the action.
DNS resolvercache, then rootBrowseryour clientServerport 443DNSlookup example.comIP address cached for the TTLTCPSYNSYN-ACKTLS 1.3ClientHelloServerHello certificateHTTPGET /200 OK the HTML
Each pair of arrows is one round trip. A cold HTTPS request waits three round trips before GET can leave. A warm, reused connection starts at GET.

Layers, addresses & latency

how a request finds the right program, and what slows it

From URL to page

List what happens after you hit EnterLook up the IP, connect, set up TLS, send the request, render the HTML.
Name the parts of a URLScheme, host, port, path, query and fragment.

TipThe fragment after # never reaches the server. Only the browser reads it.

TrapA stray query string changes the cache key. Caches treat /app.js?v=2 as a different file.

Latency and bandwidth

Tell latency from bandwidthLatency is how long one trip takes. Bandwidth is how much fits through per second.
Speed up a page that loads fifty small filesCut round trips. Each request pays the latency again.

TipDistance sets a floor on latency. Light in fiber covers about 200 km per millisecond.

Layers, ports and sockets

TCP/IP OSI examplesApplication 7, 6, 5 HTTP, DNS, SMTPTransport 4 TCP, UDPInternet 3 IP, ICMPLink 2, 1 Ethernet, Wi-Fi
Tell a layer 7 load balancer from a layer 4 oneLayer 7 reads HTTP, so it can route by path. Layer 4 sees only IPs and ports.
Say what an IP address and a port each findThe IP finds the host. The port finds the process on it.
Tell apart many clients on one portThe OS uses the four-tuple, both IPs and both ports.
Say what a socket isYour program's handle on a connection, used like a file.
Find what holds a port when bind failslsof -i :8080

TipIP moves packets with no delivery guarantee. TCP adds reliability on top when an app needs it.

TrapA server bound to 127.0.0.1 only takes local connections. Bind 0.0.0.0 to accept outside ones.

DNS lookups & records

turn a name into an IP, and change records safely

How a DNS lookup works

Look up a name that isn't cachedYour resolver asks a root server, then .com, then the authoritative server.
Watch the walk from the rootdig +trace example.com
Say why DNS uses UDPOne packet each way, and no handshake to wait for.
Say when DNS switches to TCPWhen the answer won't fit. The server sets the TC bit, and the client retries on TCP.

TipZone transfers between DNS servers use TCP too, because they move the whole zone at once.

TrapA firewall that blocks DNS over TCP breaks only the big answers, like DNSSEC ones.

DNS record types

Point a name at an IP addressA holds an IPv4 address, and AAAA an IPv6 one.
Make one name an alias of anotherA CNAME. The alias takes on all of the target's records.
Name the records for mail, verification and delegationMX for mail, TXT for verification and SPF, NS for nameservers.

TrapA CNAME can't sit at the bare domain beside NS and SOA. Providers offer ALIAS or ANAME records instead.

TTL and changing a record

Pick a TTLIt's how long resolvers cache the answer. Lower means faster changes and more queries.
Move a site to a new IPLower the TTL at least one old TTL ahead, then switch.

TrapYou can't flush other resolvers' caches. Clients keep the old IP until their copy expires.

TCP & UDP

pick a transport, and see how TCP keeps bytes in order

TCP or UDP

Send data that must arrive whole and in orderTCP. Web pages, APIs, file transfers and databases use it.
Send data where late is as bad as lostUDP. No handshake, no resends. Live video, games and DNS use it.

TipQUIC runs over UDP and adds its own resends and ordering. HTTP/3 uses it.

TrapTCP has no message boundaries. Frame each message with a length prefix or a delimiter.

Open and close a TCP connection

Open, one round tripclient -> SYNmy seq is xserver -> SYN-ACKmy seq is y, got xclient -> ACKgot y, data can flowClose, a FIN from each sideA -> FINA has no more to sendB -> ACKB may still sendB -> FINB is done tooA -> ACKA waits in TIME_WAIT
Say why TCP shakes hands firstBoth sides agree on starting sequence numbers and prove the path works both ways.
Know what opening a connection costsOne round trip before any data.
Say why closing takes four messagesEach direction closes on its own, so each side sends a FIN.

TrapA missing FIN leaves a half-open connection. It lingers until a keepalive or a timeout reaps it.

Reliable, ordered delivery

Say how TCP tracks every byteEach byte gets a sequence number. The receiver ACKs up to the first gap.
Say what happens when a segment is lostThe sender resends it after a timeout or duplicate ACKs.
Stop a fast sender from swamping a slow readerFlow control. Each ACK says how much buffer is left.
Say what a zero window meansThe receiver's buffer is full, so the sender pauses.

TipFlow control protects the receiver. Congestion control protects the network.

TrapA connection stuck at a zero window looks like a network fault. Usually the app just stopped reading.

TCP speed & port limits

why fast links start slow, and how clients run out of ports

Slow start and the bandwidth-delay product

Say how a new connection ramps upSlow start. The window starts near 10 segments and doubles each round trip.
Say what a loss does to the windowA timeout drops it to 1 segment. Duplicate ACKs halve it.
Work out how much data must be in flightBandwidth times RTT. 1 Gbit/s at 100 ms is 12.5 MB.
Work out the throughput a window allowsWindow divided by RTT. 64 KB at 100 ms is about 5 Mbit/s.

TipA short response often ends before the window opens up. Reuse warm connections.

TrapBuffers far above the bandwidth-delay product don't add speed. The extra data just queues and adds delay.

Small writes and big packets

Say why a small request can stallNagle waits for an ACK that delayed ACK holds back, for up to 200 ms.
Turn Nagle off on a socketsetsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one)
Know the usual packet sizesEthernet's MTU is 1500 bytes. The MSS, the TCP payload, is usually 1460.
Find the smallest MTU on a pathSend don't-fragment packets and shrink them when ICMP says too big.

TipWriting the header and body in one call also avoids the Nagle stall.

TrapA firewall that drops ICMP makes big packets vanish, and the connection hangs after the handshake. Clamp the MSS lower.

TIME_WAIT and running out of ports

Say what TIME_WAIT isThe side that closes first keeps the socket for twice the max segment lifetime, 60 s on Linux.
Say why TIME_WAIT existsSo the last ACK can be resent, and stray old segments can't reach a new connection.
Count sockets in TIME_WAITss -tan state time-wait | wc -l
Say how a busy client runs out of portsEach connection takes one of about 28,000 source ports, and TIME_WAIT can hold it a minute.
Stop running out of portsReuse connections. Or widen the range, set tcp_tw_reuse, or add destination IPs.

TipHave the server close first. Then TIME_WAIT piles up on the server, not on busy clients.

TrapIf connect fails with EADDRNOTAVAIL, the client ran out of source ports. The server may be fine.

TLS & HTTPS

encrypt the connection and prove who the server is

HTTPS and the TLS handshake

Name the three things TLS doesIt hides the content, proves you reached the real server, and catches tampering.
Walk through a TLS handshakeThe hellos pick a cipher, the server sends its certificate, and Diffie-Hellman makes a shared key.
Say what encrypts the data afterwardsFast symmetric encryption. The cost is the round trips up front.

TrapTurning off certificate checks to silence an error lets anyone pose as the server.

Round trips to set up HTTPS

Open a new HTTPS connectionDNS, TCP and TLS 1.3 take a round trip each, so 300 ms on a 100 ms link.
Shake hands with TLS 1.2Two round trips after TCP.
Shake hands with TLS 1.3One round trip. It always uses ephemeral keys and drops RSA key exchange, RC4 and CBC.
Resume a session with 0-RTTThe request rides in the first packet.

TipReuse connections, resume TLS sessions and use TLS 1.3. More bandwidth won't help.

TrapAttackers can replay 0-RTT data. Allow it only for idempotent reads, or a POST can run twice.

Certificate checks

List what the client checksEvery signature up to a trusted root, the validity dates and the hostname.
See the chain a server sendsopenssl s_client -connect <host>:443 -showcerts
Say how browsers check for revoked certificatesMostly from lists their vendor pushes, like Chrome's CRLSets, not live OCSP calls.

TrapA server that leaves out its intermediates works in some clients and fails in others.

HTTP methods & status codes

say what you want, and read what came back

Safe and idempotent methods

GETRead a resource
PUTReplace the whole resource
DELETERemove a resource
PATCHChange part of a resource
POSTCreate something or run an action
yesnoonly if you write it that way

TipSafe means the server changes nothing. Idempotent means a repeat leaves the same final state, so a retry is harmless.

TrapNever hide a state change behind a GET. Crawlers and prefetchers fire every link they find.

PUT, PATCH or POST

Make a partial update safe to retrySend absolute values like {"credits": 20}, not changes to apply.
Create something when the server picks the idPOST /orders. A repeat makes a second order.
Create something when the client picks the idPUT /orders/<id>. A repeat lands on the same order.

TrapA PATCH like {"add_credits": 5} is a delta. Every retry adds 5 more.

Status code families

Read a 2xxIt worked, like 200 OK or 201 Created.
Read a 3xxA redirect, or 304 saying your cached copy is still good.
Read a 4xxThe client got it wrong. Resending the same request rarely helps.
Read a 5xxThe server failed a valid request. A retry with backoff often works.

Tip401 means you're not signed in. 403 means you are, but you're not allowed.

301 or 302 redirect

Move a page for good301. Browsers cache it, and search engines update their links.
Redirect for now, like through a login page302. Clients ask for the original URL again next time.

Tip301 and 302 let clients turn a POST into a GET. 307 and 308 keep the method.

TrapA 301 sent by mistake stays in browser caches after you revert it.

Caching, cookies & sessions

skip the network, and remember who's signed in

Browser caching

Reuse a response with no request at allCache-Control: max-age=3600 keeps it fresh for an hour.
Check a stale copy without downloading it againThe browser sends its ETag in If-None-Match. A 304 says reuse it.
Store a response but check it before each useCache-Control: no-cache. It still stores a copy.
Keep a response out of every cacheCache-Control: no-store.
See a response's cache headerscurl -I https://example.comIt sends HEAD, which returns the headers without the body.

TipPut a content hash in each static file's name and cache it for a year. A deploy ships new names.

TrapA long max-age on HTML keeps users on old pages after you deploy. Keep HTML on no-cache.

Cookies and sessions

Keep the session on the serverThe cookie holds a random id. Every server then needs the shared session store.
Keep the session in a signed tokenA JWT the server checks without a lookup. It's hard to revoke before it expires.

TipEvery cookie rides on every request to its domain. Keep cookies small, and sign anything the server trusts.

TrapHttpOnly doesn't fix an XSS bug. It only stops that bug from reading the cookie.

HTTP versions & WebSockets

how each version uses its connections, and live updates

Keep-alive and HTTP/1.1

Send many requests over one connectionKeep-alive, the default in HTTP/1.1. Content-Length marks where each response ends.
Stream a body of unknown lengthUse Transfer-Encoding: chunked. Each chunk starts with its size in hex, and an empty one ends it.
Explain head-of-line blocking in HTTP/1.1One request at a time per connection, so a slow response holds up the rest.
Work around it on HTTP/1.1Browsers open about six connections per host, each with its own handshake.

TipPipelining sent requests without waiting, but responses still came back in order.

TrapA proxy that buffers the whole response undoes chunked streaming.

HTTP/2

Run many requests at once on one connectionHTTP/2 streams interleave, so a slow response no longer holds up the fast ones.
Stop resending the same headersHPACK compresses them, cookies included.
Send files before the browser asksServer push is gone from Chrome. Use 103 Early Hints.

TipHTTP/2's stream priorities are deprecated. The simpler Priority header replaces them.

TCP head-of-line blocking and HTTP/3

HTTP/2 AAwaitsAlostHTTP/2 BBwaitsBHTTP/3 AAwaitsAlostHTTP/3 BBtime

Streams A and B share one connection, and a packet of A is lost. The resend takes a round trip. On HTTP/2, B waits too. On HTTP/3, only A waits.

Say why HTTP/2 still stalls on a lost packetTCP is one ordered stream. Every stream waits for the resend, even data that already arrived.
Say how HTTP/3 avoids that stallQUIC orders each stream on its own, so only the stream that lost data waits.
Open an HTTP/3 connectionOne round trip, because QUIC folds in the TLS 1.3 handshake.
Keep a connection when a phone changes networkQUIC's connection IDs survive a switch from Wi-Fi to cellular.

TrapSome networks block UDP, so clients must fall back to HTTP/2. QUIC also uses more CPU than kernel TCP.

WebSockets, SSE and long polling

Upgrade a request to a WebSocketSend Upgrade: websocket on a GET. The server answers 101, then frames flow both ways.
Push updates with no special server supportLong polling. The server holds each request until data arrives.
Stream events one way, server to clientServer-Sent Events. They reconnect on their own but carry text only.
Push both ways at a high rateWebSockets, for chat, games and live editing.

TipEach open connection holds a socket. Pin it at the load balancer, and size limits for the peak.

TrapProxies with short idle timeouts cut long-lived connections. Send heartbeats and reconnect.

Pools, timeouts & retries

call other services without falling over

Connection pools

Skip the handshakes on each requestBorrow a warm connection from a pool. It saves round trips and the server's TLS work.
Size a poolLittle's law. 200 requests a second that each hold a connection 50 ms need about 10.
Spot a saturated poolCallers queue to borrow, then acquire timeouts fire.
Avoid resets on idle pooled connectionsMake the client's idle timeout shorter than the server's.

TipCap the pool at what the backend accepts. A pool of 500 can't help a database that takes 100.

TrapA full pool looks like a slow database. Check how long callers wait to borrow before you blame the queries.

Connect and read timeouts

Bound the wait to open a connectionSet the connect timeout near your RTT plus a margin, often a few hundred ms.
Bound the wait for response bytesSet the read timeout per endpoint. One second for a lookup, thirty for a report.
Catch a server that sends one byte at a timeAdd an overall deadline. A read timeout only times the gaps between bytes.

TrapGenerous timeouts let slow calls fill your pool, and the outage spreads.

Find the slow phase of a request

curl -so /dev/null -w "%{time_namelookup} \%{time_connect} %{time_appconnect} \%{time_starttransfer}\n" <url>0.30 0.35 0.48 1.90DNS, TCP, TLS, first byte
Read curl's timingsEach counts from the start. Here the server took 1.4 s after TLS.
Blame a slow DNS or connect phaseSlow DNS points at the resolver. A slow connect points at latency or distance.
Blame a slow first byte after TLSServer work, like a slow query or a full connection pool.

TipA warm keep-alive connection skips DNS, TCP and TLS. Time cold and warm requests separately.

Retries, backoff and idempotency keys

Back off with full jitterMath.random() * Math.min(cap, base * 2 ** attempt)
Choose which failures to retryTimeouts, 5xx and 429, on idempotent requests only.
Pick which layer retriesOne layer only. Three layers that each try 3 times make 27 calls.
Make a POST safe to retrySend an idempotency key. The server answers a repeat with the stored result.
Stop two copies of a request both runningPut a unique constraint on the key. The loser reads the winner's result.

TipWithout jitter, clients that failed together retry together and keep the server down.

TrapA timed-out write may have landed. Retry it without a key and you can charge a card twice.

Cache stampedes

Say what a cache stampede isA hot key expires, and every request misses at once and hits the database.
Prevent a stampedeLet one request refill the key while the rest wait, or serve the stale value.

TipAfter a flush or deploy, warm the hottest keys before traffic arrives.

Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 51 questions it links, not just the 7 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.