Organize the answer around ownership, limits, failure, and recovery. Definitions become interview-ready when they survive a concrete production scenario.
Question set
33 detailed answers
01What is the OSI model and what are its layers?
junior
Short answer: OSI is a reference (theoretical) model that splits networking into 7 layers, where each layer provides services to the one above it and uses services of the one below it. In practice it's used less than TCP/IP, but it's handy for discussion and troubleshooting.
In detail:
Layers from bottom to top (mnemonic: "Please Do Not Throw Sausage Pizza Away"):
| # | Layer | What it does | Data unit | Examples |
|---|---|---|---|---|
| 7 | Application | Interaction with the application | Data | HTTP, DNS, FTP, SMTP |
| 6 | Presentation | Encoding, encryption, compression | Data | TLS, JPEG, ASCII |
| 5 | Session | Setting up/managing a session | Data | sockets, RPC |
| 4 | Transport | Delivery between processes, ports | Segment (TCP)/Datagram (UDP) | TCP, UDP |
| 3 | Network | Logical addressing, routing | Packet | IP, ICMP |
| 2 | Data Link | Transfer within a network segment, MAC | Frame | Ethernet, Wi-Fi, ARP |
| 1 | Physical | Bits over the transmission medium | Bit | cables, radio, optics |
When sending, each layer adds its own header (encapsulation); when receiving, it strips it off (decapsulation). For example, HTTP data is wrapped in a TCP segment, which is wrapped in an IP packet, which is wrapped in an Ethernet frame.
Encapsulation diagram:
[ Ethernet [ IP [ TCP [ HTTP data ] ] ] ]
L2 L3 L4 L7
⚠️ Gotcha: TLS/encryption is often assigned to layer 6 (Presentation) in OSI, but in the actual TCP/IP model it's placed between transport and application. Don't confuse the "theoretical" layer with practice. Also, a MAC address is L2 and an IP address is L3; people often mix them up.
02The TCP/IP model and how it maps to OSI
middle
Short answer: TCP/IP is a practical model of 4 (sometimes 5) layers that the internet actually runs on. It's simpler than OSI and combines several OSI layers into one.
In detail:
| TCP/IP layer | OSI mapping | Protocols |
|---|---|---|
| Application | 5+6+7 (Session, Presentation, Application) | HTTP, DNS, TLS, SMTP, gRPC |
| Transport | 4 (Transport) | TCP, UDP, QUIC |
| Internet | 3 (Network) | IP, ICMP, ARP |
| Link / Network Access | 1+2 (Physical, Data Link) | Ethernet, Wi-Fi |
The key difference: OSI is a reference of "how things should be structured," while TCP/IP describes how the internet actually works. In TCP/IP, everything above transport (session, presentation, application) is left up to the application itself.
Data flow during an HTTP request:
Browser (Application) -> TCP segment (Transport) -> IP packet (Internet) -> Ethernet frame (Link) -> wire
⚠️ Gotcha: In an interview you may be asked "what layer does a router/switch work at?" A switch is L2 (by MAC), a router is L3 (by IP), and an L7 load balancer/proxy is at the application layer. Confusion here is a common mistake.
03TCP vs UDP — what's the difference and when to use each?
junior
Short answer: TCP is reliable, ordered, connection-oriented with congestion control, but slower. UDP is fast, connectionless, with no delivery or ordering guarantees. TCP for web/files, UDP for video/games/DNS.
In detail:
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake) | Connectionless |
| Reliability | Guarantees delivery (ACK + retransmit) | No guarantee |
| Ordering | Orders segments | May arrive out of order |
| Flow/congestion control | Yes | No |
| Speed/overhead | Slower, more overhead | Faster, minimal overhead |
| Header | 20+ bytes | 8 bytes |
| Use cases | HTTP, files, DBs, mail | Video, voice, games, DNS, DHCP |
TCP header (simplified): source port, destination port, sequence number, acknowledgment number, flags (SYN/ACK/FIN/RST/PSH/URG), window size, checksum. ~20 bytes without options.
UDP header: source port, destination port, length, checksum. Just 8 bytes.
When to use what:
- Video call/stream/game: better to drop a frame than wait for it to be retransmitted (latency is worse than loss) -> UDP.
- Files/web/banking transaction: every byte matters, ordering is critical -> TCP.
- DNS: a short query, retrying is cheaper than holding a connection -> UDP (falling back to TCP for large responses).
⚠️ Gotcha: "UDP doesn't guarantee delivery" doesn't mean "UDP loses data." On a healthy network UDP packets arrive just fine; there's simply no built-in retransmission mechanism. The application itself decides whether it needs reliability (for example, QUIC implements reliability on top of UDP).
04TCP: the three-way handshake
middle
Short answer: Before exchanging data, TCP establishes a connection with three messages: SYN -> SYN-ACK -> ACK. This synchronizes the initial sequence numbers of both sides.
In detail:
Client Server
| ---- SYN (seq=x) ----------> | "want to connect, my ISN=x"
| |
| <-- SYN-ACK (seq=y,ack=x+1)- | "ok, my ISN=y, acknowledging x"
| |
| ---- ACK (ack=y+1) --------> | "acknowledging y, let's go"
| |
| ===== connection open ========|
- SYN: the client sends a segment with the SYN flag and its initial sequence number (ISN = x).
- SYN-ACK: the server responds with SYN (its own ISN = y) + ACK (acknowledges x+1).
- ACK: the client acknowledges y+1. The connection is established.
Why three and not two: both sides need to (a) agree on initial sequence numbers and (b) confirm the channel works in both directions. The ISN is chosen randomly to protect against spoofing and stale duplicates.
Cost: the handshake is 1 RTT (round-trip) before the first data is sent. That's why setting up a new TCP connection isn't cheap — hence keep-alive and connection pools.
⚠️ Gotcha: SYN flood is an attack where an attacker sends many SYNs without completing the handshake, overflowing the queue of half-open connections. The defense is SYN cookies. Also important: the first data can't be sent before the handshake completes (except with TCP Fast Open).
05TCP: connection termination (4-way handshake)
middle
Short answer: Closing requires four messages because the connection is full-duplex and each side closes its own half separately: FIN -> ACK -> FIN -> ACK.
In detail:
Client Server
| ---- FIN ---------------> | "I'm done sending"
| <--- ACK ---------------- | "got it"
| <--- FIN ---------------- | "I'm done too"
| ---- ACK ---------------> | "got it"
| (TIME_WAIT ~2*MSL) |
- The client sends FIN (closes its send side).
- The server acknowledges with ACK (but may still send more data).
- The server sends FIN.
- The client acknowledges with ACK and enters the TIME_WAIT state.
TIME_WAIT: the initiator of the close waits ~2×MSL (Maximum Segment Lifetime) to reliably let any delayed packets "die out" and to correctly handle a retransmitted FIN. That's why heavily loaded servers accumulate many sockets in TIME_WAIT.
⚠️ Gotcha: Many sockets in TIME_WAIT on a server that initiates the close can exhaust ports/memory. Usually the client closes the connection. There's also a "3.5-way" variant — when the server's ACK and FIN are combined into a single segment.
06TCP: sequence numbers, ACKs, and retransmission
middle
Short answer: Every byte is numbered with a sequence number; the receiver acknowledges (ACK) which byte it expects next. If an ACK doesn't arrive within the RTO (timeout), the segment is retransmitted.
In detail:
- Sequence number numbers the bytes of the stream, not the segments.
- ACK is cumulative: "received everything up to byte N, waiting for N." If a segment in the middle is lost, the ACK will keep repeating the old value.
- Retransmission happens two ways:
- RTO (Retransmission Timeout): an ACK didn't arrive within the computed time -> retransmit.
- Fast retransmit: receiving 3 duplicate ACKs means a segment was lost — retransmit without waiting for the timeout.
- SACK (Selective ACK): an option that lets the receiver acknowledge selectively received blocks, so already-delivered data isn't retransmitted.
Example: bytes 1–1000 are sent in segments of 100. The segment 301–400 is lost. The receiver sends ACK=301 for each subsequent segment. After 3 duplicate ACK=301, the sender retransmits 301–400 (fast retransmit).
⚠️ Gotcha: The RTO is computed dynamically from the smoothed RTT (Jacobson/Karn algorithm), not fixed. Karn's algorithm forbids measuring RTT from retransmitted segments (ambiguity about which ACK they're responding to).
07TCP: flow control (sliding window)
middle
Short answer: Flow control protects a slow receiver from a fast sender. In each ACK the receiver reports its window size (advertised window) — how many bytes it's ready to accept. The sender doesn't send more.
In detail:
- The receiver has a receive buffer. In the
window sizefield of each ACK it reports how much free space remains. - Sliding window: the sender can have no more "in flight" (unacknowledged) than the window size. As ACKs arrive, the window "slides" forward.
- If the receiver's buffer is full, it advertises window=0, and the sender pauses, periodically sending a window probe.
Sender's window:
[ sent+ACKed | sent, awaiting ACK | can send | cannot ]
^----- window size -----^
Difference from congestion control: flow control is about the receiver's capacity (rwnd). Congestion control is about the network's capacity (cwnd). The actual amount "in flight" = min(rwnd, cwnd).
⚠️ Gotcha: Don't confuse flow control (protecting the receiver) with congestion control (protecting the network) — these are two distinct mechanisms with two distinct windows. "Silly window syndrome" is a pathology where the window opens in tiny increments; it's cured by Nagle's algorithm (on send) and Clark's (on receive).
08TCP: congestion control
senior
Short answer: Congestion control keeps the sender from overloading the network. TCP gradually ramps up the rate and sharply backs off at signs of loss. The key phases are slow start, congestion avoidance, and fast recovery.
In detail:
A congestion window cwnd is maintained. The actual in-flight amount = min(cwnd, rwnd).
- Slow start: cwnd starts at 1–10 MSS and doubles every RTT (exponential growth) until it reaches ssthresh.
- Congestion avoidance: after ssthresh growth is linear (+1 MSS per RTT) — careful probing of available bandwidth.
- Loss signal:
- 3 duplicate ACKs -> fast retransmit + fast recovery: ssthresh = cwnd/2, cwnd = ssthresh (moderate reduction).
- Timeout (RTO) -> severe congestion: ssthresh = cwnd/2, cwnd resets to 1, slow start again.
Algorithms: the classic Reno/NewReno, the modern CUBIC (default in Linux, more aggressive on high-latency links), BBR (Google, models bandwidth and RTT, doesn't treat loss as the sole congestion signal).
cwnd
| /\ /\
| / \ /
| / \ / slow start (exponential) -> avoidance (linear)
| / \__/ \__ loss -> reduction
+---------------------------> time
⚠️ Gotcha: On wireless networks a packet loss doesn't always mean congestion (it can be interference), but classic TCP treats any loss as congestion and reduces the rate — hence degradation on Wi-Fi/mobile. BBR partly solves this by not relying solely on loss.
09IPv4 vs IPv6: addressing
junior
Short answer: IPv4 uses 32-bit addresses (~4.3 billion), written as 4 octets (192.168.1.1). IPv6 uses 128-bit addresses (practically inexhaustible), written in hex separated by colons. IPv6 was created because IPv4 ran out.
In detail:
| IPv4 | IPv6 | |
|---|---|---|
| Length | 32 bits | 128 bits |
| Notation | 192.168.0.1 | 2001:0db8:85a3::8a2e:0370:7334 |
| Addresses | ~4.3×10⁹ | ~3.4×10³⁸ |
| Header | variable, with checksum | fixed 40 bytes, no checksum |
| NAT | widely used | mostly not needed |
| Autoconfiguration | DHCP | SLAAC + DHCPv6 |
IPv6 shortening: a run of zero groups can be collapsed with :: (once per address), and leading zeros in a group are dropped. 2001:0db8:0000:0000:0000:0000:0000:0001 = 2001:db8::1.
IPv6 removed broadcast (it has multicast/anycast), simplified the header, built in IPsec (originally), and dropped the checksum (left to the transport/link layer).
⚠️ Gotcha: IPv4 and IPv6 aren't directly compatible — you need dual-stack or tunneling/translation. The address ::1 is the IPv6 localhost (equivalent to 127.0.0.1). Don't confuse :: (any address / wildcard) with ::1 (loopback).
10Subnets, masks, public/private addresses, NAT
middle
Short answer: A mask splits an IP into a network part and a host part. Private ranges (10/8, 172.16/12, 192.168/16) aren't routed on the internet; NAT translates them into a single public address.
In detail:
- CIDR notation:
192.168.1.0/24means the first 24 bits are the network and the remaining 8 are hosts (256 addresses, of which 254 are usable for hosts, plus the network address and broadcast). - A /24 mask =
255.255.255.0. - Private ranges (RFC 1918):
10.0.0.0/8172.16.0.0/12192.168.0.0/16
- NAT (Network Address Translation): the router replaces the private src address with its own public one and records the mapping in a table (with a port — that's PAT/NAPT). The response arrives at the public address, and the router uses the table to return it to the right internal host.
PC 192.168.1.5:54321 --NAT--> 203.0.113.7:60000 --> server
<--NAT-- <-- response
NAT is the main reason IPv4 has "survived" until now: thousands of devices behind a single public IP.
⚠️ Gotcha: NAT breaks inbound "outside-in" connections (you need port forwarding / NAT traversal — STUN/TURN/hole punching, e.g. for P2P/WebRTC). Also: NAT is not a firewall, even though it incidentally hides internal addresses.
11Ports, sockets, and well-known ports
junior
Short answer: A port (16 bits, 0–65535) identifies a process/service on a host. A socket is a pair (IP address + port). A connection is uniquely identified by the four-tuple: (src IP, src port, dst IP, dst port).
In detail:
- Port ranges:
- 0–1023 — well-known (system).
- 1024–49151 — registered.
- 49152–65535 — dynamic/ephemeral (for clients).
- Well-known ports:
| Port | Service |
|---|---|
| 20/21 | FTP |
| 22 | SSH |
| 25 | SMTP |
| 53 | DNS |
| 80 | HTTP |
| 110 | POP3 |
| 143 | IMAP |
| 443 | HTTPS |
| 3306 | MySQL |
| 5432 | PostgreSQL |
| 6379 | Redis |
| 27017 | MongoDB |
A connection is identified by the 4-tuple. That's why a single server on port 443 serves thousands of clients — each has its own (src IP, src port).
⚠️ Gotcha: The client uses a random ephemeral port; the server listens on a fixed one. "Address already in use" when restarting a server is usually due to sockets in TIME_WAIT; it's cured with the SO_REUSEADDR option. And remember: a port is at the transport layer (L4), not the network layer.
12What is DNS and why is it needed?
junior
Short answer: DNS (Domain Name System) is a distributed, hierarchical system that translates human-readable domain names (example.com) into IP addresses. It's the "phone book of the internet."
In detail:
People remember names, while machines route by IP. DNS does this translation. On top of that, DNS provides:
- A layer of abstraction: you can change a server's IP without changing the name.
- Load distribution: one name -> multiple IPs (round-robin); GeoDNS returns the nearest server.
- Service information: MX (mail), TXT (verification, SPF/DKIM), etc.
It runs mainly over UDP port 53 (TCP for large responses and zone transfers). DNS over HTTPS/TLS (DoH/DoT) encrypts the queries.
⚠️ Gotcha: "Why DNS, why not just use IPs directly?" — because IPs change (migration, balancing, a CDN serves a different IP by geolocation), while names are stable and readable. Hard-coding IPs would make the infrastructure fragile.
13DNS: the hierarchy and step-by-step resolution
middle
Short answer: The DNS hierarchy: root servers -> TLD servers (.com, .ru) -> the domain's authoritative servers. A recursive resolver queries them in turn from the root downward and caches the result.
In detail:
The hierarchy is read right to left: www.example.com. (the trailing dot is the root).
Step-by-step resolution of www.example.com:
1. Browser/OS: is it in the cache? -> if yes, done.
2. Query to the recursive resolver (usually the ISP or 8.8.8.8 / 1.1.1.1).
3. Resolver -> ROOT server: "where's .com?" -> answer: "ask the .com TLD servers."
4. Resolver -> TLD server (.com): "where's example.com?" -> "ask the authoritative ns1.example.com."
5. Resolver -> authoritative server: "what's the A record for www.example.com?" -> "93.184.216.34".
6. Resolver caches the answer (for the TTL) and returns it to the client.
Client -> Recursive Resolver -> Root -> TLD (.com) -> Authoritative (example.com)
^------- caches at each step ----------|
- The recursive resolver does all the work for the client and returns the final answer.
- Iterative queries happen between the resolver and the hierarchy servers (each replies "don't know, ask over there").
⚠️ Gotcha: There are logically 13 root servers (a–m), but physically these are thousands of machines via anycast. The client almost always makes a recursive query; the iterative work is done by the resolver. Also: the first resolution is "cold" (slow), subsequent ones come from the cache.
14DNS: record types and caching/TTL
middle
Short answer: Records describe different domain data: A/AAAA (IP), CNAME (alias), MX (mail), TXT (text), NS (name servers). Each has a TTL — how many seconds it may be cached.
In detail:
| Record | Purpose |
|---|---|
| A | name -> IPv4 |
| AAAA | name -> IPv6 |
| CNAME | alias to another name (www -> example.com) |
| MX | the domain's mail server (with priority) |
| TXT | arbitrary text: SPF, DKIM, ownership verification |
| NS | the zone's authoritative name servers |
| SOA | zone metadata (serial number, TTL) |
| PTR | reverse resolution IP -> name |
| SRV | service location (host+port) |
TTL and caching: the TTL (in seconds) specifies how long resolvers/clients may keep a record. A low TTL means fast propagation of changes but more queries. A high TTL means less load but changes "take effect" slowly.
⚠️ Gotcha: A CNAME can't be placed at the domain apex (example.com) — there you need an A/AAAA or special ALIAS/ANAME records offered by the provider. Also, before a migration you lower the TTL in advance so the switchover happens quickly. "I changed DNS but the old IP still responds" — that's a still-valid cache whose TTL hasn't expired.
15HTTP as a protocol: stateless, over TCP
junior
Short answer: HTTP is an application-layer request/response protocol that runs (in versions 1.x and 2) over TCP. It's stateless: by default the server doesn't remember previous requests; state is kept by cookies/tokens.
In detail:
- Stateless: each request is self-contained. The server isn't required to keep context between requests. This simplifies scaling (any request can go to any instance).
- Over TCP: HTTP/1.1 and HTTP/2 use TCP (reliability, ordering). HTTP/3 runs over QUIC/UDP.
- State is emulated via cookies, sessions, tokens (Authorization header).
At the transport layer, one TCP connection carries text-based HTTP/1.1 or binary HTTP/2 messages. A method expresses intent (GET is safe, PUT is idempotent, POST usually is not), status codes communicate the result class, and Cache-Control, ETag, plus conditional requests govern response reuse by clients and proxies.
⚠️ Gotcha: "Stateless" refers to the protocol, not the application — the application stores state (in a DB/session). And HTTP/1.1 keep-alive doesn't make the protocol stateful: the connection is reused, but each request is still independent.
16HTTPS/TLS: the handshake in detail
senior
Short answer: HTTPS = HTTP over TLS. The TLS handshake establishes an encrypted channel: the sides negotiate ciphers, the server presents a certificate, they exchange key material via asymmetric cryptography, and then switch to a fast symmetric session key.
In detail (TLS 1.2, the classic scheme):
Client Server
| -- ClientHello --------------------> | TLS versions, list of cipher suites, random
| <-- ServerHello ------------------- | chosen cipher, random
| <-- Certificate ------------------- | server's certificate (public key)
| <-- ServerHelloDone --------------- |
| -- ClientKeyExchange --------------> | pre-master secret, encrypted with the public key
| -- ChangeCipherSpec / Finished ----> | switch to the symmetric key
| <-- ChangeCipherSpec / Finished --- |
| ====== encrypted data exchange ===== |
Steps:
- ClientHello: the client sends TLS versions, supported cipher suites, and a random number (client random).
- ServerHello + Certificate: the server picks a cipher, sends its certificate (with the public key) and a server random.
- Certificate validation: the client checks the chain of trust up to a trusted CA, the expiration, and the domain.
- Key exchange: the client generates a pre-master secret and encrypts it with the server's public key (or via ECDHE — exchanging Diffie-Hellman parameters signed by the certificate). Only the server can decrypt it with its private key.
- Session key derivation: from (client random + server random + pre-master secret) both sides derive the same symmetric session key.
- From then on all traffic is encrypted with a fast symmetric algorithm (AES).
TLS 1.3 streamlined the handshake to 1 RTT (and 0-RTT for resumption), removed obsolete ciphers, and made ECDHE mandatory (forward secrecy).
Why asymmetric crypto only for the key exchange: asymmetric encryption is slow but solves the problem of "how to agree on a secret over an open channel." Symmetric encryption is fast but requires a shared secret. So asymmetric crypto is used once to securely establish the symmetric session key, and from then on everything is symmetric.
What's encrypted: the HTTP body and headers, the path, query parameters, cookies. What's not encrypted: the destination IP address and the hostname in SNI (in plain TLS; ESNI/ECH close this), and the very fact that a connection exists.
⚠️ Gotcha: TLS provides forward secrecy only with an ephemeral key exchange (ECDHE), where the pre-master isn't transmitted encrypted under a long-lived key. With the old RSA scheme, a leak of the server's private key lets all previously recorded traffic be decrypted. Another common mistake is calling this "SSL": SSL is obsolete, TLS is what's used.
17Certificates, CAs and the chain of trust, MITM
middle
Short answer: A certificate binds a domain to a public key and is signed by a certificate authority (CA). The browser trusts root CAs from its store; the chain of signatures from the server's certificate up to the root CA forms the chain of trust. This protects against MITM.
In detail:
Chain of trust:
Root CA (in the OS/browser store)
-> Intermediate CA (signed by the root)
-> example.com server certificate (signed by the intermediate)
The browser checks: every link's signature is valid, the certificate isn't expired, the domain matches (CN/SAN), and the certificate isn't revoked (CRL/OCSP).
How it protects against MITM: a man in the middle can intercept the traffic but can't forge a valid certificate for the domain — they have neither the server's private key nor a signature from a trusted CA. The browser will show a certificate error.
When MITM is possible: if a rogue root CA is added to the trusted store (corporate proxy, malware), then interception is "legal" as far as the system is concerned. That's why corporate TLS inspection only works with the corporate CA installed.
⚠️ Gotcha: A self-signed certificate encrypts traffic just as reliably, but it doesn't authenticate the server (no trusted CA) — hence the browser warning. Encryption ≠ trust. For critical applications, certificate pinning is used (hard-binding to a specific certificate/key) to protect even against a compromised CA.
18HTTP/2 and HTTP/3 (QUIC), head-of-line blocking
middle
Short answer: HTTP/2 multiplexes many requests over a single TCP connection (binary protocol, header compression), but suffers from TCP head-of-line blocking. HTTP/3 moves everything onto QUIC over UDP, eliminating this problem.
In detail:
HTTP/1.1: one request at a time per connection (or pipelining, which never caught on in practice). Browsers opened ~6 parallel TCP connections to a domain.
HTTP/2:
- Binary framing, multiplexing: many parallel streams over a single TCP connection.
- Header compression (HPACK), server push (deprecated).
- The problem — TCP head-of-line blocking: if a single TCP segment is lost, ALL multiplexed streams wait for its retransmission, because TCP guarantees ordering across the entire connection.
HTTP/3 (QUIC):
- Runs over UDP, implementing reliability, ordering, and congestion control itself.
- Streams are independent: a packet loss in one stream doesn't block the others (HoL blocking is solved at the transport layer).
- TLS 1.3 is built into QUIC; the connection is established in 1 RTT (or 0-RTT).
- Connection migration: the connection survives an IP change (Wi-Fi -> LTE) via the Connection ID.
HTTP/2: [ HTTP streams ] -> single TCP (HoL blocking on loss)
HTTP/3: [ HTTP streams ] -> QUIC -> UDP (streams are independent)
⚠️ Gotcha: HTTP/2 solves HoL only at the application layer; at the transport layer (TCP) the blocking remains — which is exactly the motivation for HTTP/3. Also, QUIC encrypts almost the entire transport header, which complicates firewall operation and is sometimes blocked by networks (UDP/443).
19WebSockets: upgrade, full-duplex
middle
Short answer: WebSocket is a full-duplex, two-way communication protocol over a single TCP connection. It starts as an HTTP request with an Upgrade header, after which the connection "switches" to the ws protocol and stays open.
In detail:
Setup (handshake):
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
After 101 Switching Protocols the connection stays open; both sides can send messages at any time (full-duplex), without the overhead of new HTTP requests.
- vs HTTP: HTTP is request/response (the client initiates). WebSocket is bidirectional, the server can push.
- It uses the same ports 80/443 (
ws:///wss://), which is convenient for getting through firewalls. - Over TCP.
When: chats, online games, collaborative editors, trading tickers, live notifications — anything needing low latency and server push.
⚠️ Gotcha: WebSocket runs over TCP, so it too is subject to head-of-line blocking. And through L7 proxies/load balancers you have to explicitly allow Upgrade and keep long-lived connections (otherwise they're cut off by timeout). Scaling requires sticky sessions or a shared pub/sub (Redis).
20Server-Sent Events and long polling for realtime
middle
Short answer: For realtime there are three approaches over HTTP: long polling (simulating push), Server-Sent Events (a one-way stream from the server), and WebSockets (full-duplex). The choice depends on the direction and frequency of the data.
In detail:
| Technique | Direction | Connection | When |
|---|---|---|---|
| Long polling | server->client (with delay) | the request hangs until there's data, then is reopened | a simple fallback, infrequent events |
| SSE | server->client only | one long-lived HTTP connection, text/event-stream |
news feeds, notifications, progress |
| WebSocket | bidirectional | persistent TCP | chats, games, interactive |
- Long polling: the client makes a request, the server holds it open until data appears or a timeout, responds, and the client immediately sends a new one. High overhead, but works everywhere.
- SSE: the browser's
EventSource, automatic reconnect, a simple text format, server-to-client only, runs over plain HTTP (and benefits from HTTP/2 multiplexing).
⚠️ Gotcha: SSE is one-way (you can't send from client to server over the same channel — you need a separate HTTP request) and is limited by the number of connections per domain in HTTP/1.1 (~6). WebSocket is bidirectional but heavier on infrastructure. Long polling is simple but wasteful in connections and latency.
21What happens when you type a URL and press Enter?
concept
Short answer: The browser parses the URL -> resolves the domain to an IP via DNS -> establishes a TCP connection -> performs a TLS handshake (for HTTPS) -> sends an HTTP request -> receives a response -> renders the page, loading resources. This is the classic "end-to-end" question.
In detail, step by step:
1. URL parsing and browser checks
- The browser parses
https://www.example.com/page?q=1: scheme, host, port, path, query. - HSTS check (forces HTTPS), browser cache (maybe the response is already there).
2. DNS resolution
- Checking caches: browser -> OS -> hosts file -> recursive resolver.
- If not found, the recursive resolver queries root -> TLD (.com) -> the authoritative server for example.com, returning the IP (see the DNS question).
3. Establishing the TCP connection
- 3-way handshake (SYN / SYN-ACK / ACK) with the server's IP on port 443. ~1 RTT.
4. TLS handshake (for HTTPS)
- ClientHello/ServerHello, certificate and chain-of-trust validation, key exchange, derivation of the symmetric session key. ~1 RTT (TLS 1.3) or 2 RTT (TLS 1.2).
5. HTTP request
GET /page?q=1 HTTP/2
Host: www.example.com
User-Agent: ...
Cookie: session=...
Accept: text/html
6. Server processing
- Load balancer/reverse proxy/CDN -> application -> possibly a DB -> forming the response.
7. HTTP response
HTTP/2 200 OK
Content-Type: text/html
Set-Cookie: ...
Cache-Control: ...
<html>...</html>
8. Rendering in the browser
- Parsing the HTML -> building the DOM.
- Discovering links to CSS/JS/images -> parallel requests (often to a CDN), each of which may need its own DNS/TCP/TLS (or reuse connections).
- Building the CSSOM, the render tree, layout, paint, compositing.
- Executing JS, which may fetch more data (fetch/XHR).
9. Closing/reuse
- Connections are kept open (keep-alive) for subsequent requests; at the end they're closed (FIN).
URL -> DNS -> TCP -> TLS -> HTTP request -> server -> HTTP response -> rendering -> additional resources
⚠️ Gotcha: A good answer mentions caches at every level (browser, DNS, CDN), the parallelism of resource requests, and the fact that rendering is a separate large stage. A weak answer ends at "got the HTML." It's also worth mentioning that a modern browser can preload DNS/TCP (prefetch, preconnect).
22Latency vs bandwidth vs throughput, RTT
middle
Short answer: Latency is delay (the time for the trip, in ms). Bandwidth is the channel's maximum capacity (bits/s). Throughput is the actually achieved transfer rate. RTT is the round-trip time.
In detail:
- Latency (delay): how long it takes data to travel from A to B. It's made up of propagation delay (the speed of light in the medium), processing, queuing, and serialization. It's bounded by physics (across an ocean, tens of ms minimum).
- Bandwidth: the channel's theoretical maximum, the "width of the pipe" (for example, 1 Gbit/s).
- Throughput (the actual capacity): how much is really transferred given losses, congestion, and protocol overhead. Always ≤ bandwidth.
- RTT (Round-Trip Time): the "there and back" time. Critical for protocols with a handshake — each RTT adds delay before the data.
Analogy: bandwidth is the width of the pipe, latency is the length of the pipe, throughput is the actual flow of water.
Why it matters: the TCP handshake (1 RTT) + TLS handshake (1–2 RTT) means 2–3 RTT before the first byte of data. At an RTT of 100 ms that's 200–300 ms "wasted." Hence CDNs (shorten the distance = latency), keep-alive, TLS 1.3, QUIC 0-RTT.
⚠️ Gotcha: Increasing bandwidth doesn't reduce latency. A fat pipe won't speed up a "ping." For interactive applications (games, trading) it's latency/RTT that matters, not gigabits. A high "BDP" (bandwidth-delay product) requires large TCP windows, otherwise the channel is underutilized.
23Proxies: forward vs reverse, and CDN
middle
Short answer: A forward proxy sits on the client side (hides/controls clients). A reverse proxy sits in front of servers (hides them, balances load, caches, terminates TLS). A CDN is a geographically distributed network of reverse caches at the edge of the network.
In depth:
- Forward proxy: client -> proxy -> internet. Use cases: corporate traffic filtering, anonymization, caching, bypassing restrictions. The server sees the proxy's IP, not the client's.
- Reverse proxy: client -> reverse proxy -> internal servers. Use cases: load balancing, TLS termination, caching, protection, a single entry point (nginx, Envoy). The client sees the proxy, not the real servers.
Forward: [Clients] -> (proxy) -> [Internet]
Reverse: [Internet] -> (proxy) -> [Servers]
CDN (Content Delivery Network): a network of edge servers around the world that cache static content (and sometimes dynamic content) close to the user.
- Network aspect: GeoDNS/anycast routes the user to the nearest edge -> latency/RTT drops sharply.
- The edge serves from cache; on a miss it goes to the origin.
- Reduces load on the origin, absorbs DDoS, speeds up TLS (closer = lower RTT).
⚠️ Gotcha: Behind a reverse proxy/CDN, the client's real IP is passed in the X-Forwarded-For / Forwarded header; the application must read it, otherwise all clients "look like" the proxy. Anycast (one IP advertised from multiple locations) is the key mechanism for routing to the nearest edge.
24Load balancer: L4 vs L7
middle
Short answer: A load balancer distributes traffic across servers. An L4 balancer works at the transport layer (by IP/ports, without inspecting the content). An L7 balancer works at the application layer (it sees HTTP — path, headers, cookies).
In depth:
| L4 (transport) | L7 (application) | |
|---|---|---|
| Sees | IP, port, TCP/UDP | HTTP path, headers, cookies, host |
| Decisions | by 4-tuple/hash | by URL, domain, method |
| Speed | faster, cheaper | slower, more flexible |
| TLS | passes through (passthrough) | can terminate |
| Examples | LVS, AWS NLB | nginx, HAProxy, AWS ALB, Envoy |
- L4: simply forwards packets/connections, doesn't "understand" HTTP. Very fast, minimal overhead.
- L7: parses the HTTP request, can route
/apito one set of servers and/staticto another, do sticky sessions by cookie, terminate TLS, rewrite headers.
Algorithms: round-robin, least connections, hash by IP (sticky), weighted.
⚠️ Gotcha: L7 balancing requires terminating TLS at the balancer (otherwise it can't see the HTTP) — which raises questions of trust and where the certificates live. WebSockets need support for long-lived connections and Upgrade. Health checks are mandatory, otherwise traffic will be sent to a dead backend.
25Firewall in brief
junior
Short answer: A firewall is a system that filters network traffic by rules (addresses, ports, protocols, state). It can be stateless (per-packet), stateful (tracks connections), or application-layer (understands protocols).
In depth:
- Stateless (packet filter): rules by src/dst IP, ports, protocol; each packet independently.
- Stateful: remembers established connections, automatically allows return traffic (if the request is allowed, the response is too).
- Application firewall / WAF: analyzes HTTP traffic, blocks SQL injection, XSS, etc.
A typical policy: "deny everything that isn't explicitly allowed" (default deny). For example, open only port 443 to the outside.
⚠️ Gotcha: NAT ≠ firewall, even though it incidentally hides internal hosts. And a port-level firewall doesn't protect against application-layer attacks (you need a WAF for that). "Only 443 is open" does not mean the application behind it is secure.
27HTTP methods and idempotency
junior
Short answer: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS. An idempotent method produces the same result when repeated (GET, PUT, DELETE); a safe one doesn't change state (GET, HEAD). POST is not idempotent.
In depth:
| Method | Safe | Idempotent |
|---|---|---|
| GET | yes | yes |
| HEAD | yes | yes |
| OPTIONS | yes | yes |
| PUT | no | yes |
| DELETE | no | yes |
| POST | no | no |
| PATCH | no | not necessarily |
- Idempotency matters for network retries: if the response is lost, retrying PUT/DELETE is safe, whereas retrying POST may create a duplicate.
⚠️ Gotcha: Idempotency is about the effect on the server, not about getting an identical response. DELETE twice: the first deletes (200), the second returns 404, but the state is the same -> idempotent.
The full semantics of methods, status codes, and REST are in the HTTP file.
28gRPC over HTTP/2
middle
Short answer: gRPC is an RPC framework from Google that uses HTTP/2 as its transport and Protocol Buffers for serialization. It benefits from HTTP/2 multiplexing and supports streaming in both directions.
In depth:
- Transport: HTTP/2 — hence multiplexing (many calls over one connection), binary framing, header compression.
- Serialization: Protobuf — a compact binary format described in a
.protoschema (the contract). - Call types: unary, server-streaming, client-streaming, bidirectional streaming (the latter are possible precisely thanks to HTTP/2 streams).
- More efficient than JSON/REST in size and speed, with a strict contract.
⚠️ Gotcha: gRPC requires HTTP/2 end-to-end, and browsers don't give full access to HTTP/2 frames from JS — hence gRPC-Web (via a translating proxy, e.g. Envoy). Direct gRPC from the browser is impossible. Also, intermediate L7 proxies must support HTTP/2.
29Idempotency of network retries
middle
Short answer: On a network, the response can be lost even though the request was processed — the client doesn't know whether it went through. A safe retry is only possible for idempotent operations; for non-idempotent ones (POST), an idempotency key is used.
In depth:
Problem: the client sends "charge 100₽", the server charges it, but the response is lost. The client retries -> double charge.
Solutions:
- Make the operation idempotent: PUT with full state, DELETE by ID.
- Idempotency key: the client generates a unique key and sends it in a header (
Idempotency-Key). The server remembers the result by the key; a retry with the same key returns the saved result without performing the operation again. This is what Stripe and payment APIs do. - Server-side deduplication by a business identifier.
⚠️ Gotcha: "At-least-once" delivery (retries on failure) almost always requires idempotency on the receiver's side. Distributed systems give at-least-once by default, not exactly-once; exactly-once is "effectively" achieved precisely through idempotency + deduplication.
30CORS at the network level (preflight)
middle
Short answer: CORS is a browser mechanism that controls cross-site requests. For "non-simple" requests, the browser first sends a preflight OPTIONS request, and only if the server returns permissive headers does it perform the actual request.
In depth:
- By the same-origin policy, the browser blocks cross-domain requests from JS unless the server explicitly allows them.
- Preflight: for requests with non-standard methods/headers, the browser automatically sends:
OPTIONS /api/data HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Authorization
- The server responds with permissive headers:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: PUT, GET, POST
Access-Control-Allow-Headers: Authorization
Access-Control-Max-Age: 86400
- Only after that does the browser send the real request.
Max-Agecaches the preflight.
⚠️ Gotcha: CORS is browser protection, not server protection; curl/server-to-server requests ignore it. And CORS doesn't "allow" the request — it merely tells the browser to hand the response to the JS code. Simple requests (GET/POST with simple headers) don't require a preflight.
Details on CORS security and the same-origin policy are in the authentication file.
31ICMP, ping, traceroute
junior
Short answer: ICMP is a network-layer control protocol for diagnostics and error messages. Ping uses ICMP Echo to check reachability and RTT. Traceroute shows the packet's path through routers.
In depth:
- ICMP doesn't carry user data; it sends messages like "host unreachable", "time to live exceeded", "fragmentation needed".
- ping: sends an ICMP Echo Request, waits for an Echo Reply. Measures RTT and packet loss.
ping example.com. - traceroute / tracert: sends packets with an increasing TTL (1, 2, 3...). Each router, decrementing the TTL to 0, returns an ICMP "Time Exceeded" — this is how each hop along the path is revealed.
traceroute:
TTL=1 -> router 1 replies "Time Exceeded"
TTL=2 -> router 2 replies ...
... -> destination replies with Echo Reply / Port Unreachable
⚠️ Gotcha: Many hosts/firewalls block ICMP, so "ping doesn't go through" doesn't always mean the server is unreachable — it may simply be ignoring ICMP while still serving HTTP. Traceroute on Linux often uses UDP, on Windows ICMP; the results may differ.
32Keep-alive and connection pooling
middle
Short answer: Keep-alive (persistent connections) reuses a single TCP connection for multiple HTTP requests, avoiding repeated handshakes. Connection pooling is a client-side pool of pre-opened connections to a server/DB.
In depth:
- HTTP keep-alive: in HTTP/1.1 the connection is persistent by default (
Connection: keep-alive). Multiple requests go over a single TCP connection — saving the RTT of a TCP+TLS handshake for each one. - Connection pooling: the application keeps a set of open connections (to a DB, to external APIs) and reuses them instead of opening a new one for each request. Reduces latency and load (a handshake is expensive).
- TCP keep-alive (a separate thing!): low-level packets that check whether the connection is still alive, so dead ones can be freed.
Why: establishing TCP (1 RTT) + TLS (1–2 RTT) is expensive. Reuse removes these delays for subsequent requests — critical when requests are frequent.
⚠️ Gotcha: Don't confuse HTTP keep-alive (reuse at the application layer) and TCP keep-alive (liveness checking at the transport layer). Connection pools require tuning timeouts: connections that hang too long may be closed by a firewall/load balancer, and the application will get an error when it tries to use them (stale connection).
33Conceptual questions
concept
🔹 Why is the TCP handshake needed? So both sides agree on initial sequence numbers (for ordering and loss detection) and confirm the channel works in both directions before sending data. Without it you can't guarantee reliable, ordered delivery. The cost is 1 RTT of latency.
🔹 Why UDP for video calls but TCP for the web? In a video call, latency is worse than loss: it's better to skip a stale frame than to wait for it to be retransmitted and accumulate lag. TCP would retransmit and stall the whole stream (HoL blocking). On the web/for files, every byte is critical and order matters — you need TCP's reliability. A real video stack (WebRTC) builds reliability selectively on top of UDP itself.
🔹 How does HTTPS protect data if it travels through many nodes? TLS provides end-to-end encryption between client and server. Intermediate nodes (routers, ISPs) see only encrypted bytes and addresses (IP, SNI), not the content. The certificate + chain of trust guarantee you're talking to exactly the intended server, not a MITM. The certificate can't be forged without the private key and the signature of a trusted CA. So "many nodes" is no problem — they merely forward traffic that is opaque to them.
🔹 Why DNS, why not just use IPs directly? IPs change (migrations, load balancing, a CDN serves a different IP by geolocation), whereas names are stable and human-readable. DNS is a layer of indirection: you change the name->IP binding without changing references everywhere. Hard-coding IPs would make infrastructure inflexible and fragile, and would break CDNs and fault tolerance.
⚠️ Gotcha: On conceptual questions the interviewer wants reasoning about trade-offs, not a memorized definition. Always frame it as "X is better than Y when..., because...".
Source notes
References and review policy
RecallDeck’s interview answers are editorial material, reviewed against maintained official documentation where a primary reference is available. Tool selections use direct provider links and contain no affiliate placements. Features can change after the review date.
From reading to recall
Practice the full interview loop.
RecallDeck schedules the concepts you miss and keeps coding, design, and behavioral fundamentals available when the interviewer changes direction.