Study Index
FSD · Networking · From the ground up

Networking

How the web actually works under the hood, from typing a URL to a painted page — then the three ways a front end and back end actually talk: REST, GraphQL, and gRPC. Taught bottom-up: what each piece is, why it exists, where it shows up in real apps, then the deep detail an interview will actually probe.

⭐ TRICK the insight that makes it easy ⚠ PITFALL a common mistake / gotcha 💡 TIP interview-relevant aside
I

Notebook Summary (copy by hand)

Telegraphic and deck-ready — arrows over sentences. Everything here is derivable from the chaptered notes below.

HOW THE WEB WORKS
=================
client (browser) --request--> server --response: HTML/CSS/JS/img--> client
domain name -> means nothing alone -> needs an IP (DNS = the phone book)
  root(.) -> TLD(.com/.in) -> 2nd-level(google) -> subdomain(www)  [resolved right-to-left]
plumbing: laptop -> router -> ISP -> DNS(get IP) -> server -> data back
ISP tiers: local -> regional -> global, crossing oceans via UNDERSEA FIBER (not satellite — too slow/high)
data ships as PACKETS, reassembled at your local ISP (lost packets = stuck "processing...")

CACHE CHECK ORDER  (stop at first hit)
  browser HTTP cache -> service worker -> OS hosts file -> router -> ISP
  304 = "unchanged, reuse it"   (from disk cache)/(from SW) = no real network trip
⭐ browser opens only ~6-8 parallel conns PER ORIGIN -> rest QUEUE -> bundle/reduce requests

before any page data: TCP handshake ("you there?") -> TLS/SSL handshake (swap keys, encrypt)
⭐ first ~14 KB of the response is special -> fits in ONE round trip -> fast first paint
big-co "cheat the distance":  Google = PEERING (direct link, skips regional ISP hop)
                               Netflix = EDGE CACHE (rents space INSIDE the ISP)
ICANN = sets domain/TLD rules.  WHOIS = who/when registered a domain (cheap fraud check)

RENDER PIPELINE
  HTML -parse-> DOM tree  \
  CSS  -parse-> CSSOM      >--merge--> RENDER TREE -> LAYOUT -> PAINT -> COMPOSITE -> pixels
⚠ CSS = render-blocking (no flash of unstyled content)
⚠ JS <script> (no async/defer) = parser-blocking — halts HTML parsing until it runs
PROTOCOLS  (agreed rule-books for talking)
===========================================
TCP  3-way handshake(SYN/SYN-ACK/ACK), seq numbers, resends lost pkts -> RELIABLE, slower start
UDP  no handshake, no resend, packets may drop                        -> FAST, low latency
  -> TCP: web, email, files.  UDP: voice/video calls, live streaming.

HTTP   = request/response, rides on TCP.
HTTPS  = HTTP + TLS/SSL handshake -> public/session key -> both sides encrypt+decrypt
HTTP/3 = QUIC, runs on UDP (⭐ never forget: UDP, not TCP!) -> less setup overhead, header compression
WebSocket = HTTP **upgrades** (101 Switching Protocols) -> one persistent, full-duplex line
  -> use for: live chat, dashboards, real-time anything
SMTP = email, PUSH/send model (not request-response)
FTP  = large file upload/download

doodle: draw 2 parallel roads — one with a toll-gate+guard (TCP), one wide open (UDP)
REST APIs
=========
tiers:  1-tier(all-in-one) -> 2-tier(client|server) -> 3-tier(+DB) -> n-tier(+other services)
API = two programs talk, any language.  REST = one style of API (HTTP-based), NOT the only one.
⭐ stateless = server remembers NOTHING between requests -> client resends all context each time
  -> the whole reason REST scales: no session baggage, just add servers

REQUEST  = request-line(method+path+proto) + headers + body
RESPONSE = status-line(proto+code)         + headers + body

URL = scheme :// host / path ? query # fragment
  host = subdomain + domain + TLD
  ⚠ fragment/hash is NEVER sent to the server (front-end routing only)

CRUD <-> METHOD
  Create -> POST     Read -> GET      Update -> PUT(whole obj) / PATCH(only changed fields)
  Delete -> DELETE   other: HEAD(headers only) OPTIONS(CORS preflight) TRACE(debug, disable in prod)

STATUS CODES
  1xx keep going | 2xx done (200 OK,201 Created,204 NoContent)
  3xx moved (301 perm,302 temp; 307/308 PRESERVE the method)
  4xx = YOUR error (400,401 not-signed-in,403 no-perm,404,429)
  5xx = MY error   (500,502,503,504)
⭐ retry 5xx (server might work next time). NEVER retry 4xx (same bad input fails again).
⚠ strip the `Server` response header — don't hand attackers your stack + version
GraphQL
=======
client picks EXACT fields it wants, from ONE endpoint, in ONE request (even nested data)
  kills: over-fetching (got fields you didn't need) + under-fetching (needed 3 more calls)
schema (SDL) -> types: scalar(ID,String,Int,Boolean) | custom(Author,Book...) | `!` = required
Query = read.  Mutation = write.  Subscription = realtime, ws-style.
resolver(parent, args, context, info) = fn that actually fetches ONE field
  -> parent is how nested relations resolve: Book.author, Author.books
⭐ still just HTTP underneath — almost always POST. not a replacement for HTTP, a layer on top.
versioning: REST -> new path /v2   |   GraphQL -> @deprecated field, same endpoint
introspection = the schema documents itself -> playground autosuggests valid queries
gRPC & Protocol Buffers
==========================
RPC = call a function that lives on ANOTHER machine, as if it were local
gRPC = Google's RPC framework = HTTP/2 + Protocol Buffers (binary format)

.proto file (the IDL):
  service X { rpc Method(InMsg) returns (OutMsg); }
  message InMsg { string field = 1; }
  ⚠ field numbers (=1, =2…) are permanent once shipped — only ADD new ones, never reuse/change
  `repeated Foo` = a list of Foo

call flow: client fn -> client STUB -> RPC runtime --(HTTP/2, binary protobuf)--> RPC runtime
           -> server STUB -> real fn runs -> result flows back the same path

HTTP/2 gives: header compression + ONE long-lived connection + multiplexing
  -> streaming modes: client->server | server->client | bi-directional

⭐ ~10x faster than REST (binary payload + multiplexing), BUT:
⚠ not human-readable · no native browser support (needs a proxy/bridge) · no HTTP edge caching
used for: server-to-server / microservices — not public, browser-facing APIs
⭐ The whole stack in one line Every request is: resolve a name to an address (DNS), open a trusted pipe (TCP + TLS), speak an agreed dialect to ask for exactly what you need (REST, GraphQL, or gRPC), then let the browser's fixed pipeline turn the bytes that come back into pixels.

II

Detailed Study Notes

When you type a website name and hit enter, your browser doesn't magically "have" the page. It has to go fetch it from a computer somewhere else in the world, get back the raw ingredients (the page's text, styling, and behavior), and assemble them into the screen you see. What follows walks that whole round trip end to end — the journey out, the journey back, what the browser does with the result, and then the three different "languages" a front end and back end use to actually exchange data. "What happens when you type a URL?" is one of the most common frontend system-design interview questions there is, and this is the full answer.

Pick a chapter, then expand only the cards you need.

CHAPTER 1How the Web Works

You type google.com and a page appears — here is every hop it takes to get there, and what the browser does the instant the bytes arrive.

A web page is not one thing you download — it's a conversation. Your browser turns a human-friendly name into a machine address (DNS), opens a reliable, secured connection (TCP + TLS handshakes), asks a far-away server for files, and gets back HTML, CSS, and JavaScript in small packets. The browser then runs a fixed pipeline — build trees, run scripts, lay out, paint, composite — to turn those files into pixels. Every layer in between (router, ISP, caches, undersea cables) exists to make that conversation faster and more reliable.
Client, Server, and the Request–Response LoopConcept+

The whole web runs on one simple pattern: one machine asks, another machine answers.

The machine doing the asking is the client — your browser, on your laptop or phone. The machine doing the answering is the server. A server isn't anything exotic: it's just a computer that can take in a request, do some processing, and send back data. Your own laptop can be a server — the catch is reliability. It shuts down, has limited RAM/CPU/storage, and can't handle thousands of people at once. So real websites run on dedicated, high-end machines that stay on 24/7 and are always connected to the internet.

Client (browser)RequestServer Response: HTML / CSS / JS / images
  • The first response is HTML. Hit flipkart.com and the very first thing the server sends back is an HTML document — the skeleton of the page. The browser reads it and knows how to structure everything.
  • HTML, CSS, JS each have a job. HTML is the structure the browser natively understands, CSS is the look and feel, and JavaScript is the interactivity.
  • The HTML points to more files. Inside that first HTML are references to CSS, JS, and images. The browser sees them and goes back to fetch each one — more requests, more responses.
  • The Network tab shows it all. Every request your browser makes (and the response it gets) appears in DevTools → Network — the single best place to watch this loop happen.
IP Addresses & Domain NamesConcept+

A domain name is the human name; an IP address is the actual location. You always need the location to deliver anything.

For two devices to talk over the internet, each needs a unique IP address — a numeric address like 152.222.122.2. Think of it as the precise street address of a machine. Anything on the internet you want to reach needs its own IP so you can find it.

But nobody remembers numbers like that — we remember google.com, amazon.com. Those memorable names are domain names. The problem: a name alone gets you nowhere, the same way handing a postman only a person's name gets your parcel nowhere — he needs the specific address. So something has to translate the name into an IP before any real request can be sent. That translator is DNS.

Analogy · recall

Ordering Domino's: the first thing they ask is your PIN code. Your name and order mean nothing until they know where to deliver. The PIN code is your IP address — the one piece that actually tells the network where the data goes.

DNS — the Internet's Phone BookConcept+

DNS (Domain Name System) is the lookup service that turns a domain name into the IP address behind it.

When you type google.com, your request reaches a special server called a DNS server. Your machine essentially asks: "What's the IP address for google.com?" DNS is like a giant phone book — look up the name, get back the number.

A domain name isn't one flat label — it's a hierarchy, and DNS resolves it by drilling down level by level, the way you'd route a government complaint to the right department, then the right desk. There are far too many domains in the world to keep in one flat list, so the lookup is distributed across layers of servers.

ROOT ( . ) TLD — .com 2nd-level — google subdomain — www → final IP resolves right → left: www . google . com . DNS reads a domain right-to-left, narrowing the search one level at a time until it reaches the exact IP.
  • Root — the implied dot at the very end; the top of the tree, the starting point of every lookup.
  • Top-level domain (TLD).com, .org, .in, .gov. Tells DNS which broad zone to dig into.
  • Second-level domain — the organization itself: google, microsoft.
  • Third-level / subdomainwww, sales, mail. A finer slice within that org.
The Plumbing: Router, ISP & Reaching the InternetConcept+

Between your device and the wider internet sits a chain of equipment whose only job is to get your request out and the response back.

Wiring every laptop directly to every other laptop with cables would be a network hell — connecting just 8 machines would need a tangle of wires. So the real internet is a smart mix of wired and wireless links arranged in layers.

Router

Sits in your home. Takes one incoming line (LAN/fiber) and shares the internet to all your devices over Wi-Fi or LAN cable.

Modem (older)

Converted the signal coming over old telephone wires into usable internet. Today fiber often comes straight in.

ISP

Internet Service Provider (Airtel, Jio, BSNL …). The company that actually connects you to the rest of the internet.

In a multi-floor building, one central router feeds LAN/fiber cables up to a router on each floor, and each broadcasts Wi-Fi locally — that's how everyone gets a strong signal instead of one weak router covering everything. Zoom out further: your whole neighborhood usually has a central hub that takes one fiber line from the ISP and distributes it.

The high-level journey, in order
Your laptopRouterISPDNS (get IP) Server (the IP)HTML / CSS / JS back
Data Centers & the Physical InternetConcept+

"The server" is rarely one machine — it's racks of computers in a data center, connected to you by very real, very physical cables.

Billions of people use Google, Facebook, Microsoft. One machine can't serve that load, so big services run data centers: large rooms full of CPUs, RAM, storage, and power backup — no monitors, just compute. Inside, many machines map to the IPs you reach, and extra layers (like load balancers) decide which machine handles each request.

A single server also does more than dump files — it runs application code (Node.js/Express, Java servlets). When you hit a path like /engineer/chirag, the developer's code on that machine decides what to return for that exact route.

Why wires, not satellites

If the server is on the other side of the planet, how does data cross oceans? Satellites are wireless and roughly 22,000 miles up — slow over that distance and easily disrupted by weather, so not reliable for everyday traffic. Instead, the world is connected by undersea optical-fiber cables laid across the ocean floor, carrying data at close to the speed of light. That's why a page from another continent loads in a blink.

YouISPUndersea fiber cable (ocean floor) Data center: load balancer → server racks
The ISP Hierarchy & PacketsConcept+

ISPs come in tiers, and the data they move travels as small numbered packets — not one big block.

Local ISP

Small distributor that wires up your building/area and sells you a plan.

Regional ISP

Larger providers (Jio, Airtel). Often where national rules apply — blocking or allowing sites at a country level.

Global ISP

Top-tier networks governed centrally; they decide how traffic flows between countries.

A cross-country request hops local → regional → global ISP, across the ocean, then global → regional → local on the far side to reach the server — many hops each way.

Data travels in packets

The response doesn't ship as one assembled blob, the way a parcel doesn't fly back as one giant box. It's broken into many small data packets that each take whatever route is available, then get reassembled at your local ISP and handed to you. This is why a flaky connection can leave you with a half-finished result — e.g. a payment stuck on "still processing" when some packets are lost.

⚠ Why this matters Every hop and every lost packet is a place where things slow down or break. Companies like Google and Netflix obsess over optimizing these small steps — that's the whole game of frontend performance at the network layer.
Caching at Every LayerConcept+

The fastest request is the one you never have to make. Before going to a server, the browser checks a series of caches in order, stopping the moment it finds a usable copy.

  1. Browser HTTP cache — does the browser already have this resource/IP cached?
  2. Service worker cache — a script that can intercept requests and answer from its own cache.
  3. Operating system — checks the OS hosts file (you can map e.g. google.comlocalhost:3000 for local dev).
  4. Router — modern routers cache domain → IP mappings (why "restart your router" sometimes refreshes things).
  5. ISP — ISPs cache aggressively too, at a much larger scale.
What you see in the Network tab
  • 304 Not Modified — the browser asked the server, the server said "nothing changed, reuse what you have." No new data transferred.
  • 200 (from service worker) — the response came from the service worker, not the network. This can return data in ~1–2 ms — impossibly fast for a real server round trip, which is the whole point of caching.
  • (from disk cache) — served straight from the browser's on-disk cache.
💡 Interview-worthy A browser only opens about 6–8 parallel connections per origin. Any requests beyond that are queued until a slot frees up — a classic interview fact and a real reason to bundle/reduce requests.
The Handshakes: TCP, TLS/SSL & the 14 KB First TripConcept+

Before any real page data moves, the client and server do two quick "handshakes" to set up a reliable, secure connection.

CLIENT SERVER SYN — "can we talk?" SYN-ACK — "yes, here's a seq #" ACK — "confirmed" (TCP open) TLS ClientHello ServerHello + certificate + keys (TLS open) HTTP request HTTP response, in packets Two handshakes before any page data: TCP confirms both sides are ready, TLS encrypts everything after it.
TCP handshake

"Are you there and ready?" The client and server exchange an acknowledgement to confirm a reliable connection exists before sending real data — like calling ahead before a big delivery.

TLS / SSL handshake

The s in https. They swap a certificate and keys so all further messages are encrypted — no one in between can read them.

Why the first 14 KB matters

HTTP responses don't all arrive at once — they grow in chunks (roughly 14 KB, then ~28 KB, then ~56 KB …). That very first ~14 KB is special: if the critical HTML/CSS needed to show something fits inside it, the page can render meaningful content in a single round trip, and perceived performance jumps.

⭐ Keep critical first-paint data small Every extra trip to fetch bare-minimum content adds delay before the user sees anything. Aim to fit the essential HTML/CSS for first render within that early ~14 KB window.
How Big Companies Cheat the Distance: Peering & Edge CachingConcept+

Google and Netflix don't accept the slow default path — they physically move data closer to you and cut out hops.

Peering (Google)

Instead of routing every request up through regional and global ISPs, Google sets up direct connections that bypass the regional layer and reach your local ISP — acting as a proxy that reduces the number of hops.

Edge caching (Netflix)

Netflix rents space inside the ISP itself and stores its videos there. Streams come from that nearby box instead of crossing the world.

Both are the same idea: shorten the conversation. Put data physically nearer the user so fewer hops and less distance stand between request and response.

Who Governs It: ICANN & WHOISConcept+

Domain names and ownership aren't a free-for-all — specific authorities set the rules and keep the records.

ICANN

The authority that sets the guidelines for how domains and IP mappings work — who governs TLDs and the overall name-to-IP system.

WHOIS

A directory where, given a domain name, you can look up who registered it, when, when it expires, and the registrar.

💡 Practical trick A "10-year-old, super-trusted" company whose domain on whois.com shows it was registered a few months ago is a red flag. A quick WHOIS lookup is a cheap fraud check, even for non-technical situations.
The Browser Render Pipeline: HTML → PixelsConcept+

Once the files arrive, the browser runs a fixed, ordered pipeline to turn HTML, CSS, and JS into the picture on screen — one of the most-asked frontend system-design topics.

At a high level there are four phases: load the needed data, execute scripts, render the content, and paint the final result. Two facts shape everything:

CSS is render-blocking

The browser won't show anything until CSS is loaded — otherwise it would flash unstyled content.

JS is parser-blocking

A blocking <script> halts HTML parsing until it's downloaded and run. (async/defer change this.)

HTML CSS DOM tree CSSOM Render tree Layout Paint Composite — stack layers by z-index → pixels HTML and CSS parse independently, merge into the render tree, then a strict layout → paint → composite chain turns it into pixels.
  • DOM tree — HTML parsed into a tree of nodes (html → head/body → div/p/span …).
  • CSSOM — all CSS rules parsed into a parallel tree; conflicts resolved by specificity and inheritance (visible in DevTools → Computed).
  • JavaScript execution — runs on a single main thread: parse (blocking), build an AST, compile to bytecode, then execute.
  • Render tree — DOM and CSSOM merged; hidden/non-visible nodes dropped; final styles applied.
  • Layout — compute the geometry: how many boxes, what size, where each sits (the floor plan).
  • Paint — fill in pixels: colors, fonts, borders, backgrounds (tiles and paint go on).
  • Composite — stack the layers by z-index — popups and overlays on top, hidden things behind (the furniture goes in last).
Analogy · recall

Loading a web page is like building and furnishing a house. DNS is looking up the plot's address; the handshakes are confirming the owner is home and exchanging keys; delivery trucks (packets) bring materials in pieces over roads (cables). Then layout is drawing the floor plan, paint is tiling and painting the walls, and composite is arranging the furniture so you only see what's on top. You don't see the bricks — you see the finished room.

CH.1

Interview Q&A

Q1 What happens, step by step, when you type a URL and press enter?
The browser checks its caches (browser, service worker, OS, router, ISP). If not cached, it resolves the domain to an IP via DNS, opens a TCP connection (handshake), does a TLS/SSL handshake for https, then sends an HTTP request. The server responds with HTML (and references to CSS/JS/images), data arrives in packets, and the browser runs its render pipeline — DOM + CSSOM → render tree → layout → paint → composite — to display the page.
Q2 What is DNS and what are the parts of a domain name?
DNS translates a human-readable domain name into the IP address of the server hosting it — like a phone book. A domain is a hierarchy resolved top-down: root (the trailing dot) → top-level domain (.com, .in) → second-level domain (the org) → subdomain (www, mail). Each level narrows the lookup until the exact IP is found.
Q3 Why do TCP and TLS handshakes happen before the HTTP request?
TCP establishes a reliable connection — both sides confirm they're ready before sending real data. TLS/SSL then exchanges a certificate and keys so the rest of the conversation is encrypted and can't be read or hijacked in transit. Only after both handshakes does the browser send the actual HTTP request for the page.
Q4 How many requests can a browser make in parallel, and what happens beyond that?
A browser typically allows about 6–8 parallel connections per origin. Any requests beyond that limit are queued and only fire when a slot frees up. This is why reducing and bundling requests improves load time — it's a common interview question.
Q5 Why is the first ~14 KB of the response important?
HTTP responses grow in chunks (~14 KB, ~28 KB, ~56 KB …). If the critical HTML/CSS needed to render something meaningful fits in that first ~14 KB, the page can paint useful content in a single round trip — so you keep the critical first-paint payload small.
Q6 Explain the browser's critical rendering path.
HTML is parsed into the DOM tree and CSS into the CSSOM. JavaScript executes on the single main thread. DOM and CSSOM merge into the render tree (only visible nodes, with final styles). Then layout computes geometry, paint fills in pixels, and composite stacks layers by z-index so the right things appear on top.
Q7 How do companies like Google and Netflix make global delivery fast?
They move data closer to users and cut out network hops. Google uses peering — direct connections that bypass regional ISPs and reach the local ISP. Netflix uses edge caching, renting space inside ISPs to store videos locally so streams don't cross the world. Both shorten the request–response path.
client → serverdomain → IP DNS = phone bookroot · TLD · 2nd · sub router → ISP tiersundersea fiber packets reassembledcache layers 304 / from SW6–8 parallel reqs TCP handshakeTLS/SSL = https first 14 KBpeering · edge cache ICANN · WHOISDOM + CSSOM render treelayout → paint → composite CSS render-blockingJS parser-blocking
CHAPTER 2Communication Protocols

The shared rule-books two machines agree on before they exchange a single byte — TCP/UDP underneath, then HTTP, HTTPS, HTTP/3, WebSocket, SMTP, and FTP built on top.

A protocol is just a contract for communication. Almost everything on the web rides on one of two transport foundations: TCP (reliable — guarantees every packet arrives, in order) or UDP (fast — fire and forget, packets may drop). HTTP/HTTPS run on TCP for normal browsing; HTTP/3 (QUIC) runs on UDP for speed; WebSocket keeps one connection open for two-way live data; SMTP carries email; FTP moves big files. Pick the protocol by what you need: reliability or speed, request-response or live, files or messages.
TCP vs. UDP — Reliable or FastConcept+

These are the two transport "roads" every higher-level protocol drives on. Almost every networking interview comes back to this distinction, so anchor it first.

TCP (Transmission Control Protocol) is the reliable road. Before sending anything it does a three-way handshake: the client sends a SYN ("I want to talk, are you ready?"), the server replies SYN-ACK ("yes, and here's a sequence number to use"), the client sends ACK ("got it"). That sequence number is the key idea: it lets TCP detect a missing packet and resend it, so no data is lost and everything arrives in order.

UDP (User Datagram Protocol) is the fast road. No handshake, no sequence tracking — it just starts firing packets. If some get lost, UDP doesn't care and won't resend. You trade guaranteed delivery for raw speed and low latency.

CLIENT SERVER 1. SYN 2. SYN-ACK (+ sequence #) 3. ACK — connection established The sequence number handed over in step 2 is what lets TCP detect and resend a packet that never arrives.
TCP · reliable

Three-way handshake, sequence numbers, guaranteed in-order delivery, lost packets resent. Slightly slower to start. Used for web browsing, email, file transfer.

UDP · fast

No handshake, no guarantees, packets may drop. Lowest latency. Used for voice/video calls and live streaming — where a dropped frame is fine but lag is not.

Analogy · recall

Two delivery couriers. The TCP courier knocks, waits for you to confirm, takes an OTP, and reports back "delivered 100%." The UDP courier drops the parcel at your door and leaves — if it's stolen or lost, not his problem, but he's fast.

HTTP — the Web's Everyday LanguageConcept+

HTTP (HyperText Transfer Protocol) is the "mother tongue" browsers and servers use to exchange web pages and resources.

HTTP defines the structure of a request and a response — what you ask for, how the server answers, how the data is shaped. Think of it like the signs and directions on a highway: the road (TCP) carries you, but HTTP tells you how to use it to reach the right place. It runs on top of a TCP connection: open the connection, make a request, get the response.

  • Used everywhere in browsing. Loading a page, fetching images, calling an API — standard web communication is HTTP.
  • Classic HTTP = one connection per request. In the basic model, each new request opens a fresh TCP connection. (Newer versions reuse connections.)
  • It sits above the transport layer. HTTP doesn't move bytes itself — TCP does. HTTP just defines the conversation.
HTTPS — HTTP With a LockConcept+

HTTPS is plain HTTP plus encryption, so no one in the middle can read your data.

Almost everything is identical to HTTP, with one addition: after the TCP connection, it does an extra SSL/TLS handshake. The server shares a public key; the client uses it to encrypt data, and a session key is established. From then on, both sides encrypt before sending and decrypt on arrival. Anyone who intercepts a packet in between sees only scrambled bytes.

TCP handshakeTLS/SSL handshake (keys exchanged) Encrypted HTTP request/response
  • The "s" is security. When the URL starts with https, that TLS handshake is happening under the hood.
  • Two-way encryption. Server encrypts its responses; client encrypts its requests.
  • Hard to steal data. Even if a packet is intercepted, it can't be read without the keys.
HTTP/3 (QUIC) — Built on UDP for SpeedConcept+

HTTP/3 is a modern version of HTTP that runs on UDP instead of TCP, trading TCP's handshake overhead for raw speed.

Where classic HTTP leans on TCP's reliability (and its slower setup), HTTP/3 uses QUIC, which is built on UDP. It starts sending data with far less back-and-forth, and adds its own mechanisms to stay reliable on top of UDP. This is heavily used at scale by Google and YouTube.

Header compression

Compresses HTTP headers so less data travels per request.

Faster

Less connection-setup overhead than TCP-based HTTP — quicker first byte.

Better on bad networks

Handles poor/changing network conditions and large data transfer more gracefully.

⚠ Never forget HTTP/3 is built on UDP. That single fact — UDP foundation, plus reliability and speed layered on via QUIC — is the most commonly tested point about it.
WebSocket — One Open Line, Both DirectionsConcept+

WebSocket keeps a single connection open so client and server can send messages to each other anytime — no new request needed each time.

Normal HTTP is one-shot: the client asks, the server answers, done. That's wrong for live features. WebSocket fixes it with an upgrade: the connection starts as HTTP, then upgrades to a WebSocket (ws) connection using the 101 Switching Protocols status code. After that, it's a full-duplex, long-lasting line — either side can push data whenever it wants, with no repeated connection setup.

HTTP requestUpgrade (101)WebSocket (ws) open Full-duplex: both sides push anytime
  • Full-duplex — client and server can both send simultaneously over one connection.
  • Long-lasting — one persistent connection, instead of opening a new one per message.
  • Where it's used — live chat, live data streaming, analytics dashboards, YouTube comments/likes — anything real-time.
SMTP & FTP — Email and File TransferConcept+

Two special-purpose protocols: one to push email, one to move large files.

SMTP · email

Simple Mail Transfer Protocol. Mail in Gmail or Outlook is delivered via SMTP servers. It's a send/push model, not request-response: you tell the SMTP server "deliver this to these recipients," and it figures out how to route it.

FTP · files

File Transfer Protocol. A dedicated protocol for moving large files between systems, far more easily than streaming them over HTTP as binary. Tools like FileZilla use it; teams use it to move data between dev, test, and prod.

Cheat Sheet: Pick by NeedCompare+

The whole chapter in one table — what each protocol is, what it rides on, and when to reach for it.

ProtocolRuns onModelUse for
TCP3-way handshake, sequence numbersfoundation: reliable, in-order
UDPfire-and-forgetfoundation: fast, lossy
HTTPTCPrequest → responseweb browsing, APIs, assets
HTTPSTCP + TLSencrypted req/respsecure browsing (the "s")
HTTP/3UDP / QUICfast req/resphigh-scale web (YouTube, Google)
WebSocketTCP → wsfull-duplex, persistentlive chat, live data, dashboards
SMTPpush / senddelivering email
FTPupload / downloadlarge file transfer
💡 Interview tip Know two things per protocol: (1) what process it uses to communicate (handshake? upgrade? push?) and (2) what it's used for. Also learn the full forms — interviewers sometimes ask (HTTP, TCP, UDP, SSL, TLS, SMTP, FTP, QUIC).
Analogy · recall

Think of protocols as shipping methods on the same road network. TCP and UDP are the roads (one guarded and tracked, one open and fast). HTTP is the standard parcel service that drives the guarded road; HTTPS is the same service in a locked, tamper-proof box. HTTP/3 is an express courier that takes the fast road and still tracks its packages. WebSocket is a dedicated open phone line instead of mailing letters back and forth. SMTP is the postal service for letters; FTP is the freight truck for heavy cargo.

CH.2

Interview Q&A

Q1 What's the difference between TCP and UDP?
TCP is reliable: three-way handshake, sequence numbers, guarantees in-order delivery, and resends lost packets — at the cost of setup overhead. UDP is fast: no handshake, no delivery guarantees, packets can drop and won't be resent. Use TCP for web browsing, email, and file transfer; use UDP for voice/video calls and live streaming.
Q2 Explain the TCP three-way handshake.
The client sends SYN ("I want to connect"), the server replies SYN-ACK ("acknowledged, here's a sequence number"), and the client sends ACK ("confirmed"). The sequence number lets TCP track packets so it can detect and resend any that go missing, guaranteeing reliable, ordered delivery.
Q3 How is HTTPS different from HTTP?
HTTPS is HTTP plus a TLS/SSL handshake after the TCP connection. The server shares a public key, a session key is established, and all data is encrypted in transit. Anyone intercepting packets sees only scrambled data, so it's far harder to steal information than with plain HTTP.
Q4 What is HTTP/3 and what is it built on?
HTTP/3 is a modern version of HTTP built on QUIC, which runs on UDP rather than TCP. It cuts connection-setup overhead, adds header compression, and handles poor network conditions better, while layering reliability on top of UDP. The key fact: HTTP/3 is built on UDP.
Q5 What is a WebSocket and how does the connection start?
A WebSocket is a persistent, full-duplex connection where client and server can both send data anytime over a single open line. It starts as an HTTP request, then upgrades using the 101 Switching Protocols status code. After the upgrade there's no per-message connection setup, ideal for chat, live dashboards, and likes/comments.
Q6 What are SMTP and FTP used for?
SMTP delivers email — a push/send model where you hand a message and recipients to an SMTP server, which routes it. FTP is built for uploading and downloading large files between systems, used by tools like FileZilla and for moving data between dev, test, and prod machines.
protocol = contractTCP = reliable UDP = fast3-way handshake sequence numbersHTTP on TCP HTTPS = + TLSpublic/session key HTTP/3 = QUIC/UDPheader compression WebSocket = full-duplexupgrade 101 ws live dataSMTP = email push FTP = big filesreliability vs speed
CHAPTER 3REST APIs

The agreed conventions that let a client and a server exchange data cleanly, plus building one from scratch.

API = Application Programming Interface: a way for two programs to talk regardless of language. REST = REpresentational State Transfer: a popular set of rules, built on HTTP, for how that data is shaped and exchanged. The whole thing reduces to four building blocks you configure per request: the URL (where), the method (what action), headers (metadata), and the body (the data) — with a status code coming back to say what happened.
Tiers: How Apps Split Front End, Back End & DataConcept+

REST exists because we stopped cramming everything into one program. Understanding the split explains why an API is even needed.

Picture a restaurant (our running analogy): there's the dining area where customers sit and order (the front end / client) and the kitchen where food is prepared (the back end / server). As the business grew, keeping everything in one place stopped scaling — so the parts got separated.

Client Server Database request response query rows 3-tier: client, server, and database each scale and deploy independently.
1-tier

Front end, back end, and storage all bundled in one place, one codebase. Simple, but doesn't scale.

2-tier

Client and server split apart — built in different technologies, scaled separately. More flexible.

3-tier

Adds a separate database layer (the kitchen's cold/dry storage). Client ↔ server ↔ database. The common shape today.

Beyond three, an n-tier setup has the back end calling other services (payments, search, etc.). The point: once client and server are separate machines, something must carry messages between them in a structured way — that's the API.

What REST Actually IsConcept+

REST is a standard for representing and transferring data between web services, layered on top of HTTP.

  • API (Application Programming Interface) — the general idea of letting two programs communicate, even in different languages.
  • REST (REpresentational State Transfer) — one popular kind of API. It decides how the data is represented in transfer. Alternatives exist: GraphQL, gRPC, tRPC.
  • HTTP underneath — REST doesn't move bytes itself; it leverages HTTP as the foundation for the communication.
Analogy · recall

In the restaurant, the waiter is the API — carrying orders from table to kitchen and food back, along set paths, never wandering randomly. REST is the agreed standard for how dishes are packed and presented. HTTP is the physical delivery system the waiter uses.

Why REST: The BenefitsConcept+

REST is everywhere because it's simple, stateless, and inherits a lot of power from HTTP for free.

Simplicity / ease of use

Standard, predefined conventions. Call from the client with fetch, from the server with axios or request.

Stateless

The server keeps no memory of past requests. Every request carries all the info it needs (auth, context) — like a chef who needs the table number repeated every time.

Scalability

Because no state is stored, you just add capacity (horizontal or vertical scaling) as traffic grows.

Flexible data formats

Represent data as JSON (curly-brace objects) or XML. JSON dominates today; XML still common in Java/legacy systems.

Uniform interface

Uses the known URL/URI standard from HTTP, so you don't reinvent how to identify resources.

Caching

HTTP gives out-of-box caching at the network layer by tweaking headers.

Separation of concerns

Front end and back end are independent — React front end, Java/PHP/Ruby back end, any mix.

Interoperability

Language-agnostic. The producer and consumer of an API needn't share a language.

Easy testing & security

APIs are easy to test for stability; security comes via HTTPS and auth headers out of the box.

💡 Try it dummyjson.com serves free dummy REST APIs (todos, products, users, posts) for experimenting. Hitting dummyjson.com/todos returns a list of todos in JSON.
Anatomy of a Request & ResponseConcept+

Every REST message — in both directions — has three parts. Learn these and the rest is detail.

Request (client → server)

1. Request line — method + path/URL + protocol. 2. Headers — metadata (auth, content type …). 3. Body — optional data you're sending.

Response (server → client)

1. Status line — protocol + status code. 2. Headers — server metadata. 3. Body — the returned data (JSON, etc.).

Anything coming from the client lives in the request object; anything sent back lives in the response object. In DevTools → Network you can see all of it: request URL, request headers, response headers, status code, and the body (with a separate Payload tab when you send data).

The URL, Part by PartConcept+

A domain only gets you to the server. The URL carries the rest: which code to run, and what extra info to pass.

https www.engineerchirag.in /api/todos ?stack=networking&order=newest #sec-2 scheme host (sub+domain+TLD) path query params fragment Every URL segment has a job — only the fragment never leaves the browser.
  • Schemehttp or https (secure). Says which protocol to use.
  • Host — reaches the right server. Made of subdomain (www, course…) + domain name (engineerchirag) + TLD (.in, .com).
  • Path / route — digs into the server to the exact code to run. Can be a real folder structure or (usually) a dynamic route, e.g. Flipkart's /search.
  • Query params — extra info after ?, as key=value pairs joined by &. Passed into the server function.
  • Fragment / hash — after #. Used for scroll-to-section links and front-end (hash) routing. Critical: the hash is never sent to the server — so server telemetry won't see it, and hash routers can surprise you.
💡 Good practice Prefix API routes with /api and name them by resource: /api/todos, /api/users. Clear, consistent path naming matters.
HTTP Methods & CRUDConcept+

The method tells the server what action you intend. The four core actions form CRUD: Create, Read, Update, Delete.

POST · create

Add a new record. Data goes in the body. (CRUD: C)

GET · read

Retrieve data. No body needed; use URL params. (CRUD: R)

PUT / PATCH · update

PUT sends the entire object to replace it; PATCH sends only the changed field(s). (CRUD: U)

DELETE · delete

Remove a record. Pass the id in the URL param; no body. (CRUD: D)

Other methods worth knowing
  • HEAD — like GET but returns only headers, no body. Used to check if headers changed without fetching data.
  • OPTIONS — a security preflight: before a cross-origin request, the browser asks "am I allowed?" This underpins CORS.
  • CONNECT — establishes a connection ahead of time so a later request skips the handshake and is faster.
  • TRACE — diagnostic; echoes the request for debugging. Kept to dev only — it can leak server info, so disable in production.
URL & body conventions per method
MethodURL patternBody?
GET/todos or /todos/:idno (optional)
POST/todosyes (the new data)
PUT/todos/:idyes (full object)
PATCH/todos/:idyes (changed fields)
DELETE/todos/:idno

The same path can serve different methods — /todos handles GET (read all) and POST (create) at once. That reuse is a hallmark of REST.

Build It: A Tiny Express ServerBuild+

Express is a minimal framework on top of Node.js. With a few lines you get a working REST API. Here's the whole CRUD flow.

// index.js — set "type":"module" in package.json to use import
import express from 'express';
import bodyParser from 'body-parser';

const app = express();
const PORT = 5111;

app.use(bodyParser.json());   // parse JSON body for every request
let todos = [
  { id: 1, title: 'task one', completed: false },
  { id: 2, title: 'task two', completed: true },
];

// READ all
app.get('/todos', (req, res) => res.json(todos));

// CREATE
app.post('/todos', (req, res) => {
  todos.push(req.body);
  res.status(201).json({ message: 'New todo added' });
});

// UPDATE (PUT) — id from URL param
app.put('/todos/:id', (req, res) => {
  const id = req.params.id;
  const i = todos.findIndex(t => t.id == id);
  if (i === -1) return res.status(400).json({ message: 'Todo id does not exist' });
  todos[i] = { ...req.body, id };
  res.json({ message: 'Todo updated successfully' });
});

// DELETE — id from URL param
app.delete('/todos/:id', (req, res) => {
  const i = todos.findIndex(t => t.id == req.params.id);
  if (i !== -1) todos.splice(i, 1);
  res.json({ message: 'Todo deleted successfully' });
});

app.listen(PORT, () => console.log(`Server running at port ${PORT}`));
  • Setupnpm init creates package.json; npm i express body-parser installs dependencies; npm i nodemon auto-restarts on file changes.
  • A route = path + callbackapp.get('/todos', (req, res) => {...}): run this function when someone hits that path with that method.
  • Body parsing — data travels over the wire serialized (stringified). body-parser as middleware turns req.body back into a usable object for every request.
  • Test with Postman — the browser can only send GET easily; Postman lets you send POST/PUT/DELETE with a JSON body, or use curl.
Headers: Metadata on Every MessageConcept+

Headers are key-value metadata attached to requests and responses — auth, content type, caching, and more. You don't memorize them all; you stay aware of what's possible.

Request · Host / Origin

Host = the target domain you're hitting. Origin = the domain the request came from.

Request · Referer

The previous page that led to this request. Powers analytics: how many users came from LinkedIn vs Google vs WhatsApp.

Request · User-Agent

Identifies the client — OS, browser, version. Lets the server serve browser-specific bundles or block unsupported clients.

Request · Accept*

Accept (wanted response type), Accept-Language (preferred language, with q= priorities), Accept-Encoding (compression: gzip / brotli / deflate).

Request · Connection

keep-alive reuses one TCP connection across requests (default in HTTP/1.1); close ends it.

Request · Authorization / Cookie

Authorization carries credentials, often a Bearer token. Cookie auto-sends stored key-value data (e.g. auth token) on each request.

Response · Date / Content-Type

Date = when the response was generated. Content-Type = format being returned (application/json, text/html).

Response · Content-Length

Body size in bytes — lets the browser show download progress (% loaded).

Response · Set-Cookie

Tells the client to store a cookie for future requests (e.g. an auth token set at login).

Response · Caching

Cache-Control (max-age), Last-Modified, Expires, and ETag (a resource hash) govern caching and conflict detection.

⚠ Security gotcha The Server response header (e.g. Apache/2.4.41 (Unix)) leaks your software and version — a gift to attackers who know that version's exploits. Remove it explicitly. Companies have suffered breaches over this.
Analogy · recall

ETag for safe updates: it's like a version sticker on a shared document. If user A and user B both load a record (same ETag) and both edit, compare ETags on save — if the server's changed since you read it, reject the update and force a refresh, so B doesn't silently overwrite A.

Status Codes: What Happened to Your RequestConcept+

The status code tells you the outcome — success, redirect, your mistake, or the server's. Returning the right one (not 200 for everything) is what makes an API usable, grouped into five families: 1xx keep going, 2xx success, 3xx redirection, 4xx your error, 5xx the server's error.

1xx & key 2xx

100 Continue · 101 Switching Protocols (e.g. HTTP → WebSocket). 200 OK (read) · 201 Created (POST) · 202 Accepted (async job) · 204 No Content (DELETE) · 206 Partial Content (chunked download).

3xx redirects

301 Moved Permanently · 302 Found / Temporary. 307 = 302 and 308 = 301, but they preserve the method (a POST stays a POST through the redirect).

4xx client errors

400 Bad Request (invalid data) · 401 Unauthorized (not logged in) · 403 Forbidden (logged in, no permission) · 404 Not Found · 405 Method Not Allowed · 429 Too Many Requests.

5xx server errors

500 Internal Server Error · 502 Bad Gateway (proxy/gateway issue) · 503 Service Unavailable (server down) · 504 Gateway Timeout (took too long) · 507 Insufficient Storage.

Analogy · recall

You order a cold coffee. 2xx = here's your coffee. 3xx = we've moved, go to the new address. 4xx = you ordered something not on the menu (or aren't allowed in the kitchen). 5xx = we ran out of milk / the shop broke down. 4xx is "your error," 5xx is "my error."

⭐ Why it matters: retries Status codes let you write generic error handling and decide when to retry. Retrying a 400 is pointless — the same bad data fails again. Retrying a 503/504 makes sense — the server may be ready next time.
Analogy · recall

The whole chapter is one restaurant. Tiers = splitting dining room, kitchen, and storage. The waiter is the API; REST is how dishes are packed; HTTP is the delivery system. The URL is the table-and-dish address, the method is what you want done, headers are notes on the ticket, the body is the order details, and the status code is the waiter telling you whether your coffee is coming, the shop moved, you ordered wrong, or the kitchen broke.

CH.3

Interview Q&A

Q1 What is a REST API and what does REST stand for?
An API lets two programs communicate regardless of language. REST stands for REpresentational State Transfer — a popular set of conventions, built on HTTP, for how data is represented and exchanged between web services. You hit a URL with a method, optionally send headers and a body, and get back data plus a status code.
Q2 What does it mean that REST is stateless, and why is that powerful?
Stateless means the server keeps no memory of previous requests — each request must carry everything it needs (auth, context). Like a chef who needs the table number repeated every time. It's powerful because the server has no session baggage to maintain, which makes the system far easier to scale: you just add more server capacity as load grows.
Q3 Walk through the parts of a URL.
Scheme (http/https), host (subdomain + domain + TLD, which reaches the server), path/route (digs into the server to the code to run), query params (extra key=value info after ?, joined by &), and fragment/hash (after #, used for scroll targets and front-end routing). Importantly, the fragment is never sent to the server.
Q4 What is the difference between PUT and PATCH?
Both update a resource. PUT sends the entire object and replaces it — the server expects all fields. PATCH sends only the field(s) you want to change, and the server merges them into the existing record. Use PATCH for partial updates; use PUT when replacing the whole resource.
Q5 How do CRUD operations map to HTTP methods?
Create → POST, Read → GET, Update → PUT or PATCH, Delete → DELETE. POST and PUT/PATCH carry data in the body; GET and DELETE typically use URL params and no body. The same path (e.g. /todos) can serve multiple methods.
Q6 What are the five status code categories?
1xx informational (keep going), 2xx success (200 OK, 201 Created, 204 No Content), 3xx redirection (301 permanent, 302 temporary), 4xx client error (400 bad request, 401 unauthorized, 403 forbidden, 404 not found), and 5xx server error (500 internal error, 503 unavailable, 504 timeout). 4xx is "your error," 5xx is "my error."
Q7 What's the difference between 401 and 403?
401 Unauthorized means you're not authenticated — not logged in or no valid credentials, so the server won't let you in at all. 403 Forbidden means you are logged in but lack permission for that specific resource — like an employee with a badge who still can't enter the admin server room.
Q8 On which status codes should a client retry, and why?
Retry on transient server-side failures like 503 Service Unavailable or 504 Gateway Timeout — the server may succeed next time. Don't retry on 4xx client errors like 400 Bad Request or 401 Unauthorized — the same invalid input or missing auth will fail again, so retrying just wastes calls.
Q9 Why should you remove the Server response header?
The Server header (e.g. Apache/2.4.41) reveals the exact software and version running on your server. An attacker who knows that version can target its known vulnerabilities. Stripping it is a cheap, important hardening step.
API = programs talkREST = repr. state transfer on top of HTTP1/2/3-tier statelessJSON / XML req: line/headers/bodyres: status/headers/body scheme · host · path · query · hash hash not sent to serverCRUD POST/GET/PUT/PATCH/DELETEPUT full, PATCH partial HEAD/OPTIONS/CONNECT/TRACE/api/todos :id Express + body-parserserialized over wire Host vs OriginAuthorization: Bearer remove Server headerETag conflict check 2xx/3xx/4xx/5xx201 create · 204 delete 401 vs 403retry 5xx not 4xx
CHAPTER 4GraphQL

Let the client ask for exactly the data it wants — one request, one shape, no waste.

GraphQL is a graph query language (and runtime) where the client decides the response shape. Instead of many REST endpoints, you hit one endpoint and send a typed query for exactly the fields you want — killing over-fetching (too much data) and under-fetching (too many round trips). It's built on a schema of typed objects; you query to read and mutate to write; and resolver functions on the server actually fetch each field. It still rides on HTTP (almost always POST) — GraphQL is a layer of power on top, not a replacement for HTTP.
The Problem GraphQL SolvesConcept+

Our restaurant owner is going global and needs continents, countries, and languages on screen. In REST, that's three endpoints and three round trips, often returning more than needed.

REST — 3 round trips GraphQL — 1 round trip Client /api/continents /api/countries /api/languages Client one query GraphQL resolvers → graph REST returns whatever each endpoint was built to return; GraphQL returns exactly the shape the client asked for, in one trip.
REST way

Three calls: /api/continents, /api/countries, /api/languages. The client fires all three, then merges and reshapes the data itself.

GraphQL way

One request to one endpoint, listing exactly the fields wanted. The server fetches from the right sources, shapes the data, and returns it.

Why "graph"? Real data is connected: a continent has countries, a country has languages; a social post has likes, friends, friends-of-friends. Data naturally forms a graph, and GraphQL lets you query that graph in a structured, typed way.

A Query & Its ResponseBuild+

You write a query that mirrors the shape you want; the response comes back in that exact shape. (Apollo Studio / a GraphQL playground is the equivalent of Postman here.)

# client query — ask for exactly these fields, nested
query {
  continents { name countries { name languages { name } } }
}
// response — same shape you asked for
{
  "data": {
    "continents": [
      { "name": "Africa",
        "countries": [
          { "name": "Angola",
            "languages": [{ "name": "Portuguese" }] }
        ] }
    ]
  }
}

One request returns the full nested hierarchy — continents → their countries → their languages — no client-side merging needed.

BenefitsConcept+

GraphQL was open-sourced by Facebook (built 2012, public 2015). Its power comes from giving the client control and being strongly typed end to end.

No over-fetching

Ask for just name and you get only names — not the whole object.

No under-fetching

Combine what would be multiple REST calls into one request. Fewer round trips to the server.

Better mobile performance

Mobile has less RAM/bandwidth — the same query can ask for less on mobile, more on desktop.

Declarative fetching

You describe what you want, not how to get it. Clean and predictable.

Hierarchical / nested data

Get related data (continent → country → language) in one structured response.

Strongly typed

Every field has a type (ID, String, Int, Boolean …). Invalid queries error out before running.

Introspection

The schema documents itself. The playground autosuggests valid queries, fields, and shapes.

Real-time (subscriptions)

Beyond query/mutate, GraphQL has subscriptions for live, WebSocket-style updates out of the box.

REST vs. GraphQLCompare+

A top interview question. Neither "wins" outright — they trade off, and many apps use both.

RESTGraphQL
Data fetchingmultiple endpointssingle endpoint
Requestfixed structure + methodsquery (read) / mutation (write)
Over/under-fetcha problemsolved (client picks fields)
Response sizefixedflexible (client decides)
Versioningexplicit (/v1, /v2)field-level @deprecated, same endpoint
Schemaoptional / looseexplicit, strongly typed
Real-timeadd polling / WebSocketsubscriptions out of the box
Toolingthird-party (Postman)built-in playgrounds
Cachingrelies on HTTP cachefine-grained via client libs (Apollo)
Client controlnone over response shapefull control over response shape
Adoptionubiquitous, last decadefast-growing, big community
  • Same HTTP underneath. Status codes, request/response, headers — those come from HTTP, not REST. GraphQL uses them too; it just adds power on top. (GraphQL calls are almost always POST.)
  • REST isn't going away. Millions of REST services exist; you'll consume both. GraphQL is the rapidly growing newer option.
Building Blocks: Schema, Types, Query/Mutation, ResolversConcept+

Four terms unlock GraphQL. The schema (written in SDL, the Schema Definition Language) declares the shape; resolvers provide the data.

Types / Schema (SDL)

Defines the shape of your data. Scalar types are built-in: ID, String, Int, Boolean. Custom types are ones you define. ! marks a field required.

Query

The type listing everything you can read. One HTTP method (POST) for all of it.

Mutation

The type listing everything you can write — create / update / delete.

Resolver

A function that actually fetches or updates the data for a field — from a DB or another API. One-to-one with your schema fields.

A resolver's four arguments
  • parent — the parent object in the graph (e.g. the book, when resolving its author). Key for nested relationships.
  • args — arguments/filters the client passed (e.g. an id).
  • context — shared data across all resolvers in one request (e.g. the logged-in user, DB connection).
  • info — metadata about the query execution (field, path …). Rarely needed early on.
Build It: An Apollo GraphQL ServerBuild+

A books-and-authors API. The schema declares types + relationships; resolvers fetch the data, including resolving relationships via the parent argument.

// typeDefs.js — schema in SDL
const typeDefs = `#graphql
  type Author { id: ID!, name: String!, books: [Book] }
  type Book   { id: ID!, title: String!, publishedYear: Int, author: Author }

  type Query {
    authors: [Author]      # list of authors
    books: [Book]          # list of books
  }
  type Mutation {
    addBook(title: String!, authorId: ID!, publishedYear: Int): Book
  }
`;
export default typeDefs;
// resolvers.js — functions that supply the data
const resolvers = {
  Query: {
    authors: () => data.authors,
    books:   () => data.books,
  },
  // relationship resolvers use the `parent` arg
  Book: {
    author: (parent) => data.authors.find(a => a.id === parent.authorId),
  },
  Author: {
    books: (parent) => data.books.filter(b => parent.bookIds.includes(b.id)),
  },
  Mutation: {
    addBook: (parent, args) => {
      const newBook = { id: data.books.length + 1, ...args };
      data.books.push(newBook);
      return newBook;
    },
  },
};
export default resolvers;
// index.js — start a standalone Apollo server
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import typeDefs from './typeDefs.js';
import resolvers from './resolvers.js';

const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4001 } });
console.log(`Server ready at ${url}`);
  • Apollo Server needs two thingstypeDefs (the schema, including Query & Mutation) and resolvers (the implementations). The standalone server bridges to an Express/HTTP server internally.
  • Relationship resolvingBook.author and Author.books aren't in the raw data; resolvers use the parent object's authorId/bookIds to look them up, so nested queries return real data instead of null.
  • Gotcha from the build — a field defined in a resolver but not in the schema (or a case mismatch like Author vs author) throws "defined in resolver but not in schema." Schema and resolver field names must match exactly.
Calling GraphQL from the ClientBuild+

Under the hood it's just a POST with a stringified query. You can use plain fetch, or a library like Apollo Client for superpowers.

// plain fetch — no library needed
fetch('http://localhost:4001/', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: `{ books { id title author { name } } }`,
  }),
})
  .then(res => res.json())
  .then(data => console.log(data));
  • The request body carries query (stringified), optional variables (filters/args), and an optional operationName (a label for debugging).
  • Apollo Client — a wrapper giving caching and React hooks: useQuery (read) and useMutation (write) return loading, error, and data states. Wrap the app in <ApolloProvider> to use hooks.
  • Other client libs — urql, Relay (Facebook), graphql-request, graphql-ws. Server libs include Apollo Server, GraphQL Yoga, Mercurius.
Analogy · recall

REST is a fixed-menu thali — you order a plate and get whatever comes on it, and if you want three plates you place three orders. GraphQL is à la carte with one order slip: you write down exactly the dishes and portions you want, hand it over once, and the kitchen returns precisely that. The schema is the menu, queries/mutations are reading vs. changing your order, and resolvers are the cooks who actually fetch each item.

CH.4

Interview Q&A

Q1 What is GraphQL and how does it differ from REST?
GraphQL is a typed query language and runtime where the client specifies exactly which fields it wants, fetched from a single endpoint. REST exposes multiple fixed endpoints whose response shape the server controls. GraphQL eliminates over-fetching and under-fetching by letting the client pick fields and combine related data into one request.
Q2 What are over-fetching and under-fetching?
Over-fetching is getting more data than you need — e.g. a REST endpoint returns a whole object when you only wanted the name. Under-fetching is when one endpoint doesn't give enough, forcing multiple round trips. GraphQL solves both: the client requests exactly the fields it wants, including nested related data, in a single request.
Q3 What are the core building blocks of GraphQL?
The schema (written in SDL) defines types — scalar built-ins (ID, String, Int, Boolean) and custom types. Query lists what you can read; Mutation lists what you can write. Resolvers are functions that actually fetch or update the data for each field. Subscriptions add real-time updates.
Q4 What is a resolver, and what are its arguments?
A resolver is a server function that returns the data for a schema field. Its four arguments are: parent (the parent object, used to resolve relationships), args (client-supplied arguments/filters), context (data shared across all resolvers in a request), and info (execution metadata). The parent argument is how nested relationships like Book.author get resolved.
Q5 What's the difference between a query and a mutation?
A query reads data; a mutation writes it (create, update, delete). Both go over HTTP POST in GraphQL — there's no method-based distinction like REST's GET vs POST. You declare them as the Query and Mutation types in the schema, and implement them in the resolvers.
Q6 Does GraphQL replace HTTP? What status codes does it use?
No — GraphQL runs on top of HTTP, almost always via POST. The request/response structure, headers, and status codes all come from HTTP, not from GraphQL. GraphQL adds a typed schema, client-controlled responses, and tooling on top.
Q7 How does GraphQL handle versioning compared to REST?
REST typically versions with separate paths like /v1 and /v2. GraphQL avoids that: because the client selects fields, you can add new fields freely and mark old ones with the @deprecated directive on the same endpoint — evolving the schema without breaking existing clients.
Q8 Why is GraphQL called strongly typed, and what is introspection?
Every field in the schema has a defined type, so invalid queries are rejected before execution. Introspection means the schema can describe itself: playgrounds use it to autosuggest valid fields and queries and to generate live documentation, replacing the static API docs you'd hand-write for REST.
graph query languagesingle endpoint client picks fieldsno over-fetch no under-fetchon top of HTTP (POST) schema = SDLscalar vs custom types ! = requiredquery = read mutation = writeresolver = fetch fn parent/args/context/infonested via parent strongly typedintrospection subscriptions = realtime@deprecated vs /v2 Apollo ServerApollo Client hooks useQuery / useMutationfetch + stringified query
CHAPTER 5gRPC & Protocol Buffers

Call a function on another machine as if it were local — fast, typed, and binary.

gRPC = Remote Procedure Call over HTTP/2, using Protocol Buffers (protobuf) as the data format. Instead of fetching from a URL, the client invokes a method defined on the server directly. You declare the service's methods and message shapes once in a typed .proto file; code generation produces client & server stubs for any language. Data travels as compact binary, making gRPC up to ~10× faster than REST — at the cost of being non-human-readable and not natively browser-friendly.
What RPC MeansConcept+

A Remote Procedure Call lets you execute a function that lives on a remote machine as if you'd called it locally.

Normally, machine A asks machine B for data through an exposed API. With RPC, machine A (the client) calls a function written on machine B (the server) directly — you invoke a remote function from your own code as though it were defined right there.

gRPC is Google's open-source framework that implements this. Google didn't invent RPC; gRPC is the framework that drives RPC communication using Protocol Buffers over HTTP/2, with built-in support for load balancing, tracing, health checking, and authentication.

How a gRPC Call FlowsConcept+

The call passes through stubs and runtimes on both sides, which handle interfaces, serialization, and transport — so your code just calls a function.

CLIENT MACHINE SERVER MACHINE client function client stub RPC runtime real function server stub RPC runtime HTTP/2 — binary protobuf The client's call travels down through its stub and runtime, crosses as compact binary over HTTP/2, and travels back up through the server's runtime and stub.
  • Stub — the generated interface (like a GraphQL schema or TypeScript types) that knows the method signatures.
  • RPC runtime — handles the actual transport between machines.
  • The round trip — client function → client stub → client runtime → (HTTP/2, binary) → server runtime → server stub → real function executes → result serialized back the same path.
Protocol Buffers (protobuf)Concept+

Protobuf is gRPC's data format and interface definition language (IDL) — the equivalent of JSON for REST, but binary and strongly typed.

  • IDL — you define the interface (services, methods, message shapes) in a .proto file, the way JSON has a structure or GraphQL has a schema. Current version: proto3.
  • Binary on the wire — unlike REST's text JSON, protobuf serializes to binary, which is smaller and faster to encode/decode.
  • Serialize / deserialize in any language — protobuf provides the encode/decode methods for every language, so you're not tied to JS's JSON.stringify.
  • Code generation — from one .proto file, gRPC generates compatible client and server code for any language.
Less CPU / smaller

Binary data uses fewer resources — great for mobile devices with limited RAM/CPU.

Faster

Compact binary over the network plus fast serialization = quicker communication.

Why HTTP/2 & Bi-Directional StreamingConcept+

gRPC requires HTTP/2, which brings real performance wins — and unlocks streaming in multiple directions.

Header compression

Smaller headers = faster communication.

Single long-lived connection

One TCP connection reused to stream many messages, not a new one per request.

Multiplexing

Multiple data streams over that one connection.

⚠ Don't confuse with WebSocket gRPC's bi-directional streaming means data flows both ways within a single long-lived RPC connection for that one call — not a persistent always-open socket like WebSocket. gRPC supports several streaming modes: client → server, server → client, or both ways.
Defining the Service: the .proto FileBuild+

Like a GraphQL schema, the .proto declares the service's methods (rpc) and the message shapes. A customer CRUD example:

syntax = "proto3";

service CustomerService {
  rpc GetAll (Empty)              returns (CustomerList);
  rpc Get    (CustomerRequestId)  returns (Customer);
  rpc Insert (Customer)           returns (Customer);
  rpc Update (Customer)           returns (Customer);
  rpc Remove (CustomerRequestId)  returns (Empty);
}

message Empty {}

message CustomerRequestId { string id = 1; }

message Customer {
  string id      = 1;
  string name    = 2;
  int32  age     = 3;
  string address = 4;
}

message CustomerList { repeated Customer customers = 1; }
  • service groups the rpc methods; each declares its request and response message types.
  • message defines a custom type. Scalar types include string, int32, bool.
  • The field numbers (= 1, = 2 …) are sequence tags used by serialization for ordering and backward/forward compatibility. Never change an existing number once in production — only add new ones.
  • repeated means "a list of" — repeated Customer is an array of customers.
⚠ Pitfall Reusing or renumbering a field once .proto has shipped to production silently corrupts old messages on the wire — protobuf decodes by field number, not by name. Only ever add new numbers.
Build It: Server, Client & an Express BridgeBuild+

A realistic setup: a gRPC server holds the functions; a gRPC client calls them; and an Express server exposes them to the browser as REST (since browsers can't speak gRPC directly).

Browser (REST/HTTP)Express + gRPC client gRPC server (HTTP/2 + protobuf)
// server.js — the gRPC server (uses @grpc/grpc-js for JavaScript)
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');

const packageDef = protoLoader.loadSync('customers.proto', { keepCase: true });
const proto = grpc.loadPackageDefinition(packageDef);

const customers = [
  { id: '1', name: 'Chirag', age: 30, address: 'Bangalore' },
  { id: '2', name: 'Akshay', age: 28, address: 'Uttarakhand' },
];

const server = new grpc.Server();
server.addService(proto.CustomerService.service, {
  GetAll: (call, callback) => callback(null, { customers }),
  Get: (call, callback) => {
    const c = customers.find(x => x.id === call.request.id);
    callback(null, c);
  },
  // Insert, Update, Remove — plain JS on the array (or a DB call)
});
server.bindAsync('127.0.0.1:30043',
  grpc.ServerCredentials.createInsecure(),
  () => console.log('gRPC server started'));
// client.js — load the same proto, create a client stub
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const proto = grpc.loadPackageDefinition(
  protoLoader.loadSync('customers.proto', { keepCase: true }));

const client = new proto.CustomerService(
  'localhost:30043', grpc.credentials.createInsecure());
module.exports = client;
// express bridge — expose gRPC methods to the browser as REST
app.get('/', (req, res) => {
  client.GetAll({}, (err, data) => {
    if (err) return res.status(500).send(err);
    res.send(data.customers);
  });
});
  • Two libraries@grpc/grpc-js (the JS-specific gRPC bundle) and @grpc/proto-loader (loads the .proto and builds definitions).
  • Server — load the proto, create new grpc.Server(), addService with method implementations (call, callback), then bindAsync to a port.
  • Client — load the same proto, instantiate the service stub pointed at the server's address; now client.GetAll(...) etc. invoke the remote functions.
  • Express bridge — the browser hits REST endpoints; the handler calls the gRPC client internally and returns the result.
  • Gotcha from the build — the generic grpc package doesn't work in JS; use @grpc/grpc-js, and bind with bindAsync + grpc.credentials.createInsecure() on the client.
REST vs. gRPCCompare+

The comparison interviewers love. gRPC trades human-readability and browser-friendliness for raw speed and strong typing.

RESTgRPC
TransportHTTP / HTTPSHTTP/2 (required)
PayloadJSON / XML (text)Protocol Buffers (binary)
IDLnone / OpenAPI / Swagger.proto (built-in, required)
Serializationtext (JSON/XML)binary protobuf
Performanceslower (text, more trips)~10× faster (binary, multiplexing)
Streamingadd WebSocketbuilt-in: client / server / bidi
Code generationthird-party (Swagger)from .proto, language-specific
SecurityHTTPSHTTP/2 + TLS/SSL by default
Browser supportnativelimited (needs proxy/bridge)
CachingHTTP edge cachingnone (POST under the hood)
Adoptionubiquitousgrowing, server-to-server
Pros & ConsConcept+

When to reach for gRPC, and what it costs you.

Advantages

Performance (~10× faster: protobuf binary, multiplexing, header compression from HTTP/2). Built-in streaming (client / server / bi-directional). Code generation — language-agnostic client/server from one .proto. Service discovery & load balancing built in. Security via HTTP/2 + TLS by default.

Disadvantages

Non-human-readable (binary — hard to inspect on the wire). Limited browser support (needs a proxy/bridge like our Express layer). No edge caching (everything is POST under the hood). Steeper learning curve — less widely known, though adoption is rising fast.

💡 Where it's used Mostly server-to-server communication in microservices and distributed systems. Google uses gRPC heavily for internal service-to-service calls; analytics tools needing fast server communication increasingly adopt it for the ~10× speedup.
Analogy · recall

REST is like mailing a letter to an address and getting a reply — readable, universal, a bit slow. gRPC is like having a direct intercom line into the other office where you press a labeled button and a specific clerk does a specific task — you're not fetching a document, you're triggering an action. The .proto file is the labeled button panel both offices agreed on; the messages travel as sealed, compact binary pouches (protobuf) down one fast dedicated line (HTTP/2) — lightning quick, but you can't read the pouch in transit, and the public lobby (browser) can't use the intercom without a receptionist (proxy).

CH.5

Interview Q&A

Q1 What is gRPC and how does it differ from REST?
gRPC is Google's open-source RPC framework: the client directly invokes a method defined on the server, rather than fetching from a URL. It runs on HTTP/2 and sends data as binary Protocol Buffers instead of text JSON, making it much faster. REST is resource/URL-based over HTTP with human-readable JSON; gRPC is action/method-based, binary, strongly typed, and mainly used for server-to-server communication.
Q2 What is a Remote Procedure Call?
An RPC lets a client execute a function that lives on a remote server as if it were a local function call. Instead of requesting data and processing it yourself, you call the remote method by name with arguments and get back its return value. gRPC implements this with generated stubs and runtimes that handle the transport and serialization transparently.
Q3 What are Protocol Buffers, and why binary?
Protocol Buffers (protobuf) are gRPC's interface definition language and serialization format, defined in a .proto file. Data is serialized to compact binary rather than text JSON, so it's smaller on the wire and faster to encode/decode. Protobuf provides serialization for every language, and code generation produces matching client/server code.
Q4 Why does gRPC require HTTP/2?
HTTP/2 gives gRPC header compression, a single long-lived connection, and multiplexing of multiple streams over that one connection. This enables low-overhead, high-throughput communication and bi-directional streaming. Together with binary protobuf, these are the main reasons gRPC can be around 10× faster than REST.
Q5 What streaming modes does gRPC support?
gRPC supports unary (single request/response), client-to-server streaming, server-to-client streaming, and bi-directional streaming — you choose the direction. Bi-directional here means data flows both ways within a single long-lived RPC connection for that call, which is different from a persistent always-open WebSocket.
Q6 What goes in a .proto file?
The syntax version (proto3), one or more services grouping rpc methods with their request/response message types, and message definitions describing each type's fields with scalar types and sequence field numbers. Field numbers must stay stable in production for serialization compatibility; repeated marks a list.
Q7 What are the main downsides of gRPC?
Its binary payload is not human-readable, so traffic is hard to inspect. Browsers don't natively support gRPC, so you need a proxy or bridge (e.g. an Express REST layer). It has no HTTP edge caching since everything is POST under the hood, and it has a steeper learning curve than REST.
gRPC = RPC by Googlecall remote function on HTTP/2protobuf = binary .proto = IDL (proto3)service + rpc + message field numbers stablerepeated = list code-gen any languagestub + runtime serialize/deserializeheader compression single long connectionmultiplexing bidi streaming~10x faster server-to-server@grpc/grpc-js proto-loaderbindAsync + insecure no browser supportno edge caching express bridge
III

Key Takeaways

Every request is resolve a name to an address, open a trusted pipe, then speak an agreed dialect to ask for exactly what you need — REST's fixed endpoints, GraphQL's client-shaped query, or gRPC's direct function call. The dialect changes; the three-step shape never does.