04. Clients, Servers & APIs

Learning goals

By the end of this lesson you will be able to:

  • Trace the full lifecycle of a request from browser tap to database and back
  • Explain the roles of client, server, API, and database in plain language
  • Design REST-style HTTP APIs with sensible URLs, verbs, status codes, and JSON bodies
  • Understand when GraphQL, gRPC, WebSockets, and webhooks appear (awareness level)
  • Apply authentication, idempotency, pagination, and versioning patterns
  • Write API specs suitable for system design interviews (LLD section)
  • Avoid common API design mistakes that cause pain at scale

Client and server โ€” the basics

Everyday analogy: ordering at a restaurant

RoleRestaurantSoftware
ClientYou (the customer)Browser, mobile app, IoT device
ServerKitchen + wait staffAPI server running business logic
Request"I'll have the pasta, no onions"GET /api/v1/feed or POST /api/v1/orders
ResponsePlate of food (or "we're out of pasta")JSON data + HTTP status code
DatabasePantry / inventory ledgerPostgreSQL, MongoDB, etc.

The client initiates. The server responds. The client never talks to the database directly in a typical web app โ€” the server is the gatekeeper.

Basic request flow

What each piece does

ComponentResponsibilityStateless or stateful?
ClientUI, local state, initiates requestsHolds user session token locally
Server (API)Auth, validation, business rules, orchestrationShould be stateless (see below)
DatabaseDurable storage, queries, transactionsStateful โ€” source of truth

The full request lifecycle (step by step)

When you tap "Refresh" on a social feed, more happens than you might think:

StepWhat happensFailure mode
1. DNS lookupDomain โ†’ IP addressDNS outage โ†’ app unreachable
2. TLS handshakeEncrypted connection establishedCertificate expired โ†’ browser warning
3. Load balancerPicks a healthy app serverAll backends down โ†’ 503
4. AuthServer validates tokenInvalid token โ†’ 401 Unauthorized
5. Business logicQuery cache or DBDB timeout โ†’ 500 or degraded response
6. ResponseJSON back to clientMalformed JSON โ†’ client parse error

Understanding this lifecycle helps you debug ("is it DNS? LB? auth? DB?") and design (where does caching fit? where is auth checked?).


Stateless app servers (critical concept)

A stateless app server does not store user-specific data in its own memory between requests. Any server can handle any request.

Library desk analogy

Stateful (bad for scale): One librarian remembers your account in their head. You must always go to that librarian.

Stateless (good for scale): Any librarian can help you โ€” they look up your account in the shared system (database/Redis) using your library card (JWT/session ID).

Why stateless matters:

BenefitExplanation
Horizontal scalingAdd more servers; LB distributes freely
Easy failoverServer dies โ†’ LB routes to others; no lost in-memory sessions
Simple deploysKill old servers, start new ones; no session migration
Predictable loadAny server can serve any user

Session data lives in Redis or the database, not in server RAM alone.


What is an API?

An API (Application Programming Interface) is the contract between client and server:

  • Which URLs exist
  • What data you send (request body, headers, query params)
  • What data you get back (response body, status codes)
  • What errors look like

Post office analogy

The API is like the official form at the post office:

  • Form number 1040 = "Register a package" โ†’ POST /api/v1/parcels
  • Required fields: sender, recipient, weight โ†’ request JSON schema
  • You get back a tracking number โ†’ response { "trackingId": "..." }
  • If weight exceeds limit โ†’ error 400 with message "Max weight 30kg"

If the post office changes the form without telling anyone (breaking change), customers' automated systems break. Same with APIs โ€” hence versioning.

Properties of good APIs

PropertyWhat it meansExample
Predictable namingConsistent URL patterns/users/:id/posts, not /getUserPosts?id=
Correct HTTP verbsGET reads, POST creates, etc.Never GET /deleteUser/42
Explicit errorsMachine-readable error codes + human message{ "error": "INVALID_URL", "message": "..." }
VersionedBreaking changes don't break old clients/api/v1/... vs /api/v2/...
DocumentedRequest/response examples existOpenAPI/Swagger spec
Paginated listsNever return unbounded arrays?cursor=abc&limit=20

REST-style APIs (deep dive for beginners)

REST (Representational State Transfer) is the most common API style for web and mobile apps. It models the world as resources (nouns) manipulated by HTTP verbs (actions).

Resources + verbs

HTTP VerbMeaningSafe?Idempotent?Example
GETRead a resourceYesYesGET /users/42
POSTCreate a new resourceNoNoPOST /urls
PUTReplace entire resourceNoYesPUT /users/42
PATCHPartial updateNoNo*PATCH /users/42
DELETERemove resourceNoYesDELETE /posts/9
  • Safe = doesn't change server state (GET should never delete data)
  • Idempotent = calling twice has the same effect as calling once (important for retries โ€” covered later)

*PATCH idempotency depends on implementation; design it to be idempotent when possible.

URL design principles

Do โœ…Don't โŒWhy
/users/42/posts/getUserPosts?userId=42Nouns in URLs; verbs are HTTP methods
/api/v1/urls/api/createUrlResource-oriented
Plural nouns: /notes/noteConvention; pick one and stay consistent
POST /users (create)POST /createUserPOST to collection creates a member

Worked example: URL shortener API

Create a short URL:

POST /api/v1/urls
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

{
  "longUrl": "https://example.com/very/long/path?page=1",
  "customAlias": "my-link",
  "expiresAt": "2027-01-01T00:00:00Z"
}

Success response:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/urls/aZ9kQ2

{
  "shortCode": "aZ9kQ2",
  "shortUrl": "https://short.ly/aZ9kQ2",
  "longUrl": "https://example.com/very/long/path?page=1",
  "createdAt": "2026-08-06T14:30:00Z"
}

Redirect (separate endpoint โ€” often no auth):

GET /aZ9kQ2

HTTP/1.1 302 Found
Location: https://example.com/very/long/path?page=1

Error response:

HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "error": "ALIAS_TAKEN",
  "message": "Custom alias 'my-link' is already in use"
}

Common HTTP status codes

CodeMeaningWhen to use
200 OKSuccess (read/update)GET /users/42 found
201 CreatedResource createdPOST /urls success
204 No ContentSuccess, empty bodyDELETE /posts/9
400 Bad RequestClient sent invalid dataMissing required field
401 UnauthorizedNot authenticatedMissing or expired token
403 ForbiddenAuthenticated but not allowedUser trying to delete someone else's post
404 Not FoundResource doesn't existGET /users/99999
409 ConflictState conflictDuplicate alias
429 Too Many RequestsRate limitedToo many requests per minute
500 Internal Server ErrorServer bugUnhandled exception
503 Service UnavailableTemporarily downMaintenance or overload

In system design interviews, mention status codes for main error paths โ€” it shows you think about the full contract.


Other API styles (awareness)

You won't design these in every interview, but you should recognize when they appear:

StyleTransportBest forTrade-off
REST + JSONHTTPMost web/mobile apps, public APIsSimple; sometimes over-fetching
GraphQLHTTP (usually POST)Mobile apps needing flexible queriesClient specifies exact fields; server complexity
gRPCHTTP/2, binary (Protobuf)Internal microservice communicationFast, typed; not browser-friendly natively
WebSocketsPersistent TCP connectionReal-time chat, live sports scores, gamingBidirectional; connection management at scale
WebhooksHTTP POST to your URLEvent notifications (payment succeeded, CI finished)Server pushes to you; you must handle retries

When to mention each in an interview

ScenarioRecommended style
URL shortener, notes app, basic CRUDREST
Instagram mobile app (feed + profile + comments in one screen)GraphQL often wins
Payment service โ†” fraud detection servicegRPC
Chat app message deliveryWebSockets (or long polling as simpler fallback)
Stripe telling your server "payment completed"Webhook

For beginners and most case studies in this course, HTTP JSON REST APIs are the default. Mention alternatives when the use case clearly calls for them.


Designing APIs for system design interviews

In the LLD section of an interview, write:

  1. Endpoint list โ€” method + path + one-line description
  2. Request / response JSON โ€” for 2โ€“3 key endpoints
  3. Status codes โ€” for main success and error cases
  4. Auth method โ€” who can call what

Example LLD: Notes app API

POST   /api/v1/notes              Create a note
GET    /api/v1/notes/:id          Get a single note
GET    /api/v1/notes?limit=20     List my notes (paginated)
PATCH  /api/v1/notes/:id          Update note title/body
DELETE /api/v1/notes/:id          Delete a note

Auth: JWT Bearer token on all endpoints except none (all require login)

Create note:

POST /api/v1/notes
Request:
{
  "title": "Grocery list",
  "body": "Milk, eggs, bread"
}

Response 201:
{
  "id": "note_8x7kQ",
  "title": "Grocery list",
  "body": "Milk, eggs, bread",
  "createdAt": "2026-08-06T10:00:00Z",
  "updatedAt": "2026-08-06T10:00:00Z"
}

Errors:
  400 โ€” missing title or body
  401 โ€” not authenticated
  413 โ€” body exceeds 100 KB limit

Authentication (auth)

Authentication = verifying who is calling.
Authorization = verifying what they're allowed to do.

Highway toll analogy

  • Authentication: Showing your transponder โ€” the system knows which car you are
  • Authorization: Some lanes are HOV-only โ€” being identified isn't enough; you need 2+ passengers

Common auth patterns

PatternHow it worksBest for
None (public)No auth header requiredPublic URL redirects, read-only public data
API keyX-API-Key: abc123 in headerServer-to-server, developer APIs
Session cookieServer sets cookie after login; browser sends automaticallyTraditional web apps
JWT (Bearer token)Authorization: Bearer eyJ...Mobile apps, SPAs, microservices
OAuth 2.0Delegate auth to Google/GitHub/etc."Sign in with Google"
mTLSClient and server both present certificatesHigh-security service-to-service

Quick auth map for system design

Endpoint typeTypical auth
Public read (URL redirect)None
User actions (create post, send message)JWT or session cookie
Admin actions (ban user, view all data)JWT + role check (admin)
Service-to-service (payment โ†’ ledger)mTLS or signed internal token
Third-party developer APIAPI key + rate limiting

In interviews, one sentence is enough: "User-facing endpoints require JWT; the redirect endpoint is public; internal services use mTLS."

Go deeper: 17. Authentication & Authorization โ€” OAuth flows, token lifetimes, RBAC vs ownership, and where auth checks live in an HLD.


Idempotency (critical for reliability)

Idempotency means: calling an operation multiple times has the same effect as calling it once.

Why it matters: the double-charge problem

Without idempotency, network retries double-charge the customer.

Idempotency key pattern

POST /api/v1/payments
Idempotency-Key: unique-key-from-client-uuid
Content-Type: application/json

{ "amount": 5000, "currency": "usd" }

Server logic:

  1. Check if Idempotency-Key was seen before
  2. If yes โ†’ return the stored result (don't re-process)
  3. If no โ†’ process payment, store result keyed by idempotency key
HTTP MethodNaturally idempotent?
GETYes
PUTYes (replace same resource)
DELETEYes (delete twice = still deleted)
POSTNo โ€” always use idempotency keys for critical POSTs
PATCHOften no โ€” design carefully

Rule of thumb: Any POST that moves money, sends email, or creates an irreversible side effect needs an idempotency key.


Pagination (never return unbounded lists)

Returning SELECT * FROM posts for a user with 100,000 posts will:

  • Slow down the database
  • Blow up response size
  • Timeout the client

Offset pagination (simple but flawed at scale)

GET /api/v1/feed?offset=40&limit=20

Returns items 41โ€“60.

ProsCons
Easy to implementSlow for large offsets (OFFSET 100000)
Supports "jump to page 5"Inconsistent if new items inserted while paginating

Cursor pagination (preferred at scale)

GET /api/v1/feed?cursor=eyJpZCI6MTIzfQ&limit=20

Cursor = opaque token encoding "last seen item" (often base64 of { "createdAt": "...", "id": 123 }).

Response includes next cursor:

{
  "items": [ ... ],
  "nextCursor": "eyJpZCI6MTQzfQ",
  "hasMore": true
}
ProsCons
Consistent performance at any depthNo arbitrary page jumping
Stable if new items addedSlightly more complex

Interview default: Recommend cursor-based for feeds, timelines, and message history.


API versioning

APIs change. Versioning prevents breaking existing clients.

Strategies

StrategyExampleProsCons
URL path/api/v1/users, /api/v2/usersObvious, easy to routeURL clutter
HeaderAccept: application/vnd.myapp.v2+jsonClean URLsHarder to test in browser
Query param/api/users?version=2SimpleEasy to forget

Recommendation for beginners: URL path versioning (/api/v1/...) โ€” clearest in diagrams and interviews.

What counts as a breaking change?

Breaking (needs new version)Non-breaking (same version OK)
Removing a fieldAdding a new optional field
Renaming a fieldAdding a new endpoint
Changing field typeAdding a new optional query param
Changing error codesAdding a new error code

Worked example: Chat app API (interview LLD)

WebSocket: wss://api.chatapp.com/v1/ws
  โ€” Persistent connection for real-time message delivery
  โ€” Client sends/receives JSON frames

REST endpoints:

POST   /api/v1/messages           Send message (also via WebSocket)
GET    /api/v1/messages?cursor=   Message history (paginated)
GET    /api/v1/users/:id/presence Online/offline status
POST   /api/v1/auth/login         Login, receive JWT

Send message (REST fallback):

POST /api/v1/messages
Authorization: Bearer eyJ...

Request:
{
  "recipientId": "user_456",
  "body": "Hey, are you free tonight?"
}

Response 201:
{
  "messageId": "msg_abc123",
  "senderId": "user_789",
  "recipientId": "user_456",
  "body": "Hey, are you free tonight?",
  "sentAt": "2026-08-06T18:00:00Z",
  "status": "delivered"
}

WebSocket frame (real-time):

{
  "type": "message.new",
  "payload": {
    "messageId": "msg_abc123",
    "senderId": "user_789",
    "body": "Hey, are you free tonight?",
    "sentAt": "2026-08-06T18:00:00Z"
  }
}

Note how REST handles CRUD/history while WebSockets handle real-time push โ€” a common hybrid pattern.


Common API design mistakes

MistakeProblemFix
Verbs in URLsPOST /createUserPOST /users
GET that mutates stateGET /deletePost/9DELETE /posts/9
No paginationReturning 50,000 itemsCursor pagination with limit
No idempotency on POST paymentsDouble-charge on retryIdempotency-Key header
Generic 500 for everythingClients can't handle errorsSpecific 4xx codes with error bodies
No versioning planBreaking mobile apps on deploy/api/v1/ from day one
Leaking internal IDsSequential IDs enable scrapingUse UUIDs or public IDs
No rate limitingAbuse, DDoS, runaway costs429 + rate limit headers
Returning stack tracesSecurity leakGeneric 500 message; log details server-side

Check your understanding

Question 1

Why prefer stateless app servers? What do you do with session data instead?

Question 2

What HTTP verb and URL pattern should you use to fetch a single user with id 42?

Question 3

Why is idempotency critical for payment APIs? Describe the idempotency key pattern.

Question 4

What's the difference between authentication and authorization? Give an example of each.

Question 5

Offset pagination vs cursor pagination โ€” when prefer cursors?

Question 6

You're designing a chat app. Would you use REST, WebSockets, or both? Why?

Question 7

A client receives 403 Forbidden on DELETE /api/v1/posts/9. What likely happened?

Question 8

Name two breaking API changes that would require a new version.

Detailed answers

1. Stateless app servers

Stateless servers let the load balancer send any request to any server. Benefits: easy horizontal scaling, painless failover, simple deploys.

Session data (login state, shopping cart) goes in a shared store โ€” Redis or the database โ€” keyed by session ID or JWT. The server reads it per request but doesn't own it in local RAM.

2. Fetch user 42

GET /api/v1/users/42

GET because it's a read. Noun (users) in the URL. ID in the path. No verb in the URL.

3. Idempotency for payments

Network failures cause clients to retry requests. Without idempotency, POST /payments run twice charges the customer twice.

Idempotency key pattern: Client sends a unique Idempotency-Key header (UUID). Server checks if it's seen this key: if yes, return the cached result; if no, process and store the result. Retries become safe.

4. Auth vs authorization

  • Authentication: Proving identity. Example: logging in with email/password and receiving a JWT.
  • Authorization: Proving permission. Example: user is logged in (authenticated) but tries to delete another user's post โ†’ 403 Forbidden (not authorized).

5. Cursor vs offset pagination

Prefer cursor pagination for:

  • Large datasets (feeds, timelines, message history)
  • Real-time data where items are inserted during pagination
  • When consistent performance matters (offset 100,000 is slow in SQL)

Offset is fine for small admin tables or when users need "jump to page 5."

6. Chat app โ€” REST + WebSockets

Both:

  • WebSockets for real-time message delivery (push to recipient instantly)
  • REST for history (GET /messages?cursor=), login, profile, and as a fallback send mechanism

Pure REST requires polling ("any new messages? any new messages?") which is wasteful at scale.

7. 403 on DELETE /posts/9

The user is authenticated (otherwise 401) but not allowed to delete this post. Likely: they're trying to delete someone else's post, or their account lacks permission (e.g., not a moderator).

8. Breaking changes requiring new version

Any two of:

  • Removing a response field clients depend on
  • Renaming userId to user_id
  • Changing createdAt from string to integer timestamp
  • Changing 200 success to 204 with empty body for an endpoint that previously returned data
  • Removing an endpoint entirely

Non-breaking: adding a new optional field, adding a new endpoint.


Next: How DNS Resolution Works โ€” how api.myapp.com becomes an IP.

Then: HTTP & the Network Path โ†’ Load Balancing.