Episode 1 — Fundamentals / 1.2 — Client Server Architecture

Interview Questions: Client-Server Architecture

Practice questions with model answers for client-server, HTTP, frontend/backend, hosting, and related topics commonly asked in software engineering interviews.

How to use this material (instructions)

  1. Read lessons in orderREADME.md, then 1.2.a1.2.g.
  2. Practice out loud — aim for 1–2 minutes per question, then compare to the model answer.
  3. Structure answers — definition → example → trade-off/security note.
  4. Pair with exercises1.2-Exercise-Questions.md.
  5. Quick review1.2-Quick-Revision.md.

Beginner (Q1–Q8)

Q1. What is client-server architecture?

Why interviewers ask: Tests whether you understand the most basic pattern that powers the web.

Model answer:

Client-server architecture is a distributed computing model where work is split between two roles:

  • Clients initiate requests — they ask for data, pages, or actions (e.g. a browser, a mobile app, a CLI tool).
  • Servers listen for those requests, process them (auth, business logic, database queries), and send back responses.

The client and server communicate over a network using protocols like HTTP/HTTPS. Many clients can connect to the same server; one client can talk to many servers over time. The most common architecture on the web is 3-tier: client → application server → database.

ASCII summary:

Client (browser/app)  ──request──►  Server (API/logic)  ──query──►  Database
                     ◄──response──                     ◄──data───

Q2. What is the difference between a client and a server?

Model answer:

AspectClientServer
RoleInitiates requests; displays UIListens, processes, responds
LocationUser's device (laptop, phone)Datacenter, cloud, managed platform
SoftwareBrowser, mobile app, CLINginx, Express, Django, database processes
Who initiates?Client always starts the conversationServer responds (may push via WebSockets/SSE)
Trust levelUntrusted — user can inspect/modify anythingTrusted — enforces rules, holds secrets
ExamplesChrome loading a pageNginx + Node.js API + PostgreSQL

Key distinction: The client is for experience (what the user sees); the server is for truth (who you are, what you're allowed to do, what data exists).


Q3. What is HTTP and how does the request/response cycle work?

Why interviewers ask: HTTP is the backbone of the web — this checks foundational knowledge.

Model answer:

HTTP (HyperText Transfer Protocol) is the application-layer protocol that browsers and servers use to exchange data. It is:

  • Stateless — each request is independent; the server doesn't remember previous requests
  • Text-based (HTTP/1.x) — human-readable headers
  • Request–response — client sends a request; server returns one response

The cycle:

  1. Client builds an HTTP request: method (GET/POST/PUT/DELETE), URL path, headers (Host, Accept, Cookie, Authorization), optional body
  2. Request travels over TCP (+ TLS for HTTPS)
  3. Server receives, parses, and processes the request (routing, auth, DB query, template rendering)
  4. Server sends an HTTP response: status code (200, 404, 500), headers (Content-Type, Cache-Control, Set-Cookie), body (HTML, JSON, image)
  5. Client handles the response — renders HTML, processes JSON, displays errors
Browser                               Server
   │                                     │
   │── GET /api/users HTTP/1.1 ────────►│
   │   Host: api.example.com            │
   │   Accept: application/json          │
   │                                     │  query DB, build response
   │◄── HTTP/1.1 200 OK ────────────────│
   │    Content-Type: application/json   │
   │    {"users": [...]}                 │

Q4. What happens when you type a URL in the browser and press Enter?

Why interviewers ask: The single most common "whole stack" question. Tests whether you can connect DNS, TCP, TLS, HTTP, and rendering.

Model answer (structured walkthrough):

  1. URL parsing — Browser splits the URL into scheme, host, path, query, fragment. Checks HSTS to force HTTPS if needed.
  2. DNS resolution — Resolve hostname to IP: browser cache → OS cache → router → ISP recursive resolver → root → TLD → authoritative nameserver.
  3. TCP connection — Three-way handshake: SYN → SYN-ACK → ACK (1 RTT).
  4. TLS handshake — If HTTPS: ClientHello → ServerHello + certificate + key exchange → encrypted channel (1 additional RTT with TLS 1.3).
  5. HTTP requestGET /path HTTP/1.1 with Host, cookies, Accept headers.
  6. Server processing — Route request → auth → business logic → DB query → build response.
  7. HTTP response — Status 200 + headers + HTML body (compressed with gzip/brotli).
  8. Parsing & rendering — HTML → DOM; CSS → CSSOM; DOM + CSSOM → Render Tree → Layout → Paint → Composite.
  9. Subresource loading — CSS, JS, images, fonts discovered during parsing → each triggers its own HTTP cycle.
  10. JavaScript execution — Scripts run; event listeners attached; API calls fired; page becomes interactive.

Total time: ~100–500ms on a fast connection; 3–8 seconds on slow 3G.


Q5. What is the difference between front-end and back-end?

Model answer:

DimensionFront-endBack-end
Also calledClient-sideServer-side
What it doesUI, interactions, animations, client validationBusiness logic, auth, database, API, security enforcement
Runs whereBrowser (or native app)Server, container, serverless function
LanguagesHTML, CSS, JavaScript/TypeScriptPython, Node.js, Java, Go, Ruby, PHP, C#, Rust
FrameworksReact, Vue, Angular, SvelteExpress, Django, Spring Boot, Rails, Laravel, FastAPI
SecurityXSS, token leaks, dependency supply chainSQL injection, auth bypass, secret management, SSRF

Restaurant analogy: Front-end is the dining room (ambiance, menu card, how the waiter speaks). Back-end is the kitchen (recipes, ingredients, food safety). The API is the waiter carrying orders and plates.

Full-stack means working across both — owning features from UI to database.


Q6. What is the difference between a static website and a dynamic website?

Model answer:

Static WebsiteDynamic Website
HTML producedPre-built files served as-isGenerated per request from code + data
Server workFile lookup onlyCode execution, DB queries, template rendering
PersonalizationNone at origin (can add via client JS or APIs)Natural (sessions, roles, per-user content)
SpeedVery fast (CDN-friendly, predictable)Variable (depends on server processing)
CostCheap at scale (no compute per request)Compute + DB costs scale with traffic
Content updatesRedeploy/rebuildUpdate data in DB, instant
ExamplesPortfolio, docs, blog, landing pageSocial feed, dashboard, e-commerce, SaaS

Modern spectrum: SSG (build-time static) → ISR (static + background regen) → SSR (per-request) → CSR (browser-rendered from API). Many sites mix models per route.


Q7. What is web hosting?

Model answer:

Web hosting is the service of storing your website's files and code on a server connected to the internet 24/7 so anyone can access them. The hosting provider gives you:

  • Server space (disk/SSD for files and databases)
  • Compute (CPU/RAM for server-side code)
  • Bandwidth (data transfer capacity)
  • Public IP (so the internet can reach your server)
  • Uptime guarantee (e.g. 99.9% = ~8.7 hours downtime/year)
  • Security (firewalls, DDoS protection, SSL certificates)

Types of hosting:

TypeOne-liner
SharedMany sites on one server; cheapest; limited control
VPSVirtual machine with guaranteed resources; root access
DedicatedEntire physical machine; maximum performance
CloudPool of virtual servers; scales on demand; pay-as-you-go
Static hostingFiles only, served via CDN (Vercel, Netlify, GitHub Pages)
PaaSPlatform manages infrastructure; you deploy code (Render, Heroku)
ServerlessFunctions run on demand; no idle cost (Lambda, Cloudflare Workers)

Domain + Hosting: A domain name (example.com) is the address; hosting is the building. DNS records (A, CNAME) connect the address to the building.


Q8. What is an API?

Model answer:

An API (Application Programming Interface) is a contract between two pieces of software — it defines what you can ask for and what format the answers come in. In web development, it usually means an HTTP API where the front-end sends requests to the back-end and receives structured data (usually JSON).

Common API styles:

StyleKey idea
RESTResources as URLs, standard HTTP methods, stateless, JSON responses
GraphQLSingle endpoint; client specifies exactly what data it wants; schema-driven
gRPCBinary protocol (Protocol Buffers); fast; strong typing; used for service-to-service
WebSocketPersistent two-way connection; real-time updates (chat, live feeds)

Intermediate (Q9–Q15)

Q9. What is the difference between HTTP and HTTPS?

Model answer:

  • HTTP sends data in plain text — anyone on the network path can read or alter it (man-in-the-middle attack).
  • HTTPS is HTTP over TLS — it provides encryption (confidentiality), integrity (tamper detection), and authentication (server proves identity via X.509 certificate).

The server needs a TLS certificate (often from Let's Encrypt, free). HSTS forces HTTPS even if the user types http://. Modern browsers mark HTTP-only sites as "Not Secure."


Q10. Explain the most common HTTP status codes.

Model answer:

CodeNameMeaning
200OKSuccess; body contains the result
201CreatedResource created successfully; often includes Location header
204No ContentSuccess; no body (e.g. delete succeeded)
301Moved PermanentlyResource has a new permanent URL (SEO: update links)
302FoundTemporary redirect
304Not ModifiedCached copy is still valid; use it
400Bad RequestMalformed request (missing fields, bad syntax)
401UnauthorizedAuthentication required or failed ("who are you?")
403ForbiddenAuthenticated but not allowed ("I know who you are; you can't")
404Not FoundResource doesn't exist
429Too Many RequestsRate limited; often includes Retry-After
500Internal Server ErrorServer bug/crash
502Bad GatewayProxy/gateway got invalid response from upstream
503Service UnavailableOverload or maintenance

401 vs 403: 401 = authentication problem (missing/invalid credentials). 403 = authorization problem (credentials are valid but you're not allowed).


Q11. What is CORS?

Model answer:

CORS (Cross-Origin Resource Sharing) is a browser-enforced security mechanism based on the Same-Origin Policy. Browsers block JavaScript from reading responses from a different origin unless the server explicitly allows it.

An "origin" is defined by: scheme + host + port (e.g. https://app.example.com:443).

How it works:

  1. Browser sends request with Origin header
  2. For "non-simple" requests (custom headers, PUT/DELETE, etc.), browser sends an OPTIONS preflight first
  3. Server responds with Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers
  4. If the response headers allow the origin, browser lets JavaScript access the response

Key point: CORS is a browser constraint. curl, Postman, and server-to-server calls are not restricted by CORS.


Q12. What is the difference between cookies, localStorage, and sessionStorage?

Model answer:

CookieslocalStoragesessionStorage
Size~4KB per cookie~5–10MB~5–10MB
Sent with requestsYes (automatically via Cookie header)No (must be sent manually in JS)No
ExpirationExpires/Max-Age or sessionNever (persists until cleared)Tab/window close
Accessible fromServer (via headers) + client (JS, unless HttpOnly)Client JS onlyClient JS only
Use caseSessions, auth tokens, trackingUser preferences, cached dataTemporary form data

Security: Cookies with HttpOnly cannot be accessed by JavaScript (protects against XSS). Always use Secure (HTTPS only) and SameSite (CSRF protection).


Q13. Explain the browser rendering pipeline.

Model answer:

When the browser receives HTML, it goes through the critical rendering path:

  1. Parse HTML → Build DOM (Document Object Model) tree
  2. Parse CSS → Build CSSOM (CSS Object Model) tree
  3. Combine DOM + CSSOM → Render Tree (only visible elements)
  4. Layout (Reflow) → Calculate size and position of every element
  5. Paint → Fill in pixels: colors, text, borders, shadows, images
  6. Composite → Assemble painted layers; send final frame to screen (GPU-accelerated)

Blocking resources:

  • CSS is render-blocking — browser won't paint until CSSOM is built
  • JS (without async/defer) is parser-blocking — HTML parsing stops while script downloads and executes

Q14. What is the difference between SSR, CSR, SSG, and ISR?

Model answer:

ApproachHTML producedFreshnessBest for
SSR (Server-Side Rendering)Per request on serverHigh (live data)Dynamic pages, SEO + personalization
CSR (Client-Side Rendering)In the browser via JSDepends on API callsSPAs, authenticated app interiors
SSG (Static Site Generation)At build timeStale until rebuildDocs, blogs, marketing pages
ISR (Incremental Static Regen)Static + background revalidationTunableMostly-static with occasional updates

Modern meta-frameworks (Next.js, Nuxt, SvelteKit) let you choose per route.


Q15. What is a CDN and how does it improve performance?

Model answer:

A CDN (Content Delivery Network) is a network of servers distributed worldwide. Your files are copied to edge locations so users are served from the nearest server.

How it helps:

  • Lower latency — shorter physical distance = shorter RTT
  • Offload origin — fewer requests reach your actual server
  • Caching — static assets served from edge without origin work
  • DDoS absorption — distributed infrastructure absorbs attacks
  • TLS termination at edge — handshake with nearby server

Without CDN: User in Tokyo → crosses ocean → US server → 200ms RTT. With CDN: User in Tokyo → nearby Tokyo edge → 10ms RTT.


Advanced (Q16–Q20)

Q16. What are WebSockets, and how do they differ from HTTP?

Model answer:

WebSockets provide a persistent, full-duplex communication channel over a single TCP connection. Unlike HTTP's request-response model, both client and server can send messages at any time without the other asking.

HTTPWebSocket
ModelRequest → Response (client initiates)Full-duplex (both sides send freely)
ConnectionShort-lived (or keep-alive for reuse)Long-lived (stays open)
OverheadHeaders on every request/responseMinimal framing after initial handshake
Use caseCRUD, page loads, APIsChat, live feeds, gaming, real-time dashboards

How it starts: A WebSocket begins as an HTTP request with Upgrade: websocket header. If the server agrees (101 Switching Protocols), the connection upgrades to WebSocket protocol.

Alternative: Server-Sent Events (SSE) — one-way server → client push over HTTP. Simpler than WebSockets when you only need server-to-client updates.


Q17. How would you design the architecture for a web application that needs to handle 10 million users?

Model answer (framework):

  1. CDN at the edge for static assets + DDoS protection
  2. Load balancer distributing traffic across multiple app servers
  3. Stateless app servers (horizontal scaling; session state in Redis, not in memory)
  4. Database layer: primary + read replicas; sharding for write scale; connection pooling
  5. Caching: Redis/Memcached for hot data (user sessions, feed results, config)
  6. Async processing: Message queues (Kafka, RabbitMQ, SQS) for emails, notifications, analytics
  7. Search: Elasticsearch/Typesense for full-text search
  8. Monitoring: Metrics (Prometheus), logs (ELK), tracing (Jaeger), alerting
  9. Auto-scaling: Scale app servers by CPU/latency; scale workers by queue depth
Users → CDN → Load Balancer → App Servers (stateless)
                                    │
                          ┌─────────┼─────────┐
                          ▼         ▼         ▼
                        Cache    Primary DB  Message Queue
                        (Redis)  (+ replicas)    │
                                                 ▼
                                            Async Workers

Q18. What is the difference between monolithic and microservices architecture?

Model answer:

MonolithMicroservices
StructureOne codebase, one deployment unitMany small, independent services
DeploymentDeploy everything togetherDeploy each service independently
ScalingScale the entire appScale individual services
CommunicationIn-process function callsNetwork calls (HTTP, gRPC, message queues)
ComplexitySimpler to start; harder to scaleHarder to start; easier to scale
Team structureOne team can own it allService per team (Conway's Law)
Best forMVPs, small teams, early stageLarge orgs, complex domains, independent scaling needs

Key insight: Start monolithic; extract services when you have a clear reason (scaling bottleneck, team independence, deployment isolation). Premature microservices add network complexity, debugging difficulty, and operational overhead.


Q19. What is REST, and what makes an API "RESTful"?

Model answer:

REST (Representational State Transfer) is an architectural style for APIs, defined by Roy Fielding. A RESTful API typically follows these conventions:

PrincipleWhat it means
Resources as URLs/users/42, /products, /orders/99/items
Standard HTTP methodsGET = read, POST = create, PUT = replace, PATCH = update, DELETE = remove
StatelessEach request contains all info needed; server doesn't store client state between requests
RepresentationsResources can have multiple formats (JSON, XML); client uses Accept header
HATEOAS (ideal)Responses include links to related actions (rarely implemented fully in practice)

Example:

GET    /api/users         → list users
GET    /api/users/42      → get user 42
POST   /api/users         → create a user (body: JSON)
PUT    /api/users/42      → replace user 42
PATCH  /api/users/42      → partially update user 42
DELETE /api/users/42      → delete user 42

Q20. How do you secure a web application? Name at least 5 security practices.

Model answer:

PracticeWhat it prevents
HTTPS everywhereEavesdropping, tampering, MITM attacks
Input validation + parameterized queriesSQL injection, command injection
Output encodingXSS (Cross-Site Scripting)
CSRF tokensCross-Site Request Forgery
Authentication (bcrypt, OAuth, MFA)Unauthorized access
Authorization checks on every requestPrivilege escalation, IDOR
HttpOnly + Secure + SameSite cookiesCookie theft via XSS, CSRF
Rate limitingBrute force, abuse
CORS configurationUnauthorized cross-origin access
Dependency scanningSupply chain attacks
Content Security Policy (CSP)Inline script injection
Secrets management (never in client code)API key / credential leakage

Rule of thumb: Never trust the client. Validate on the server. Defense in depth.


Quick-Fire (Yes / No + one line)

QuestionAnswerOne-line rationale
Can a machine be both client and server?YesLocal dev: browser (client) talks to localhost server on same machine.
Is HTTP stateless?YesEach request is independent; state is added via cookies/tokens/sessions.
Does CORS apply to curl or Postman?NoCORS is enforced by browsers only.
Is 403 always "you're logged in but forbidden"?NoSome APIs misuse 403 for unauthenticated; RFC prefers 401 for that.
Can a static site have interactive features?YesClient-side JS + external API calls; the initial document is static.
Is serverless really "no servers"?NoServers exist; you just don't manage them.
Should you validate input on the client AND server?YesClient for UX; server for security (client can be bypassed).
Is GraphQL a replacement for REST?NoIt's an alternative with different trade-offs (flexibility vs complexity).

Interview Tips

  1. Start high-level, then drill down. Offer a skeleton answer first; ask if they want more depth on a specific part.
  2. Use real examples. "When I load Twitter..." is more convincing than abstract descriptions.
  3. Draw diagrams. Even in a text-based interview, describe what you would draw: "Imagine the browser on the left, server on the right, arrows for request and response."
  4. Name the trade-offs. "Static sites are fast and cheap but lack personalization" shows depth.
  5. Mention security. For any client-server question, note that the server is the trust boundary. "Never trust the client" is always a good line.
  6. Know HTTP status codes. 200, 201, 301, 304, 400, 401, 403, 404, 500, 502, 503 — memorize these.
  7. Understand the rendering pipeline. DOM → CSSOM → Render Tree → Layout → Paint → Composite. This shows you understand how browsers actually work.

Use this alongside the 1.2 Exercise Questions for hands-on practice and deeper review.