Home/Interview Questions/Computer Networks

Computer Networks Interview Questions and Answers

Last updated:

Check out 46 of the most common Computer Networks interview questions, then take an AI-powered practice interview

TCP/IPHTTPDNSSubnettingNetwork Security
46+
Questions
18
Basic
18
Intermediate
10
Advanced
Q1

Walk me through the OSI seven layer model and map each layer to something you actually touch in a modern web stack.

BasicOSI and TCP/IP Models

Answer

OSI has seven layers, bottom up: Physical, Data Link, Network, Transport, Session, Presentation, Application. The useful version of this answer attaches each layer to a real object. Physical is the fibre from your ONT to the Jio exchange, the Cat6 run to the switch, the WiFi radio, voltages and light pulses.

Data Link is Ethernet frames and MAC addresses, the switch on your office floor, 802.11 on WiFi, and ARP living at the boundary between this layer and the one above. Network is the IP packet, your default gateway, routers, and BGP between ISPs; this is the layer that gets a packet across networks it has never seen. Transport is TCP and UDP, port numbers, and the socket your Node or Java process binds to.

Session in practice is folded into the layers around it, but TLS session resumption and RPC session semantics live conceptually here. Presentation is encoding and encryption: TLS, gzip and brotli compression, JSON versus protobuf, UTF-8. Application is HTTP, DNS, SMTP, WebSocket, gRPC, the protocols your code speaks directly.

The TCP/IP model that the internet actually implements has four layers: Link (OSI 1 and 2), Internet (OSI 3), Transport (OSI 4) and Application (OSI 5, 6 and 7). Say explicitly that OSI is a teaching and troubleshooting reference model, not an implementation. What the interviewer is probing is whether you can localise a fault: a certificate error is layer 6 or 7, a routing loop is layer 3, a duplex mismatch is layer 1 or 2, and knowing which layer to look at first is the whole point of the model.

OSI layer        Unit      Address        Real thing you touch          Tool
7 Application    Data      URL / hostname HTTP, DNS, gRPC, SMTP        curl, dig
6 Presentation   Data      none           TLS, gzip, JSON, UTF-8        openssl s_client
5 Session        Data      none           TLS resumption, RPC session   openssl s_client
4 Transport      Segment   Port           TCP, UDP, sockets             ss, netstat
3 Network        Packet    IP address     IP, ICMP, routing, BGP        ping, traceroute
2 Data Link      Frame     MAC address    Ethernet, WiFi, ARP, VLAN     ip neigh, arp
1 Physical       Bit       none           Fibre, Cat6, radio            ethtool, link LEDs

TCP/IP mapping
  Application  = OSI 7 + 6 + 5
  Transport    = OSI 4
  Internet     = OSI 3
  Link         = OSI 2 + 1

Key Points

  • Seven OSI layers, four TCP/IP layers, and the mapping between them
  • OSI is a reference model; the internet implements TCP/IP
  • Each layer has its own addressing: port, IP, MAC
  • The real value is fault localisation, not memorisation
💡 Pro Tip: Never recite the seven layers as a bare list. Attach one concrete object and one diagnostic tool to each layer. Panels hear the list version fifty times a week and the mapped version twice.
Q2

Trace the encapsulation of a single HTTP POST as it goes down the stack from your browser to the wire, naming every header that gets added.

BasicOSI and TCP/IP Models

Answer

Encapsulation means each layer wraps the data from the layer above with its own header, and decapsulation reverses it on the receiving host. Start at the application: your browser builds an HTTP request, a request line, headers and a JSON body, maybe two kilobytes of text. TLS then encrypts it into one or more TLS records, each with a small record header giving content type, version and length.

The transport layer hands the ciphertext to TCP, which splits it into segments no larger than the MSS and prepends a twenty byte header carrying source port, destination port, sequence number, acknowledgement number, flags and window size. That segment goes to the network layer, which prepends a twenty byte IPv4 header with source IP, destination IP, TTL, protocol number 6 for TCP, and a header checksum. The data link layer wraps that packet in an Ethernet frame: destination MAC, source MAC, EtherType 0x0800, plus a four byte CRC trailer.

Finally the physical layer serialises the bits onto copper, fibre or radio. Two details interviewers push on. First, the destination MAC is the MAC of your default gateway, not of the remote server, because MAC addressing is local to the link; the IP header keeps the real destination end to end while the Ethernet header is rewritten at every hop.

Second, TTL is decremented by each router, which is exactly the mechanism traceroute abuses. The total overhead is roughly fifty four bytes per packet before payload, which is why very small packets are expensive at scale.

Browser payload
  [ HTTP request: POST /api/apply HTTP/1.1 ... {json} ]

+ TLS record header (5 bytes)
  [ TLS ][ encrypted HTTP ]

+ TCP header (20 bytes: sport, dport, seq, ack, flags, window)
  [ TCP ][ TLS ][ encrypted HTTP ]

+ IP header (20 bytes: src IP, dst IP, TTL, proto=6, checksum)
  [ IP ][ TCP ][ TLS ][ encrypted HTTP ]

+ Ethernet header (14 bytes) and CRC trailer (4 bytes)
  [ ETH ][ IP ][ TCP ][ TLS ][ encrypted HTTP ][ CRC ]

Key point at each router hop:
  ETH header  -> rewritten (new src/dst MAC for the next link)
  IP header   -> kept, TTL decremented by 1, checksum recomputed
  TCP payload -> untouched

Key Points

  • Each layer prepends its own header; Ethernet also appends a CRC trailer
  • Destination MAC is the default gateway, destination IP is the real server
  • Ethernet header is rewritten at every hop, IP header survives end to end
  • Roughly 54 bytes of headers per packet before payload
Q3

What happens end to end when you type goodspace.ai in a browser and press Enter? Take it all the way to pixels on screen.

BasicDNS and Application Layer

Answer

This is the single most asked networking question in Indian interviews, and the panel is grading structure, not trivia. Answer in ordered stages. First the browser parses the input, decides it is a URL not a search term, normalises it and checks the HSTS preload list, which for a preloaded domain upgrades http to https before any request leaves.

Next, name resolution walks a cache chain: browser DNS cache, OS resolver cache, the hosts file, then the configured recursive resolver, typically your ISP or 8.8.8.8. If the recursive resolver has nothing cached, it queries a root server for the ai TLD nameservers, then the TLD servers for the authoritative nameservers of goodspace.ai, then the authoritative server for the A or AAAA record, and caches the result for the record TTL. With an IP in hand the OS consults its routing table, sees the destination is off link, and needs the MAC of the default gateway, so it checks the ARP cache and broadcasts an ARP request if there is a miss.

Now TCP: a three way handshake, SYN, SYN-ACK, ACK, one round trip. Then TLS: ClientHello with SNI and supported ciphers, ServerHello with certificate and key share, certificate chain validation against the trust store, and in TLS 1.3 one round trip to a working session. Then the HTTP request goes out with Host, User-Agent, Accept and Cookie headers, and the server replies with a status line, headers and HTML. The browser parses the HTML, discovers CSS, JS and images, opens more connections or multiplexes over HTTP/2, builds the DOM and CSSOM, computes layout, and paints.

1. URL parse + HSTS check      http -> https upgrade if preloaded
2. DNS resolution
     browser cache -> OS cache -> /etc/hosts -> recursive resolver
     resolver -> root (.) -> TLD (.ai) -> authoritative -> A record
3. Routing decision              dest not on my subnet -> send to gateway
4. ARP                           who has 192.168.1.1 ? -> gateway MAC
5. TCP handshake                 SYN -> SYN,ACK -> ACK        (1 RTT)
6. TLS handshake                 ClientHello(SNI) -> ServerHello+cert
                                 cert chain validated -> keys (1 RTT in 1.3)
7. HTTP request
     GET / HTTP/2
     :authority: goodspace.ai
     accept: text/html
8. Response  200, text/html, cache-control, set-cookie
9. Render    parse HTML -> DOM, CSS -> CSSOM, JS, layout, paint

Measure the whole thing:
  curl -s -o /dev/null -w "dns=%{time_namelookup} conn=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" https://goodspace.ai

Key Points

  • Cache chain first: browser, OS, hosts file, then recursive resolver
  • Recursion order is root, then TLD, then authoritative nameserver
  • ARP resolves the gateway MAC, not the server MAC
  • TCP handshake, then TLS handshake, then the HTTP exchange
  • Rendering is DOM plus CSSOM, layout, paint
💡 Pro Tip: Give the stage headings first in about twenty seconds, then ask which stage they want in depth. It shows structure and lets the interviewer steer, which beats a four minute monologue every time.
Q4

TCP or UDP: pick one for a video call, for DNS, for a multiplayer game, and for a UPI payment, and defend each choice.

BasicTransport Layer

Answer

The framing that scores is: TCP buys reliability and ordering at the cost of latency and head of line blocking, UDP buys speed and control at the cost of doing reliability yourself. Video call: UDP. A frame that arrives late is worthless, so retransmitting it wastes bandwidth and delays everything behind it.

WebRTC runs media over UDP with RTP, uses forward error correction and concealment for loss, and only falls back to TCP when a firewall blocks UDP entirely, at which point call quality visibly degrades. DNS: UDP on port 53 for ordinary queries, because a query and response usually fit in one datagram and setting up a TCP connection for a two hundred byte exchange would triple the latency. DNS falls back to TCP when a response exceeds the size limit, which is why blocking TCP 53 on a firewall breaks DNSSEC and large zone responses.

Multiplayer game: UDP for position and state updates, because the newest state supersedes the old one and re sending a stale position is pointless; games layer their own sequencing and reliability only on the messages that need it, such as inventory changes. UPI payment: TCP, always, over TLS. A payment must not be lost, duplicated or reordered, and you want the transport to guarantee delivery so the application only has to worry about idempotency keys and retries. The senior follow up is HTTP/3, which runs over UDP through QUIC and rebuilds reliability, ordering and congestion control in user space, so the TCP versus UDP split is now about who implements reliability rather than whether you get it.

Property            TCP                      UDP
Connection          handshake required       connectionless
Reliability         acks + retransmission    none
Ordering            guaranteed               none
Flow control        sliding window           none
Congestion control  built in                 you build it
Header size         20 bytes                 8 bytes
Head of line block  yes                      no

Decision table
  Video / voice (WebRTC)   UDP   late frame is useless
  DNS query                UDP   one shot, TCP fallback for big answers
  Game state updates       UDP   newest state wins
  UPI payment / API        TCP   must not lose or reorder
  Bulk file transfer       TCP   throughput and integrity
  HTTP/3                   UDP   QUIC rebuilds reliability in user space

See which transport a socket uses:
  ss -tunap | grep 443

Key Points

  • TCP gives reliability, ordering and congestion control; UDP gives control and low latency
  • Late media frames are worthless, so real time media uses UDP
  • DNS is UDP first with TCP fallback for large responses
  • Payments use TCP over TLS plus application level idempotency
💡 Pro Tip: Never answer this as a feature list. Pick each use case, name the property that decides it, and say the consequence out loud. The interviewer is testing judgement, and a comparison table with no decision attached reads as memorised.
Q5

Explain the TCP three way handshake segment by segment, including what each side learns from it.

BasicTransport Layer

Answer

The handshake exists to synchronise sequence numbers in both directions and to confirm that both hosts can send and receive. Segment one: the client sends SYN with a randomly chosen initial sequence number, say 1000, plus options in the header, MSS, window scale factor, SACK permitted, and often a timestamp. The client socket moves to SYN_SENT.

Segment two: the server, whose listening socket is in LISTEN, replies with SYN and ACK together. It carries the server's own random initial sequence number, say 5000, and an acknowledgement number of 1001, meaning I have your byte stream up to 1000 and expect 1001 next. The server socket is now in SYN_RECEIVED and the connection sits in the SYN queue.

Segment three: the client sends ACK with sequence 1001 and acknowledgement 5001. Both sides move to ESTABLISHED and the connection moves from the SYN queue to the accept queue, where your application's accept call picks it up. Points that separate a good answer.

Initial sequence numbers are randomised deliberately, to make blind injection of segments by an off path attacker impractical. The MSS, window scale and SACK options are only negotiated here, so if a middlebox strips window scaling from the SYN the connection is permanently capped at a 64 kilobyte window. The handshake costs one full round trip before a single byte of data moves, which on a two hundred millisecond rural link is real user visible delay, and it is why TCP Fast Open and TLS 1.3 early data exist. Also note the client's ACK can carry data, so the third segment is not always empty.

Client                                          Server
  |                                               | LISTEN
  |  SYN  seq=1000  win=64240                     |
  |  opts: mss=1460 sackOK wscale=7               |
  |==============================================>| SYN_RECEIVED
SYN_SENT                                           |
  |  SYN,ACK  seq=5000  ack=1001  win=65535       |
  |<==============================================|
  |  ACK  seq=1001  ack=5001                      |
ESTABLISHED ======================================> ESTABLISHED

Watch it live:
  sudo tcpdump -i any -n "tcp port 443 and tcp[tcpflags] & (tcp-syn|tcp-ack) != 0"

Queue sizing that matters under load:
  net.ipv4.tcp_max_syn_backlog   SYN queue depth
  net.core.somaxconn             accept queue depth
  listen(fd, backlog)            app side of the accept queue

Key Points

  • Purpose is sequence number synchronisation in both directions
  • MSS, window scale and SACK are negotiated only in the SYN and SYN-ACK
  • Initial sequence numbers are randomised to resist blind injection
  • Costs one full round trip before any data moves
Q6

What exactly do TCP sequence and acknowledgement numbers count, and what does a duplicate ACK tell the sender?

BasicTransport Layer

Answer

They count bytes, not packets, and that is the answer most candidates get wrong. The sequence number in a segment is the byte offset of the first byte of that segment's payload within the sender's stream, starting from a randomly chosen initial sequence number. If the ISN is 1000 and you send 500 bytes, that segment has seq 1001 and the next has seq 1501.

The acknowledgement number is the next byte the receiver expects, so ack 1501 means everything up to and including byte 1500 arrived. This is cumulative acknowledgement: one ACK confirms everything below it, so a lost ACK is harmless as long as a later one arrives. SYN and FIN each consume one sequence number even though they carry no payload, which is why the handshake acknowledges 1001 rather than 1000.

Now the duplicate ACK. Suppose segments 1, 2, 3, 4 are sent and segment 2 is lost. The receiver gets 1 and acks 1501.

It then gets 3, which is out of order, so it cannot advance the cumulative ack and repeats ack 1501. Same for 4. The sender sees the same acknowledgement number arriving repeatedly with no new data acknowledged, and after three duplicate ACKs it concludes segment 2 was lost and retransmits immediately rather than waiting for the retransmission timeout.

That is fast retransmit. Because cumulative acks cannot express holes, modern stacks negotiate SACK in the handshake, which lets the receiver report exactly which byte ranges it holds so the sender retransmits only the gap instead of everything after it.

ISN = 1000 (chosen randomly at handshake)

Send 3 segments of 500 bytes each:
  seg A  seq=1001  len=500   covers bytes 1001..1500
  seg B  seq=1501  len=500   covers bytes 1501..2000   <== LOST
  seg C  seq=2001  len=500   covers bytes 2001..2500

Receiver acks:
  got A        -> ack=1501            "send me 1501 next"
  got C (gap)  -> ack=1501  DUP #1    plus SACK block 2001..2500
  got D (gap)  -> ack=1501  DUP #2
  got E (gap)  -> ack=1501  DUP #3    -> sender does fast retransmit of B

SACK option in the ACK lets the sender resend ONLY 1501..2000

Count retransmissions on a box:
  netstat -s | grep -i retrans
  ss -ti dst 10.0.3.9 | grep -o "retrans:[^ ]*"

Key Points

  • Sequence and acknowledgement numbers count bytes, not packets
  • ACK number is the next expected byte, and acknowledgement is cumulative
  • SYN and FIN each consume one sequence number
  • Three duplicate ACKs trigger fast retransmit; SACK reports the exact hole
Q7

Walk through TCP connection termination. Why does it take four segments and which side ends up in TIME_WAIT?

BasicTransport Layer

Answer

TCP connections are full duplex, so each direction is closed independently and that is why teardown needs four segments rather than three. The side that closes first, the active closer, sends FIN and enters FIN_WAIT_1. The peer's TCP acknowledges that FIN immediately and enters CLOSE_WAIT; the active closer moves to FIN_WAIT_2.

At this point the connection is half closed: the closer will send no more data but can still receive, which is exactly how a client can send a request, close its write side, and still read the response. When the peer's application finishes and calls close, its TCP sends its own FIN and moves to LAST_ACK. The active closer acknowledges that FIN and enters TIME_WAIT, waiting for twice the maximum segment lifetime, sixty seconds on Linux, before the socket is finally freed.

The passive closer goes straight to CLOSED once its FIN is acknowledged. Two things interviewers dig into. First, TIME_WAIT always lands on the side that closed first, so if your server closes connections after each response your server accumulates TIME_WAIT sockets, and if the client closes then the client does.

Second, CLOSE_WAIT piling up is an application bug, not a network problem: it means the peer sent FIN, the kernel acknowledged it, and your code never called close on the socket, usually a leaked file descriptor in an error path. TIME_WAIT is normal and self healing; thousands of CLOSE_WAIT sockets means you are leaking descriptors and will eventually hit the process limit.

Active closer                              Passive closer
ESTABLISHED                                ESTABLISHED
  |  FIN  seq=x                              |
  |=========================================>| CLOSE_WAIT
FIN_WAIT_1                                   |  (app has not called close yet)
  |  ACK  ack=x+1                            |
  |<=========================================|
FIN_WAIT_2                                   |
  |                       app calls close()  |
  |  FIN  seq=y                              |
  |<=========================================| LAST_ACK
  |  ACK  ack=y+1                            |
  |=========================================>| CLOSED
TIME_WAIT (2*MSL, 60s on Linux) -> CLOSED

Check which states you are accumulating:
  ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn

  12043 TIME-WAIT     normal if this box closes first
    418 ESTAB
    902 CLOSE-WAIT    BUG: your code is not calling close()

Key Points

  • Four segments because each direction closes independently
  • Half close lets the closer keep receiving after sending FIN
  • TIME_WAIT lands on whichever side closed first, for 2 times MSL
  • Growing CLOSE_WAIT is an application leak, not a network issue
💡 Pro Tip: If asked about CLOSE_WAIT, say the word 'application bug' in the first sentence. It is the fastest way to signal you have actually debugged a production socket leak rather than read a diagram.
Q8

What identifies a TCP connection uniquely? Explain how one server on port 443 handles fifty thousand simultaneous clients.

BasicTransport Layer

Answer

A TCP connection is identified by a four tuple: source IP, source port, destination IP, destination port. The listening socket is a separate thing from the connected sockets. Your server binds one listening socket to 0.0.0.0:443.

When a client connects, accept returns a new socket whose four tuple includes the client's IP and ephemeral port, so fifty thousand clients produce fifty thousand distinct four tuples all sharing the same server IP and port 443. There is no per connection port consumption on the server side, which is why the common belief that a server can only handle 65,535 connections is wrong. The 65,535 limit applies to the client side, and only per destination four tuple: a single client machine opening connections to one server IP and port is bounded by its ephemeral port range, on Linux typically 32768 to 60999, giving about 28,000 concurrent connections to that one destination.

That is why a load test box or an API gateway hammering one upstream runs out of ports long before the upstream runs out of capacity, and the fixes are more source IPs, a wider ephemeral range, or connection reuse via keep alive. What actually bounds the server is file descriptors and memory: every connected socket is a descriptor with send and receive buffers, so ulimit for open files, the system wide file max, and socket buffer sizing are the real ceilings. Ports 0 to 1023 are well known and need privilege to bind on Unix, 1024 to 49151 are registered, and the rest are ephemeral.

Connection identity = (src IP, src port, dst IP, dst port)

  10.1.4.7:51422  ->  35.200.1.9:443     connection 1
  10.1.4.7:51423  ->  35.200.1.9:443     connection 2   (same client!)
  49.36.180.2:60110 -> 35.200.1.9:443    connection 3

Server side: one listening socket, N connected sockets, all on :443

  ss -tanp | head
  State   Recv-Q Send-Q  Local Address:Port   Peer Address:Port
  LISTEN  0      4096          0.0.0.0:443          0.0.0.0:*    users:(("nginx"))
  ESTAB   0      0          10.0.2.15:443       49.36.180.2:60110
  ESTAB   0      0          10.0.2.15:443       49.36.180.2:60111

Client side limit (per destination), not server side:
  cat /proc/sys/net/ipv4/ip_local_port_range   -> 32768 60999

Real server ceilings:
  ulimit -n                       per process file descriptors
  cat /proc/sys/fs/file-max       system wide

Key Points

  • Four tuple identifies a connection: src IP, src port, dst IP, dst port
  • One listening socket serves unlimited connected sockets on the same port
  • The 65,535 limit is a client side per destination limit, not a server limit
  • Server ceilings are file descriptors and socket buffer memory
Q9

Explain the structure of an IPv4 address, why address classes are obsolete, and what CIDR notation actually means.

BasicSubnetting and Addressing

Answer

An IPv4 address is 32 bits written as four decimal octets, and it always splits into a network portion and a host portion. The classful scheme divided the space by leading bits: class A, 0.0.0.0 to 127.255.255.255, with an 8 bit network and 16.7 million hosts; class B, 128 to 191, with 16 bits of network and 65,534 hosts; class C, 192 to 223, with 24 bits of network and 254 hosts; class D, 224 to 239, reserved for multicast; class E, 240 and above, reserved. Classes are obsolete because the granularity was catastrophic.

An organisation needing 2,000 addresses had to take a class B and waste 63,000, or take eight class C blocks and carry eight routes. That wasted the address space and exploded the global routing table. CIDR, introduced in 1993, threw away the fixed boundaries and made the network length explicit as a suffix: 192.168.10.0/24 means the first 24 bits are network and the remaining 8 are host.

The suffix maps directly to a subnet mask, /24 is 255.255.255.0, because it is 24 ones followed by 8 zeros in binary. Usable hosts are 2 to the power of host bits, minus two, because the all zeros host is the network address and the all ones host is the directed broadcast. CIDR also enables supernetting: four adjacent /24s can be advertised as one /22, which is how ISPs keep the global BGP table from exploding. Multicast at 224.0.0.0/4 and loopback at 127.0.0.0/8 survive from the classful era as reserved ranges.

192.168.10.0/24 in binary
  11000000.10101000.00001010.00000000
  |====== network (24 bits) =====||host|

Mask /24
  11111111.11111111.11111111.00000000  = 255.255.255.0

Prefix   Mask              Block size   Usable hosts
/8       255.0.0.0         16777216     16777214
/16      255.255.0.0       65536        65534
/22      255.255.252.0     1024         1022
/24      255.255.255.0     256          254
/26      255.255.255.192   64           62
/28      255.255.255.240   16           14
/30      255.255.255.252   4            2      (point to point links)
/31      255.255.255.254   2            2      (RFC 3021 p2p, no bcast)
/32      255.255.255.255   1            1      (single host / loopback)

usable = 2^(32 - prefix) - 2

Key Points

  • 32 bits split into network and host portions
  • Classes wasted address space and bloated routing tables
  • CIDR makes the prefix length explicit and allows any boundary
  • Usable hosts equal 2 to the host bits minus 2, for network and broadcast
Q10

My laptop says 192.168.1.7 but an IP checker site shows 49.36.180.24. Explain what is happening, and the difference between NAT and PAT.

BasicSubnetting and Addressing

Answer

192.168.1.7 is an RFC 1918 private address. Three ranges are reserved for private use: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. These are not routable on the public internet, every router on the internet drops them, so every home and office in India reuses the same numbers behind their own router. 49.36.180.24 is the public address your ISP assigned to the WAN side of that router.

The translation between the two is NAT. Strictly, basic NAT is a one to one mapping of a private address to a public address, which does not help you share a single address. What your Jio or Airtel router actually does is PAT, port address translation, also called NAT overload or masquerading.

When your laptop sends a packet from 192.168.1.7:51422 to a server, the router rewrites the source to 49.36.180.24:60001, records the mapping in a translation table, and forwards it. The reply comes back to 49.36.180.24:60001, the router looks up the table, rewrites the destination back to 192.168.1.7:51422 and delivers it on the LAN. The port number is what disambiguates your phone, laptop and TV all sharing one public IP. Consequences an interviewer will chase: inbound connections are impossible without an explicit port forward or UPnP mapping, which is why peer to peer and WebRTC need STUN and TURN to traverse NAT; translation entries expire, which is why an idle SSH session dies after a few minutes unless you enable keep alives; and many Indian ISPs put you behind carrier grade NAT so even your router's WAN address is private in the 100.64.0.0/10 range.

Private ranges (RFC 1918), never routed on the public internet
  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

Other reserved space
  127.0.0.0/8       loopback
  169.254.0.0/16    link local (APIPA: you got here because DHCP failed)
  100.64.0.0/10     carrier grade NAT (your ISP's shared space)

PAT translation table inside the home router
  Inside local          Inside global           Outside
  192.168.1.7:51422 <-> 49.36.180.24:60001 <-> 142.250.183.14:443
  192.168.1.9:44120 <-> 49.36.180.24:60002 <-> 142.250.183.14:443
  192.168.1.4:38891 <-> 49.36.180.24:60003 <-> 35.200.1.9:443

One public IP, many devices, disambiguated by the translated port.

Key Points

  • RFC 1918 ranges are private and dropped by internet routers
  • NAT is one to one; PAT overloads one public IP using ports
  • Inbound connections need port forwarding, STUN or TURN
  • Carrier grade NAT at 100.64.0.0/10 means even your WAN IP may be private
Q11

Subnet 192.168.10.0/24 into blocks that each support at least 50 hosts. Give the mask, network, broadcast and usable range for every subnet, and show the binary.

BasicSubnetting and Addressing

Answer

Work it in four steps and say the steps out loud, because the panel is grading method as much as the answer. Step one, size the host portion. You need 50 usable hosts, and usable equals 2 to the host bits minus 2.

Five host bits give 30, not enough. Six host bits give 62, which is enough. So you need 6 host bits.

Step two, derive the prefix: 32 minus 6 equals /26, and the mask is 26 ones then 6 zeros, which is 255.255.255.192. Step three, compute the block size, which is 256 minus 192 equals 64, or equivalently 2 to the 6. Subnets therefore start at multiples of 64 in the fourth octet: 0, 64, 128, 192.

That gives four subnets from the original /24. Step four, for each subnet the network address is the first address, the broadcast is the last, and the usable range is everything in between. Subnet 1 is 192.168.10.0/26, broadcast .63, usable .1 to .62.

Subnet 2 is 192.168.10.64/26, broadcast .127, usable .65 to .126. Subnet 3 is 192.168.10.128/26, broadcast .191, usable .129 to .190. Subnet 4 is 192.168.10.192/26, broadcast .255, usable .193 to .254.

Each has 62 usable addresses, so you waste 12 per subnet, which is the cost of the power of two boundary. The shortcut for locating an arbitrary host: AND the address with the mask. 192.168.10.100 has fourth octet 01100100, ANDed with 11000000 gives 01000000, which is 64, so that host lives in the third subnet, 192.168.10.64/26, broadcast 192.168.10.127.

Requirement: 50 hosts per subnet, from 192.168.10.0/24

Step 1  host bits:  2^5 - 2 = 30  (too small)
                    2^6 - 2 = 62  (works)   -> 6 host bits
Step 2  prefix:     32 - 6 = /26
        mask:       11111111.11111111.11111111.11000000 = 255.255.255.192
Step 3  block size: 256 - 192 = 64

Subnet   Network            Usable range                   Broadcast
1        192.168.10.0/26    192.168.10.1   to .62          192.168.10.63
2        192.168.10.64/26   192.168.10.65  to .126         192.168.10.127
3        192.168.10.128/26  192.168.10.129 to .190         192.168.10.191
4        192.168.10.192/26  192.168.10.193 to .254         192.168.10.255

Locate host 192.168.10.100:
  address 4th octet  01100100   (100)
  mask    4th octet  11000000   (192)
  AND                01000000   (64)   -> network 192.168.10.64/26
                                        broadcast 192.168.10.127

Verify on a box:
  ipcalc 192.168.10.100/26
  sipcalc 192.168.10.0/24 -s 26

Key Points

  • Size host bits first: 2 to the host bits minus 2 must cover the requirement
  • 50 hosts needs 6 host bits, so /26 and mask 255.255.255.192
  • Block size is 256 minus the interesting octet, here 64
  • AND the address with the mask to find any host's network
💡 Pro Tip: Memorise the block size table for the last octet: 128, 192, 224, 240, 248, 252, 254. Then any subnetting question becomes arithmetic you can do in fifteen seconds on a whiteboard instead of two minutes of binary.
Q12

What is ARP, what lives in the ARP cache, and what is gratuitous ARP used for?

BasicIP and Routing

Answer

ARP, Address Resolution Protocol, maps a layer 3 IPv4 address to a layer 2 MAC address on the local link. It exists because a host cannot put a packet on Ethernet without a destination MAC, and it only knows the destination IP. The flow: the host checks whether the destination IP is on its own subnet by ANDing both addresses with its mask.

If it is on link, it needs that host's MAC. If it is off link, it needs the default gateway's MAC instead, which is the detail people miss. It looks in the ARP cache; on a miss it broadcasts an ARP request to ff:ff:ff:ff:ff:ff asking who has 192.168.1.1.

Every host on the broadcast domain sees it, only the owner replies with a unicast ARP reply containing its MAC, and the requester caches the pair for typically a few minutes. ARP has no authentication whatsoever, which is the basis of ARP poisoning: any host can reply claiming to own any IP, and the victim will believe it, giving the attacker a man in the middle position on the LAN. Gratuitous ARP is an unsolicited ARP announcement for your own address, sent as a broadcast.

It has three legitimate uses: detecting duplicate IPs at boot, updating switch MAC address tables when a machine moves ports, and, most importantly in production, failover. When a virtual IP moves from a dead primary to a standby, the standby fires gratuitous ARP so every device on the segment updates its cache and traffic follows the VIP within a second instead of waiting for a cache timeout. IPv6 replaces ARP with Neighbour Discovery, which runs over ICMPv6 and uses multicast instead of broadcast.

Host 192.168.1.7 wants to reach 142.250.183.14 (off link)
  1. AND both with mask -> different networks -> use default gateway
  2. need MAC of gateway 192.168.1.1, check cache -> miss
  3. broadcast: "who has 192.168.1.1? tell 192.168.1.7"
  4. unicast reply: "192.168.1.1 is at 44:e9:dd:1a:2b:c0"

Read the cache (modern and legacy commands):
  ip neigh show
  192.168.1.1 dev wlan0 lladdr 44:e9:dd:1a:2b:c0 REACHABLE
  192.168.1.9 dev wlan0 lladdr 8c:85:90:11:22:33 STALE

  arp -a
  gateway (192.168.1.1) at 44:e9:dd:1a:2b:c0 [ether] on wlan0

Clear a poisoned or stale entry:
  sudo ip neigh flush dev wlan0

Detect poisoning: the same MAC claiming several IPs, or the gateway IP
suddenly mapping to a new MAC mid session.

Key Points

  • Maps IP to MAC on the local link only
  • Off link destinations resolve the gateway MAC, not the server MAC
  • Request is broadcast, reply is unicast, result is cached briefly
  • Gratuitous ARP drives virtual IP failover and duplicate address detection
Q13

Explain the DHCP DORA process and what goes wrong when a client ends up with a 169.254.x.x address.

BasicIP and Routing

Answer

DHCP hands a client its IP address, subnet mask, default gateway, DNS servers and lease time. The exchange is four messages, DORA. Discover: the client has no address, so it broadcasts from 0.0.0.0 to 255.255.255.255 on UDP port 67, carrying its MAC and a transaction ID.

Offer: any DHCP server on the segment replies with a candidate address, mask, gateway, DNS list and lease duration. Request: the client broadcasts a request naming the offer it accepted, and the broadcast is deliberate so that any other servers that made offers can withdraw them. Acknowledge: the chosen server confirms, commits the binding, and the client configures the interface.

The lease is time bounded. At fifty percent of the lease, T1, the client unicasts a renewal to the same server; at 87.5 percent, T2, it broadcasts to any server. Because Discover is a broadcast, it does not cross a router, so on a routed network you either put a DHCP server on each VLAN or configure an IP helper address on the router so it relays DHCP as unicast to a central server.

A 169.254.x.x address means link local autoconfiguration kicked in because no DHCP server answered: the switch port is in the wrong VLAN, the DHCP scope is exhausted, the relay is missing, spanning tree held the port down through the client's timeout, or a rogue DHCP server on the LAN is answering faster with garbage. The fast triage is to check whether the client sees any Offer at all, because Discover with no Offer and Discover with a wrong Offer are completely different problems.

DORA (client has no IP yet, so Discover and Request are broadcast)

  Client 0.0.0.0:68  [DISCOVER] >  255.255.255.255:67
  Server 192.168.1.1 [OFFER]    >  client (ip, mask, gw, dns, lease)
  Client 0.0.0.0:68  [REQUEST]  >  255.255.255.255:67  (names the offer)
  Server 192.168.1.1 [ACK]      >  client (binding committed)

Renewal timers
  T1 = 50%   of lease  -> unicast renew to the same server
  T2 = 87.5% of lease  -> broadcast rebind to any server

See it on the client:
  sudo dhclient -v wlan0
  ip addr show wlan0
  cat /var/lib/dhcp/dhclient.leases

  sudo tcpdump -i any -n port 67 or port 68

Symptom: 169.254.23.90/16 on the interface
  = no DHCP ACK received. Check VLAN, scope exhaustion, ip helper-address
    on the router, spanning tree portfast, or a rogue DHCP server.

Key Points

  • Discover, Offer, Request, Acknowledge over UDP 67 and 68
  • Request is broadcast so unchosen servers can release their offers
  • Broadcasts do not cross routers, so relay via an IP helper address
  • 169.254.x.x means link local fallback, no DHCP server answered
Q14

Read me a Linux routing table and explain exactly how the kernel decides where to send a packet destined for 8.8.8.8.

BasicIP and Routing

Answer

The kernel makes a forwarding decision per packet by consulting the routing table, and the rule is longest prefix match: among all routes whose network contains the destination, the one with the longest prefix wins, and metric breaks ties only between routes of equal prefix length. A typical laptop table has three kinds of entry. A default route, 0.0.0.0/0 via the gateway on a given interface, prefix length zero so it matches everything and loses to every other route.

Connected routes, such as 192.168.1.0/24 dev wlan0 with a scope of link, installed automatically when you configure an address on an interface; these have no gateway because the destination is directly reachable. Specific routes added by a VPN or by hand, for example 10.20.0.0/16 via 10.8.0.1 dev tun0. For 8.8.8.8 the kernel checks each route: 192.168.1.0/24 does not contain it, 10.20.0.0/16 does not contain it, 0.0.0.0/0 does.

So the default route wins, the next hop is 192.168.1.1, the outgoing interface is wlan0, and the source address is chosen from that interface. The kernel then needs the gateway's MAC and hits ARP. A classic production trap is a VPN that pushes 0.0.0.0/1 and 128.0.0.0/1: those two routes cover the whole space with prefix length one, so they beat the existing default without deleting it, which is how full tunnelling is implemented and why removing the VPN cleanly matters. Use the route get form to ask the kernel directly rather than reasoning by eye.

ip route show
  default via 192.168.1.1 dev wlan0 proto dhcp metric 600
  10.20.0.0/16 via 10.8.0.1 dev tun0 proto static
  169.254.0.0/16 dev wlan0 scope link metric 1000
  192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.7

Legacy view of the same table:
  netstat -rn
  Destination     Gateway         Genmask         Flags  Iface
  0.0.0.0         192.168.1.1     0.0.0.0         UG     wlan0
  10.20.0.0       10.8.0.1        255.255.0.0     UG     tun0
  192.168.1.0     0.0.0.0         255.255.255.0   U      wlan0

Decision for 8.8.8.8 (longest prefix match):
  192.168.1.0/24  no match
  10.20.0.0/16    no match
  0.0.0.0/0       match, prefix len 0  -> chosen by default

Ask the kernel instead of guessing:
  ip route get 8.8.8.8
  8.8.8.8 via 192.168.1.1 dev wlan0 src 192.168.1.7 uid 1000

Key Points

  • Longest prefix match decides, metric only breaks ties at equal length
  • Connected routes have scope link and no gateway
  • Default route 0.0.0.0/0 matches everything and loses to any specific route
  • ip route get answers the question authoritatively for one destination
Q15

Hub, switch and router: explain the difference in terms of collision domains and broadcast domains.

BasicIP and Routing

Answer

A hub is a layer 1 repeater. It takes bits in on one port and blasts them out of every other port with no understanding of frames. Every device attached shares one collision domain and one broadcast domain, so two hosts transmitting at once collide, CSMA/CD backs both off, and effective throughput collapses as you add devices.

Hubs are extinct outside lab exercises. A switch is a layer 2 device. It reads the source MAC of every incoming frame and builds a MAC address table mapping MAC to port, then forwards frames only out of the port where the destination MAC lives.

Each port is its own collision domain, which combined with full duplex means collisions effectively no longer occur. But a switch still floods broadcasts and unknown unicast out of every port, so the whole switch, and every switch connected to it, forms one broadcast domain. A router is a layer 3 device.

It forwards based on destination IP using the routing table, rewrites the layer 2 header at each hop, decrements TTL, and crucially does not forward broadcasts. So each router interface bounds a broadcast domain. The counting rule interviewers use: collision domains equal the number of switch and router ports, broadcast domains equal the number of router interfaces plus the number of VLANs. VLANs matter here because they let one physical switch host several broadcast domains, giving you router style segmentation without extra hardware, and inter VLAN traffic then has to pass through a router or a layer 3 switch.

Device   Layer  Forwards on   Collision domains   Broadcast domains
Hub      1      nothing       1 for all ports     1
Switch   2      MAC address   1 per port          1 (per VLAN)
Router   3      IP address    1 per port          1 per interface

Switch MAC address table
  VLAN  MAC Address       Type     Port
  10    8c85.9011.2233    DYNAMIC  Gi0/1
  10    44e9.dd1a.2bc0    DYNAMIC  Gi0/2
  20    a4c3.f012.7788    DYNAMIC  Gi0/9

Frame handling on a switch
  known unicast    -> forward out one port
  unknown unicast  -> flood to all ports in the VLAN
  broadcast        -> flood to all ports in the VLAN
  multicast        -> flood unless IGMP snooping is on

Counting example: 2 switches (8 ports each) joined to 1 router with 2 interfaces
  collision domains  = 16 switch ports + 2 router ports = 18
  broadcast domains  = 2 (one per router interface)

Key Points

  • Hub is layer 1, one collision domain, no intelligence
  • Switch is layer 2, one collision domain per port, one broadcast domain per VLAN
  • Router is layer 3, does not forward broadcasts, bounds each broadcast domain
  • VLANs create multiple broadcast domains on one physical switch
Q16

Name the DNS record types you would configure for a production domain and say what each one does.

BasicDNS and Application Layer

Answer

A record maps a hostname to an IPv4 address, AAAA maps it to an IPv6 address. CNAME is an alias pointing one name at another name, and the strict rule is that a CNAME cannot coexist with any other record at the same name, which is why you cannot put a CNAME at the zone apex where SOA and NS already live. Providers work around this with ALIAS or CNAME flattening, resolving the target at the authoritative server and returning an A record.

MX designates mail servers with a priority number, lower being preferred, and MX targets must be hostnames with A records, never IPs and never CNAMEs. TXT holds arbitrary text and in practice carries SPF policy, DKIM public keys, DMARC policy and domain verification tokens for Google Workspace or a payment gateway. NS lists the authoritative nameservers for the zone and must match the delegation held by the parent, which for a .in domain is the registry; a mismatch is the most common cause of intermittent resolution failures.

SOA is the start of authority, one per zone, holding the primary nameserver, the responsible email address, the serial number that drives zone transfers, and the timers, refresh, retry, expire and the minimum TTL that governs negative caching. SRV publishes a service, protocol, priority, weight, port and target, used by SIP, XMPP, LDAP and Kubernetes headless services. Worth adding: PTR for reverse lookups, which mail reputation depends on, and CAA to declare which certificate authorities may issue for your domain.

dig +noall +answer goodspace.ai ANY

goodspace.ai.        300  IN A     35.200.1.9
goodspace.ai.        300  IN AAAA  2600:1901:0:9d3f::
goodspace.ai.       3600  IN MX    10 aspmx.l.google.com.
goodspace.ai.       3600  IN MX    20 alt1.aspmx.l.google.com.
goodspace.ai.       3600  IN TXT   "v=spf1 include:_spf.google.com ~all"
_dmarc.goodspace.ai. 3600 IN TXT   "v=DMARC1; p=quarantine; rua=mailto:d@goodspace.ai"
goodspace.ai.      86400  IN NS    ns1.example-dns.com.
www.goodspace.ai.    300  IN CNAME goodspace.ai.
_sip._tcp.goodspace.ai. 3600 IN SRV 10 60 5060 sip1.goodspace.ai.
goodspace.ai.       3600  IN CAA   0 issue "letsencrypt.org"

SOA and its timers
goodspace.ai. 3600 IN SOA ns1.example-dns.com. hostmaster.goodspace.ai. (
    2026081701  ; serial   bump on every change
    7200        ; refresh
    3600        ; retry
    1209600     ; expire
    300 )       ; minimum = NEGATIVE cache TTL

Query one type only:
  dig +short MX goodspace.ai
  nslookup -type=TXT goodspace.ai 8.8.8.8

Key Points

  • A and AAAA for addresses, CNAME for aliases but never at the apex
  • MX needs a priority and a hostname target, never an IP or CNAME
  • TXT carries SPF, DKIM, DMARC and verification tokens
  • SOA minimum controls negative caching, not positive TTL
Q17

Which HTTP methods are safe, which are idempotent, and what do 301, 302, 401, 403, 429, 502 and 504 each tell you?

BasicHTTP and the Web

Answer

Safe means the method should not change server state: GET, HEAD and OPTIONS are safe. Idempotent means sending the request N times has the same effect as sending it once: GET, HEAD, OPTIONS, PUT and DELETE are idempotent, POST and PATCH are not. This matters operationally because proxies, browsers and client libraries will automatically retry idempotent requests on a timeout, so if you implement a payment as a POST you must add an idempotency key or a retried request charges the user twice.

PUT replaces a resource wholesale at a client chosen URI, POST creates a subordinate resource at a server chosen URI, PATCH applies a partial change. On status codes: 301 is a permanent redirect and browsers cache it aggressively, sometimes indefinitely, so shipping a wrong 301 is very hard to undo, use 302 or 307 while you are unsure. 307 and 308 are the method preserving versions, because 301 and 302 historically caused clients to rewrite a POST into a GET. 401 means unauthenticated, the credentials are missing or invalid, and the response must carry a WWW-Authenticate header; 403 means authenticated but not permitted, so retrying with the same token is pointless. 429 is rate limited and should carry Retry-After; a good client honours it with backoff and jitter. 502 bad gateway means your reverse proxy reached the upstream but got an invalid or aborted response, typically the app crashed or closed the connection. 504 gateway timeout means the upstream never answered within the proxy timeout, which is a slow query or a deadlock, not a crash.

Method   Safe   Idempotent   Typical use
GET      yes    yes          read
HEAD     yes    yes          headers only, existence and size checks
OPTIONS  yes    yes          CORS preflight, capability discovery
PUT      no     yes          full replace at a known URI
DELETE   no     yes          remove
POST     no     NO           create, non idempotent actions
PATCH    no     NO           partial update

A real exchange
  POST /api/v1/applications HTTP/1.1
  Host: api.goodspace.ai
  Content-Type: application/json
  Idempotency-Key: 6f1b2c9a-4e88-4b2f-9a11-5c7d0a3e1f22
  Authorization: Bearer eyJhbGci...

  HTTP/1.1 201 Created
  Location: /api/v1/applications/48213
  Cache-Control: no-store

Status quick read
  301 moved permanently   cached hard by browsers, hard to undo
  302 / 307 found         temporary, 307 preserves the method
  401 unauthenticated     fix the credentials, WWW-Authenticate expected
  403 forbidden           authenticated but not allowed, retry will not help
  429 too many requests   honour Retry-After, back off with jitter
  502 bad gateway         upstream answered badly or died
  504 gateway timeout     upstream never answered in time

Key Points

  • Safe means no state change; idempotent means repeat safe
  • POST and PATCH are not idempotent, so payments need idempotency keys
  • 401 is authentication, 403 is authorisation
  • 502 is a broken upstream response, 504 is an upstream that never replied
💡 Pro Tip: When asked about status codes, immediately volunteer the 401 versus 403 and the 502 versus 504 distinctions. Those two pairs are what the interviewer was going to ask next anyway.
Q18

How does traceroute actually discover each hop, and why do some hops show asterisks?

BasicTroubleshooting

Answer

Traceroute exploits the TTL field in the IP header. Every router that forwards a packet decrements TTL by one, and when TTL reaches zero the router discards the packet and sends back an ICMP Time Exceeded message, type 11, whose source address is that router. Traceroute sends probes with TTL 1, gets Time Exceeded from the first hop and learns its address.

Then TTL 2, learning hop two, and so on until a probe reaches the destination. The destination does not send Time Exceeded; classic Unix traceroute sends UDP to an unlikely high port so the destination replies with ICMP Port Unreachable, type 3 code 3, which marks the end. Windows tracert uses ICMP Echo instead and ends on an Echo Reply.

Three probes per hop are sent by default, which is why you see three round trip times. Asterisks mean no reply arrived within the timeout, and the important interviewing point is that this usually does not mean the packet was dropped. Many routers rate limit ICMP generation or are configured not to generate Time Exceeded at all, security appliances filter ICMP, and some carrier cores hide internal hops entirely.

If traffic still reaches the destination on the final line, the intermediate asterisks are cosmetic. Two more real world caveats: round trip times can appear to decrease at a later hop because each measurement is independent and the return path may differ, so do not read the column as cumulative latency; and MPLS backbones can hide several physical hops behind one logical entry. Use the TCP variant with the destination port when firewalls block UDP and ICMP, since a probe to port 443 usually gets through.

traceroute -n goodspace.ai
 1  192.168.1.1      1.204 ms   1.118 ms   1.061 ms
 2  100.64.0.1      12.442 ms  11.980 ms  12.310 ms   (CGNAT hop)
 3  * * *                                              (ICMP suppressed)
 4  49.45.2.113     18.902 ms  19.114 ms  18.771 ms
 5  72.14.221.20    41.330 ms  40.882 ms  41.005 ms
 6  35.200.1.9      42.118 ms  41.995 ms  42.240 ms

Mechanism
  probe TTL=1 -> hop 1 drops it, replies ICMP Time Exceeded (type 11)
  probe TTL=2 -> hop 2 drops it, replies ICMP Time Exceeded
  ...
  probe TTL=n -> destination replies ICMP Port Unreachable (UDP mode)

When ICMP and UDP are filtered, probe the real service port:
  sudo traceroute -T -p 443 goodspace.ai

Bidirectional view that separates forward and return path loss:
  mtr -rwzbc 100 goodspace.ai

Key Points

  • Increasing TTL forces each hop in turn to reply with ICMP Time Exceeded
  • Asterisks usually mean ICMP is rate limited or filtered, not that traffic is dropped
  • Round trip times are per probe and the return path may differ
  • Use the TCP mode on port 443 when ICMP and UDP are blocked
Q19

Explain recursive versus iterative DNS resolution, and name who does which part of the work.

IntermediateDNS and Application Layer

Answer

Your device, the stub resolver, does almost nothing. It sends one recursive query to a configured resolver and says: give me the final answer, do not send me a referral. That resolver, run by your ISP or by Google at 8.8.8.8 or Cloudflare at 1.1.1.1, accepts the responsibility and then does the real work using iterative queries.

Iterative means each server it asks either answers authoritatively or returns a referral to servers closer to the answer, and the resolver follows the chain itself. Starting cold for www.goodspace.ai the resolver asks a root server, one of the thirteen root nameserver identities served from hundreds of anycast instances including several in India. The root does not know the answer but returns the nameservers for the .ai TLD.

The resolver asks a .ai TLD server, which returns a referral to the authoritative nameservers for goodspace.ai. The resolver asks those, gets the authoritative A record, caches it for the TTL, and returns it to your stub resolver. So there is exactly one recursive query in the whole flow and three or four iterative ones.

Two follow ups to be ready for. Glue records: if the nameserver for goodspace.ai is ns1.goodspace.ai, resolving the nameserver requires the zone you are trying to reach, so the parent zone includes the nameserver's A record as glue to break the circularity. And the authoritative answer flag, aa, in the response header tells you whether you got the answer from the zone's own server or from a cache, which is exactly how you prove a stale cache is the culprit during an incident.

Stub resolver (your laptop) sends ONE recursive query:
  dig www.goodspace.ai            (RD flag set: recursion desired)

The recursive resolver then does the iterative walk:
  dig +trace www.goodspace.ai

  .            518400 IN NS a.root-servers.net.      (root)
  ai.           172800 IN NS a.nic.ai.               (referral to TLD)
  goodspace.ai. 172800 IN NS ns1.example-dns.com.    (referral to authoritative)
  www.goodspace.ai. 300 IN A  35.200.1.9             (authoritative answer)

Ask a specific server directly, bypassing every cache:
  dig @ns1.example-dns.com www.goodspace.ai

Read the header flags to prove where an answer came from:
  ;; flags: qr aa rd; ...     aa = authoritative, straight from the zone
  ;; flags: qr rd ra; ...     no aa = you were served from a cache

Key Points

  • One recursive query from the stub, many iterative queries from the resolver
  • Root returns the TLD servers, TLD returns the authoritative servers
  • Glue records break the circular dependency for in zone nameservers
  • The aa flag distinguishes an authoritative answer from a cached one
Q20

We changed the A record two hours ago and set TTL to 300, but one user in Pune still lands on the old server. Explain every place the old answer could be cached.

IntermediateDNS and Application Layer

Answer

There are at least six caches between your zone file and that user, and the TTL you set only controls one of them going forward. First, the TTL that matters is the one that was in effect when the record was last fetched, not the one you just set. If the record was on a 24 hour TTL and you lowered it to 300 at change time, every resolver that cached the old answer keeps it for the remaining old TTL.

Lowering TTL must be done at least one old TTL before the change, which is the number one operational lesson here. Second, the recursive resolver itself, and some ISP resolvers in India serve stale answers deliberately or ignore short TTLs and enforce a floor of 30 or 60 minutes. Third, the operating system resolver cache, systemd-resolved on Linux, the DNS Client service on Windows, mDNSResponder on macOS.

Fourth, the browser's own DNS cache, which in Chrome is separate from the OS cache and visible at the net internals page. Fifth, the application: JVM based services cache DNS forever by default unless the networkaddress.cache.ttl security property is set, which is a classic outage cause on failover. Sixth, connection pooling above DNS entirely: an open keep alive connection or an HTTP client pool holds a socket to the old IP and never re resolves until that connection closes, so the user can be pinned to a dead backend indefinitely. Diagnose by querying the authoritative server directly, then the user's resolver, and comparing the remaining TTL counting down in successive queries.

1. What does the zone actually say? (bypasses every cache)
   dig @ns1.example-dns.com goodspace.ai A
   goodspace.ai. 300 IN A 35.200.1.9

2. What does the user's resolver say, and how stale is it?
   dig @8.8.8.8 goodspace.ai A
   goodspace.ai. 141 IN A 35.200.1.4      <- OLD IP, 141s left on the cache
   run it twice: if the TTL counts DOWN, it is a cache, not the zone

3. OS cache
   resolvectl flush-caches          (systemd)
   sudo dscacheutil -flushcache     (macOS)
   ipconfig /flushdns               (Windows)

4. Browser cache
   chrome://net-internals/#dns

5. JVM: caches forever by default
   networkaddress.cache.ttl=60      in java.security

6. Connection pool: an open keep alive socket never re resolves
   ss -tanp | grep 35.200.1.4

Lesson: lower the TTL at least one OLD TTL before the migration.

Key Points

  • The old TTL governs the cutover, so lower TTL well before the change
  • Six cache layers: resolver, OS, browser, app runtime, connection pool, plus ISP TTL floors
  • A TTL counting down in repeated digs proves you are hitting a cache
  • JVM DNS caching and keep alive pools defeat DNS changes entirely
💡 Pro Tip: Say 'lower the TTL one old TTL before the migration' unprompted. It instantly marks you as someone who has done a real DNS cutover rather than someone who has read about TTLs.
Q21

How does a CDN send a user in Chennai to a Chennai edge instead of a Mumbai one? Compare DNS based routing with anycast.

IntermediateDNS and Application Layer

Answer

Two mechanisms, often combined. DNS based geo routing: you CNAME your hostname to the CDN, so resolution ends at the CDN's authoritative nameservers. Those servers look at who is asking and return different A records to different askers.

Historically they used the resolver's source IP, which is wrong when the user is in Chennai but using 8.8.8.8, so EDNS Client Subnet was introduced, letting the recursive resolver pass a truncated prefix of the client's address, typically a /24, so the authoritative server can decide on the real client location. It returns the Chennai edge IP to a Chennai prefix and the Mumbai edge IP to a Mumbai prefix. TTLs are kept short, 20 to 60 seconds, so the CDN can steer traffic away from a congested or failed PoP quickly.

The weakness is that steering granularity is only as good as the resolver's honesty about client subnet, and failover takes at least one TTL. Anycast: the CDN advertises the same IP prefix into BGP from many locations at once. Routers pick whichever announcement is closest in BGP terms, so a packet from an Airtel user in Chennai naturally lands on the nearest PoP that Airtel peers with, often at an exchange in Chennai or Mumbai, with no DNS involvement at all.

Failover is near instant because withdrawing a BGP announcement reroutes traffic in seconds. The catch is that BGP closeness is policy based, not geographic, so a poorly peered ISP can send Chennai traffic to Singapore, and long lived TCP flows can theoretically break if routing changes mid connection, which is one reason QUIC's connection IDs are useful.

DNS based steering: same name, different answer per region

  dig +short cdn.goodspace.ai @8.8.8.8            (resolver in Mumbai)
  103.21.244.18

  dig +short cdn.goodspace.ai @a-chennai-resolver
  103.21.245.72

  Chain that makes it work:
  www.goodspace.ai.  CNAME  goodspace.ai.cdn-provider.net.
  goodspace.ai.cdn-provider.net.  30  IN A  <nearest edge>

EDNS Client Subnet lets the authoritative server see the real client prefix:
  dig +subnet=49.36.180.0/24 cdn.goodspace.ai

Anycast: one IP announced from many PoPs via BGP
  1.1.1.1 is announced from Mumbai, Chennai, Singapore, Frankfurt ...
  your packets reach whichever is nearest in BGP terms

  Prove which PoP served you (many CDNs expose a debug endpoint):
  curl -s https://cdn.goodspace.ai/cdn-cgi/trace | grep colo
  colo=MAA        (MAA = Chennai, BOM = Mumbai)

  Confirm with latency, not with the IP:
  ping -c 5 cdn.goodspace.ai

Key Points

  • DNS steering returns different A records per client region, aided by EDNS Client Subnet
  • Short TTLs let the CDN drain a failing PoP, but failover costs one TTL
  • Anycast announces one prefix from many sites and lets BGP choose
  • BGP closeness is policy based, so it is not always geographically nearest
Q22

Explain TCP flow control with the sliding window, and what a zero window means in a packet capture.

IntermediateTransport Layer

Answer

Flow control protects the receiver from being overrun by a fast sender, and it is entirely separate from congestion control, which protects the network. Every TCP segment carries a window field advertising how many more bytes the receiver's buffer can accept beyond the last acknowledged byte. The sender may have at most that many bytes in flight and unacknowledged.

As the receiving application reads data out of the socket buffer, the buffer drains, the advertised window grows, and the usable range slides forward, hence sliding window. The window field is only 16 bits, capping it at 65,535 bytes, which is far too small for modern links: on a 100 millisecond round trip that limits you to about 5 megabits per second regardless of available bandwidth. That is why window scaling exists, negotiated only in the SYN, multiplying the advertised window by a power of two up to a gigabyte.

If a middlebox strips the option from the SYN, throughput is permanently capped and looks like a mysterious bandwidth ceiling. A zero window means the receiver's buffer is completely full and the sender must stop. This is almost never a network problem: it means the receiving application is not calling read fast enough, a slow consumer, a blocked thread, a GC pause, or a downstream database stalling a worker.

The sender then sends periodic zero window probes so it learns when space frees up, because a window update is a pure ACK and could be lost with nobody retransmitting it. In a capture you look for TCP ZeroWindow followed by TCP Window Update, and on the server you look for a persistently non empty receive queue in ss output.

Receiver advertises win=65535, has acked up to byte 5000

  bytes:  ...5000 | 5001 ......................... 70535 | 70536...
          acked   |<===== sender may have this in flight ====>|
                  |            window = 65535                 |

App reads 20000 bytes -> buffer drains -> window grows -> range slides right

Window scaling (negotiated in the SYN only)
  wscale=7  ->  advertised 65535 means 65535 * 128 = ~8 MB
  stripped by a middlebox -> permanent throughput ceiling

Zero window in a capture (Wireshark labels)
  1841  10.0.2.9 -> 10.0.4.3  TCP ZeroWindow  [ACK] win=0
  1902  10.0.2.9 -> 10.0.4.3  TCP Window Update win=64240

On the box, a stuck receive queue is the same signal:
  ss -tin
  State  Recv-Q Send-Q  Local Address:Port  Peer Address:Port
  ESTAB  262144 0       10.0.2.9:8080       10.0.4.3:51233
         cubic wscale:7,7 rtt:38.2/1.4 cwnd:10

  Recv-Q pinned at the buffer size = the APPLICATION is not reading.

Key Points

  • Flow control protects the receiver, congestion control protects the network
  • Window field is 16 bits, so window scaling is mandatory for fast links
  • Window scaling is negotiated only in the SYN and can be stripped by middleboxes
  • Zero window means a slow consuming application, not a slow network
Q23

Explain TCP congestion control through slow start, congestion avoidance, fast retransmit and fast recovery, then compare Reno, CUBIC and BBR on a lossy Indian mobile link.

IntermediateTransport Layer

Answer

The sender keeps a congestion window, cwnd, and may have at most the minimum of cwnd and the receiver's advertised window in flight. Slow start: cwnd begins at about ten segments and doubles every round trip, exponential growth, until it hits the slow start threshold or a loss occurs. Congestion avoidance: past the threshold, cwnd grows by roughly one segment per round trip, linear, probing carefully for more capacity.

Loss detection splits into two paths. If three duplicate ACKs arrive, the sender does fast retransmit, resending the missing segment immediately without waiting for the retransmission timeout, then fast recovery, halving cwnd and continuing from there rather than collapsing to one. If instead the retransmission timeout fires, that is treated as severe congestion: cwnd drops to one segment and slow start restarts, which is catastrophic for throughput.

The comparison is where the Indian context lands. Classic Reno uses that additive increase, multiplicative decrease pattern, halving on every loss. On a 4G link where packets are lost to radio interference rather than to queue overflow, Reno interprets random loss as congestion and repeatedly halves the window, so a link with two percent loss and a 120 millisecond round trip delivers a fraction of its real capacity.

CUBIC, the Linux default, grows as a cubic function of time since the last loss, recovering aggressively after a reduction, which handles high bandwidth delay product paths far better. BBR ignores loss as a congestion signal entirely and instead models the bottleneck bandwidth and minimum round trip time, pacing to that estimate. On lossy mobile paths BBR often delivers multiples of CUBIC's throughput, which is why Google deployed it for YouTube.

cwnd over time

  cwnd
   ^            fast retransmit + fast recovery (3 dup ACKs)
   |                 /|\        cwnd halved, continue linearly
   |        _____/     v ______/
   |      /  congestion avoidance (linear, +1 MSS per RTT)
   |    /  <- ssthresh
   |  /  slow start (exponential, doubles per RTT)
   | /
   +==> time

  RTO fires instead? cwnd = 1 MSS, back to slow start. Brutal.

Algorithm comparison
  Reno   loss based, halve on every loss.   Random radio loss destroys it.
  CUBIC  loss based, cubic regrowth.        Linux default, good on high BDP.
  BBR    model based (bandwidth + min RTT). Ignores random loss, paces output.

Inspect and change on Linux:
  sysctl net.ipv4.tcp_congestion_control
  net.ipv4.tcp_congestion_control = cubic

  cat /proc/sys/net/ipv4/tcp_available_congestion_control
  reno cubic bbr

  sudo sysctl -w net.ipv4.tcp_congestion_control=bbr

Per socket evidence:
  ss -ti | grep -E "cubic|bbr|cwnd|retrans"
  cubic wscale:7,7 rtt:118.4/6.2 cwnd:14 retrans:0/312 lost:2

Key Points

  • Slow start is exponential, congestion avoidance is linear
  • Three duplicate ACKs give fast retransmit and fast recovery; an RTO resets cwnd to one
  • Reno and CUBIC treat any loss as congestion, which punishes lossy radio links
  • BBR models bandwidth and minimum RTT and ignores random loss
Q24

Our gRPC client sees a consistent 40 millisecond stall on small requests over a fast LAN. Explain how Nagle's algorithm and delayed ACK interact to cause this.

IntermediateTransport Layer

Answer

This is the classic Nagle plus delayed ACK deadlock, and 40 milliseconds is the fingerprint because that is the Linux delayed ACK timer. Nagle's algorithm exists to stop a sender flooding the network with tiny packets: if there is already unacknowledged data outstanding, TCP buffers any new small write until either a full MSS worth accumulates or the outstanding data is acknowledged. Delayed ACK exists on the receiver for the mirror reason: rather than acknowledge every segment immediately, wait up to 40 milliseconds hoping either more data arrives so one ACK can cover several segments, or the application produces a response so the ACK can piggyback on it.

Individually both are sensible. Together they deadlock in a specific pattern: the application does two writes for one logical message, a small header then a small body, common in RPC framing or in code that writes headers and payload separately. The first write goes out immediately.

The second is smaller than an MSS and there is unacknowledged data outstanding, so Nagle holds it. The receiver has an incomplete message so the application produces no response, so there is nothing to piggyback on, so delayed ACK waits its full timer. Forty milliseconds later the ACK fires, Nagle releases the buffered write, and the request completes.

The fixes, in order of preference: coalesce the writes into a single write or writev so there is no second small segment at all, which fixes the root cause; or set TCP_NODELAY on the socket to disable Nagle, which is what almost every RPC framework, HTTP client and database driver does by default. Disabling delayed ACK is rarely available and rarely the right lever.

Pathological sequence (two small writes per message)

  t=0ms    client write(header, 12 bytes)   -> sent immediately
  t=0ms    client write(body, 80 bytes)     -> Nagle BUFFERS it
                                               (unacked data outstanding)
  t=0ms    server receives 12 bytes, message incomplete, no response
           delayed ACK timer starts
  t=40ms   delayed ACK fires
  t=40ms   Nagle releases the 80 bytes
  t=41ms   server finally has the full message

Fix 1 (best): one write, one segment
  writev(fd, iov, 2);            // header + body in a single syscall

Fix 2: disable Nagle on the socket
  int one = 1;
  setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));

  // Node.js
  socket.setNoDelay(true);
  // Java
  socket.setTcpNoDelay(true);
  // Go: net.TCPConn has NoDelay ON by default

Spot it in a capture: request duration clustering at almost exactly 40ms
  tshark -r cap.pcap -Y "tcp.analysis.ack_rtt > 0.039"

Key Points

  • Nagle buffers a small write while unacknowledged data is outstanding
  • Delayed ACK waits up to 40ms hoping to piggyback the acknowledgement
  • Two small writes per message deadlock the pair for the full timer
  • Fix by coalescing writes, or set TCP_NODELAY as RPC frameworks do
💡 Pro Tip: The number 40 milliseconds is the giveaway. If an interviewer describes a latency that is suspiciously constant and close to 40ms on a LAN, say Nagle and delayed ACK before they finish the sentence.
Q25

Define MTU, MSS and path MTU discovery, and explain a PMTUD black hole where small requests work but large POSTs hang.

IntermediateIP and Routing

Answer

MTU is the largest layer 3 payload a link will carry, 1500 bytes on standard Ethernet. MSS is the largest TCP payload a segment may carry, which is MTU minus the IP header minus the TCP header, so 1460 on a plain 1500 byte Ethernet path. Each side announces its own MSS in the SYN and the smaller value governs.

IPv4 routers may fragment a packet larger than the outgoing link's MTU, but only if the Don't Fragment bit is clear; modern stacks set DF on essentially all TCP traffic, and IPv6 forbids router fragmentation entirely. So instead the router drops the packet and returns ICMP type 3 code 4, fragmentation needed, carrying the next hop MTU. The sender caches that value for the destination and lowers its segment size.

That is path MTU discovery, and it depends entirely on ICMP getting back to the sender. A black hole happens when a firewall or security appliance somewhere on the path blocks all ICMP, a depressingly common default. Now the mechanics: the handshake, small GETs and even the TLS handshake are all small packets, so they pass fine.

The moment your client sends a large POST body or the server sends a large response, full sized segments hit a link with a lower MTU, typically a tunnel, an IPsec VPN, or PPPoE on a broadband line where 1492 is normal. The router drops them and sends ICMP that never arrives. TCP retransmits the same oversized segment forever and the connection hangs, then times out.

The symptom is unmistakable: the connection establishes, small requests succeed, large payloads hang. Fix by allowing ICMP type 3 code 4, or clamp MSS on the tunnel interface.

MTU 1500  ->  MSS = 1500 - 20 (IP) - 20 (TCP) = 1460
  with TCP timestamps option: usable payload drops to 1448
  IPsec / PPPoE / GRE tunnels typically give 1400 to 1492

Find the real path MTU by binary searching with DF set:
  ping -M do -s 1472 goodspace.ai      # 1472 + 28 = 1500, works
  ping -M do -s 1473 goodspace.ai
  ping: local error: message too long, mtu=1500

  ping -M do -s 1420 through-the-vpn-host   # ok
  ping -M do -s 1421 through-the-vpn-host   # "Frag needed and DF set"
  -> path MTU is 1449 -> clamp MSS to 1409

Symptom signature of a PMTUD black hole
  TCP handshake        OK   (small packets)
  TLS handshake        OK   (small packets)
  GET /health          OK   (small response)
  POST 8KB body        HANGS then times out

Fixes
  1. Allow ICMP type 3 code 4 (fragmentation needed) inbound on the firewall
  2. Clamp MSS on the tunnel with an iptables mangle rule on the FORWARD
     chain, matching SYN packets, target TCPMSS, with the clamp mss to pmtu
     option (or set an explicit mss value)
  3. Check the cached path MTU the kernel learned:
     ip route get 35.200.1.9

Key Points

  • MSS is MTU minus IP and TCP headers, negotiated in the SYN
  • PMTUD relies on ICMP fragmentation needed messages reaching the sender
  • Blocking ICMP creates a black hole: handshake works, large payloads hang
  • Fix by permitting ICMP type 3 code 4 or clamping MSS on the tunnel
Q26

Our API server has 30,000 sockets in TIME_WAIT and is starting to refuse new connections. Explain what TIME_WAIT is for and what you would actually change.

IntermediateTransport Layer

Answer

First, diagnose before tuning. TIME_WAIT exists for two reasons. One, to absorb a lost final ACK: if the passive closer's FIN is retransmitted because your ACK was lost, the socket must still exist to acknowledge it again, otherwise the peer receives RST and logs a spurious error.

Two, to prevent delayed duplicate segments from a closed connection being delivered into a new connection that happens to reuse the same four tuple; the 2 times maximum segment lifetime wait, 60 seconds on Linux, guarantees any straggler has expired. So TIME_WAIT is correctness machinery, not a leak. Second, work out which side is closing.

TIME_WAIT accumulates on whoever closes first. If your server is closing, the interesting question is why: usually a proxy or client not using keep alive, or a keepalive requests limit set too low so nginx closes after N requests, or an application closing the connection after every response. On a server, TIME_WAIT sockets are cheap because they are bound to your one listening port and each has a distinct client four tuple, so 30,000 of them mostly costs memory.

Refusing connections is far more likely to be file descriptor exhaustion or an accept queue overflow, which you verify with the listen overflow counter, than TIME_WAIT itself. Real fixes: enable keep alive end to end so connections are reused instead of churned; raise the keepalive requests ceiling; raise the file descriptor limit and somaxconn; and enable tcp_tw_reuse, which lets the kernel reuse a TIME_WAIT socket for a new outgoing connection safely using timestamps. Do not enable tcp_tw_recycle, it was removed in Linux 4.12 precisely because it broke clients behind NAT.

Confirm the state distribution first:
  ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn
  30184 TIME-WAIT
    612 ESTAB
      3 LISTEN

Who is closing? Look at the local port on the TIME-WAIT sockets:
  ss -tan state time-wait | head
  Local Address:Port     Peer Address:Port
  10.0.2.15:8080         10.0.4.71:53122      <- local port 8080 = WE close
  10.0.2.15:47122        10.0.9.3:5432        <- ephemeral local = we are the client

Is it actually TIME_WAIT causing refusals? Usually not:
  netstat -s | grep -i "listen"
  4821 times the listen queue of a socket overflowed
  4821 SYNs to LISTEN sockets dropped

  ulimit -n
  cat /proc/sys/net/core/somaxconn

Real fixes
  keepalive_timeout 65;        # nginx: reuse connections
  keepalive_requests 10000;    # stop closing after 100 requests
  upstream api { keepalive 64; }

  sysctl -w net.ipv4.tcp_tw_reuse=1        # safe, timestamp protected
  sysctl -w net.core.somaxconn=4096

  tcp_tw_recycle: REMOVED in Linux 4.12, broke NATed clients. Never use.

Key Points

  • TIME_WAIT absorbs a retransmitted FIN and blocks stale duplicates into a reused four tuple
  • It lands on whichever side closes first, so find out why your server closes
  • Connection refusals are usually descriptor or accept queue exhaustion, not TIME_WAIT
  • Enable keep alive and tcp_tw_reuse; tcp_tw_recycle was removed for breaking NAT
Q27

Using VLSM, carve 10.20.0.0/22 into subnets for departments needing 500, 200, 60 and 10 hosts, plus point to point links. Show your working.

IntermediateSubnetting and Addressing

Answer

VLSM means variable length subnet masking: instead of splitting a block into equal pieces, you allocate each requirement the smallest power of two that fits, largest requirement first. Allocating largest first is not a stylistic choice, it prevents fragmenting the space so badly that a large block no longer fits contiguously. Start with the parent: 10.20.0.0/22 covers 10.20.0.0 through 10.20.3.255, which is 1024 addresses.

Requirement one, 500 hosts. Nine host bits give 510 usable, so /23, mask 255.255.254.0. Allocate 10.20.0.0/23, spanning 10.20.0.0 to 10.20.1.255, usable 10.20.0.1 to 10.20.1.254, broadcast 10.20.1.255.

Requirement two, 200 hosts. Eight host bits give 254 usable, so /24, mask 255.255.255.0. Next free address is 10.20.2.0, so allocate 10.20.2.0/24, usable .1 to .254, broadcast 10.20.2.255.

Requirement three, 60 hosts. Six host bits give 62, so /26, mask 255.255.255.192. Next free is 10.20.3.0, allocate 10.20.3.0/26, usable 10.20.3.1 to .62, broadcast 10.20.3.63.

Requirement four, 10 hosts. Four host bits give 14, so /28, mask 255.255.255.240. Allocate 10.20.3.64/28, usable 10.20.3.65 to .78, broadcast 10.20.3.79.

That leaves 10.20.3.80 through 10.20.3.255 free, 176 addresses, which you carve into /30s for router to router links, each giving exactly two usable addresses, or /31s if your kit supports RFC 3021. Always state the mask, network, broadcast, usable range and remaining free space, because that is the marking scheme.

Parent: 10.20.0.0/22  =  10.20.0.0 to 10.20.3.255  (1024 addresses)
Rule: allocate LARGEST requirement first.

Need 500 -> 2^9-2 = 510 -> /23  mask 255.255.254.0   block 512
  Network    10.20.0.0/23
  Usable     10.20.0.1   to  10.20.1.254
  Broadcast  10.20.1.255

Need 200 -> 2^8-2 = 254 -> /24  mask 255.255.255.0   block 256
  Network    10.20.2.0/24
  Usable     10.20.2.1   to  10.20.2.254
  Broadcast  10.20.2.255

Need 60  -> 2^6-2 = 62  -> /26  mask 255.255.255.192 block 64
  Network    10.20.3.0/26
  Usable     10.20.3.1   to  10.20.3.62
  Broadcast  10.20.3.63

Need 10  -> 2^4-2 = 14  -> /28  mask 255.255.255.240 block 16
  Network    10.20.3.64/28
  Usable     10.20.3.65  to  10.20.3.78
  Broadcast  10.20.3.79

Remaining free: 10.20.3.80 to 10.20.3.255 (176 addresses)
  Point to point links, /30 each (2 usable):
  10.20.3.80/30   usable .81 and .82    broadcast .83
  10.20.3.84/30   usable .85 and .86    broadcast .87
  10.20.3.88/30   usable .89 and .90    broadcast .91

Binary check on the /23 boundary (3rd octet):
  mask   11111111.11111111.11111110.00000000  = 255.255.254.0
  10.20.0.x and 10.20.1.x share the same network because bit 8 of
  the third octet is the last network bit.

Key Points

  • Allocate the largest requirement first to avoid fragmenting the block
  • Round every requirement up to the next power of two, then subtract two
  • 500 needs /23, 200 needs /24, 60 needs /26, 10 needs /28
  • Leftover space becomes /30 or /31 point to point links
💡 Pro Tip: Write the four columns, network, usable range, broadcast, mask, before you start calculating. Interviewers mark on completeness, and candidates who compute correctly but forget the broadcast address lose marks they earned.
Q28

Explain IPv6 addressing basics and why IPv6 adoption in India is unusually high compared to most countries.

IntermediateSubnetting and Addressing

Answer

IPv6 addresses are 128 bits written as eight groups of four hex digits, with two compression rules: leading zeros in a group may be dropped, and one run of all zero groups may be replaced with a double colon, used at most once so the expansion is unambiguous. The standard structure for a global unicast address is a 48 or 56 bit prefix from your provider, a 16 bit subnet field, and a 64 bit interface identifier, which is why /64 is the universal subnet size and why subnetting in IPv6 is about prefix delegation, not about conserving hosts. Key address types: 2000::/3 global unicast, fe80::/10 link local, present on every interface and used by neighbour discovery and routing protocols, fc00::/7 unique local, the rough analogue of RFC 1918, and ff00::/8 multicast.

IPv6 removes broadcast entirely, replacing it with multicast groups, and replaces ARP with Neighbour Discovery over ICMPv6, which is why blocking all ICMPv6 breaks IPv6 completely rather than just breaking ping. There is no NAT in the normal case, and addresses are usually assigned by stateless autoconfiguration from router advertisements rather than DHCP. India is a leading adopter, consistently above sixty percent of traffic, essentially because of mobile.

Jio launched in 2016 as a greenfield all IP network with no legacy IPv4 estate to protect and no realistic way to obtain enough IPv4 addresses for hundreds of millions of subscribers, so it deployed IPv6 natively with 464XLAT and NAT64 to reach IPv4 only destinations. Airtel and Vodafone Idea followed. The practical consequence for engineers here: your service must publish AAAA records and your backend must handle IPv6 source addresses in logs, rate limiters and allow lists, where a per address limit is wrong because a subscriber gets a whole /64.

Full form
  2001:0db8:0000:0000:0000:ff00:0042:8329
Drop leading zeros
  2001:db8:0:0:0:ff00:42:8329
Compress one zero run (only once)
  2001:db8::ff00:42:8329

Structure of a global unicast address
  2001:db8:acad: 0001 : 0000:0000:0000:0010
  |=== /48 provider ===|sub |=== interface id (64 bits) ===|
  /64 is the standard subnet size, always.

Ranges to know
  2000::/3     global unicast (routable)
  fe80::/10    link local (every interface has one, used by ND)
  fc00::/7     unique local (the RFC 1918 analogue)
  ff00::/8     multicast (IPv6 has NO broadcast)
  ::1/128      loopback
  64:ff9b::/96 NAT64 well known prefix

Commands
  ip -6 addr show
  ip -6 route show
  ping6 goodspace.ai
  dig AAAA goodspace.ai +short
  curl -6 -s -o /dev/null -w "%{http_code} %{remote_ip}\n" https://goodspace.ai

Backend gotcha: rate limiting per IPv6 address is wrong.
  A single subscriber holds an entire /64. Key your limiter on the /64.

Key Points

  • 128 bits, double colon compresses one zero run, /64 is the standard subnet
  • No broadcast and no ARP; multicast plus Neighbour Discovery over ICMPv6
  • Jio deployed greenfield IPv6 with NAT64 and 464XLAT, pulling India above 60 percent
  • Rate limit on the /64, not on the individual IPv6 address
Q29

Explain Cache-Control, ETag and conditional requests, and design the caching headers for an HTML page, a hashed JS bundle and a private API response.

IntermediateHTTP and the Web

Answer

Cache-Control drives everything. The directives worth knowing: max-age sets freshness lifetime in seconds for any cache; s-maxage overrides it for shared caches like a CDN; public and private say whether a shared cache may store the response at all; no-cache is widely misunderstood, it permits storing but requires revalidation on every use; no-store forbids storing anywhere and is the one you want for sensitive data; immutable tells the browser not to revalidate even on reload; and stale-while-revalidate lets a cache serve a slightly stale copy while refreshing in the background, which removes revalidation latency from the critical path. ETag is a validator, an opaque token identifying a specific representation.

When a cached copy expires, the client revalidates by sending If-None-Match with the stored ETag; if the resource is unchanged the server returns 304 Not Modified with no body, so you pay one round trip instead of the full payload. Last-Modified with If-Modified-Since is the weaker one second granularity equivalent. Now the three designs.

A hashed JS bundle whose filename changes on every build is immutable content, so cache it for a year, publicly, with the immutable directive, and never revalidate. An HTML shell must not be cached hard, because it references those hashed filenames and a stale HTML file points at deleted bundles; use no-cache with an ETag so the browser always revalidates cheaply, or a short max-age with stale-while-revalidate. A private API response containing user data must carry Cache-Control private with no-store, and if it varies by auth token you also need Vary Authorization so a shared cache never serves one user's data to another.

Hashed static asset: /assets/app.9f2c1b8e.js
  Cache-Control: public, max-age=31536000, immutable
  ETag: "9f2c1b8e"
  -> browser never even revalidates for a year

HTML shell: /index.html
  Cache-Control: no-cache
  ETag: "v41-a83f"
  -> stored, but revalidated every time (cheap 304)

  Revalidation exchange:
  GET /index.html HTTP/1.1
  If-None-Match: "v41-a83f"

  HTTP/1.1 304 Not Modified
  ETag: "v41-a83f"
  (no body: one RTT instead of 40KB)

Private API response: /api/v1/me
  Cache-Control: private, no-store
  Vary: Authorization

CDN cached, browser fresh, background refresh:
  Cache-Control: public, max-age=60, s-maxage=600, stale-while-revalidate=86400

Check what you are actually sending:
  curl -sI https://goodspace.ai/assets/app.9f2c1b8e.js | grep -i -E "cache|etag|age|vary"
  cache-control: public, max-age=31536000, immutable
  age: 84213                 <- how long the CDN has held it
  x-cache: HIT

Key Points

  • no-cache means revalidate every time; no-store means never store at all
  • ETag plus If-None-Match yields a bodyless 304 revalidation
  • Hash the filename and cache for a year with immutable; never cache the HTML shell hard
  • Private responses need private, no-store and a Vary on Authorization
Q30

Explain how cookies are scoped, and what SameSite, Secure, HttpOnly and the Domain attribute each protect against.

IntermediateHTTP and the Web

Answer

A cookie is set with Set-Cookie in a response and returned in the Cookie header on subsequent matching requests. Scope is decided by Domain, Path, Secure and SameSite, and importantly cookie scoping ignores the port and largely ignores the scheme, so cookies are not bound by the same origin policy the way localStorage is. Domain: if omitted, the cookie is host only and sent to exactly that host.

If you set Domain to goodspace.ai it is sent to that host and every subdomain, which is how a session works across www and api subdomains, but it also means any subdomain, including one you gave to a third party for a landing page, can read and overwrite it. Path narrows by URL prefix and is weak security because a page can navigate. HttpOnly stops JavaScript reading the cookie via document.cookie, which is the primary mitigation for session theft through cross site scripting; a stolen token in localStorage has no equivalent protection, which is the main argument for cookie based sessions.

Secure stops the cookie being sent over plain HTTP, defending against network interception and against a downgrade attack. SameSite defends against cross site request forgery. Strict means the cookie is never sent on any cross site request, including a top level navigation, so a user clicking a link from Gmail to your dashboard arrives logged out.

Lax, the modern browser default, sends it on top level GET navigations but not on cross site POSTs, images or iframes, which blocks classic CSRF while keeping links working. None sends it everywhere but browsers require Secure alongside it, and that combination is what third party embeds and cross domain SSO need.

Set-Cookie: session=eyJhbGciOi...; Domain=.goodspace.ai; Path=/;
            Max-Age=1209600; Secure; HttpOnly; SameSite=Lax

Attribute            Protects against                      Notes
HttpOnly             XSS reading the session               document.cookie blocked
Secure               plaintext interception / downgrade    HTTPS only
SameSite=Lax         CSRF via cross site POST              browser default now
SameSite=Strict      CSRF, harder                          breaks inbound links
SameSite=None        nothing, it opts OUT                  requires Secure
Domain=.example.com  nothing, it WIDENS scope              every subdomain reads it
Path=/admin          weak scoping only                     not a security boundary

Cross site behaviour of SameSite=Lax
  user clicks a link from mail.google.com to goodspace.ai   cookie SENT
  evil.com auto submits a POST to goodspace.ai              cookie NOT sent
  evil.com loads <img src=goodspace.ai/logout>              cookie NOT sent

Inspect what the server set:
  curl -sI https://goodspace.ai/api/login | grep -i set-cookie
  curl -c jar.txt -b jar.txt https://goodspace.ai/api/me

Key Points

  • Domain widens scope to every subdomain, it does not restrict it
  • HttpOnly is the main XSS mitigation for session tokens
  • SameSite Lax is the browser default and blocks classic CSRF
  • SameSite None requires Secure and is only for genuine cross site use
Q31

A GET to our API works from the browser but a POST with a JSON body fails with a CORS error. Explain preflight and exactly which headers fix it.

IntermediateHTTP and the Web

Answer

The browser splits cross origin requests into simple and preflighted. A request is simple if the method is GET, HEAD or POST and the headers are limited to a small safe list, with Content-Type restricted to application/x-www-form-urlencoded, multipart/form-data or text/plain. Your GET qualified, so the browser sent it directly and only checked the response for Access-Control-Allow-Origin.

Your POST sends Content-Type application/json, which is not on the safe list, and probably an Authorization header, which is also not, so the browser first sends an OPTIONS preflight to the same URL carrying Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server must answer that OPTIONS with 2xx and echo permission: Access-Control-Allow-Origin matching the origin, Access-Control-Allow-Methods including POST, and Access-Control-Allow-Headers listing content-type and authorization. Add Access-Control-Max-Age so the browser caches the preflight and stops sending an extra round trip before every POST, which on a 200 millisecond link is a visible latency win.

If you send credentials, cookies or a TLS client certificate, three extra rules apply: the request must set credentials include, the server must return Access-Control-Allow-Credentials true, and Access-Control-Allow-Origin must be the exact origin, because the wildcard is rejected outright when credentials are involved. Two things that catch people. CORS is enforced by the browser, not the server: curl and Postman succeed because they never check, which is why the bug appears to be browser only. And an auth middleware or a load balancer that rejects OPTIONS with 401 or 405 before your CORS handler runs will break preflight while every other route looks fine.

Preflight the browser sends automatically
  OPTIONS /api/v1/applications HTTP/1.1
  Origin: https://app.goodspace.ai
  Access-Control-Request-Method: POST
  Access-Control-Request-Headers: content-type, authorization

What the server MUST answer
  HTTP/1.1 204 No Content
  Access-Control-Allow-Origin: https://app.goodspace.ai
  Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
  Access-Control-Allow-Headers: content-type, authorization
  Access-Control-Allow-Credentials: true
  Access-Control-Max-Age: 86400
  Vary: Origin

With credentials, the wildcard is REJECTED
  Access-Control-Allow-Origin: *            invalid when credentials are used
  Access-Control-Allow-Origin: https://app.goodspace.ai   correct

Reproduce the preflight by hand:
  curl -i -X OPTIONS https://api.goodspace.ai/v1/applications \
    -H "Origin: https://app.goodspace.ai" \
    -H "Access-Control-Request-Method: POST" \
    -H "Access-Control-Request-Headers: content-type"

If that returns 401 or 405, your auth middleware runs before CORS.
OPTIONS must be unauthenticated.

Key Points

  • JSON content type and custom headers make a request non simple, forcing OPTIONS preflight
  • Server must echo allowed origin, methods and headers on the OPTIONS response
  • Credentials require an exact origin and Allow-Credentials true, never the wildcard
  • CORS is browser enforced, so curl succeeding proves nothing
💡 Pro Tip: The first diagnostic question to ask out loud is whether the OPTIONS request is even reaching the application. Auth middleware rejecting OPTIONS is the single most common cause and naming it early looks like experience.
Q32

Explain HTTP keep alive, why HTTP/1.1 pipelining failed, and how HTTP/2 multiplexing changes the picture.

IntermediateHTTP and the Web

Answer

In HTTP/1.0 every request opened a new TCP connection and closed it after the response, so each object cost a handshake, a TLS handshake, and a fresh slow start with a tiny congestion window. HTTP/1.1 made persistent connections the default: the connection stays open, requests go one after another, and Connection close is the explicit opt out. That removed the per object handshake cost but left a strict rule, one outstanding request at a time per connection.

Browsers worked around it by opening six connections per origin, and web developers worked around that with domain sharding, spreading assets over several hostnames. Pipelining was HTTP/1.1's attempt to fix it properly: send several requests without waiting for responses. It failed in practice because responses still had to come back in request order, so one slow response blocked every response behind it, application layer head of line blocking.

Combined with buggy proxies that mishandled pipelined requests, browsers disabled it, and it is effectively dead. HTTP/2 solves this at the application layer with binary framing and multiplexing: many logical streams share one TCP connection, each frame is tagged with a stream identifier, and responses can interleave and complete out of order. It also adds HPACK header compression, which matters enormously because repeated cookie and user agent headers dominate small requests, plus stream prioritisation.

With HTTP/2 you use one connection per origin, and domain sharding becomes actively harmful because it fragments that single connection and multiplies handshakes. The honest caveat: HTTP/2 removed head of line blocking only above TCP, and TCP still delivers bytes in order, so a single lost packet stalls every multiplexed stream, which is what HTTP/3 addresses.

HTTP/1.0   conn per request
  [handshake][GET a][close][handshake][GET b][close] ...

HTTP/1.1   persistent, but serialised (1 in flight per conn)
  [handshake][GET a][resp a][GET b][resp b][GET c][resp c]
  Connection: keep-alive
  Keep-Alive: timeout=65, max=1000
  Browser workaround: 6 parallel connections per origin

HTTP/1.1 pipelining (dead)
  [GET a][GET b][GET c] ... responses MUST return in order
  slow a  ->  b and c wait  ->  application layer head of line blocking

HTTP/2   one connection, interleaved streams
  stream 1: HEADERS DATA .... DATA
  stream 3:        HEADERS DATA DATA
  stream 5:   HEADERS DATA
  frames interleave on the wire, responses complete out of order
  + HPACK header compression, + stream priorities

Check the negotiated protocol (ALPN happens during TLS):
  curl -sI https://goodspace.ai | head -1
  HTTP/2 200

  openssl s_client -connect goodspace.ai:443 -alpn h2 < /dev/null 2>/dev/null | grep ALPN
  ALPN protocol: h2

With HTTP/2, DELETE your domain sharding. It now hurts.

Key Points

  • Keep alive removes per object handshake and slow start cost
  • Pipelining failed because responses had to return in request order
  • HTTP/2 multiplexes many streams over one connection with binary framing and HPACK
  • Domain sharding is counterproductive once HTTP/2 is in use
Q33

Walk through the TLS handshake and the chain of trust. What actually changed in TLS 1.3, and what does a browser certificate warning really mean?

IntermediateNetwork Security

Answer

TLS combines asymmetric and symmetric cryptography because asymmetric operations are slow. Asymmetric crypto is used once, to authenticate the server and agree on a shared secret; symmetric crypto, typically AES-GCM or ChaCha20-Poly1305, encrypts the actual traffic. The handshake: ClientHello carries supported versions, cipher suites, a random value, the SNI extension naming the host, and in TLS 1.3 a key share guess.

ServerHello picks a cipher suite and returns the server's key share. The server sends its certificate chain and a signature proving it holds the private key for the certificate. Both sides derive the same session keys via ephemeral Diffie Hellman, which gives forward secrecy: recording today's traffic and stealing the server key later does not decrypt it.

The chain of trust: the leaf certificate is signed by an intermediate CA, the intermediate by a root CA, and the root is in the operating system or browser trust store. The client validates the signature chain up to a trusted root, checks the hostname against the subject alternative name, checks the validity dates, and checks revocation via OCSP stapling. TLS 1.3 changes: one round trip instead of two, all obsolete algorithms removed including RSA key transport, static Diffie Hellman, RC4, CBC modes and compression, so forward secrecy is mandatory; and everything after ServerHello is encrypted, including the certificate.

SNI remains in the clear, which is why Encrypted Client Hello exists. A certificate warning means one of: expired, hostname mismatch, self signed or an untrusted issuer, or a broken chain because the server did not send the intermediate. HSTS makes the browser refuse to let the user click through, which is the point.

TLS 1.3 handshake (1 RTT)
  Client -> ClientHello  { versions, ciphers, key_share, SNI=goodspace.ai }
  Server -> ServerHello  { chosen cipher, key_share }
            {EncryptedExtensions, Certificate, CertificateVerify, Finished}
  Client -> Finished  + application data

  TLS 1.2 needed 2 RTT and allowed RSA key transport (no forward secrecy).

Chain of trust
  leaf: CN=goodspace.ai            signed by ->
  intermediate: R11                signed by ->
  root: ISRG Root X1               present in the OS trust store

Inspect it:
  openssl s_client -connect goodspace.ai:443 -servername goodspace.ai < /dev/null
  ...
  Verify return code: 0 (ok)
  Protocol  : TLSv1.3
  Cipher    : TLS_AES_128_GCM_SHA256

  echo | openssl s_client -connect goodspace.ai:443 2>/dev/null \
    | openssl x509 -noout -dates -subject -ext subjectAltName

What a warning actually means
  NET::ERR_CERT_DATE_INVALID          expired or clock skew on the client
  NET::ERR_CERT_COMMON_NAME_INVALID   hostname not in the SAN list
  NET::ERR_CERT_AUTHORITY_INVALID     self signed, or MISSING INTERMEDIATE
                                      (works in curl on your Mac, fails on Android)

HSTS removes the click through:
  Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

Key Points

  • Asymmetric crypto authenticates and agrees keys, symmetric crypto encrypts the data
  • Ephemeral Diffie Hellman gives forward secrecy, mandatory in TLS 1.3
  • TLS 1.3 is one round trip and encrypts the certificate; SNI stays in the clear
  • A missing intermediate certificate is the classic works on my laptop failure
💡 Pro Tip: Mention the missing intermediate certificate case unprompted. It is the one TLS failure almost every engineer has actually hit in production, and naming it immediately signals you have shipped HTTPS rather than only read about it.
Q34

For a live application status feed, compare WebSockets, server sent events and long polling. Which would you pick and what breaks each one in production?

IntermediateHTTP and the Web

Answer

Long polling: the client makes an ordinary request and the server holds it open until data is available or a timeout fires, then the client immediately reconnects. It works through any proxy and needs no special infrastructure, which is its only real advantage. Costs: a held request occupies a connection and often a worker on the server, every message pays full HTTP header overhead, and there is a race window between the response returning and the next request being established during which events must be buffered server side.

Server sent events: a single HTTP response with content type text/event-stream that stays open and streams text frames. It is unidirectional, server to client only, runs over plain HTTP so it works with existing auth, cookies, compression and CDNs, and the browser EventSource API handles automatic reconnection and gap recovery via the Last-Event-ID header for free. Limits: text only, no binary, and under HTTP/1.1 it consumes one of the browser's six connections per origin, so several tabs exhaust the budget, a problem that disappears under HTTP/2.

WebSockets: an HTTP request with Upgrade websocket and a 101 Switching Protocols response, after which the connection is a full duplex binary message channel. It is the right choice when the client also sends frequently, chat, collaborative editing, trading. Costs: it is not HTTP any more, so your normal middleware, logging, caching and auth do not apply; sticky routing or a shared pub sub backplane like Redis is required across multiple servers; and proxies kill idle connections so you need application level pings. For a status feed the traffic is one directional, so server sent events is the correct answer, and saying that instead of reflexively picking WebSockets is what the interviewer is testing.

Server sent events (unidirectional, plain HTTP)
  GET /api/v1/applications/stream
  Accept: text/event-stream

  HTTP/1.1 200 OK
  Content-Type: text/event-stream
  Cache-Control: no-cache
  X-Accel-Buffering: no          <- REQUIRED behind nginx or nothing flushes

  id: 1042
  event: status
  data: {"applicationId":48213,"status":"shortlisted"}

  : keepalive comment every 20s so proxies do not time out

  Client reconnects automatically and sends Last-Event-ID: 1042

WebSocket upgrade (bidirectional, binary capable)
  GET /ws HTTP/1.1
  Upgrade: websocket
  Connection: Upgrade
  Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
  Sec-WebSocket-Version: 13

  HTTP/1.1 101 Switching Protocols
  Upgrade: websocket
  Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Test from the shell:
  curl -N -H "Accept: text/event-stream" https://api.goodspace.ai/v1/stream

Choice matrix
  server -> client only, text     SSE          simplest, free reconnection
  both directions, low latency    WebSocket    needs sticky routing or pub sub
  must traverse hostile proxies   long poll    highest overhead, last resort

Key Points

  • Long polling works anywhere but pays full HTTP overhead per message
  • SSE is unidirectional over plain HTTP with free reconnection and Last-Event-ID
  • WebSockets are full duplex but bypass HTTP middleware and need sticky routing or a backplane
  • Disable proxy buffering and send periodic keepalives for any streaming response
Q35

Compare L4 and L7 load balancing, and explain sticky sessions and what a good health check looks like.

IntermediateIP and Routing

Answer

An L4 load balancer works at the transport layer. It sees IP addresses and ports, hashes or round robins the four tuple to a backend, and forwards packets or proxies the TCP stream without parsing the payload. It is fast, protocol agnostic, and cannot see TLS content, so it cannot route by URL path or Host header, cannot add headers, and cannot retry a failed HTTP request because it has no idea where one request ends.

An L7 load balancer terminates the connection, parses HTTP, and can route on host, path, method, header or cookie, rewrite URLs, inject X-Forwarded-For, terminate TLS, apply rate limits, and safely retry an idempotent request on another backend. The cost is CPU and the fact that TLS terminates at the balancer, so you either accept plaintext internally or re encrypt. In practice modern stacks put an L4 balancer in front for raw distribution and an L7 proxy such as nginx, Envoy or an ALB behind it.

Sticky sessions pin a client to one backend, either by hashing the source IP, which breaks badly when many users share one NAT address, or by setting a cookie the balancer reads. Stickiness is a workaround for server side session state; it undermines even load distribution, makes deployments disruptive, and means a backend failure logs those users out. Prefer stateless backends with sessions in Redis or a signed token.

Health checks: a check that only opens a TCP connection tells you the process is alive, not that it works. Use an HTTP endpoint that verifies the critical dependencies, keep it cheap, separate liveness from readiness so a warming instance is removed rather than restarted, and require several consecutive failures before ejecting so one slow response does not cascade.

L4 (transport)                      L7 (application)
sees IP + port                      sees method, host, path, headers, cookies
hashes the 4 tuple                  routes /api to one pool, /static to another
cannot retry a request              retries idempotent requests on another backend
no TLS visibility                   terminates TLS, injects X-Forwarded-For
very cheap                          more CPU, more capability

nginx as the L7 tier
  upstream api {
    least_conn;
    server 10.0.2.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.2.12:8080 max_fails=3 fail_timeout=10s;
    keepalive 64;
  }
  location /api/ {
    proxy_pass http://api;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_next_upstream error timeout http_502;
  }

Stickiness by cookie (better than source IP hashing behind NAT)
  sticky cookie srv_id expires=1h path=/;

Health checks: separate the two
  GET /healthz   liveness   process is up. Restart if this fails.
  GET /readyz    readiness  DB pool, cache and migrations OK.
                            Remove from the pool if this fails, do NOT restart.

  Thresholds: 2s timeout, 3 consecutive failures to eject, 2 to return.

Key Points

  • L4 routes on the four tuple; L7 parses HTTP and can route, rewrite and retry
  • Source IP stickiness breaks behind carrier NAT where thousands share an address
  • Prefer stateless backends with shared session storage over sticky sessions
  • Separate liveness from readiness and require consecutive failures before ejecting
Q36

What is the difference between a forward proxy and a reverse proxy, and where does a CDN edge fit?

IntermediateIP and Routing

Answer

The distinction is which side the proxy represents and who knows it exists. A forward proxy sits in front of clients and acts on their behalf. The client is explicitly configured to use it, through browser settings or the HTTP_PROXY environment variable, and the destination server never knows the real client, it only sees the proxy's address.

Corporate networks use forward proxies for outbound filtering, URL allow lists, malware scanning, caching of shared downloads, and audit logging. In cloud infrastructure a NAT gateway or an egress proxy plays the same role, giving every outbound call a single stable source IP, which matters when a payment provider or a partner API allow lists your addresses. A reverse proxy sits in front of servers and acts on their behalf.

The client thinks it is talking to the origin and knows nothing about the proxy. This is nginx, HAProxy, Envoy, Cloudflare, an Application Load Balancer. It does TLS termination so certificates live in one place, load balancing across backends, response caching, compression, request routing by path or host, rate limiting, and it hides your internal topology so a backend is never directly exposed.

A CDN edge is a geographically distributed reverse proxy with caching as its primary purpose. It terminates TLS close to the user, cutting handshake round trips dramatically for someone in Chennai reaching an origin in Mumbai or Singapore, serves cacheable assets from the edge, and for uncacheable requests still helps by holding a warm, well tuned connection to the origin over an optimised backbone rather than making the user's mobile connection traverse the whole path. The header to check is X-Forwarded-For, which the reverse proxy sets so your application still learns the real client IP.

Forward proxy: represents the CLIENT, client is configured, server is unaware
  [ employee laptop ] -> [ corporate proxy ] -> [ internet ]
  export HTTPS_PROXY=http://proxy.corp.local:3128
  curl -x http://proxy.corp.local:3128 https://goodspace.ai

Reverse proxy: represents the SERVER, client is unaware
  [ user ] -> [ nginx / ALB / Cloudflare ] -> [ app-1, app-2, app-3 ]

  server {
    listen 443 ssl http2;
    server_name api.goodspace.ai;
    location / {
      proxy_pass http://api_backend;
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
  }

CDN edge = a reverse proxy replicated worldwide, cache first
  user in Chennai -> MAA edge (TLS terminates here, ~8ms)
                  -> cache HIT: served, origin never touched
                  -> cache MISS: warm keepalive connection to origin

Read the real client IP behind a proxy:
  X-Forwarded-For: 49.36.180.24, 172.71.30.9
                   ^ real client   ^ intermediate proxy
  Trust only the hop count you control, or an attacker spoofs the header.

Key Points

  • Forward proxy fronts clients and is explicitly configured; reverse proxy fronts servers and is invisible
  • Reverse proxies handle TLS termination, load balancing, caching and routing
  • A CDN edge is a globally replicated reverse proxy, cutting handshake round trips
  • X-Forwarded-For carries the real client IP and must only be trusted from your own hops
Q37

HTTP/2 multiplexes streams over one connection, so why does one lost packet still stall every stream? Explain how HTTP/3 and QUIC fix it properly.

AdvancedHTTP and the Web

Answer

HTTP/2 removed head of line blocking at the application layer only. Its framing lets many streams interleave, so a slow response no longer blocks the ones behind it in the HTTP sense. But all those streams ride on one TCP connection, and TCP presents a single strictly ordered byte stream to the application.

If a segment carrying frames for stream 3 is lost, the kernel holds every subsequent byte in the receive buffer until the retransmission arrives, because it cannot deliver byte N+1 before byte N. Streams 1, 5 and 7 may have arrived completely and be sitting in that buffer, fully intact and undeliverable. So HTTP/2 traded six independent TCP connections, where a loss stalled one sixth of the traffic, for one connection where a single loss stalls everything.

On a clean fibre link this is a clear win. On a 4G connection in a moving train with two percent loss it is often worse than HTTP/1.1, which is exactly the counterintuitive result the interviewer is fishing for. QUIC fixes it by moving the transport into user space over UDP.

It maintains per stream sequencing and delivery: a lost packet blocks only the streams whose data it carried, so the others are delivered immediately. QUIC also folds the transport and cryptographic handshakes together, giving a one round trip connection setup and zero round trip resumption; encrypts almost the entire transport header, so middleboxes cannot ossify it; and identifies connections by a connection ID rather than the four tuple, so a phone switching from WiFi to 5G keeps the same connection instead of resetting every socket. Deploy considerations: some enterprise firewalls block UDP 443, so you keep HTTP/2 as fallback and advertise HTTP/3 with the Alt-Svc header.

HTTP/2 over TCP: one loss stalls everything

  wire:  [s1][s3][s5][s3][s7][s3][s5]
                      ^ LOST
  kernel receive buffer holds s5 and s7 complete, but cannot deliver them,
  because TCP must hand bytes to the app IN ORDER.
  -> every stream waits for the s3 retransmission (1 RTT minimum)

HTTP/3 over QUIC (UDP): loss is scoped to one stream

  wire:  [s1][s3][s5][s3][s7][s3][s5]
                      ^ LOST
  s1, s5, s7 delivered to the app immediately.
  Only s3 waits for its retransmission.

Other QUIC wins
  1 RTT handshake (transport + TLS 1.3 combined), 0 RTT on resumption
  connection ID, not the 4 tuple -> WiFi to 5G handover survives
  encrypted transport headers -> middleboxes cannot ossify the protocol
  pluggable congestion control in user space

Advertise and verify
  Alt-Svc: h3=":443"; ma=86400

  curl -sI https://goodspace.ai | head -1
  HTTP/3 200

  ss -uan | grep :443        # HTTP/3 traffic is UDP, not TCP

Key Points

  • HTTP/2 solved head of line blocking only above TCP
  • TCP delivers bytes in order, so one loss stalls every multiplexed stream
  • QUIC keeps per stream ordering over UDP, scoping loss to one stream
  • Connection IDs survive network changes; UDP 443 blocking needs an HTTP/2 fallback
💡 Pro Tip: The strongest version of this answer names the case where HTTP/2 is worse than HTTP/1.1: a high loss mobile link. Volunteering a downside of the newer technology is what separates a senior answer from a marketing summary.
Q38

How does BGP actually choose a route, and why can one misconfiguration take large parts of the internet offline?

AdvancedIP and Routing

Answer

BGP is the exterior gateway protocol that glues about eighty thousand autonomous systems into one internet. Peers form a TCP session on port 179 and exchange reachability: I can reach this prefix, and here is the AS path to get there. Unlike interior protocols, BGP is a path vector protocol driven by policy, not by shortest path.

The decision process, in order: highest weight (Cisco local), highest local preference, locally originated routes, shortest AS path, lowest origin type, lowest MED, eBGP preferred over iBGP, lowest IGP metric to the next hop, then oldest route and lowest router ID as tie breakers. Business policy is expressed through local preference for inbound traffic and AS path prepending for outbound, which is why the shortest path in BGP is often not the fastest path. The fragility comes from BGP being built on trust.

Announcing a prefix you do not own is technically trivial, and if your prefix is more specific than the legitimate one, longest prefix match means the whole internet prefers it. That is the Pakistan Telecom YouTube incident of 2008, and effectively what happened in several later outages. Two failure classes matter.

A hijack or route leak: an AS announces or re announces prefixes it should not, and traffic for a large service is drawn into a network that cannot deliver it. A withdrawal: an operator pushes a bad policy and their routers withdraw their own prefixes, so the entire network becomes unreachable from outside, which is what took Facebook offline for six hours in 2021, worsened because their own DNS servers withdrew their routes when they lost backbone reachability. Mitigations are RPKI origin validation, IRR based prefix filters, maximum prefix limits on sessions, and the MANRS practices.

BGP best path selection, in order
  1. highest WEIGHT               (Cisco, local to the router)
  2. highest LOCAL_PREF           (policy: how WE exit)
  3. locally originated
  4. shortest AS_PATH             (the famous one, but 4th)
  5. lowest ORIGIN                (IGP < EGP < incomplete)
  6. lowest MED                   (hint to a neighbour on how to enter US)
  7. eBGP over iBGP
  8. lowest IGP metric to next hop
  9. oldest route, then lowest router ID

A more specific announcement wins on longest prefix match, always:
  legitimate: 208.65.152.0/22  origin AS36561
  hijack:     208.65.153.0/24  origin AS17557   <- more specific, wins globally

Operational views
  show ip bgp 35.200.1.0/24
  show ip bgp summary
  show ip bgp neighbors 203.0.113.1 advertised-routes

Public looking glass check during an incident:
  whois -h whois.radb.net 35.200.1.0/24

Defences
  RPKI ROA          cryptographically binds prefix to origin AS
  prefix filters     accept only what the IRR says a peer may announce
  max prefix limit   tear down a session that suddenly announces 500k routes
  BGP communities    tag and control propagation

Key Points

  • Path vector protocol over TCP 179, driven by policy not shortest path
  • AS path length is only the fourth tiebreaker, after weight and local preference
  • A more specific hijacked prefix wins globally because of longest prefix match
  • RPKI, prefix filters and max prefix limits are the standard mitigations
Q39

Compare RIP, OSPF and BGP. When would you actually run OSPF, and what happens during an OSPF adjacency failure?

AdvancedIP and Routing

Answer

RIP is a distance vector protocol using hop count as its only metric, capped at 15 hops, broadcasting its whole table every 30 seconds. It converges slowly and suffers count to infinity, patched with split horizon, route poisoning and hold down timers. It is effectively a teaching protocol now.

OSPF is a link state interior gateway protocol. Every router floods link state advertisements describing its own links, so all routers in an area build an identical link state database and independently run Dijkstra's shortest path first algorithm over it. Its metric is cost, derived from bandwidth, so a gigabit path beats a three hop hundred megabit path, which RIP would get wrong.

OSPF scales through areas: area 0 is the backbone, all other areas must attach to it, and area border routers summarise between them so a flap inside one area does not force a full recomputation everywhere. BGP is the exterior protocol, path vector, policy driven, built for scale and administrative independence rather than for speed. The rule of thumb: OSPF or IS-IS inside one administrative domain, an enterprise campus or a data centre fabric, BGP between domains and increasingly inside large data centres too because of its policy control.

Adjacency formation is a classic deep question. Neighbours progress through Down, Init, Two Way, ExStart, Exchange, Loading, Full. If a pair sticks in Two Way that is expected on a broadcast segment for routers that are neither designated nor backup designated.

Stuck in ExStart usually means an MTU mismatch, because database description packets fail to exchange. Neighbours that never form at all usually differ in hello or dead interval, area identifier, authentication, or subnet mask on the segment.

Protocol  Type             Metric        Scope       Convergence
RIP       distance vector  hop count(15) tiny LANs   slow (30s updates)
OSPF      link state       cost from BW  one domain  fast (seconds)
IS-IS     link state       cost          ISP cores   fast
BGP       path vector      policy        between AS  slow by design

OSPF neighbour states
  Down -> Init -> Two Way -> ExStart -> Exchange -> Loading -> Full

  show ip ospf neighbor
  Neighbor ID   Pri State      Dead Time  Address      Interface
  10.0.0.2      1   FULL/DR    00:00:33   10.1.1.2     GigabitEthernet0/1
  10.0.0.3      1   EXSTART/DR 00:00:31   10.1.1.3     GigabitEthernet0/2

Stuck state, likely cause
  INIT        hellos are one way (ACL or unidirectional link)
  TWO WAY     normal on a broadcast segment for non DR/BDR pairs
  EXSTART     MTU MISMATCH on the interface (classic)
  never forms mismatched area id, hello/dead timers, auth, or subnet mask

Cost is derived from bandwidth:
  cost = reference bandwidth / interface bandwidth
  default reference is 100 Mbps, so 1G and 10G both cost 1 unless you
  raise the reference bandwidth on EVERY router consistently.

Areas keep the database small:
  area 0 = backbone, every other area attaches to it via an ABR

Key Points

  • RIP counts hops, OSPF runs Dijkstra on a shared link state database, BGP applies policy
  • OSPF cost comes from bandwidth, so it picks fast paths not short ones
  • Areas bound flooding and Dijkstra recomputation; area 0 is the backbone
  • ExStart stuck adjacency almost always means an MTU mismatch
Q40

Explain VLANs and 802.1Q trunking, then explain what spanning tree prevents and why a switching loop is so much worse than a routing loop.

AdvancedIP and Routing

Answer

A VLAN partitions one physical switch into several logical broadcast domains. Ports assigned to VLAN 10 cannot see broadcasts from VLAN 20 even on the same chassis, and traffic between them must pass through a router or a layer 3 switch, where you can apply access control lists. Trunking carries multiple VLANs over one physical link between switches by tagging each frame: 802.1Q inserts a four byte tag after the source MAC, containing a 12 bit VLAN identifier, giving 4094 usable VLANs, and a three bit priority field for class of service.

One VLAN on each trunk is the native VLAN, whose frames traverse untagged, and a native VLAN mismatch between two switches silently merges two broadcast domains, which is both an outage and a security hole. Now spanning tree. Redundant links between switches create physical loops, and layer 2 has no TTL field.

An Ethernet frame has nothing to decrement, so a broadcast entering a loop circulates forever, is duplicated at every switch that floods it, and multiplies exponentially. Within seconds a broadcast storm saturates every link, MAC address tables thrash as the same source MAC appears on multiple ports, CPUs peak, and the entire layer 2 domain stops passing traffic including the management plane you would use to fix it. A routing loop merely burns TTL and dies after a bounded number of hops.

STP prevents this by electing a root bridge, computing the least cost path to it from every switch, and putting redundant ports into a blocking state. Classic STP takes 30 to 50 seconds to converge; Rapid STP converges in a few seconds and is the modern default. Enable portfast plus BPDU guard on access ports so a user plugged switch cannot become root.

802.1Q tag: 4 bytes inserted after the source MAC
  [ dst MAC ][ src MAC ][ 0x8100 | PCP | DEI | VID(12 bits) ][ type ][ payload ]
  VID range 1 to 4094 (0 and 4095 reserved)

Access vs trunk
  interface Gi0/5
    switchport mode access
    switchport access vlan 10

  interface Gi0/24
    switchport mode trunk
    switchport trunk allowed vlan 10,20,30
    switchport trunk native vlan 999      # unused VLAN, deliberately

Why a layer 2 loop is catastrophic
  IP packet  -> has TTL -> a routing loop dies after 64 hops
  Ethernet frame -> NO TTL -> a broadcast circulates forever,
                     duplicated at every switch that floods it,
                     growing exponentially = broadcast storm
  Symptoms: 100% link utilisation, MAC table flapping, switch CPU pegged,
            management access lost, whole VLAN down.

STP port states (classic)
  Blocking -> Listening -> Learning -> Forwarding   (30 to 50s)
  Rapid STP: Discarding -> Learning -> Forwarding   (a few seconds)

  show spanning-tree vlan 10
  Root ID    Priority 4096  Address 0011.2233.4455  Cost 4
  Interface  Role Sts Cost  Prio.Nbr
  Gi0/24     Root FWD 4     128.24
  Gi0/23     Altn BLK 4     128.23     <- the loop is broken here

Protect the access edge
  spanning-tree portfast
  spanning-tree bpduguard enable
  spanning-tree guard root

Key Points

  • VLANs create separate broadcast domains; 802.1Q tags frames on trunks
  • A native VLAN mismatch silently merges two broadcast domains
  • Ethernet has no TTL, so a layer 2 loop produces an exponential broadcast storm
  • STP blocks redundant ports; use Rapid STP with portfast and BPDU guard at the edge
💡 Pro Tip: The sentence that lands here is that Ethernet has no TTL. If you lead with that one fact, the whole explanation of why a switching loop is catastrophic follows naturally and you sound like you understand the mechanism rather than the acronym.
Q41

Explain SYN flood, volumetric DDoS, ARP poisoning, DNS spoofing and a TLS stripping man in the middle, and give a real mitigation for each.

AdvancedNetwork Security

Answer

SYN flood: the attacker sends SYN packets with spoofed sources and never completes the handshake, so each one occupies a half open entry in the SYN queue until it times out, and legitimate SYNs get dropped. Mitigation is SYN cookies, where the server encodes the connection state into the initial sequence number it returns and allocates nothing until the final ACK arrives, proving the client can receive; plus a larger SYN backlog and upstream filtering. Volumetric DDoS: raw bandwidth exhaustion, usually amplified by reflecting off open UDP services with a large response to small request ratio, DNS, NTP monlist, memcached at over fifty thousand times amplification.

You cannot absorb this at your origin; you need upstream scrubbing at a provider with terabit capacity, anycast to spread the load, and BCP 38 source address validation deployed by networks to stop the spoofing that makes reflection possible. ARP poisoning: any host on the LAN sends unsolicited ARP replies claiming to own the gateway IP, so victims send their traffic to the attacker. Mitigations are dynamic ARP inspection on the switch, validating ARP against the DHCP snooping binding table, plus port security and 802.1X.

DNS spoofing: the attacker races a forged response to the resolver. Mitigations are source port randomisation, the 0x20 encoding trick, DNSSEC for cryptographic origin validation, and DNS over TLS or HTTPS for transport privacy. TLS stripping: the attacker intercepts the initial plaintext HTTP request and proxies the site over HTTP while talking HTTPS upstream, so the user never sees a certificate error because there is no certificate. HSTS with preload defeats it because the browser refuses plaintext for that domain before any request is sent, which is precisely why preload matters.

SYN flood
  attacker: SYN from spoofed 203.0.113.x, never ACKs
  server:   SYN queue fills, legitimate SYNs dropped

  netstat -s | grep -i "SYNs to LISTEN"
  184203 SYNs to LISTEN sockets dropped

  sysctl -w net.ipv4.tcp_syncookies=1
  sysctl -w net.ipv4.tcp_max_syn_backlog=8192
  sysctl -w net.ipv4.tcp_synack_retries=2

Amplification factors (why reflection works)
  DNS ANY        ~54x
  NTP monlist    ~556x
  memcached      ~51000x
  Fix: never expose these to the internet; deploy BCP 38 anti spoofing.

ARP poisoning on the LAN
  ip neigh show
  192.168.1.1 lladdr aa:bb:cc:dd:ee:ff REACHABLE   <- gateway MAC CHANGED
  192.168.1.9 lladdr aa:bb:cc:dd:ee:ff REACHABLE   <- same MAC, two IPs

  Switch side: ip dhcp snooping + ip arp inspection vlan 10

DNS cache poisoning defences
  source port randomisation + 0x20 query name casing
  DNSSEC:  dig +dnssec goodspace.ai | grep -E "RRSIG|ad"

TLS stripping
  user types goodspace.ai -> plaintext HTTP request -> attacker proxies it
  Defence: HSTS preload, so the browser NEVER sends that first plaintext request
  Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

Key Points

  • SYN cookies let a server survive half open floods without allocating state
  • Reflection and amplification need upstream scrubbing plus BCP 38 source validation
  • Dynamic ARP inspection tied to DHCP snooping stops ARP poisoning
  • HSTS preload is the only real defence against TLS stripping on the first request
Q42

Explain stateful inspection in a firewall, and compare IPsec and WireGuard for a site to site VPN. When does split tunnelling bite you?

AdvancedNetwork Security

Answer

A stateless packet filter evaluates each packet against rules on addresses, ports and flags with no memory. To allow outbound web browsing you would have to permit all inbound traffic from source port 443, which an attacker trivially abuses by sourcing packets from that port. A stateful firewall maintains a connection tracking table.

When it permits an outbound SYN it records the four tuple and state, and it then allows only packets belonging to that established flow back in, automatically. Return traffic needs no rule at all, and out of state packets, a bare ACK or a RST for a flow nobody opened, are dropped. This is what iptables expresses with conntrack states NEW, ESTABLISHED, RELATED and INVALID, where RELATED covers helper protocols like FTP data channels that negotiate ports in band.

The practical failure mode is table exhaustion under load or during a flood, when new legitimate connections get dropped even though CPU is idle. VPNs. IPsec operates at layer 3, has two phases, IKE for key exchange and ESP or AH for the data, supports tunnel and transport modes, and is universally interoperable across vendors, which is why it dominates enterprise site to site and telco deployments.

Its cost is complexity: a large configuration surface, awkward NAT traversal requiring UDP encapsulation on port 4500, and painful debugging of phase mismatches. WireGuard is roughly four thousand lines of code, runs in the kernel over UDP, uses a fixed modern cipher suite with no negotiation, authenticates by public key, and is dramatically simpler and faster, but it has no built in dynamic addressing or certificate infrastructure. Split tunnelling sends only corporate prefixes over the tunnel. It bites you when internal names resolve through public DNS to public addresses that then bypass the tunnel, and when a partner allow lists your VPN egress IP but your traffic leaves locally instead.

Stateless vs stateful
  stateless: to allow outbound HTTPS you must permit inbound src port 443
             -> attacker sources packets from 443 and walks in
  stateful:  permit outbound NEW, then allow ESTABLISHED back automatically

Linux conntrack based ruleset (long option names written out in words,
the real flags take a leading double hyphen)
  iptables -A INPUT -m conntrack -j ACCEPT  [ctstate ESTABLISHED,RELATED]
  iptables -A INPUT -p tcp -m conntrack -j ACCEPT  [ctstate NEW] [dport 443]
  iptables -A INPUT -m conntrack -j DROP    [ctstate INVALID]
  iptables -P INPUT DROP

  conntrack -L | head
  tcp 6 431990 ESTABLISHED src=10.0.2.15 dst=35.200.1.9 sport=51422 dport=443

  Table exhaustion looks like random connection failures at low CPU:
  sysctl net.netfilter.nf_conntrack_count
  sysctl net.netfilter.nf_conntrack_max
  dmesg | grep "nf_conntrack: table full"

IPsec vs WireGuard
  IPsec      layer 3, IKEv2 + ESP, tunnel/transport modes, vendor neutral,
             NAT traversal over UDP 4500, large config surface
  WireGuard  ~4k lines, UDP, fixed modern crypto, public key peers,
             far simpler and faster, no dynamic addressing or PKI of its own

Split tunnel traps
  internal.goodspace.ai resolves publicly -> traffic bypasses the tunnel
  partner allow lists your VPN egress IP -> local egress gets 403
  Check what the tunnel actually claims:
    ip route get 10.20.4.9
    ip route get 8.8.8.8

Key Points

  • Stateful firewalls track flows so return traffic needs no explicit rule
  • Conntrack table exhaustion causes random failures while CPU stays idle
  • IPsec is interoperable but complex; WireGuard is simple, fast and opinionated
  • Split tunnelling breaks DNS assumptions and IP allow lists
Q43

Our API is slow only for users in Chennai. Everyone else is fine. Walk me through your investigation, command by command.

AdvancedTroubleshooting

Answer

Work top down through the layers and prove each one before moving on, because the answer to which layer is broken determines who fixes it. Step zero, quantify: is this a slow first byte, meaning the server or path is slow, or slow overall, meaning throughput and payload size? Use curl with the timing write out format from a Chennai vantage point and from a control location.

That single command splits the total into DNS lookup, TCP connect, TLS handshake, time to first byte and total, and it usually solves half of these cases in one shot. If namelookup is the large component, it is DNS: check which resolver those users get, whether your CDN is returning a distant edge for that prefix, and whether the geo steering has EDNS Client Subnet visibility. If connect time is large, it is round trip and routing: run mtr for a hundred packets in both directions to separate forward path loss from return path loss, because loss shown at an intermediate hop with clean hops after it is ICMP rate limiting, not real loss.

If appconnect minus connect is large, the TLS handshake is expensive, which points at extra round trips, a missing OCSP staple, or a large certificate chain. If starttransfer minus appconnect is large, the origin is genuinely slow for those requests, so go to server side traces and correlate by region rather than blaming the network. Then look at what is regionally specific: which CDN PoP is serving them, whether a specific ISP is affected, whether it is only mobile users. Confirm with real user monitoring split by ISP and city rather than trusting one traceroute, because a single path measurement from your laptop is not evidence about a population.

0. Quantify: split the request into phases (run from Chennai and a control)
  curl -s -o /dev/null -w "dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total} ip=%{remote_ip}\n" https://api.goodspace.ai/v1/health

  Chennai:  dns=0.412 tcp=0.489 tls=0.701 ttfb=1.930 total=1.944
  Mumbai:   dns=0.021 tcp=0.043 tls=0.088 ttfb=0.146 total=0.151
  -> DNS is 20x slower AND ttfb is 13x slower. Two separate problems.

1. DNS: which resolver, which answer, how long
  dig api.goodspace.ai | grep "Query time"
  dig +short api.goodspace.ai
  cat /etc/resolv.conf
  dig +subnet=49.36.180.0/24 api.goodspace.ai      # what geo steering returns

2. Path and loss, both directions, over many packets
  mtr -rwzbc 200 api.goodspace.ai
  HOST                    Loss%  Snt  Avg  Best  Wrst StDev
  4. AS9829 49.45.2.113   12.0%  200  188   41   980  210    <- real loss
  5. AS15169 72.14.221.20  0.0%  200   44   42    51    2    <- so hop 4 was
                                                              ICMP rate limit

3. Which edge served them
  curl -sI https://api.goodspace.ai/v1/health | grep -i -E "x-cache|cf-ray|server"
  cf-ray: 8f2a1c...-SIN        <- Chennai users hitting SINGAPORE, not MAA

4. Is the origin slow, or the path?
  ssh api-1 'curl -s -o /dev/null -w "%{time_total}\n" http://localhost:8080/v1/health'
  0.011   -> origin is fine, the problem is in the path or the edge

5. Confirm on a population, not one laptop
  RUM p95 TTFB grouped by city and ASN over 24h

Key Points

  • Split the request into DNS, connect, TLS and TTFB before forming any theory
  • mtr over many packets separates real loss from ICMP rate limiting
  • Check which CDN PoP is actually serving the affected region
  • Prove the origin is fast locally before blaming the network, and confirm with RUM by ASN
💡 Pro Tip: Always start by measuring, never by theorising. Interviewers grade this question on whether your first sentence is a hypothesis or a command. Say the curl timing breakdown first and the rest of the answer writes itself.
Q44

Under load our reverse proxy logs intermittent 502s and clients see connection reset by peer. How do you prove where the reset originates?

AdvancedTroubleshooting

Answer

A connection reset is a TCP RST, and the whole investigation is about establishing who sent it and why. Sources of RST: a connection attempt to a port with no listener, an application closing a socket that still has unread data in its receive buffer, a socket closed with the linger option set to zero, a firewall or load balancer configured to reject rather than drop, or a middlebox tearing down an idle flow whose state it has expired. The 502 is a separate but usually related signal: your reverse proxy reached the upstream and got either nothing or an invalid response, which most often means the upstream closed the connection mid response.

Start structured. Check whether 502s correlate with request rate, with a specific upstream instance, or with deployments. Then check the accept queue: if the listen backlog overflows, the kernel drops SYNs or resets them and you see this exact symptom under load only, which the listen overflow counter proves directly.

Then check keep alive timing, which causes the classic race: if your upstream idle timeout is shorter than the proxy's, the upstream closes an idle pooled connection at the exact moment the proxy reuses it, so the proxy gets a RST on a request it just sent and returns 502. The rule is that the upstream keepalive timeout must be strictly longer than the proxy's, usually by several seconds. Capture with tcpdump filtered to RST packets and read the direction from the source address, and correlate the exact timestamp with the proxy error log. File descriptor exhaustion and conntrack table exhaustion produce the same shape and should be checked in parallel.

1. Who is sending the RST? Filter for it directly.
  sudo tcpdump -i any -n "tcp[tcpflags] & tcp-rst != 0 and port 8080"
  15:41:02.118 IP 10.0.2.11.8080 > 10.0.1.5.51422: Flags [R.], seq 1, ack 1
                  ^ the UPSTREAM is resetting, not the client

2. Accept queue overflow (only shows up under load)
  netstat -s | grep -i -E "listen|overflow"
  8123 times the listen queue of a socket overflowed
  8123 SYNs to LISTEN sockets dropped

  ss -ltn
  State  Recv-Q Send-Q Local Address:Port
  LISTEN 129    128          0.0.0.0:8080     <- Recv-Q at the backlog limit

  sysctl -w net.core.somaxconn=4096   and raise listen() backlog in the app

3. The keep alive race (the classic cause of intermittent 502)
  nginx    keepalive_timeout 65s   to upstream
  upstream server.keepAliveTimeout 5s
  -> upstream closes an idle pooled conn exactly as nginx reuses it -> RST -> 502
  RULE: upstream idle timeout MUST exceed the proxy's, with headroom.

4. Resource exhaustion, checked in parallel
  ls /proc/$(pgrep -f node | head -1)/fd | wc -l
  cat /proc/sys/fs/file-max
  dmesg | grep -E "conntrack: table full|Out of memory"

5. Correlate the capture timestamp with the proxy log
  grep "upstream prematurely closed" /var/log/nginx/error.log | tail -20

Key Points

  • Filter tcpdump on the RST flag and read the source to find who reset
  • Listen queue overflow reproduces only under load and is proven by the overflow counter
  • Upstream keepalive timeout shorter than the proxy's causes intermittent 502s
  • Check file descriptor and conntrack exhaustion in parallel, they look identical
💡 Pro Tip: Bring up the keep alive timeout mismatch yourself. It is a real production bug that most candidates have never met, and describing the exact race, upstream closing as the proxy reuses, is far more convincing than listing possible causes of a 502.
Q45

What are DNS over HTTPS and DNS over TLS, and what operational problems do they create for a corporate network or a split horizon setup?

AdvancedNetwork Security

Answer

Classic DNS runs in cleartext over UDP 53, so anyone on the path, your ISP, a coffee shop WiFi operator, a national filter, can see every hostname you resolve and can forge answers. DNS over TLS wraps DNS in TLS on its own port, 853, so it is encrypted but still identifiable and blockable by port. DNS over HTTPS sends DNS queries as HTTPS requests to a resolver endpoint on port 443, so it is indistinguishable from ordinary web traffic and effectively unblockable without breaking HTTPS.

Both protect confidentiality and integrity in transit. Neither authenticates the data at the zone level, that is DNSSEC's job, and the two are complementary, not alternatives. The operational problems are real.

Split horizon DNS, where internal.company.com resolves to a private address inside the network and either nothing or a public address outside, breaks completely when a browser bypasses the OS resolver and queries a public DoH endpoint directly; the user gets the external answer and cannot reach the internal service, which usually presents as intermittent because it depends on which application resolved the name. Enterprise policy enforcement based on DNS filtering, malware blocking, parental controls and compliance logging, is bypassed by the same mechanism. Diagnosis gets harder because you can no longer capture DNS traffic on the wire.

Mitigations: canary domains, where a browser queries a specific name and disables DoH if the network signals it should, network policy pushing the internal resolver as a DoH endpoint the browser trusts, and enterprise device management. The honest interview position is that this is a privacy versus control tradeoff, and the fix is running your own DoH resolver rather than blocking encrypted DNS.

Transport comparison
  Do53   UDP/TCP 53   cleartext, visible and forgeable on path
  DoT    TCP 853      encrypted, easy to identify and block by port
  DoH    HTTPS 443    encrypted, indistinguishable from web traffic
  DNSSEC any          authenticates the DATA, not the transport

Query a DoH endpoint by hand
  curl -s -H "accept: application/dns-json" \
    "https://cloudflare-dns.com/dns-query?name=goodspace.ai&type=A" | jq .Answer

  [{"name":"goodspace.ai","type":1,"TTL":300,"data":"35.200.1.9"}]

Check DNSSEC validation separately
  dig +dnssec goodspace.ai | grep -E "RRSIG|flags"
  ;; flags: qr rd ra ad;      ad = authenticated data

Split horizon breakage
  inside  : internal.goodspace.ai -> 10.20.4.9   (internal resolver)
  outside : internal.goodspace.ai -> NXDOMAIN
  browser using DoH bypasses the internal resolver -> NXDOMAIN inside the office
  Symptom: works in curl (uses the OS resolver), fails in Chrome. Intermittent
  by application, which is what makes it confusing.

Enterprise controls
  canary domain: use-application-dns.net -> answer NXDOMAIN to disable DoH
  push an internal DoH endpoint via device management instead of blocking

Key Points

  • DoT uses port 853 and is blockable; DoH rides port 443 and is not
  • Encrypted transport is not DNSSEC; one protects the path, the other the data
  • DoH in the browser bypasses split horizon DNS and enterprise filtering
  • Run your own DoH resolver rather than trying to block encrypted DNS
Q46

A user on a train sees their session survive a WiFi to 4G switch but die when the network drops to 2G in a tunnel. Explain TCP retransmission timeouts, RTT estimation and SACK in that context.

AdvancedTransport Layer

Answer

TCP sets its retransmission timeout from a running estimate of the round trip time, using Jacobson's algorithm: a smoothed RTT and a smoothed RTT variance, both updated with exponential weighted moving averages on every measurement, with RTO computed as the smoothed RTT plus four times the variance, floored at a minimum, 200 milliseconds on Linux. Karn's algorithm forbids taking an RTT sample from a retransmitted segment, because you cannot tell which transmission the ACK belongs to, and TCP timestamps solve that properly by carrying an echo value. When a retransmission times out the RTO doubles, exponential backoff, and cwnd collapses to one segment with slow start restarting.

Now the scenario. A WiFi to 4G handover changes the client's IP address, so strictly the four tuple changes and any established TCP connection is dead; what actually survives is either an application layer reconnection you never noticed, or a QUIC connection whose connection ID is independent of the address, or a carrier grade NAT keeping the mapping. Say that explicitly, because interviewers often expect the wrong folk answer here.

The tunnel case is different and worse. Falling to 2G does not change the address; it changes the path characteristics catastrophically, round trip time jumping from 60 milliseconds to over a second with heavy loss. The RTO estimate was tuned for the fast path, so it fires immediately, cwnd collapses, and each successive failure doubles the timeout to 2, 4, 8 seconds.

Meanwhile the application layer or load balancer idle timeout expires and tears the session down before TCP recovers. SACK helps by letting the sender retransmit only the missing ranges rather than everything after the first gap, which matters enormously when loss is bursty.

RTO estimation (Jacobson / Karels)
  SRTT    = (1 - a) * SRTT + a * sample          a = 1/8
  RTTVAR  = (1 - b) * RTTVAR + b * |SRTT - sample|   b = 1/4
  RTO     = SRTT + 4 * RTTVAR      clamped to [200ms, 120s] on Linux

  Karn: never sample RTT from a retransmitted segment.
  TCP timestamps fix that by echoing the sender's value.

Exponential backoff in the tunnel
  RTT 60ms  -> RTO ~300ms
  drop to 2G: RTT 1200ms, heavy loss
  RTO fires -> cwnd = 1, slow start
  still lost -> RTO 600ms -> 1.2s -> 2.4s -> 4.8s -> 9.6s ...
  meanwhile the LB idle timeout (60s) kills the session first

SACK: retransmit only the holes
  without SACK: cumulative ack stalls at the first gap, sender resends
                everything after it (go back N behaviour in practice)
  with SACK:    receiver reports "I have 2001..3000 and 4001..5000"
                sender resends only 3001..4000

Observe on the client
  ss -ti dst api.goodspace.ai
  cubic wscale:8,7 rto:1240 rtt:1180.4/210.2 cwnd:1 ssthresh:2
       bytes_retrans:184320 retrans:0/214 lost:12 sacked:8

  sysctl net.ipv4.tcp_sack net.ipv4.tcp_timestamps net.ipv4.tcp_retries2

Design response: idempotent requests, resumable uploads, application level
retry with jitter, and HTTP/3 so the connection ID survives the handover.

Key Points

  • RTO is smoothed RTT plus four times RTT variance, floored at 200ms on Linux
  • Karn's algorithm bars RTT samples from retransmissions; timestamps solve it
  • An IP change kills a TCP connection; only QUIC connection IDs survive it
  • SACK retransmits only the missing ranges, which matters most under bursty loss

Companies Hiring Computer Networks

TCS
Infosys
Wipro
Cisco
Accenture
Microsoft
Walmart Global Tech
Zoho

Salary Insights

Average in India
₹4-22 LPA

Frequently Asked Questions

What salary can I expect in India with strong computer networks skills in 2026?

It depends heavily on which track you are on. On the software engineering side, where networking is one skill among many, services majors such as TCS, Infosys, Wipro, Cognizant, Accenture and Capgemini pay roughly ₹3.5 to 7 LPA at entry and ₹8 to 16 LPA at three to six years. Product companies and funded startups, Flipkart, Razorpay, Swiggy, Zerodha, CRED, Zoho, Freshworks, PhonePe and Meesho, pay ₹12 to 24 LPA at entry and ₹28 to 50 LPA at senior level, and SRE or platform roles where networking is core sit at the top of that band. Global captives such as Microsoft, Walmart Global Tech, Atlassian, Adobe and Salesforce pay ₹18 to 32 LPA at entry and ₹45 LPA and above for senior infrastructure engineers. On the dedicated network engineer track, employers such as Cisco, HCLTech, Tech Mahindra, Jio and Airtel pay ₹3 to 6 LPA for NOC and L1 support roles, ₹6 to 12 LPA with a CCNA and two to four years of hands on work, and ₹15 to 30 LPA for CCNP or CCIE level network architects and cloud networking specialists.

How long does it take to prepare computer networks for interviews?

For a software engineering interview, three to four weeks of focused effort is realistic if you already know basic programming. Week one: OSI and TCP/IP models, encapsulation, TCP versus UDP, the handshake and teardown, and the full what happens when you type a URL walk, which alone covers a surprising share of questions. Week two: IP addressing, subnetting until you can do a problem in under a minute, NAT, ARP, DHCP and routing basics. Week three: DNS in depth, HTTP semantics, caching, cookies, CORS and TLS. Week four: hands on troubleshooting with dig, curl timing output, ss, traceroute and tcpdump on your own machine, because the practical questions are what separate candidates. For the network engineer track, budget three to four months, because you need configuration fluency: build labs in Packet Tracer, GNS3 or EVE-NG, configure VLANs, trunks, OSPF and BGP, break them deliberately and fix them. If you are targeting CCNA, most people take three to five months alongside a job.

Is CCNA still worth doing in India in 2026?

For the network engineer track, yes, and it is often a hard filter. Recruiters at Cisco partners, HCLTech, Tech Mahindra, Wipro network services, Jio and Airtel routinely screen resumes on the certification, and NOC and L1 job postings frequently list it as mandatory. The measurable effect is on the entry band: candidates with a CCNA and real lab experience typically start around ₹4.5 to 7 LPA against ₹3 to 4 LPA without, and it shortens the path to L2 and L3 roles. For a software engineer, backend, full stack or mobile, a CCNA is poor return on investment; nobody hiring for a Node or Java role cares, and the same months spent on distributed systems, cloud networking and Linux would pay far more. The nuanced middle case is cloud and DevOps: a CCNA gives you genuinely useful fundamentals for understanding VPCs, subnets, security groups, peering and transit gateways, but an AWS or Azure networking specialty certification maps more directly to what those interviews test. Whichever you choose, the certificate opens the door and the lab work gets you through it.

Which networking topics are asked most in Indian campus placements?

Campus rounds at services companies concentrate on a predictable set, so prepare these first. The OSI and TCP/IP models with layer to protocol mapping is nearly guaranteed. TCP versus UDP with examples appears in almost every panel. The three way handshake, and often the four way termination, comes up constantly. What happens when you type a URL and press Enter is the single most repeated question across TCS, Infosys, Wipro, Accenture and Capgemini drives. IP address classes, private ranges and one subnetting calculation appear in written tests and interviews alike. DNS resolution and the common record types are standard. HTTP versus HTTPS with a basic account of what TLS provides comes up regularly, as do HTTP status codes. Router versus switch versus hub, and ping versus traceroute, are common quick fire questions. Product company campus rounds go further, adding congestion control, HTTP caching, load balancing and a debugging scenario. If you have limited time, master the URL walk, TCP versus UDP, the handshake and subnetting, and you will handle most of what a campus panel asks.

Do software engineers really need computer networks, or is it only for network engineers?

Software engineers need it, but a different slice of it. You will never configure OSPF or terminate fibre, so the routing and switching depth that a network engineer lives in is not your job. What is your job is everything that touches the request path: why an API call takes eight hundred milliseconds and how much of that was DNS, why a deploy caused connection resets, why CORS blocks one endpoint and not another, why a certificate works on your laptop and fails on Android, why your service holds thirty thousand sockets open, and why a cross region call is slow no matter how fast your code is. Every one of those is a networking question and every one of them shows up in production. Interviewers know this, which is why the questions have moved towards scenarios. The practical minimum for a backend or full stack engineer is: TCP behaviour and connection lifecycle, HTTP semantics and caching, DNS and TLS, load balancer and proxy behaviour, and the ability to run dig, curl with timing, ss and tcpdump without looking anything up.

How does networking show up specifically in backend, DevOps and SRE interviews?

Backend interviews use networking to test whether you understand your own service's failure modes: connection pooling and keep alive, timeouts and retries with idempotency, why a retry storm amplifies an outage, HTTP caching headers, CORS, and TLS termination. Expect at least one scenario question such as why an endpoint got slower after adding a downstream call. DevOps interviews go one layer out: VPC design and subnetting, security groups versus network ACLs, NAT gateways and egress IPs for partner allow lists, service discovery through DNS, ingress controllers, and how traffic reaches a pod through a service and a load balancer. SRE interviews are the deepest and most scenario driven: you get a symptom, elevated p99 latency, intermittent 502s, packet loss to one region, and you are graded on your investigation order, on whether you measure before theorising, and on whether you know the commands. Expect ss, tcpdump, mtr, dig and curl timing output to appear as things you must read out loud from a screen rather than describe abstractly.

What is the best way to practise subnetting so I can do it under interview pressure?

Speed comes from two memorised tables and a fixed four step method, not from doing binary arithmetic every time. Memorise the block sizes for the last octet, 128, 192, 224, 240, 248, 252, 254, mapped to the prefixes /25 through /31, and memorise the powers of two up to 1024. Then always run the same four steps: size the host bits so that two to the host bits minus two covers the requirement, derive the prefix and mask, compute the block size as 256 minus the interesting octet, and list network, usable range and broadcast for each subnet. Practise by generating your own problems, take any random address and prefix and compute its network and broadcast in under thirty seconds, then verify with ipcalc or sipcalc on your laptop. Do ten a day for two weeks and it becomes automatic. For the network engineer track, add VLSM problems where you allocate several differently sized departments from one block, always largest first, since that is the format Cisco track interviews use on a whiteboard.

Introduction

Computer networks is the one core subject that shows up in almost every Indian technical interview, whether you are sitting for a campus drive at TCS, a lateral backend round at Razorpay, or a network engineer opening at Cisco Bangalore. The reason is simple: networking is where theory and production meet. An interviewer can ask you to recite the OSI layers and find out in thirty seconds whether you memorised a diagram, then ask why a DNS change did not take effect for one user in Pune and find out whether you have ever debugged anything. In 2026 the questions have shifted noticeably towards the practical end. Fewer panels ask you to draw the OSI stack in isolation, and many more ask what happens when you type a URL and press Enter, why a server has thirty thousand sockets in TIME_WAIT, or why an API is slow only for users on a particular ISP.

This keyword attracts two very different audiences and the interviews are not the same. If you are on the software engineer path, backend, full stack, DevOps or SRE, networking is examined as debugging ability. Panels at Flipkart, PhonePe, Swiggy, Zerodha, Microsoft India and Walmart Global Tech want TCP versus UDP with a real decision attached, TCP handshake and connection teardown, HTTP semantics, caching headers, CORS, TLS, load balancer behaviour at layer four versus layer seven, and a clean troubleshooting workflow using ping, dig, curl, ss and tcpdump. Subnetting still appears, usually as one worked example, because it proves you can think in binary. Nobody will ask you to configure OSPF areas, but everybody will ask you why a request took eight hundred milliseconds and which part of that was DNS.

If you are on the network engineer path, the shape changes. Cisco, Juniper, HCLTech, Tech Mahindra, Jio, Airtel, NOC and managed services roles go deep on the routing and switching side: VLANs and trunking, spanning tree, OSPF adjacency states, BGP attributes and route selection, NAT translation tables, access control lists, IPsec tunnels and IPv6 deployment. Here subnetting and VLSM are examined hard, often with three or four worked problems on a whiteboard under time pressure, and a CCNA or CCNP is a genuine differentiator on your resume rather than a decoration. This page covers 46 questions across both tracks, 18 basic, 18 intermediate and 10 advanced, with real commands, real protocol behaviour and the follow up questions Indian panels actually ask after your first answer.

Ready to practice Computer Networks interviews?

Don't just read, practice these Computer Networks questions live with an AI interviewer that asks follow-ups and scores your answers.

AI-powered practice
Instant feedback
Free to start
Start Free Mock Interview