Computer Networks & the Internet
How data actually gets from one computer to another — from cables to HTTPS. Simple words, real depth, tied to the web apps you build. Print this page for a PDF.
1. What a Network Really Is
A network is two or more devices joined together so they can send each other data. That's it. Two laptops on the same Wi-Fi are a network.
The Internet is a network of networks. Your home network, your college network, Google's network — millions of them, all agreeing to pass data to each other.
Think of the postal system. Every house has an address, letters go through sorting offices, and nobody needs to know the whole route — each office just knows where to send the letter next.
The handful of ideas everything else builds on
- Address — every device needs one so data can find it. On the Internet that's an IP address, like
142.250.183.14. - Packet — data isn't sent in one big lump. It's cut into small pieces called packets, each with the address written on it.
- Protocol — a set of rules both sides agree on, like "say hello before you talk" or "number your pages". HTTP, TCP and IP are all protocols.
- Client and server — the client asks (your browser), the server answers (the computer hosting the website). A server is just a computer whose job is to wait for requests.
fetch() you write, every API call, every slow page load, every CORS error is a networking event. Knowing what happens underneath turns "it doesn't work" into "the DNS lookup is failing" — and that's the difference interviewers look for.2. How the Internet Is Built
Your device connects to an ISP (Internet Service Provider) — Jio, Airtel, BT, Comcast. Your ISP connects to bigger ISPs, and the biggest ones own the backbone: huge fibre-optic cables running across countries and under oceans.
Nobody owns "the Internet". It works because all these companies agree to carry each other's traffic.
Your street joins a main road, the main road joins a motorway, and motorways connect cities. Your ISP is the local road; the backbone is the motorway.
Packet switching vs circuit switching
| Circuit switching | Packet switching | |
|---|---|---|
| How it works | Reserve a full path before talking | Cut data into packets, send each one separately |
| Example | Old landline phone calls | The Internet |
| Sharing | Path is yours alone, even during silence | Everyone shares the same links |
| If a link breaks | Call drops | Packets go around it |
| Downside | Wastes capacity | Packets can arrive late, out of order, or not at all |
Packet switching is "best effort": the network tries, but makes no promises. Making delivery reliable is a job pushed up to TCP (section 19).
Who's who
- Tier 1 ISPs own the backbone and swap traffic with each other for free (called peering).
- Regional and local ISPs pay bigger ones to carry their traffic (called transit).
- IXPs (Internet Exchange Points) are buildings where many networks plug into each other to swap traffic directly.
- Undersea cables carry over 95% of traffic between continents. Satellites are a tiny share.
3. Network Types & Topologies
Network types are named by how big an area they cover — a room, a building, a city, or the world.
A topology is the shape of the wiring — who is connected to whom.
| Type | Stands for | Covers | Example |
|---|---|---|---|
| PAN | Personal Area Network | A few metres | Phone to earbuds over Bluetooth |
| LAN | Local Area Network | A home, office or building | Your home Wi-Fi |
| MAN | Metropolitan Area Network | A city | A city-wide cable network |
| WAN | Wide Area Network | Countries, the world | The Internet; a company joining offices |
Topologies in one line each
- Bus — everyone on one cable. Cheap, but one fault takes down all. Mostly history now.
- Star — every device plugs into a central switch. One cable breaking only affects one device. If the switch dies, everything stops.
- Ring — each device passes data to the next in a loop.
- Mesh — many links between devices. Full mesh means every pair is linked: with n devices that's
n(n−1)/2cables. Reliable but costly. - Tree / hybrid — stars joined together. Most office networks look like this.
4. Network Devices
Each device has one main job. The interview question is almost always "what's the difference between a hub, a switch and a router?" — and the answer is how smart they are about where data goes.
A hub shouts every message to the whole room. A switch walks over and hands it to the right person. A router posts it to another building.
| Device | What it does | Works with | Layer |
|---|---|---|---|
| Hub | Copies every incoming signal out of every port. No intelligence. Mostly obsolete. | Raw signals | 1 — Physical |
| Switch | Connects devices inside one network. Learns which device is on which port and sends data only there. | MAC addresses | 2 — Data Link |
| Router | Connects different networks together and picks the path between them. | IP addresses | 3 — Network |
| Modem | "Modulator–demodulator". Turns your digital data into a signal that can travel over the phone line, cable or fibre — and back. | Signals on the line | 1 — Physical |
| Access point | Lets Wi-Fi devices join a wired network. A wireless version of a switch port. | MAC addresses | 2 — Data Link |
| Gateway | The "exit door" of a network. Also used for anything that translates between two different kinds of network or protocol. | Varies | Often 3 and up |
| Firewall | Decides which traffic is allowed in and out, using rules. | IPs, ports, sometimes content | 3–7 |
Your "Wi-Fi router" at home is really five devices in one box
Modem → talks to your ISP over the fibre/cable line
Router → joins your home network to the Internet
Switch → the LAN ports on the back
Access point → the Wi-Fi
DHCP + NAT + firewall → hands out addresses, shares one public IP, blocks junk
Default gateway
Your computer's default gateway is the router it sends anything to when the destination isn't on the local network. At home, it's usually 192.168.1.1 or 192.168.0.1. If the gateway is wrong, you can reach your printer but not Google.
5. Latency, Bandwidth & Throughput
Latency is how long one piece of data takes to get there — a delay, measured in milliseconds.
Bandwidth is how much data could flow per second — the maximum, measured in Mbps or Gbps.
Throughput is how much data actually flows per second right now. It's always lower than bandwidth.
A motorway: latency is how long the drive takes; bandwidth is how many lanes it has; throughput is how many cars actually got through this hour, traffic jams included.
Where latency comes from
- Propagation delay — the time for the signal to physically travel. Light in fibre goes about 200,000 km per second, so London to Mumbai (~7,200 km) takes at least ~36 ms one way. You can't fix physics; you can only move the server closer.
- Transmission delay — the time to push all the bits onto the wire. Bigger files, slower links → longer.
- Queuing delay — waiting in a router's queue behind other packets. This is what spikes when the network is busy.
- Processing delay — the time a router takes to read the header and decide where to send it. Tiny.
RTT — the number that matters most for web apps
RTT (round-trip time) is the time to send something and get a reply. Opening an HTTPS connection needs several round trips before any data arrives (TCP handshake, then TLS). With an RTT of 100 ms, that's a few hundred milliseconds of nothing.
Other words you'll hear
- Jitter — how much latency jumps around. Bad for video calls and games.
- Packet loss — the percentage of packets that never arrive. Even 1–2% makes TCP slow down sharply.
- Mbps vs MBps — megabits vs megabytes. 8 bits = 1 byte, so a 100 Mbps line downloads at about 12.5 MB per second at best.
6. Why Layers? The OSI Model
Sending data across the world is a huge problem. So it's split into layers, each solving one small part and trusting the layer below to handle the rest.
The OSI model splits networking into 7 layers. It's a teaching model — a way to talk about where something happens. Real networks follow the simpler TCP/IP model (next section).
Sending a gift: you write the card (application), wrap it (presentation), the courier picks it up (transport), sorting centres route it between cities (network), a van drives it down your street (data link), and the road itself is the physical layer. The person writing the card never thinks about roads.
Each layer's job, in one line
- Physical — send raw 1s and 0s as electrical signals, light or radio waves.
- Data Link — get data to the next device on the same local network, using MAC addresses. Spots damaged data.
- Network — get data across many networks to the right computer, using IP addresses. Picks the route.
- Transport — get data to the right program on that computer, using port numbers. TCP also makes it reliable.
- Session — open, keep and close a conversation between two programs.
- Presentation — make the data readable: character encoding, compression, encryption.
- Application — the protocol your app actually speaks: HTTP, DNS, SMTP.
Memorise bottom-up with "Please Do Not Throw Sausage Pizza Away" (Physical, Data Link, Network, Transport, Session, Presentation, Application).
7. OSI vs TCP/IP — the Full Table
TCP/IP is the model the Internet actually runs on. It has 4 layers (some books say 5, splitting Link into Data Link and Physical).
In interviews, people still say "layer 4" or "layer 7" using OSI numbers. So learn OSI for vocabulary, TCP/IP for how things really work.
| OSI layer | TCP/IP layer | Data unit (PDU) | Address used | Protocols | Devices |
|---|---|---|---|---|---|
| 7 Application | Application | Data / message | URL, domain name | HTTP, DNS, SMTP, FTP, SSH, DHCP | L7 load balancer, proxy, WAF |
| 6 Presentation | TLS*, UTF-8, JPEG, gzip | ||||
| 5 Session | Session setup, RPC | ||||
| 4 Transport | Transport | Segment (TCP) / Datagram (UDP) | Port | TCP, UDP, QUIC | L4 load balancer, firewall |
| 3 Network | Internet | Packet | IP address | IP, ICMP, OSPF, BGP | Router, L3 switch |
| 2 Data Link | Link | Frame | MAC address | Ethernet, Wi-Fi (802.11), ARP* | Switch, bridge, access point, network card |
| 1 Physical | Bits | — | Cables, fibre, radio | Hub, repeater, modem, cables |
* Some protocols don't fit neatly. TLS sits between TCP and HTTP, so people place it at 5, 6 or "4.5". ARP links IP (layer 3) to MAC (layer 2), so it's placed at either. If an interviewer pushes, say exactly that — it shows you understand the models are simplifications.
PDU names — a common quick-fire question
Application → data / message
Transport → segment (TCP) or datagram (UDP)
Network → packet
Data Link → frame
Physical → bits
8. Encapsulation
As your data goes down the layers, each layer wraps it in its own envelope — a header with the information that layer needs. This is encapsulation.
At the other end, the data goes up the layers and each one removes its own envelope. That's decapsulation.
A letter in an envelope, inside a courier bag, inside a delivery van. Each handler only opens the wrapping meant for them.
What each header carries
| Header | Key fields | Question it answers |
|---|---|---|
| TCP | Source port, destination port, sequence number, ack number, flags | Which program? Which piece is this? |
| IP | Source IP, destination IP, TTL, protocol | Which computer, anywhere in the world? |
| Ethernet | Source MAC, destination MAC, type | Which device on this local network? |
9. MAC Addresses, Ethernet & ARP
Every network card has a MAC address — a hardware ID set at the factory, like 3c:22:fb:9a:10:4e. It's used to deliver data to the right device on the same local network.
Ethernet is the set of rules for sending data over a local wired network (Wi-Fi follows very similar rules). ARP is how a device finds out which MAC address belongs to an IP address.
Your IP address is like your postal address — it can change when you move. Your MAC address is like your name — it stays with you. The postman uses the address to reach your street, then the name to find you in the house.
MAC vs IP
| MAC address | IP address | |
|---|---|---|
| Layer | 2 — Data Link | 3 — Network |
| Size | 48 bits, written as 6 hex pairs | 32 bits (IPv4) or 128 bits (IPv6) |
| Set by | Manufacturer (burned into the card) | The network (usually DHCP) |
| Scope | Only matters on the local network | Works across the whole Internet |
| Changes? | Rarely (phones now randomise it for privacy) | Yes, when you change networks |
The first half of a MAC address (24 bits) identifies the maker — the OUI. ff:ff:ff:ff:ff:ff is the broadcast address: "everyone on this network".
An Ethernet frame
| Preamble | Dest MAC | Source MAC | Type | Payload (the IP packet) | FCS |
| 8 bytes | 6 bytes | 6 bytes | 2 B | 46 – 1500 bytes | 4 bytes |
- Type says what's inside — for example IPv4 or IPv6.
- The payload can be at most 1500 bytes. That limit is the MTU (Maximum Transmission Unit). Bigger IP packets must be split up.
- FCS (Frame Check Sequence) holds a CRC — a checksum.
Error detection with CRC
The sender runs the frame through a maths formula and attaches the result (the CRC). The receiver runs the same formula. If the answers don't match, a bit got flipped on the way, and the frame is thrown away. Ethernet detects errors; it doesn't fix them. Re-sending is TCP's job, higher up.
Simpler checks you may be asked about: a parity bit (one extra bit making the count of 1s even or odd — catches single-bit errors only) and a checksum (add the data up; IP, TCP and UDP headers each use one).
How a switch learns
- A frame arrives on port 3 from MAC
AA. The switch writes down "AAis on port 3" in its MAC table. - It looks up the destination MAC. If it knows the port, it sends the frame out of that port only.
- If it doesn't know yet, it floods the frame out of every port. When the reply comes back, it learns that MAC too.
ARP — finding the MAC for an IP
Your laptop wants to send to 192.168.1.1 (the router) but needs its MAC.
1. Broadcast to everyone: "Who has 192.168.1.1? Tell 192.168.1.10"
2. The router replies: "192.168.1.1 is at 3c:22:fb:9a:10:4e"
3. Laptop saves it in its ARP cache for a few minutes.
$ arp -a # see your ARP cache
Your computer only ever ARPs for devices on its own network. To reach Google, it ARPs for the router's MAC and hands the packet to the router.
VLANs, briefly
A VLAN (Virtual LAN) splits one physical switch into several separate networks. Guests, staff and printers can share the same hardware but can't see each other's traffic. Traffic between VLANs must go through a router or firewall.
10. IPv4 Addresses & Classes
An IPv4 address is a 32-bit number, written as four numbers from 0 to 255 separated by dots: 192.168.1.10. Each of the four parts is 8 bits, called an octet.
Every address has two parts: the network part (which street) and the host part (which house on that street).
A phone number: the area code finds the city, the rest finds the person. All phones in one city share the area code.
192 .168 .1 .10
11000000 .10101000 .00000001 .00001010 ← the same thing in binary
32 bits → 2^32 ≈ 4.3 billion possible addresses (not enough — hence NAT and IPv6)
Classes — the old system (still asked)
| Class | First octet | Default mask | Network / host split | Use |
|---|---|---|---|---|
| A | 1 – 126 | 255.0.0.0 (/8) | N.H.H.H — few huge networks | Very large organisations |
| B | 128 – 191 | 255.255.0.0 (/16) | N.N.H.H | Medium organisations |
| C | 192 – 223 | 255.255.255.0 (/24) | N.N.N.H — many small networks | Small networks |
| D | 224 – 239 | — | — | Multicast (one-to-many) |
| E | 240 – 255 | — | — | Reserved / experimental |
127 is missing from class A on purpose: 127.0.0.0/8 is loopback. 127.0.0.1 (localhost) always means "this same computer" — that's how your dev server on localhost:3000 works without any network at all.
Classes wasted addresses badly — a company needing 300 addresses had to take a whole class B (65,536). Since 1993 the Internet uses CIDR instead (next section). Learn classes for interviews, but say they're obsolete.
Special addresses to recognise
| Address | Meaning |
|---|---|
127.0.0.1 | Loopback — this machine |
0.0.0.0 | "Any address" — a server listening on it accepts connections on every network card |
255.255.255.255 | Broadcast to everyone on the local network |
169.254.x.x | Link-local — your computer gave itself this because DHCP failed. A clue that something's wrong. |
10.x, 172.16–31.x, 192.168.x | Private ranges (section 12) |
127.0.0.1 can't be reached from outside the container, because loopback means "only me". Listen on 0.0.0.0 instead.11. CIDR & Subnetting
CIDR notation writes an address with a slash and a number: 192.168.10.0/24. The number says how many bits from the left are the network part. The rest are for hosts.
Subnetting means cutting one network into smaller ones by borrowing host bits for the network part.
A big plot of land (/24) divided into four equal smaller plots (/26). Same land, more fences.
The only formula you need
host bits = 32 − prefix
total addresses = 2^(host bits)
usable hosts = 2^(host bits) − 2 (first = network address, last = broadcast)
| Prefix | Subnet mask | Total addresses | Usable hosts |
|---|---|---|---|
| /8 | 255.0.0.0 | 16,777,216 | 16,777,214 |
| /16 | 255.255.0.0 | 65,536 | 65,534 |
| /24 | 255.255.255.0 | 256 | 254 |
| /25 | 255.255.255.128 | 128 | 126 |
| /26 | 255.255.255.192 | 64 | 62 |
| /27 | 255.255.255.224 | 32 | 30 |
| /28 | 255.255.255.240 | 16 | 14 |
| /30 | 255.255.255.252 | 4 | 2 (point-to-point link) |
| /32 | 255.255.255.255 | 1 | A single host |
A subnet mask is the same idea as the prefix, written as an address: 1s for network bits, 0s for host bits. /26 = 26 ones = 11111111.11111111.11111111.11000000 = 255.255.255.192.
Worked example — split 192.168.10.0/24 into 4 subnets
Need 4 subnets → borrow 2 bits (2² = 4) → /24 + 2 = /26
Host bits left → 32 − 26 = 6 → 2⁶ = 64 addresses each
Usable hosts → 64 − 2 = 62 per subnet
Mask → 255.255.255.192 (128 + 64 = 192)
Block size → 256 − 192 = 64
Question style: "Which subnet is 192.168.10.150/26 in?"
- Block size for /26 is 64. Multiples: 0, 64, 128, 192.
- 150 sits between 128 and 191 → network address is 192.168.10.128.
- Broadcast is the last one in the block: 192.168.10.191.
- Usable hosts: .129 to .190.
Question style: "I need 50 hosts per subnet. What prefix?"
Find the smallest power of 2 where 2^n − 2 ≥ 50. 2⁵ − 2 = 30 (too small), 2⁶ − 2 = 62 (enough). So 6 host bits → /26.
Two computers, same subnet?
AND each IP with the mask; if the results match, they're on the same subnet and can talk directly. If not, traffic goes via the router. With /26, 192.168.10.70 (block .64) and 192.168.10.130 (block .128) are on different subnets, even though they look close.
10.0.0.0/16, then subnets like 10.0.1.0/24 (public) and 10.0.2.0/24 (private). Security group rules like 0.0.0.0/0 mean "any address at all".12. Private IPs & NAT
There aren't enough IPv4 addresses for every device on Earth. So homes and offices use private addresses inside, which aren't reachable from the Internet, and share one public address to go out.
NAT (Network Address Translation) is the trick your router uses to make that sharing work.
An office with one phone number and a receptionist. Staff have internal extensions. When someone calls out, the outside world only sees the main number — the receptionist remembers who made which call so replies reach the right desk.
Private ranges (memorise these)
| Range | CIDR | Size | Typically seen |
|---|---|---|---|
| 10.0.0.0 – 10.255.255.255 | 10.0.0.0/8 | ~16.7 million | Companies, cloud VPCs |
| 172.16.0.0 – 172.31.255.255 | 172.16.0.0/12 | ~1 million | Docker networks, companies |
| 192.168.0.0 – 192.168.255.255 | 192.168.0.0/16 | 65,536 | Home routers |
Thousands of homes all use 192.168.1.10 at the same time. That's fine — routers on the Internet refuse to carry private addresses, so they never clash.
What NAT costs you
- Nobody outside can start a connection to you. The router has no table entry for an unknown incoming request, so it drops it. That's accidental security — and why hosting a game server at home needs port forwarding.
- Peer-to-peer gets hard. Video calls (WebRTC) use tricks called STUN and TURN to get two NAT-ed devices talking.
- It breaks the original idea that every device has its own reachable address. IPv6 restores that.
ipconfig / ifconfig and you'll see a private address like 192.168.1.10. Search "what is my IP" and you'll see a completely different public one. The gap between the two is NAT.13. IPv6
IPv6 is the newer version of IP with 128-bit addresses instead of 32. That's about 3.4 × 10³⁸ addresses — enough for every device forever, so NAT isn't needed.
Addresses are written as 8 groups of 4 hex digits separated by colons.
Full: 2001:0db8:0000:0000:0000:ff00:0042:8329
Shortened: 2001:db8::ff00:42:8329
Rule 1: drop leading zeros in each group (0db8 → db8, 0042 → 42)
Rule 2: replace ONE run of all-zero groups with :: (only once per address)
::1 → loopback (IPv6's 127.0.0.1)
fe80::/10 → link-local (only valid on this network)
IPv4 vs IPv6
| IPv4 | IPv6 | |
|---|---|---|
| Address size | 32 bits, ~4.3 billion | 128 bits, ~3.4 × 10³⁸ |
| Written as | 192.168.1.10 | 2001:db8::1 |
| NAT | Needed everywhere | Not needed — every device can have a public address |
| Getting an address | DHCP | Can configure itself (SLAAC) or use DHCPv6 |
| Finding MACs | ARP | NDP (Neighbour Discovery) |
| Broadcast | Yes | No — uses multicast instead |
| Header | Variable, has a checksum | Fixed 40 bytes, no checksum (simpler for routers) |
| DNS record | A | AAAA |
The switch-over is slow because IPv4 and IPv6 can't talk to each other directly. Most networks run both side by side — called dual stack.
http://[::1]:3000. If localhost works but your Node app doesn't respond, it may be listening on IPv4 only while localhost resolved to ::1.14. Routing
Routing is choosing the path a packet takes between networks. Each router keeps a routing table: a list of "to reach these addresses, send to that neighbour".
A router never plans the whole journey. It only decides the next hop.
Road signs at each junction. No sign shows the full route to Edinburgh — each just says "Edinburgh, this way".
A routing table
Destination Next hop Interface
192.168.1.0/24 (direct) eth0 ← my own local network
10.20.0.0/16 192.168.1.254 eth0 ← office network via another router
0.0.0.0/0 203.0.113.1 wan0 ← default route: everything else → ISP
If several entries match, the router picks the most specific one — the longest prefix. This is called longest prefix match. 0.0.0.0/0 matches everything, so it's used only when nothing better does.
Static vs dynamic routing
| Static | Dynamic | |
|---|---|---|
| Who writes the routes | A person, by hand | Routers share and learn routes automatically |
| If a link fails | Stays broken until someone fixes it | Routers find another path |
| Good for | Small, simple networks; the default route at home | Large networks, the Internet |
The two families of dynamic routing
- Distance vector — each router tells its neighbours "here's how far I am from everything". Simple, but slow to notice failures. Called "routing by rumour". Example: RIP, which counts hops and gives up after 15.
- Link state — each router tells everyone about its own direct links. Every router builds a full map and runs Dijkstra's shortest-path algorithm on it. Faster and smarter, but uses more memory. Example: OSPF.
RIP, OSPF and BGP at a glance
| Protocol | Type | Used | Picks the path by |
|---|---|---|---|
| RIP | Distance vector | Small networks (mostly old) | Fewest hops |
| OSPF | Link state | Inside one organisation | Lowest cost (based on link speed) |
| BGP | Path vector | Between organisations — the whole Internet | Policies, business deals, path length |
The Internet is made of tens of thousands of Autonomous Systems (ASes) — each is one organisation's network (an ISP, Google, Cloudflare). BGP is how ASes tell each other "I can reach these addresses". It's the glue of the Internet. When a company publishes a wrong BGP route, whole services disappear — that's what took Facebook offline for six hours in 2021.
15. ICMP, TTL, Ping & Traceroute
ICMP (Internet Control Message Protocol) is the network's messaging system for errors and checks — "that host is unreachable", "your packet expired". It doesn't carry your app's data.
TTL (Time To Live) is a counter in every IP packet. Each router lowers it by 1. When it hits 0, the packet is thrown away. This stops lost packets from looping forever.
Ping
$ ping google.com
64 bytes from 142.250.183.14: icmp_seq=1 ttl=117 time=12.4 ms
64 bytes from 142.250.183.14: icmp_seq=2 ttl=117 time=11.9 ms
ping sends an ICMP Echo Request; the target replies with an Echo Reply. It tells you: is the host reachable, and what's the round-trip time? A ping failing doesn't always mean the host is down — many servers and firewalls simply block ICMP.
Traceroute — the clever use of TTL
Send a packet with TTL=1 → the 1st router drops it, replies "Time Exceeded" → now you know hop 1
Send a packet with TTL=2 → the 2nd router drops it, replies → hop 2
…keep going until the destination itself replies.
$ traceroute google.com (Windows: tracert google.com)
1 192.168.1.1 1.2 ms ← your home router
2 10.45.0.1 8.7 ms ← your ISP
3 * * * ← this router doesn't answer; not necessarily a problem
4 142.250.183.14 12.1 ms ← arrived
Traceroute shows where on the path things slow down or stop. A big jump in time between two hops points to the slow link.
Common ICMP messages
- Echo Request / Reply — ping.
- Destination Unreachable — no route, or the port is closed.
- Time Exceeded — TTL hit zero (what traceroute relies on).
ttl=117 probably started at 128 and crossed 11 routers. In IPv6 the same field is called Hop Limit — a more honest name, since it counts hops, not time.16. Ports & Sockets
An IP address gets data to the right computer. A port gets it to the right program on that computer. Ports are numbers from 0 to 65535.
A socket is one end of a conversation: an IP address plus a port, like 142.250.183.14:443. Programs read and write to sockets the way they read and write files.
The IP address is a block of flats; the port is the flat number. The building is right, but without the flat number the letter can't be delivered.
Port ranges
| Range | Name | Used for |
|---|---|---|
| 0 – 1023 | Well-known | Standard services (HTTP, SSH). Need admin rights to listen on. |
| 1024 – 49151 | Registered | Apps like databases (3306, 5432) and dev servers (3000, 8080) |
| 49152 – 65535 | Ephemeral | Picked at random by your OS for the client side of each connection |
Ports worth knowing by heart
| Port | Service | Port | Service |
|---|---|---|---|
| 20, 21 | FTP (data, control) | 143 / 993 | IMAP / IMAP over TLS |
| 22 | SSH, SFTP | 443 | HTTPS (and HTTP/3 over UDP) |
| 23 | Telnet (insecure) | 587 | SMTP for sending mail from an app |
| 25 | SMTP (server to server) | 3306 | MySQL |
| 53 | DNS | 5432 | PostgreSQL |
| 67, 68 | DHCP (server, client) | 6379 | Redis |
| 80 | HTTP | 27017 | MongoDB |
| 110 / 995 | POP3 / POP3 over TLS | 3000, 5173, 8080 | Common dev servers |
How one server port handles thousands of users
Every connection is identified by five things together — the 5-tuple:
(protocol, source IP, source port, destination IP, destination port)
TCP, 49.36.10.5:52344 → 104.18.2.1:443
TCP, 49.36.10.5:52345 → 104.18.2.1:443 ← same user, second tab: different source port
TCP, 117.200.8.9:60111 → 104.18.2.1:443 ← different user
All three hit port 443, but each 5-tuple is unique, so the server keeps them apart. A port is not "used up" by one connection.
Sockets in code
// Server: create → bind to a port → listen → accept connections
const net = require("net");
net.createServer(socket => {
socket.on("data", d => socket.write("echo: " + d));
}).listen(4000, "0.0.0.0");
// Client: create → connect to IP:port → send/receive
const client = net.connect(4000, "127.0.0.1", () => client.write("hi"));
Express, fetch, database drivers — they all sit on top of exactly this. app.listen(3000) is "open a socket on port 3000 and wait".
lsof -i :3000 (macOS/Linux) or netstat -ano | findstr :3000 (Windows).17. TCP vs UDP
TCP is careful: it sets up a connection, numbers every byte, re-sends anything lost, and delivers everything in order. Slower, but nothing goes missing.
UDP just fires packets off. No connection, no re-sending, no ordering. Faster and lighter, but some data may be lost.
TCP is a recorded-delivery parcel — signed for, tracked, re-sent if lost. UDP is shouting across a room — quick, but if they didn't hear, you don't repeat yourself.
| TCP | UDP | |
|---|---|---|
| Connection | Yes — handshake first | No — just send |
| Reliable | Yes — lost data is re-sent | No — lost is lost |
| Ordered | Yes | No |
| Flow & congestion control | Yes — slows down if the receiver or network is overwhelmed | No — sends as fast as you tell it |
| Header size | 20–60 bytes | 8 bytes |
| Data shape | A continuous stream of bytes | Separate messages (datagrams) |
| Speed | Slower to start, steady | Fast, low delay |
| Used by | HTTP/1.1 & 2, SSH, email, databases, file transfer | DNS, video calls, online games, live streaming, DHCP, QUIC (HTTP/3) |
Why would anyone want unreliable delivery?
Because for some data, late is as bad as lost. In a video call, a missing frame from half a second ago is useless — re-sending it would only freeze the call while it waits. Better to skip it and show the next one. Games, live audio and video all think this way.
DNS uses UDP because a lookup is one small question and one small answer. A handshake would triple the cost. If no answer comes back, the client simply asks again.
18. The 3-Way Handshake & 4-Way Teardown
Before TCP sends any data, both sides agree they're ready and pick starting numbers for counting bytes. That's the 3-way handshake: SYN, SYN-ACK, ACK.
Closing takes four steps because each side shuts its own direction separately — the 4-way teardown.
A phone call: "Hello, can you hear me?" — "Yes, I can hear you, can you hear me?" — "Yes." Then you talk. At the end: "I'm done." — "OK." … "I'm done too." — "OK, bye."
Opening, step by step
- SYN — client: "I want to connect. My bytes will start counting from 100."
- SYN-ACK — server: "Got it, I expect 101 next. My bytes start from 300."
- ACK — client: "Got it, I expect 301 next." Connection open.
Starting numbers are random, not 0 — that makes it hard for an attacker to guess them and inject fake packets.
Why three steps, not two?
Both sides must prove they can send and receive. After step 2, the client knows both directions work, but the server doesn't yet know the client received its reply. Step 3 confirms it. It also stops an old, delayed SYN from opening a ghost connection.
Closing
TCP is two one-way streams. FIN means "I've finished sending" — but I can still receive. So each side sends its own FIN and gets its own ACK. The side that closes first waits in TIME_WAIT (typically 30 seconds to 2 minutes) in case its final ACK got lost and the other side re-sends its FIN.
A connection can also be cut instantly with RST (reset) — what you get when you connect to a port nobody is listening on: "connection refused".
19. Reliability, Flow Control & Congestion Control
TCP has three different jobs that sound alike:
Reliability — make sure every byte arrives, once, in order.
Flow control — don't send faster than the receiver can handle.
Congestion control — don't send faster than the network can handle.
Flow control is not overfilling your friend's cup. Congestion control is not jamming the motorway everyone shares.
Reliability — sequence numbers and ACKs
- Every byte has a sequence number. The receiver uses them to put pieces back in order and spot gaps.
- The receiver sends an ACK (acknowledgement) saying "I've got everything up to byte N; send N+1 next".
- If no ACK comes back within a timeout, the sender assumes the data was lost and re-sends it (retransmission).
- If the sender gets three duplicate ACKs for the same byte, it doesn't wait for the timeout — the later packets are getting through, so one must be missing. It re-sends straight away (fast retransmit).
- Duplicates are spotted by sequence number and quietly dropped.
Flow control — the sliding window
Waiting for an ACK after every packet would be painfully slow. Instead the sender may have a window of data "in flight" — sent but not yet acknowledged. As ACKs arrive, the window slides forward and more can be sent.
bytes: [ acked ][ sent, waiting for ACK ][ can send now ][ must wait ]
|<-------------- window ---------------->|
ACK arrives → the left edge moves right → the whole window slides →
The receiver tells the sender how big that window can be in every ACK (the receive window, rwnd). If the receiving app is slow to read, its buffer fills, it advertises a smaller window, and the sender slows down. Window 0 means "stop for now".
Congestion control — slow start and AIMD
The sender keeps a second limit, the congestion window (cwnd), guessing how much the network can take. It actually sends min(rwnd, cwnd).
- Slow start — begin small (traditionally 1 segment, about 10 today) and double
cwndevery round trip. Despite the name, this grows very fast. - Once it reaches a threshold (
ssthresh), switch to congestion avoidance: grow by just 1 segment per round trip. This is the additive increase. - When a loss is detected, assume the network is congested and cut back hard:
- Three duplicate ACKs (mild) → halve
cwndand continue. This is the multiplicative decrease. - A timeout (serious) → drop
cwndright back and start slow start again.
- Three duplicate ACKs (mild) → halve
Together this pattern is called AIMD — Additive Increase, Multiplicative Decrease. The speed graph looks like a sawtooth: climb slowly, drop sharply, climb again. It's what lets millions of connections share the Internet fairly without anyone in charge.
20. DNS — the Internet's Phone Book
Computers find each other by IP address, but people remember names. DNS (Domain Name System) turns a name like example.com into an IP address.
No single computer holds every name. DNS is a tree of servers, each responsible for one part of the name, and answers are cached everywhere along the way.
Asking for directions: you ask a helpful local (the resolver). They don't know, so they ask the country office (root), who points them to the city office (.com), who points them to the right building (the domain's own server), who finally gives the exact address.
The full lookup order
- Browser cache — visited recently? Done.
- OS cache and the hosts file (
/etc/hosts) — a manual override list. - Recursive resolver — usually your ISP's, or a public one like Cloudflare's
1.1.1.1or Google's8.8.8.8. Has a big shared cache. - Root servers — 13 named root server addresses, each copied to hundreds of machines worldwide. They only know where each top-level domain lives.
- TLD servers — for
.com,.org,.in… They know which name servers handle each domain. - Authoritative name server — the one that actually holds the domain's records (often at Cloudflare, Route 53 or your registrar). Gives the final answer.
Record types
| Record | Maps | Example |
|---|---|---|
| A | Name → IPv4 address | example.com → 203.0.113.10 |
| AAAA | Name → IPv6 address | example.com → 2001:db8::10 |
| CNAME | Name → another name (an alias) | www.example.com → example.netlify.app |
| MX | Which servers receive email for this domain | example.com → mail.google.com (priority 10) |
| NS | Which name servers are authoritative | example.com → ns1.cloudflare.com |
| TXT | Free text — domain ownership checks, email anti-spoofing (SPF, DKIM) | "v=spf1 include:_spf.google.com ~all" |
| PTR | IP → name (reverse lookup) | 10.113.0.203.in-addr.arpa → example.com |
| SOA | Admin info about the zone | Primary server, serial number, timers |
Caching and TTL
Every record has a TTL (time to live) in seconds — how long others may cache it. A TTL of 3600 means "you can reuse this answer for an hour".
- Long TTL → fewer lookups, faster, but changes take longer to reach everyone.
- Short TTL → changes spread fast, but more lookups.
"DNS propagation takes up to 48 hours" really means: old answers are still sitting in caches until their TTL runs out. Before moving a site to a new server, lower the TTL a day ahead.
example.com), only on subdomains like www. That's why hosts like Vercel and Netlify ask for an A record on the root, or why DNS providers offer "ALIAS" / "CNAME flattening".21. DHCP — Getting an Address Automatically
When you join a Wi-Fi network, you don't type in an IP address. DHCP (Dynamic Host Configuration Protocol) hands one to you automatically, along with everything else you need to get online.
Checking into a hotel: you arrive, the front desk gives you a room number, tells you where the exit and the restaurant are, and the room is yours until checkout.
DORA — the four steps
1. Discover client → everyone "Is there a DHCP server? I need an address."
(from 0.0.0.0 to 255.255.255.255 — it has no IP yet)
2. Offer server → client "You can have 192.168.1.23."
3. Request client → everyone "I'll take 192.168.1.23, please."
(broadcast, so any other servers that offered know)
4. Ack server → client "Confirmed. It's yours for 24 hours."
What you get
- Your IP address
- The subnet mask (which addresses are local)
- The default gateway (the router to send everything else to)
- DNS servers to use
- A lease time — the address is borrowed, not owned. Devices renew at about halfway through.
DHCP runs over UDP — server port 67, client port 68. At home, your router is the DHCP server.
169.254, no DHCP server answered, so it gave itself a "link-local" address. You're not really on the network. Servers and printers usually get a reserved or static address instead, so they don't move around.22. HTTP — Requests, Responses & Methods
HTTP (HyperText Transfer Protocol) is the language browsers and servers speak. The client sends a request; the server sends back a response. Every web page, image and API call is one of these exchanges.
In HTTP/1.1 it's just readable text sent over a TCP connection — you could type it by hand.
Anatomy of a request
POST /api/orders?coupon=SAVE10 HTTP/1.1 ← method, path + query, version
Host: shop.example.com ← headers: extra information
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
Cookie: session=abc123
← blank line = headers are over
{"productId": 42, "qty": 2} ← body (optional)
Anatomy of a response
HTTP/1.1 201 Created ← version, status code, reason
Content-Type: application/json
Set-Cookie: cart=; Max-Age=0
Cache-Control: no-store
{"orderId": 9001, "status": "pending"}
Methods
| Method | Meaning | Has body? | Safe | Idempotent |
|---|---|---|---|---|
| GET | Read something | No | Yes | Yes |
| POST | Create something / trigger an action | Yes | No | No |
| PUT | Replace the whole thing | Yes | No | Yes |
| PATCH | Change part of it | Yes | No | Not guaranteed |
| DELETE | Remove it | Usually no | No | Yes |
| HEAD | Like GET, but headers only | No | Yes | Yes |
| OPTIONS | "What am I allowed to do here?" (used by CORS) | No | Yes | Yes |
- Safe = doesn't change anything on the server. Browsers and crawlers assume GET is safe, so never delete things on a GET link.
- Idempotent = doing it twice has the same effect as once. Deleting order 5 twice still leaves order 5 deleted. POSTing twice creates two orders — which is why a "retry" on a payment POST is dangerous and needs an idempotency key.
REST over HTTP, briefly
REST is a style for designing APIs on top of HTTP: URLs name things (nouns), and the HTTP method says what to do with them.
GET /users → list users
GET /users/7 → one user
POST /users → create a user
PATCH /users/7 → update part of user 7
DELETE /users/7 → delete user 7
GET /users/7/orders → user 7's orders
✗ POST /getUser ✗ GET /deleteUser?id=7 ← verbs in URLs, wrong methods
REST also means stateless requests (each carries everything needed, like an auth token) and using proper status codes — next section.
23. Status Codes, Headers, Cookies & Statelessness
A status code is a three-digit number telling you how the request went. The first digit is the category — learn those five and you can guess any code.
Headers are labelled notes attached to a request or response. Cookies are small pieces of data the server asks the browser to store and send back.
Status code families
| Range | Meaning | Ones to know |
|---|---|---|
| 1xx | Info, keep going | 101 Switching Protocols (upgrading to WebSocket) |
| 2xx | Success | 200 OK · 201 Created · 204 No Content |
| 3xx | Go somewhere else | 301 Moved Permanently · 302 Found (temporary) · 304 Not Modified (use your cache) · 307/308 redirect keeping the method |
| 4xx | You (the client) got it wrong | 400 Bad Request · 401 Unauthorized · 403 Forbidden · 404 Not Found · 405 Method Not Allowed · 409 Conflict · 422 Unprocessable · 429 Too Many Requests |
| 5xx | The server got it wrong | 500 Internal Server Error · 502 Bad Gateway · 503 Service Unavailable · 504 Gateway Timeout |
- 401 vs 403 — 401 means "I don't know who you are" (log in). 403 means "I know who you are, and you're not allowed".
- 502 vs 504 — both come from a proxy or load balancer in front of your app. 502: the app sent back garbage or refused the connection (often it crashed). 504: the app took too long to answer.
- 301 vs 302 — browsers and search engines remember a 301 for good. Use 302 while testing.
Headers worth knowing
| Header | Direction | Purpose |
|---|---|---|
Host | Request | Which website — lets one server host many domains. Required in HTTP/1.1. |
Content-Type | Both | Format of the body: application/json, text/html |
Accept | Request | Formats the client would like back |
Authorization | Request | Credentials, e.g. Bearer <token> |
User-Agent | Request | Which browser or client is asking |
Cache-Control | Both | Caching rules: max-age=3600, no-store |
ETag / If-None-Match | Both | A version fingerprint; lets the server reply 304 "unchanged" |
Content-Encoding | Response | Compression used: gzip, br |
Location | Response | Where to go for a redirect (3xx) or the new item (201) |
Set-Cookie / Cookie | Response / Request | Store a cookie / send it back |
HTTP is stateless
Stateless means the server doesn't remember anything between requests. Each request is handled as if it's the first one ever. That makes servers simple and easy to scale — any server can handle any request.
But apps need to know "this is still Ada, logged in". So state is carried by the request itself, using:
- Cookies holding a session ID, which the server looks up in its session store, or
- Tokens (like a JWT) in the
Authorizationheader, which carry the user's identity inside them.
Cookies
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=86400
| Attribute | What it does |
|---|---|
HttpOnly | JavaScript can't read it — protects the session from XSS attacks |
Secure | Only sent over HTTPS |
SameSite | Strict / Lax / None — whether it's sent on requests from other sites. Helps stop CSRF. |
Max-Age / Expires | How long it lives. Without either, it's deleted when the browser closes. |
Domain / Path | Which URLs it gets sent to |
24. HTTP/1.1 vs HTTP/2 vs HTTP/3
The meaning of HTTP never changed — same methods, status codes and headers. What changed is how the bytes travel, each version fixing the biggest slowdown of the one before.
HTTP/1.1 is a single-lane checkout: one customer at a time. HTTP/2 lets many customers be served on one lane, interleaved. HTTP/3 gives each customer their own lane, so one slow customer holds nobody else up.
| HTTP/1.1 (1997) | HTTP/2 (2015) | HTTP/3 (2022) | |
|---|---|---|---|
| Runs on | TCP | TCP | QUIC, which runs on UDP |
| Format | Plain text | Binary frames | Binary frames |
| Requests per connection | One at a time (keep-alive reuses the connection) | Many at once — multiplexing | Many at once, fully independent |
| Head-of-line blocking | Yes, per connection | Fixed at HTTP level, but one lost TCP packet still stalls all streams | Gone — a lost packet only stalls its own stream |
| Header compression | None | HPACK | QPACK |
| Encryption | Optional | Effectively required by browsers | Built in (TLS 1.3 inside QUIC) |
| Connection setup | TCP + TLS: 2–3 round trips | Same | 1 round trip, or 0 when resuming |
The key words explained
- Head-of-line blocking — when the item at the front of a queue is stuck, everything behind it waits. In HTTP/1.1, a slow response blocks the next one on that connection, so browsers open about 6 connections per site as a workaround.
- Multiplexing — HTTP/2 chops many requests into small numbered frames and mixes them on one connection. No need for 6 connections, or old hacks like sprite sheets and bundling everything into one file.
- Why HTTP/2 still blocks — TCP insists on delivering bytes in order. If one packet is lost, TCP holds back everything after it, even frames for other requests.
- QUIC — rebuilds reliability on top of UDP but tracks each stream separately. It also survives network changes (connection migration) — walk from Wi-Fi to mobile data and the download continues.
25. HTTPS & TLS
HTTPS is just HTTP sent through an encrypted tunnel. The tunnel is made by TLS (Transport Layer Security; its old name was SSL).
TLS gives you three things: encryption (nobody in between can read it), integrity (nobody can change it unnoticed) and authentication (you're really talking to the real site, not an impostor).
A sealed, tamper-proof envelope, plus an ID card checked by a trusted authority before you hand anything over.
Symmetric vs asymmetric encryption
| Symmetric | Asymmetric (public-key) | |
|---|---|---|
| Keys | One shared secret key locks and unlocks | A pair: a public key (share with anyone) and a private key (never shared) |
| Speed | Very fast | Slow — around 1000× slower |
| Problem | How do two strangers agree on the key safely? | Too slow for bulk data |
| Examples | AES, ChaCha20 | RSA, elliptic curves (ECDHE, ECDSA) |
| TLS uses it for | All the actual data | The handshake — proving identity and agreeing on the shared key |
So TLS uses the slow, clever kind once, to safely set up the fast kind. Best of both.
The handshake, in steps
- ClientHello — the browser says which TLS versions and ciphers it supports, and sends its half of the key exchange (a "key share").
- ServerHello — the server picks a cipher, sends its own key share, and its certificate, signed to prove it owns the matching private key.
- Both sides combine the two key shares and calculate the same session key. An eavesdropper who saw both shares still can't work it out — that's the maths of Diffie–Hellman.
- The browser checks the certificate: right domain? not expired? signed by someone it trusts? If anything fails, you see the big red warning page.
- Both send Finished. From now on, everything is encrypted with the fast symmetric session key.
Older TLS 1.2 needed two round trips, and sometimes encrypted the key with the server's RSA public key instead. TLS 1.3 dropped that because if the private key leaked later, old recorded traffic could be decrypted. With fresh keys per session (forward secrecy), it can't.
Certificates and the chain of trust
- A certificate says "this public key belongs to example.com", and is signed by a Certificate Authority (CA) like Let's Encrypt or DigiCert.
- Your browser and OS ship with a list of trusted root CAs. Roots sign intermediate CAs, which sign websites' certificates. The browser follows that chain back to a root it trusts.
- Anyone can make a certificate, but only a trusted CA's signature makes browsers accept it. That's what stops an attacker from pretending to be your bank.
/search?q=secret is protected; the fact you visited the site is not.26. Email, FTP & SSH
Email uses different protocols for sending and receiving. SMTP sends mail. POP3 or IMAP fetch it into your mail app.
FTP moves files. SSH gives you a secure terminal on a remote machine.
SMTP is the postal service delivering the letter to your letterbox. POP3 is emptying the letterbox into your house. IMAP is leaving the letters in the box and reading them from any house you own.
Email protocols
| SMTP | POP3 | IMAP | |
|---|---|---|---|
| Job | Send (push) mail | Download mail | Sync mail |
| Where mail lives | — | Moved to your device, usually removed from the server | Stays on the server; all devices see the same thing |
| Multiple devices | — | Poor | Great — read on phone, it's read on laptop too |
| Ports (secure) | 25 server-to-server, 587 for apps | 110 (995) | 143 (993) |
You (Gmail app) ──SMTP──▶ Gmail server ──SMTP──▶ Outlook's server ◀──IMAP── Your friend's phone
(found via the MX record in DNS)
When your app sends a password-reset email through a service like SendGrid or SES, it's speaking SMTP (port 587) or that service's HTTP API.
FTP and friends
- FTP (ports 20/21) — old file transfer. Uses two connections: one for commands, one for data. Sends passwords in plain text. Avoid it.
- SFTP — file transfer over SSH (port 22). Encrypted. What you should use.
- FTPS — FTP wrapped in TLS. Works, but less common.
SSH
SSH (Secure Shell, port 22) gives you an encrypted command line on another computer — how you log into a cloud server. It replaced Telnet, which sent everything, passwords included, unencrypted.
ssh-keygen -t ed25519 # make a key pair
ssh-copy-id ubuntu@203.0.113.10 # put the PUBLIC key on the server
ssh ubuntu@203.0.113.10 # log in — no password needed
ssh -L 5432:localhost:5432 ubuntu@host # tunnel: reach the server's database locally
SSH keys use asymmetric encryption: the server holds your public key and challenges you to prove you have the private one. That's also how GitHub knows it's you on git push.
27. Real-Time: Polling, Long Polling, SSE & WebSockets
Normal HTTP is "client asks, server answers". The server can't speak first. For chat, live scores or notifications, you need a way for the server to push updates.
There are four main ways, from simplest to most capable.
Short polling is a child asking "are we there yet?" every minute. Long polling is asking once, and the driver only answers when you arrive. SSE is the driver giving a running commentary. WebSockets is a proper two-way conversation.
| Technique | How it works | Direction | Good for |
|---|---|---|---|
| Short polling | Client asks "anything new?" every few seconds | Client → server | Simple dashboards; low traffic |
| Long polling | Client asks; server holds the request open until there's news (or a timeout), then the client asks again | Feels like server push | Fallback when nothing else works |
| SSE (Server-Sent Events) | One long-lived HTTP response that the server keeps writing events into | Server → client only | Notifications, live feeds, streaming AI responses |
| WebSockets | An HTTP request is "upgraded" into a permanent two-way connection | Both ways, any time | Chat, multiplayer games, collaborative editing |
SSE in a few lines
// Browser
const es = new EventSource("/events");
es.onmessage = e => console.log(JSON.parse(e.data)); // auto-reconnects if dropped
// Server response
Content-Type: text/event-stream
data: {"score": "2-1"}
data: {"score": "3-1"}
WebSockets — how the upgrade works
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols ← from here on, it's no longer HTTP
Upgrade: websocket
Connection: Upgrade
// Browser
const ws = new WebSocket("wss://example.com/chat"); // wss = WebSocket over TLS
ws.onmessage = e => render(e.data);
ws.send(JSON.stringify({ text: "hi" }));
Choosing
- Only the server needs to push? SSE — simpler, plain HTTP, reconnects by itself, works with normal load balancers.
- Both sides talk often and fast? WebSockets.
- Updates are rare and a few seconds' delay is fine? Plain polling is honestly fine.
28. What Happens When You Type a URL and Press Enter
This is the classic networking interview question, because the answer touches almost every section on this page.
The short version: find the server's address (DNS), open a connection (TCP), secure it (TLS), ask for the page (HTTP), then the browser turns the reply into pixels.
The answer, step by step
- Parse the URL. The browser splits
https://shop.example.com/cartinto scheme (https), host and path. If you typed words, not a URL, it becomes a search instead. If the site is on the HSTS list, the browser goes straight to HTTPS. It also checks whether a fresh copy is already in its cache. - DNS lookup. Browser cache → OS cache → hosts file → resolver → root → TLD → authoritative server. Result: an IP address (section 20).
- TCP connection. The OS picks a random source port and does the 3-way handshake with the server's IP on port 443 (section 18). With HTTP/3, this and the next step are combined into QUIC over UDP.
- TLS handshake. Agree a cipher, check the certificate, derive the session key (section 25).
- Send the HTTP request.
GET /cartwith headers —Host, cookies,Accept,User-Agent. Underneath, it's wrapped into TCP segments, IP packets and Ethernet/Wi-Fi frames, and routed hop by hop across the Internet (sections 8, 14). - The server works. Often it first hits a CDN or load balancer, then a reverse proxy like Nginx, then your app (Express, Django…), which may query a database or cache, and builds the response.
- The response comes back. Status code, headers (
Content-Type,Cache-Control,Set-Cookie), and the HTML body. - The browser renders. Parse HTML into the DOM, find
<link>,<script>and<img>tags and fetch them too (more requests, usually on the same connection), parse CSS into the CSSOM, combine them into a render tree, work out the layout (sizes and positions), then paint pixels. JavaScript runs and may fetch more data.
fetch() your frontend makes.29. CDNs, Proxies & Load Balancers
A proxy is a middleman that passes requests on for someone else. Which side it works for decides its name.
A forward proxy sits in front of clients and hides them. A reverse proxy sits in front of servers and hides them. A load balancer is a reverse proxy that shares requests across many servers. A CDN is a worldwide network of reverse proxies that keep copies of your files close to users.
A forward proxy is a personal assistant who makes calls for you, so the other side never sees your number. A reverse proxy is a company switchboard — callers dial one number and never know which desk picks up.
Forward vs reverse proxy
| Forward proxy | Reverse proxy | |
|---|---|---|
| Works for | The clients | The servers |
| Hides | Who the client is | Which server(s) actually answer |
| Set up by | The user or their company | The website owner |
| Used for | Company web filtering, getting around blocks, caching for an office | TLS termination, load balancing, caching, compression, rate limiting, security |
| Examples | Corporate proxy, Squid | Nginx, HAProxy, Cloudflare, AWS ALB |
Forward: [You] → [Proxy] → Internet → [Server] server sees the proxy, not you
Reverse: [You] → Internet → [Nginx] → [App 1 | App 2 | App 3] you see Nginx, not the apps
Load balancers — L4 vs L7
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Can see | IPs and ports only | The full HTTP request: URL, headers, cookies |
| Routes by | Connection — "send this TCP connection to server 2" | Content — "/api/* to the API servers, /images/* to storage" |
| Speed | Faster, very little work per packet | Slower, must decrypt and read each request |
| Can it do TLS, cookies, redirects? | No | Yes |
| Example | AWS NLB | AWS ALB, Nginx, Cloudflare |
Ways to pick a server
- Round robin — take turns: 1, 2, 3, 1, 2, 3.
- Least connections — send to whoever is least busy.
- IP hash — the same client always goes to the same server ("sticky").
- Health checks — the balancer pings each server regularly and stops sending traffic to any that fail.
CDNs
A CDN (Content Delivery Network — Cloudflare, Akamai, CloudFront) has servers called edge servers in hundreds of cities. A user in Chennai gets your images from a server in Chennai, not from your origin server in Virginia. That cuts latency from ~250 ms to ~10 ms.
- Best for static files — images, CSS, JS, videos. Many CDNs can also cache API responses and run code at the edge.
- You control caching with headers:
Cache-Control: public, max-age=31536000, immutablefor files with a hash in their name (app.3f9a2c.js). - Bonus: the CDN absorbs traffic spikes and DDoS attacks before they reach your server.
X-Forwarded-For header (and in Express, set app.set("trust proxy", 1)).30. CORS
Browsers follow the same-origin policy: JavaScript on one site can't read responses from a different site, unless that site says it's allowed.
CORS (Cross-Origin Resource Sharing) is how the server says "it's fine, this other site may read my responses" — using response headers.
A bouncer (the browser) checking the guest list. The list is written by the venue (the server). The bouncer only works at the door of the browser — someone using curl walks straight past.
What counts as the same origin
An origin is scheme + host + port. All three must match.
https://app.example.com ← our page
https://app.example.com/api ✓ same origin (path doesn't matter)
http://app.example.com ✗ different scheme
https://api.example.com ✗ different host (even a subdomain)
https://app.example.com:8443 ✗ different port
http://localhost:5173 → http://localhost:3000 ✗ different port — the classic dev error
Simple requests vs preflight
For "simple" requests (GET, or a POST with a form-type body), the browser just sends it and checks the answer's headers. For anything else — PUT, DELETE, JSON bodies, custom headers like Authorization — it first sends a preflight OPTIONS request to ask permission.
OPTIONS /api/orders
Origin: https://app.example.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: Authorization
← 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600 ← cache this permission for 10 minutes
Only if the preflight says yes does the browser send the real request.
Cookies across origins
To send cookies cross-origin, the frontend must use credentials: "include" and the server must reply Access-Control-Allow-Credentials: true with a specific origin — * is not allowed with credentials.
// Express
app.use(cors({ origin: "https://app.example.com", credentials: true }));
31. Network Security
Network security is about controlling who can reach what, and making sure data in transit can't be read, changed or faked.
Most attacks either sit in the middle of a conversation, pretend to be someone else, or simply flood a target until it falls over.
Firewalls
A firewall checks traffic against rules like "allow port 443 from anywhere, allow port 22 only from the office IP, block everything else".
- Packet filter — looks at each packet's IPs and ports alone.
- Stateful firewall — remembers connections, so replies to things you started are let back in automatically. Most firewalls (and cloud security groups) work this way.
- WAF (Web Application Firewall) — layer 7. Reads HTTP requests and blocks things like SQL injection patterns.
VPN
A VPN (Virtual Private Network) builds an encrypted tunnel from your device to another network. Everything goes through the tunnel, so the café Wi-Fi only sees scrambled data heading to the VPN server. Companies use VPNs to let staff reach internal systems as if they were in the office. A VPN hides your traffic from the local network — it doesn't make you anonymous to the VPN provider.
Common attacks
| Attack | What happens | Defence |
|---|---|---|
| Man-in-the-middle (MITM) | The attacker secretly sits between you and the server, reading or changing traffic. Easy on open Wi-Fi. | HTTPS everywhere, certificate checks, HSTS |
| DDoS (Distributed Denial of Service) | Thousands of hijacked machines flood a target with traffic until real users can't get in. | CDN / DDoS protection services, rate limiting, autoscaling |
| SYN flood (a type of DoS) | Send loads of SYNs and never finish the handshake, filling the server's table of half-open connections. | SYN cookies, firewall limits |
| DNS spoofing / cache poisoning | Fake DNS answers send you to the attacker's IP instead of the real site. | DNSSEC (signed DNS answers), DoH/DoT, and HTTPS — the fake site can't show a valid certificate |
| ARP spoofing | On a local network, the attacker announces "the router's IP is at my MAC", so traffic flows through them — a local MITM. | Switch protections (Dynamic ARP Inspection), encryption, VPN on untrusted networks |
| Packet sniffing | Capturing traffic on a network and reading anything unencrypted. | Encrypt everything in transit (TLS, SSH) |
| Port scanning | Probing which ports are open to find weak services. Often the first step of an attack. | Close unused ports; firewall rules |
A developer's checklist
- HTTPS only, with HSTS. Redirect HTTP to HTTPS.
- Expose as few ports as possible. Databases should never be open to the Internet — keep them on a private network.
- Rate-limit login and other expensive endpoints (respond 429).
- SSH with keys, not passwords.
- Secure, HttpOnly, SameSite cookies.
32. Useful Commands
When something "doesn't load", these commands tell you which layer is broken. Work from the bottom up: do I have an address? can I reach the host? does the name resolve? is the port open? what does the server actually say?
| Command | Answers |
|---|---|
ipconfig (Windows) · ifconfig / ip addr (Mac/Linux) | What's my IP, subnet mask and gateway? |
ping host | Can I reach it, and how long does a round trip take? |
traceroute host · tracert host (Windows) | Which routers does traffic go through, and where does it slow down or stop? |
nslookup example.com | What IP does this name resolve to? |
dig example.com | Same, with full detail — record types, TTLs, which server answered |
curl -v https://example.com | The full HTTP conversation, including TLS and headers |
netstat -an · ss -tulpn (Linux) | Which ports are open and which connections exist? |
lsof -i :3000 | Which process is using port 3000? |
arp -a | The IP-to-MAC table for my local network |
nc -zv host 5432 | Is this one port open on that host? |
Examples you'll actually use
# DNS
dig example.com # A record and its TTL
dig example.com MX +short # mail servers only
dig @8.8.8.8 example.com # ask Google's resolver directly (bypass your own)
dig +trace example.com # walk root → TLD → authoritative yourself
# HTTP
curl -I https://example.com # headers only (HEAD)
curl -v https://example.com # everything: DNS, TCP, TLS, headers
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"Ada"}' http://localhost:3000/users
curl -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} total:%{time_total}\n" \
-o /dev/null -s https://example.com # where does the time go?
# Ports and processes
lsof -i :3000 # who's using my port?
ss -tulpn # all listening TCP/UDP ports (Linux)
netstat -ano | findstr :3000 # Windows equivalent
A debugging order that works
ping 8.8.8.8works? Then your connection to the Internet is fine.ping google.comfails but the line above worked? It's DNS.- Host pings, but the site won't load? Check the port with
nc -zvorcurl -v— firewall, or the app isn't running. - Connects but errors? Read the status code and headers in
curl -vor the browser's Network tab.
Interview Q&A — quick answers
Foundations and layers
- What is the Internet? A network of networks — many independent networks (ISPs, companies, clouds) that agree to carry each other's traffic using IP.
- Packet switching vs circuit switching? Packet switching cuts data into packets that share links and are routed separately (the Internet). Circuit switching reserves a whole path for the call (old phones).
- Hub vs switch vs router? Hub repeats everything to every port (L1). Switch sends frames only to the right port using MAC addresses (L2). Router connects different networks using IP addresses (L3).
- Name the OSI layers. Physical, Data Link, Network, Transport, Session, Presentation, Application — "Please Do Not Throw Sausage Pizza Away".
- OSI vs TCP/IP? OSI is a 7-layer teaching model; TCP/IP is the 4-layer model the Internet actually uses (Application, Transport, Internet, Link).
- PDU at each layer? Data → segment/datagram → packet → frame → bits.
- What is encapsulation? Each layer wraps the data from above with its own header on the way down; the receiver strips them on the way up.
- Latency vs bandwidth vs throughput? Delay per trip / maximum capacity / what you actually get.
Addressing and routing
- MAC vs IP address? MAC is a 48-bit hardware ID used on the local network (L2). IP is a logical address used across networks (L3) and changes when you move networks.
- What does ARP do? Finds the MAC address for an IP on the local network by broadcasting "who has this IP?"
- How many usable hosts in a /27? 2⁵ − 2 = 30.
- What subnet is 10.1.1.200/26 in? Block size 64 → 10.1.1.192/26, broadcast 10.1.1.255, hosts .193–.254.
- Private IP ranges? 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.
- What is NAT, and why does it exist? The router swaps many private addresses for one public address and tracks the mappings. It exists because IPv4 ran out of addresses.
- Why IPv6? 128-bit addresses — effectively unlimited, no NAT needed, simpler headers, no broadcast.
- Static vs dynamic routing? Routes typed by hand vs routes learned automatically from other routers.
- Distance vector vs link state? Share your distances with neighbours (RIP) vs share your links with everyone and compute the shortest path yourself (OSPF).
- What is BGP? The protocol that routes between Autonomous Systems — how the networks that make up the Internet tell each other what they can reach.
- How does traceroute work? Sends packets with TTL 1, 2, 3… Each router that drops one at TTL 0 replies "Time Exceeded", revealing itself.
Transport
- TCP vs UDP? TCP: connection, reliable, ordered, flow and congestion control, more overhead. UDP: no connection, no guarantees, fast and light.
- When would you use UDP? When late data is useless — video calls, games, live streams — or for tiny exchanges like DNS. Also as the base for QUIC.
- Explain the 3-way handshake. SYN (here's my starting number) → SYN-ACK (got it, here's mine) → ACK (got yours). Both sides confirm they can send and receive.
- Why 4 steps to close? Each direction closes separately: FIN/ACK from each side. The server may still send data between its ACK and its FIN.
- What is TIME_WAIT? The side that closes first waits a while in case its final ACK was lost and the other side resends its FIN.
- Flow vs congestion control? Flow control protects the receiver (receive window). Congestion control protects the network (congestion window, slow start, AIMD).
- What is a socket? One endpoint of a connection — an IP address plus a port. A connection is identified by the 5-tuple.
- How can one server port serve thousands of clients? Each connection has a different source IP/port, so every 5-tuple is unique.
Application layer and the web
- How does DNS resolution work? Browser/OS cache → recursive resolver → root → TLD → authoritative, with answers cached for their TTL.
- A vs CNAME? A maps a name to an IPv4 address; CNAME maps a name to another name.
- What is DHCP / DORA? Automatic IP configuration: Discover, Offer, Request, Acknowledge. Gives IP, mask, gateway, DNS, lease.
- GET vs POST? GET reads, has no body, is safe and idempotent and can be cached. POST sends a body to create or act, and isn't idempotent.
- PUT vs PATCH? PUT replaces the whole resource (idempotent); PATCH changes part of it.
- 401 vs 403? Not logged in vs logged in but not allowed.
- 502 vs 504? Proxy got a bad/no response from the app vs proxy waited too long for the app.
- Why is HTTP stateless and how do apps keep you logged in? Each request stands alone, which makes scaling easy. State travels in cookies (session ID) or tokens (JWT) with every request.
- HTTP/1.1 vs 2 vs 3? 1.1: text, one request at a time per connection. 2: binary, multiplexed on one TCP connection. 3: over QUIC/UDP, no TCP head-of-line blocking, faster setup.
- How does HTTPS work? TLS handshake: asymmetric crypto proves the server's identity (certificate) and agrees a shared key; symmetric encryption protects the actual data.
- Why not use asymmetric encryption for everything? It's far too slow; symmetric is fast once both sides share a key.
- SMTP vs POP3 vs IMAP? Send mail / download and remove from the server / sync and keep on the server.
- WebSockets vs SSE vs long polling? Two-way persistent connection / one-way server push over HTTP / repeated held-open requests.
- What happens when you type a URL? Parse → DNS → TCP → TLS → HTTP request → server work → response → render (DOM, CSSOM, layout, paint).
Infrastructure and security
- Forward vs reverse proxy? Forward acts for clients and hides them; reverse acts for servers and hides them.
- L4 vs L7 load balancer? L4 routes by IP and port only; L7 reads HTTP and can route by path, header or cookie.
- What does a CDN do? Caches content on servers near users to cut latency and offload the origin.
- What is CORS? A browser rule letting a server allow specific other origins to read its responses. It doesn't protect the server itself.
- What is a preflight request? An
OPTIONSrequest the browser sends first, for non-simple requests, to ask the server's permission. - What is a MITM attack and how do you stop it? An attacker relaying and reading your traffic; HTTPS with certificate checks and HSTS.
- What is a DDoS? A flood of traffic from many machines to overwhelm a service; defended with CDNs, rate limits and scrubbing services.
- What does a VPN do? Encrypts all your traffic in a tunnel to another network.
Learning Path
- The big picture — clients, servers, IP addresses, packets. Run
ipconfig/ifconfigand find your private IP, then search "what is my IP" for the public one. - Layers — learn the OSI names and the TCP/IP mapping until you can draw the table from memory.
- Watch real traffic — open the browser's Network tab on any site. Look at methods, status codes, headers, cookies and the Timing breakdown.
- DNS hands-on —
diga few domains, look at A, CNAME, MX and TTLs. Trydig +trace. - Subnetting drills — do ten "which subnet / how many hosts" questions until the block-size method is automatic.
- TCP — draw the handshake and teardown from memory. Run
curl -vand match what you see to the steps. - Build with sockets — a tiny TCP echo server in Node, then an HTTP server without Express, so you see HTTP is just text over TCP.
- HTTPS — set up a site with a free Let's Encrypt certificate. Inspect the certificate chain in the browser.
- Real-time — build a small chat with WebSockets and a notification feed with SSE.
- Deployment networking — put an app behind Nginx as a reverse proxy, then a CDN. Fix the CORS error you'll certainly hit.
- Practise the classic answer — explain "what happens when you type a URL" out loud in under three minutes.
- Then — Wireshark to see packets for real, cloud networking (VPCs, subnets, security groups), and HTTP/3 and QUIC in more depth.