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.
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 runsPROTOCOLS (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 APIsDetailed 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.
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.
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.
- The first response is HTML. Hit
flipkart.comand 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.
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 — 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 / subdomain —
www,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.
Sits in your home. Takes one incoming line (LAN/fiber) and shares the internet to all your devices over Wi-Fi or LAN cable.
Converted the signal coming over old telephone wires into usable internet. Today fiber often comes straight in.
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
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.
The ISP Hierarchy & PacketsConcept+
ISPs come in tiers, and the data they move travels as small numbered packets — not one big block.
Small distributor that wires up your building/area and sells you a plan.
Larger providers (Jio, Airtel). Often where national rules apply — blocking or allowing sites at a country level.
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.
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.
- Browser HTTP cache — does the browser already have this resource/IP cached?
- Service worker cache — a script that can intercept requests and answer from its own cache.
- Operating system — checks the OS
hostsfile (you can map e.g.google.com→localhost:3000for local dev). - Router — modern routers cache domain → IP mappings (why "restart your router" sometimes refreshes things).
- 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.
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.
"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.
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.
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.
The authority that sets the guidelines for how domains and IP mappings work — who governs TLDs and the overall name-to-IP system.
A directory where, given a domain name, you can look up who registered it, when, when it expires, and the registrar.
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.)
- 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).
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.
Interview Q&A
Q1 What happens, step by step, when you type a URL and press enter?
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?
.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?
Q4 How many requests can a browser make in parallel, and what happens beyond that?
Q5 Why is the first ~14 KB of the response important?
Q6 Explain the browser's critical rendering path.
Q7 How do companies like Google and Netflix make global delivery fast?
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.
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.
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.
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.
- 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.
Compresses HTTP headers so less data travels per request.
Less connection-setup overhead than TCP-based HTTP — quicker first byte.
Handles poor/changing network conditions and large data transfer more gracefully.
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.
- 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.
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.
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.
| Protocol | Runs on | Model | Use for |
|---|---|---|---|
TCP | — | 3-way handshake, sequence numbers | foundation: reliable, in-order |
UDP | — | fire-and-forget | foundation: fast, lossy |
HTTP | TCP | request → response | web browsing, APIs, assets |
HTTPS | TCP + TLS | encrypted req/resp | secure browsing (the "s") |
HTTP/3 | UDP / QUIC | fast req/resp | high-scale web (YouTube, Google) |
| WebSocket | TCP → ws | full-duplex, persistent | live chat, live data, dashboards |
| SMTP | — | push / send | delivering email |
| FTP | — | upload / download | large file transfer |
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.
Interview Q&A
Q1 What's the difference between TCP and UDP?
Q2 Explain the TCP three-way handshake.
Q3 How is HTTPS different from HTTP?
Q4 What is HTTP/3 and what is it built on?
Q5 What is a WebSocket and how does the connection start?
Q6 What are SMTP and FTP used for?
The agreed conventions that let a client and a server exchange data cleanly, plus building one from scratch.
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.
Front end, back end, and storage all bundled in one place, one codebase. Simple, but doesn't scale.
Client and server split apart — built in different technologies, scaled separately. More flexible.
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.
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.
Standard, predefined conventions.
Call from the client with fetch, from the server with
axios or request.
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.
Because no state is stored, you just add capacity (horizontal or vertical scaling) as traffic grows.
Represent data as JSON (curly-brace objects) or XML. JSON dominates today; XML still common in Java/legacy systems.
Uses the known URL/URI standard from HTTP, so you don't reinvent how to identify resources.
HTTP gives out-of-box caching at the network layer by tweaking headers.
Front end and back end are independent — React front end, Java/PHP/Ruby back end, any mix.
Language-agnostic. The producer and consumer of an API needn't share a language.
APIs are easy to test for stability; security comes via HTTPS and auth headers out of the box.
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.
- Scheme —
httporhttps(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
?, askey=valuepairs 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.
/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.
Add a new record. Data goes in the body. (CRUD: C)
Retrieve data. No body needed; use URL params. (CRUD: R)
PUT sends the entire object to replace it; PATCH sends only the changed field(s). (CRUD: U)
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
| Method | URL pattern | Body? |
|---|---|---|
GET | /todos or /todos/:id | no (optional) |
POST | /todos | yes (the new data) |
PUT | /todos/:id | yes (full object) |
PATCH | /todos/:id | yes (changed fields) |
DELETE | /todos/:id | no |
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}`));
- Setup —
npm initcreatespackage.json;npm i express body-parserinstalls dependencies;npm i nodemonauto-restarts on file changes. - A route = path + callback —
app.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-parseras middleware turnsreq.bodyback 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.
Host = the target domain you're hitting. Origin = the domain the request came from.
The previous page that led to this request. Powers analytics: how many users came from LinkedIn vs Google vs WhatsApp.
Identifies the client — OS, browser, version. Lets the server serve browser-specific bundles or block unsupported clients.
Accept
(wanted response type), Accept-Language (preferred language, with
q= priorities), Accept-Encoding (compression:
gzip / brotli / deflate).
keep-alive
reuses one TCP connection across requests (default in HTTP/1.1); close
ends it.
Authorization
carries credentials, often a Bearer token. Cookie auto-sends stored
key-value data (e.g. auth token) on each request.
Date = when
the response was generated. Content-Type = format being returned
(application/json, text/html).
Body size in bytes — lets the browser show download progress (% loaded).
Tells the client to store a cookie for future requests (e.g. an auth token set at login).
Cache-Control
(max-age), Last-Modified, Expires, and
ETag (a resource hash) govern caching and conflict detection.
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.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.
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).
301 Moved Permanently · 302 Found / Temporary. 307 = 302 and 308 = 301, but they preserve the method (a POST stays a POST through the redirect).
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.
500 Internal Server Error · 502 Bad Gateway (proxy/gateway issue) · 503 Service Unavailable (server down) · 504 Gateway Timeout (took too long) · 507 Insufficient Storage.
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."
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.
Interview Q&A
Q1 What is a REST API and what does REST stand for?
Q2 What does it mean that REST is stateless, and why is that powerful?
Q3 Walk through the parts of a URL.
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?
Q5 How do CRUD operations map to HTTP methods?
/todos) can serve multiple methods.Q6 What are the five status code categories?
Q7 What's the difference between 401 and 403?
Q8 On which status codes should a client retry, and why?
Q9 Why should you remove the Server response header?
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.Let the client ask for exactly the data it wants — one request, one shape, no waste.
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 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.
Ask for just name
and you get only names — not the whole object.
Combine what would be multiple REST calls into one request. Fewer round trips to the server.
Mobile has less RAM/bandwidth — the same query can ask for less on mobile, more on desktop.
You describe what you want, not how to get it. Clean and predictable.
Get related data (continent → country → language) in one structured response.
Every field has a type (ID, String, Int, Boolean …). Invalid queries error out before running.
The schema documents itself. The playground autosuggests valid queries, fields, and shapes.
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.
| REST | GraphQL | |
|---|---|---|
| Data fetching | multiple endpoints | single endpoint |
| Request | fixed structure + methods | query (read) / mutation (write) |
| Over/under-fetch | a problem | solved (client picks fields) |
| Response size | fixed | flexible (client decides) |
| Versioning | explicit (/v1, /v2) | field-level @deprecated, same endpoint |
| Schema | optional / loose | explicit, strongly typed |
| Real-time | add polling / WebSocket | subscriptions out of the box |
| Tooling | third-party (Postman) | built-in playgrounds |
| Caching | relies on HTTP cache | fine-grained via client libs (Apollo) |
| Client control | none over response shape | full control over response shape |
| Adoption | ubiquitous, last decade | fast-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.
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.
The type listing everything you can read. One HTTP method (POST) for all of it.
The type listing everything you can write — create / update / delete.
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 things —
typeDefs(the schema, including Query & Mutation) andresolvers(the implementations). The standalone server bridges to an Express/HTTP server internally. - Relationship resolving —
Book.authorandAuthor.booksaren't in the raw data; resolvers use theparentobject'sauthorId/bookIdsto look them up, so nested queries return real data instead ofnull. - Gotcha from the build — a field defined in a resolver but not in the schema (or a
case mismatch like
Authorvsauthor) 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), optionalvariables(filters/args), and an optionaloperationName(a label for debugging). - Apollo Client — a wrapper giving caching and React hooks:
useQuery(read) anduseMutation(write) returnloading,error, anddatastates. 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.
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.
Interview Q&A
Q1 What is GraphQL and how does it differ from REST?
Q2 What are over-fetching and under-fetching?
Q3 What are the core building blocks of GraphQL?
Q4 What is a resolver, and what are its arguments?
Q5 What's the difference between a query and a mutation?
Q6 Does GraphQL replace HTTP? What status codes does it use?
Q7 How does GraphQL handle versioning compared to REST?
/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?
Call a function on another machine as if it were local — fast, typed, and binary.
.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.
- 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
.protofile, 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
.protofile, gRPC generates compatible client and server code for any language.
Binary data uses fewer resources — great for mobile devices with limited RAM/CPU.
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.
Smaller headers = faster communication.
One TCP connection reused to stream many messages, not a new one per request.
Multiple data streams over that one connection.
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. repeatedmeans "a list of" —repeated Customeris an array of customers.
.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).
// 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.protoand builds definitions). - Server — load the proto, create
new grpc.Server(),addServicewith method implementations(call, callback), thenbindAsyncto 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
grpcpackage doesn't work in JS; use@grpc/grpc-js, and bind withbindAsync+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.
| REST | gRPC | |
|---|---|---|
| Transport | HTTP / HTTPS | HTTP/2 (required) |
| Payload | JSON / XML (text) | Protocol Buffers (binary) |
| IDL | none / OpenAPI / Swagger | .proto (built-in, required) |
| Serialization | text (JSON/XML) | binary protobuf |
| Performance | slower (text, more trips) | ~10× faster (binary, multiplexing) |
| Streaming | add WebSocket | built-in: client / server / bidi |
| Code generation | third-party (Swagger) | from .proto, language-specific |
| Security | HTTPS | HTTP/2 + TLS/SSL by default |
| Browser support | native | limited (needs proxy/bridge) |
| Caching | HTTP edge caching | none (POST under the hood) |
| Adoption | ubiquitous | growing, 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.
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).
Interview Q&A
Q1 What is gRPC and how does it differ from REST?
Q2 What is a Remote Procedure Call?
Q3 What are Protocol Buffers, and why binary?
.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?
Q5 What streaming modes does gRPC support?
Q6 What goes in a .proto file?
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?
Key Takeaways
- The web is a conversation, not a download. DNS resolves a name to an address, TCP+TLS open a trusted pipe, and the browser's fixed pipeline (DOM+CSSOM → render tree → layout → paint → composite) turns the bytes that come back into pixels.
- Every layer exists to make that conversation faster or safer: caching at five levels, only 6–8 parallel connections per origin, the first ~14 KB special, and companies like Google and Netflix physically shortening the path (peering, edge caching).
- Protocols are just contracts: TCP trades speed for reliability, UDP trades reliability for speed. HTTP/HTTPS ride TCP; HTTP/3 rides UDP; WebSocket upgrades HTTP into one persistent, full-duplex line.
- REST, GraphQL, and gRPC are three answers to the same question — how should a client and server exchange data — each trading off differently: REST for ubiquity and caching, GraphQL for client-controlled shape, gRPC for raw server-to-server speed.
- Know the anatomy on both sides: a REST request is method + URL + headers + body; a response is status + headers + body. GraphQL replaces many endpoints with one typed schema. gRPC replaces a URL with a directly-callable method over binary protobuf.
- Status codes and retries are mechanical once you know the five families: 1xx/2xx/3xx are informational to fine, 4xx is your mistake (never retry), 5xx is the server's (retry might help).