Skip to content

Client-Server Architecture and Its Variants ​

"Separation of concerns is the principle behind the client-server constraints." — Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, PhD dissertation, UC Irvine, 2000, §3.4.1

Summary: Client-server splits a system into components that ask (clients) and components that answer (servers) so each can change, scale and fail on its own; almost every other style in this path is a refinement of it, and almost every production bug at the boundary comes from forgetting where the state lives. Focus: The style and its roles, two-/three-/n-tier layouts, thick and thin clients, stateless servers and the six places state can live, request-response versus push (polling, long polling, SSE, WebSocket, gRPC streaming), HTTP semantics that matter (methods, idempotency, caching, conditional requests, content negotiation), API styles, peer-to-peer as the contrast, SPA/SSR/hypermedia, mobile and offline-first, security at the boundary, load balancing and session affinity, client-server inside microservices, and API evolution, with Go (net/http) and Laravel 13 code and one order-tracking page built three ways. Learning goal: Given a feature, say which side owns which state, pick request-response or a push channel with a reason, name the HTTP mechanism (method, header, status code) that makes it safe to retry and cache, and explain what changes when the server is one process, many replicas, or a fleet of microservices.

This chapter belongs to the Architecture Styles group. It teaches the style and its variants; the wire-level mechanics live in the System Design networking chapters and are linked, not repeated. The layered inside of a server is in Layered Monolithic Architecture; how services call each other is in Service Communication; how a style differs from a pattern is in Styles vs Patterns.

Page map ​

If you are looking forGo to
The whole page in a few tablesEverything in one minute
Why the style exists and what it costsWhy it exists
Fielding, Shaw and Garlan, Tanenbaum, HTTPWhere it comes from
Roles, request-response, separation of concernsThe style
Two-tier, three-tier, n-tierTiers
Thick versus thin clientsThick and thin clients
Sessions, tokens, where state livesStateless servers
Polling, long polling, SSE, WebSocket, gRPC streamsRequest-response vs push
Methods, idempotency, ETag, 304, AcceptClient-server over HTTP
REST, gRPC, GraphQLAPI styles
The opposite stylePeer-to-peer
SPA, SSR, Inertia, Livewire, HTMXRendering models
Mobile, sync, conflictsMobile and offline-first
Authentication, TLS, CORS, CSRFSecurity at the boundary
Replicas, sticky sessionsLoad balancing
Services calling servicesInside microservices
Versioning, compatibilityEvolution
Retry, timeouts, 429, 503Mechanics and Solving the classic problems
Which option whenChoosing
Go server and clientGo
Laravel API, Sanctum, SSE, ReverbLaravel
Order tracking three waysWorked example
Monolith to distributedIn architecture
Hands-on exerciseLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
ClientThe side that starts a conversationBrowser, mobile app, another serviceNobody knows who may initiate
ServerThe side that waits and answers; owns the data and the rulesGET /orders/42 handlerRules scattered across every client
Request-responseOne question, one answer, then the exchange is overHTTP GET returns 200Fine for fetching; wrong for "tell me when it changes"
TierA deployable layer of the systemBrowser, app server, databaseLogic mixed with storage or UI
Thin clientLittle logic; the server decides and rendersServer-rendered pageSlow UI on poor networks
Thick clientMuch logic runs on the deviceMobile app with local databaseLogic duplicated and hard to update
Stateless serverNeeds nothing remembered from the previous requestBearer token carries the identityCannot add replicas freely
PushThe server sends without being asked each timeSSE, WebSocketClients hammer the server with polling
IdempotentRepeating it has the same effect as doing it oncePUT, DELETE, GETA retry charges the card twice
Conditional request"Send it only if it changed"If-None-Match then 304Full payload every poll
API styleThe shape of the contractREST, gRPC, GraphQLContract arguments in every code review
Offline-firstThe app works without a connection and syncs laterNotes app on a trainLost data and "no network" screens

The style in one table.

QuestionAnswer
Who starts a conversation?The client, always (except push channels the client opened)
Who owns the data and the rules?The server
How does it scale?More server replicas behind a load balancer; the client scales with its users for free
What does it cost?A network between the two, so latency, partial failure and a contract that must evolve
What is the main design question?Where does state live (client, server memory, shared store, database)?

Seven ways to learn about a change.

OptionDirectionConnectionTypical latencyTypical use
Short pollingclient asks repeatedlynew request each timeup to one intervalorder status every 10 s
Long pollingclient asks, server holdsrequest parked up to ~25 snear real timechat on hostile networks
SSE (Server-Sent Events)server to clientone long GETnear real timenotifications, progress, LLM tokens
WebSocketboth waysone upgraded TCP connectionnear real timechat, collaborative editing, games
gRPC server streamingserver to clientone HTTP/2 streamnear real timeinternal feeds
gRPC bidirectional streamingboth waysone HTTP/2 streamnear real timeinternal real-time pipelines
Webhookserver to a server URLone POST per eventsecondspayment provider tells you a payment settled

Why it exists ​

Before client-server, the program, the user interface and the data lived on one machine (a mainframe with terminals, or a desktop with a file). Two things broke that: many users needed the same data, and the machine on the desk became more powerful than the one in the machine room. Splitting the system lets the data and rules live once, in a place you operate, while the interface lives wherever the user is.

Without the split (everything local)With the split (client-server)
Each user has a private copy; sharing means copying filesOne source of truth; every client sees the same order
Updating means reinstalling everywhereFix the server once; clients stay the same
Security is the user's laptopSecrets and checks live on a machine you control
Free from network failureA network sits in the middle: latency and partial failure are now part of design
Scales by buying bigger desksScales by replicating servers

The analogy we reuse: a restaurant. The customer (client) looks at a menu and places an order; the kitchen (server) owns the recipes, the stock and the stove. The waiter is the protocol. If every customer had to know the recipes, you would have a thick client and a very chaotic kitchen. If the waiter must remember "table 5 wanted it spicy" instead of writing it on the slip, the restaurant cannot add waiters freely: that is a stateful server.

Three common misunderstandings, up front ​

  1. "Client-server means a browser talking to a web server." No. Fielding's definition is about components and constraints; a mobile app, a CLI, a cron job and your own billing service are all clients. The browser is one client among many.
  2. "Stateless means the system stores nothing." No. The server process keeps nothing between requests; the state moved to the client, a shared store or the database. The system is full of state.
  3. "Push needs WebSocket." No. For one-way updates SSE is simpler, cheaper to operate and reconnects by itself; plain polling with 304 is simpler still and is often enough.

Where it comes from ​

Mainframes to client-server, 1980s. Terminals sent keystrokes to a central computer. Personal computers and local networks made two-tier systems common: a desktop program speaking SQL directly to a database server. The 1990s added the web and the three-tier shape: browser, application server, database.

Shaw and Garlan, 1996. Mary Shaw and David Garlan's Software Architecture: Perspectives on an Emerging Discipline listed client-server among the common architectural styles (alongside pipes and filters, layered systems and others) and framed a style as a family of systems with a vocabulary of components and connectors, and constraints on how to combine them (secondary source for this page: the book was not fetched, so nothing is quoted from it). This is the sense in which this chapter uses "style"; see Styles vs Patterns.

Fielding, 2000. In chapter 3 of his dissertation, Fielding builds the Web's style by adding constraints one at a time: client-server first, then stateless, cache, uniform interface, layered system and optional code-on-demand. The chapter text we read:

"The client-server style is the most frequently encountered of the architectural styles for network-based applications." — Fielding, dissertation, §3.4.1 (saved text: fielding-ch3)

"A proper separation of functionality should simplify the server component in order to improve scalability. This simplification usually takes the form of moving all of the user interface functionality into the client component. The separation also allows the two types of components to evolve independently, provided that the interface doesn't change." — Fielding, §3.4.1

Tanenbaum and van Steen (Distributed Systems: Principles and Paradigms; secondary source for this page) describe the same idea as application layering, with multi-tiered architectures, and discuss stateless versus stateful servers as a design axis. We use their vocabulary (tiers, stateless and stateful servers) and cite them as the textbook reference, not as quotations.

HTTP. The protocol that carries most client-server traffic today is specified in RFC 9110 (HTTP Semantics, June 2022), which describes HTTP as a "stateless request/response protocol" (§3.4, saved text: rfc9110). RFC 9111 (HTTP Caching) is its sibling. Server push beyond request-response arrived as Server-Sent Events (WHATWG HTML Standard) and WebSocket (RFC 6455, December 2011).

text
     Year   Idea                                    What changed in practice
1    1960s  Terminal to mainframe                   All logic central, dumb client
2    1980s  Two-tier: desktop app + SQL server      Rich clients, shared database
3    1990s  Web: browser + app server + DB          Three tiers, thin client, HTTP
4    2000   Fielding's REST constraints              Stateless + cache + uniform interface
5    2010s  SPAs, mobile apps, JSON APIs            Thick clients again, API-first
6    2011   WebSocket (RFC 6455), SSE                Push without polling
7    2020s  Server-driven UI (Inertia, Livewire, HTMX) A swing back to the server, with islands of interactivity

The concept catalogue ​

The client-server style {#style} Must-know ​

In plain words: Two kinds of component: one asks, one answers. The asker does not need to know how the answerer works, only what it can be asked.

Common misunderstanding: "The server is the powerful machine and the client is the weak one." Power is irrelevant. A server is defined by its role: it owns a resource and responds. Your laptop becomes a server the moment it listens on a port.

Definition: A style in which a client component initiates requests over a connector and a server component, which owns the resources and the rules to change them, answers. Fielding derives it from separation of concerns: the user interface goes to the client, data storage and business rules to the server. Everything else (HTTP, gRPC, SQL wire protocol, SMTP) is a choice of connector.

text
     Client                                      Server
1    open connection (TCP + TLS)           ->
2    send request (method, target, headers) ->
3                                                authenticate, authorize, validate
4                                                read or change state (DB, cache)
5                                          <-    response (status, headers, body)
6    interpret, update UI                         forget the request (stateless)

Real scenarios: a browser loading a product page; a mobile app fetching a feed; a cron job calling an internal pricing API; a payment SDK calling the provider; psql talking to PostgreSQL (the database is a server too).

What the style givesHowWhat it costs
Independent evolutionContract between sides stays stableThe contract becomes a public API with compatibility duty
Server simplicity and scaleUI moved away from the serverLatency on every interaction
Central controlRules and data in one placeSingle place that must be available (and replicated)
Client varietyWeb, iOS, Android, CLI share one serverEvery client is a version you do not control

How to use it: write the server as if clients are hostile and old (validate everything, never trust a UI check) and write the client as if the server is slow and sometimes absent (timeouts, retries, cached state, an offline state). Go: tiers example; Laravel: routes and Sanctum.

Tiers: two-tier, three-tier, n-tier {#tiers} Must-know ​

In plain words: A tier is a box you can deploy on a separate machine. Two-tier: client and database. Three-tier: client, application server, database. N-tier: more boxes in between (CDN, load balancer, gateway, services, caches).

Common misunderstanding: "Tiers and layers are the same." A layer is a code-level grouping inside one program (controller, service, repository); a tier is a physical or process boundary with a network call between its sides. A three-layer monolith is usually one tier on the server side. See Layered Monolithic Architecture.

Definition: A tier is a deployment unit that communicates with its neighbours over a network; adding a tier adds a hop, a failure mode and a place to scale or secure independently.

2-tier (thick client)UI + business logicdesktop appDatabase serverSQL over TCP3-tier (thin client)Browser / appApp server (logic)DatabaseHTTPSQLpresentationlogicdatan-tier (layers added for scale and safety)ClientCDNLBGatewayOrders svcBilling svcPostgres + cachePayments DBevery arrow is a client calling a server; middle boxes are both

The picture shows the three shapes. In the n-tier row, every middle box is a server to the box on its left and a client of the box on its right.

ShapeTypical stackStrengthWeaknessStill seen in
Two-tierDesktop app speaks SQL to PostgreSQL, SQL Server or OracleSimple, fast to build, rich UIBusiness rules in every client; database exposed; every client holds a connection; updating means redeploying clientsInternal tools, point-of-sale, legacy ERP
Three-tierBrowser or app, Laravel or Go server, PostgreSQL or MySQLRules in one place; database private; clients stay thinThe app server is the bottleneck and single point to replicateMost web applications
N-tierClient, CDN, load balancer, gateway, services, cache, databasesEach tier scales and is secured on its ownLatency adds up, more to operate, partial failuresLarge platforms
text
     Request path of one page view in an n-tier system (milliseconds are illustrative)
1    browser -> CDN                               edge cache hit?  yes: done in ~20 ms
2    CDN -> load balancer                         miss: forward
3    load balancer -> gateway                     TLS ends here, rate limit, auth check
4    gateway -> orders service                    ~3 ms inside the datacenter
5    orders service -> Redis                      cache hit?  yes: ~1 ms
6    orders service -> PostgreSQL                 miss: ~5 ms, then fill the cache
7    response travels back through every tier     p99 = sum of the slowest hops

Real scenarios: a Laravel monolith with PostgreSQL (three-tier); the same app with Redis, a CDN and a read replica (n-tier without microservices); a marketplace with a gateway and fifty services (n-tier with many services).

What decides the number of tiers: only add a tier for a reason you can name (scale it independently, protect it, cache in front of it, give it a different team). Each tier adds one network hop; see Distribution of Components for why a remote call is not a local call.

Thick and thin clients {#thick-thin} Important ​

In plain words: A thin client mostly displays what the server decided. A thick (fat, rich) client holds logic and data of its own.

Common misunderstanding: "Modern equals thick, thick equals better." The pendulum swings: terminals (thin), desktop apps (thick), early web (thin), SPAs and mobile (thick), server-driven UI and hypermedia (thin again). Neither wins; each moves cost between the network, the server and the device.

Definition: The thickness of a client is how much business logic, validation, state and data it owns. Fielding's code-on-demand constraint is the gentlest form of thickness: the server ships code (JavaScript) and the client runs it.

PropertyThin clientThick client
Logic lives inserverdevice (and duplicated on the server for safety)
Updatedeploy the server; every user gets itapp store review, or code-on-demand in the browser
Works offlinenoyes, if it holds data
Server loadhigher (renders, decides)lower per interaction
Network sensitivityhigh: every click is a round triplow after the first load
Securityrules cannot be bypassedrules on the device can be bypassed; the server must re-check
Examplesclassic Laravel Blade, Livewire, HTMX, terminalSPA with React, native iOS app, desktop IDE
text
     Same action, "change quantity to 3 and see the new total"
     Thin (server-rendered):                      Thick (SPA/native):
1    click                                        click
2    POST /cart/items/9 {qty:3}  ->               compute total locally (instant UI)
3                  server computes, renders  <-   PATCH /cart/items/9 {qty:3} in background
4    page or fragment updates (~150 ms)           server answers; reconcile if totals differ

Fix / rule: put every rule on the server and put only convenience on the client; the client may predict (optimistic UI), the server decides. The decision between the two is revisited in Rendering models.

Stateless servers and where state lives {#stateless} Must-know ​

In plain words: A stateless server answers each request using only what the request carries plus what it can look up in a shared place. It does not remember you from last time, so any replica can serve you.

Common misunderstanding: "Statelessness means no sessions." You can still have a login session; the question is where it is stored. A session id in a cookie that points to a row in Redis is a stateless server (it can be killed and restarted) with a stateful system.

Definition: Fielding's constraint, verbatim:

"...such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client." — Fielding, dissertation, §5.1.3 (saved text: fielding-ch5)

Real systems relax "entirely on the client": they keep session state in a shared store. What must hold is that the server process carries nothing that another replica lacks.

CLIENTAPP SERVERS (replicas)SHARED STATECookie: session idsmall, sent every requestBearer token (JWT / opaque)identity + scopesURL / query / hidden fieldpage, filters, cursorlocalStorage / IndexedDBdrafts, offline queueIn-memory UI stateReplica Ano per-user memoryReplica Bany replica answersReplica Cadd or kill freelyonly caches that can be lost(local memo, compiled templates)Session store (Redis)TTL, revocableCache (Redis, CDN)derived, can be rebuiltDatabase (source of truth)orders, users, versionsQueue / brokerwork in flightObject storage (uploads)requestlookupcarries stateholds staterule: every request must be answerable by any replica from what it carries plus what it can look up

The map shows the six places state can live: in the client (cookie, token, URL, local storage, memory), in the app servers (only throw-away caches), and in shared stores (session store, cache, database, queue, object storage).

WhereExampleProsConsRevocation
Client, signed token (JWT, Sanctum token)Authorization: Bearer ...No lookup (JWT); easy to scaleSize on every request; leaked token works until expiryHard for self-contained JWT; easy for a database token
Client, cookie with session idSet-Cookie: laravel_session=...Browser handles it; HttpOnly hides it from JavaScriptCSRF risk; cookies only for same siteDelete the server row
Client, URL or hidden field?page=3&cursor=...Linkable, cacheable, back button worksVisible and tamperable: validaten/a
Server memoryin-process sessionFastestDies with the process; forces sticky sessionsRestart loses everyone
Shared storeRedis, Memcached, databaseAny replica can read; revocable; TTLOne more dependency, one more hopDelete the key
Databasesessions, personal_access_tokens tablesDurable, queryableLoad on the primary for every requestDelete the row
text
     Stateful server (sticky)                     Stateless server (shared store)
1    login -> replica A stores session in RAM     login -> replica A writes session to Redis
2    next request -> balancer sends to B          next request -> any replica reads Redis
3    B: "who are you?"  -> 401, user is logged out B: finds the session, answers
4    fix: sticky sessions (pin to A)              A dies: nobody notices
5    A dies: everyone pinned to A is logged out

Real scenarios: a shopping cart (client cookie, Redis, or database by user id); a multi-step form (hidden field with signed state, or draft rows); a login (session in Redis, or a token); a search with filters (URL query string so it can be shared); a WebSocket subscription (state is the open connection: a stateful connection even if the HTTP side is stateless).

Fix / how to use it: ask for every piece of state "who loses it if this process dies?". If the answer is "a user", move it to a shared store or the client.

sql
-- Laravel's database session driver (php artisan session:table) and Sanctum tokens: state in the data tier
CREATE TABLE sessions (
    id            varchar(255) PRIMARY KEY,
    user_id       bigint NULL,
    ip_address    varchar(45),
    user_agent    text,
    payload       text NOT NULL,
    last_activity integer NOT NULL
);
CREATE INDEX sessions_user_id_index ON sessions (user_id);
CREATE INDEX sessions_last_activity_index ON sessions (last_activity);
-- Any replica can run this lookup, so replicas stay interchangeable
SELECT payload FROM sessions WHERE id = $1 AND last_activity > extract(epoch FROM now()) - 7200;

Go: state/main.go shows a session store next to an HMAC-signed token. Laravel: set SESSION_DRIVER=redis (or database) and use Sanctum tokens for non-browser clients.

Request-response versus push {#push} Must-know ​

In plain words: Request-response means the client must ask every time. If the client needs to know "has my order shipped?", it either keeps asking (polling) or leaves a line open for the server to speak first (push).

Common misunderstanding: "The server pushes to the client." In HTTP the server cannot open a connection to a browser. Every push channel is a connection the client opened (SSE, WebSocket, long poll) and the server keeps writing into. Webhooks are the exception, and they go from a server to another server.

Definition: Five client-initiated techniques, plus webhooks for server-to-server.

timeorder status changes on the serverShort pollingnew request each tickdelay up to one intervalLong pollingrequest parked, then repeatedheld 25 s, 204answer at once, then re-askSSEone GET, server to client onlyheartbeatevent id=7WebSocketupgrade, then both waysclient frameping/ponggRPC streamHTTP/2 stream, typedserver-streaming or bidirectional, deadline set by the client

The timeline shows when the client learns about a change at the dashed line: after the next tick (short polling), at once with a re-ask (long polling), or on the already open stream (SSE, WebSocket, gRPC).

TechniqueMechanismStrengthsWeaknessesBrowser support and proxy notes
Short pollingGET every N seconds; If-None-Match makes unchanged answers a body-less 304Simplest; cacheable; CDN-friendly; statelessLatency up to N; wasted requests; load grows with users times rateEverywhere
Long pollingGET held until data or timeout (~25 s), then re-issuedNear real time; works through nearly every proxyOne parked request per user; each answer costs a full request; ordering and gaps need careEverywhere
SSEOne GET, Content-Type: text/event-stream, server writes id:, event:, data: lines; EventSource reconnects and sends Last-Event-IDSimple; automatic reconnect and resume; plain HTTP; text onlyOne direction; over HTTP/1.1 browsers allow about six connections per host (MDN); proxies may buffer (X-Accel-Buffering: no)All current browsers (WHATWG; MDN: Chrome 6+, Firefox 6+, Safari 5+)
WebSocketHTTP Upgrade handshake then framed TCP messages (RFC 6455)Both directions; low overhead per message; binaryOwn protocol: no HTTP caching, no automatic resume, must check Origin, harder load balancing and auth; every connection is stateAll current browsers
gRPC streamingHTTP/2 stream with Protocol Buffers messages; server, client or bidirectionalTyped contract; deadlines; backpressure via HTTP/2 flow controlBrowsers need gRPC-Web or a proxy; internal use mostlyServices, mobile SDKs
WebhookProvider POSTs to your URL when an event happensNo polling by youYou must be reachable, verify signatures, accept duplicates and reorderingServer to server

RFC 6455 states the relation to HTTP plainly: "The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request." (§1.7, saved text: rfc6455). MDN warns about SSE over HTTP/1.1: "SSE suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is per browser and is set to a very low number (6)." (saved text: txt/mdn-sse; HTTP/2 lifts it).

text
     SSE on the wire (server to client)                  Reconnect after a network drop
1    GET /orders/42/events  Accept: text/event-stream    1  EventSource waits `retry:` ms (3000 here)
2    200  Content-Type: text/event-stream                2  GET again with Last-Event-ID: 7
3    retry: 3000                                         3  server replays events with id > 7
4    id: 7                                               4  stream continues, no gap
5    event: status
6    data: {"seq":7,"status":"shipped"}
7    (blank line ends the event)
8    : keep-alive                    <- comment line every ~20 s keeps proxies from closing the idle stream

Real scenarios: an order-tracking page (SSE or polling); a live auction or chat (WebSocket); a build log (SSE); a CI dashboard on a corporate proxy (long polling); LLM answer streaming (SSE; Laravel's eventStream was designed for it); a driver's phone sending positions (WebSocket or gRPC client stream); a payment provider telling you a charge settled (webhook).

Operational facts that bite: each push connection holds a file descriptor and memory for its whole life, so capacity is concurrent connections, not requests per second; a deploy or a load balancer idle timeout (often 60 s) drops every connection at once and they all reconnect together (the thundering herd), so add jitter to client back-off; slow consumers need backpressure (Go: bounded channel and drop or disconnect; gRPC: HTTP/2 flow control). See Real-Time Communication and Backpressure & Flow Control.

Fix / how to use it: the decision table and the worked example below show all three of polling, SSE and WebSocket in Go and Laravel.

Client-server over HTTP {#http} Must-know ​

In plain words: HTTP is the language most clients and servers speak. A request names a method (what to do), a target (what to do it to) and headers (extra facts); the response carries a status code and a body.

Common misunderstanding: "GET and POST are the only methods that matter and POST is for anything that changes data." The methods carry promises: safe (no change), idempotent (repeat is harmless), cacheable. Retry logic, caches and CDNs all rely on those promises; breaking them (a GET that deletes) breaks everything built on top.

Definition: RFC 9110 defines the semantics. Safe: "Request methods are considered 'safe' if their defined semantics are essentially read-only". Idempotent: "A request method is considered 'idempotent' if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." (§9.2.1 and §9.2.2, saved text: rfc9110).

MethodSafeIdempotentCacheableTypical useRetry after a timeout?
GETyesyesyesread a resourceyes
HEADyesyesyesheaders only (existence, size, ETag)yes
OPTIONSyesyesnoCORS preflight, capabilitiesyes
PUTnoyesnoreplace a resource at a known URLyes
DELETEnoyesnoremove a resourceyes
POSTnonorarelycreate, run an actiononly with an Idempotency-Key
PATCHnonot guaranteednopartial updateonly if you make it idempotent (version check)
text
     Why POST needs an idempotency key
1    client: POST /payments {amount: 50}  Idempotency-Key: k-91   ->
2    server: charge card, store result under k-91
3    network drops the response              <- (lost)
4    client times out, retries: POST ... Idempotency-Key: k-91  ->
5    server: key k-91 exists -> return stored result, no second charge

Status codes you must know:

CodeMeaningClient should
200 / 201 / 204OK / created (send Location) / success, no bodyproceed
301 / 308moved permanently (308 keeps the method)update the link
304not modified: use your cached copyreuse cache
400 / 422malformed request / valid syntax but invalid data (Laravel validation returns 422)fix input, do not retry as-is
401not authenticated (no or bad credentials)log in or refresh the token
403authenticated but not alloweddo not retry
404 / 410not found / gonestop
409conflict with current state (version mismatch)re-read, merge, retry
412precondition failed (If-Match did not match)re-read, retry
429too many requests (honour Retry-After)back off
500 / 502 / 503 / 504server error / bad gateway / unavailable / gateway timeoutretry only idempotent calls, with jittered back-off

Caching and conditional requests. A validator (ETag or Last-Modified) lets a client ask "has it changed?" without downloading the body.

text
     Conditional GET (cache validation)                   Optimistic update (If-Match)
1    GET /orders/42/status   ->                           GET /orders/42  ->
2    <- 200  ETag: "42-7"  Cache-Control: no-cache        <- 200  ETag: "v5"
3    ... later ...                                        PUT /orders/42  If-Match: "v5"  ->
4    GET /orders/42/status  If-None-Match: "42-7" ->      <- 200  ETag: "v6"   (or 412 if someone else wrote)
5    <- 304 Not Modified  (no body, a few hundred bytes)
HeaderDirectionPurpose
Cache-Control: max-age=N, no-cache, no-store, private, public, s-maxage, stale-while-revalidateresponsehow long and by whom it may be reused. no-cache means "store it, but revalidate", no-store means "never store"
ETag / If-None-Matchresponse / requestopaque version tag; 304 when equal
Last-Modified / If-Modified-Sinceresponse / requesttime-based validator, one-second resolution
If-Matchrequestwrite only if the version still matches; 412 otherwise (optimistic concurrency over HTTP)
Vary: Accept-Encoding, Accept-Languageresponsewhich request headers the cached copy depends on
Accept, Accept-Language, Accept-Encodingrequestcontent negotiation: the client states what it can take
Content-Type, Content-Encoding, Content-Languageresponsewhat the server actually chose
Retry-Afterresponseseconds or date to wait after 429/503
Idempotency-Keyrequestclient-chosen key to deduplicate POST (an IETF draft convention; Stripe popularised it)
text
     Content negotiation (server-driven)
1    GET /report/9  Accept: application/json;q=1, text/csv;q=0.5  Accept-Language: fa, en;q=0.6
2    <- 200  Content-Type: application/json  Content-Language: fa  Vary: Accept, Accept-Language
3    GET /report/9  Accept: application/pdf  ->  <- 406 Not Acceptable (or 415 for a request body type)

Primary reading: RFC 9110 (semantics), RFC 9111 (caching), MDN Conditional requests and Content negotiation. Protocol versions (HTTP/1.1 keep-alive, HTTP/2 multiplexing, HTTP/3 over QUIC) are in HTTP Evolution.

Fix / how to use it: make reads GET with an ETag; make updates PUT or PATCH with If-Match; make creates POST with an Idempotency-Key; return the right status code, not 200 with an error in the body. Go: tracking/poll.go and client/main.go. Laravel: ConditionalGet middleware.

API styles: REST, RPC and gRPC, GraphQL {#api-styles} Important ​

In plain words: The API style is the shape of the contract: nouns and a few verbs (REST), a remote function call (RPC), or "ask for exactly the fields you want" (GraphQL).

Common misunderstanding: "REST means JSON over HTTP." Most "REST APIs" are really JSON resource APIs. Fielding's REST also requires the uniform interface including hypermedia (HATEOAS: the response tells the client what it can do next); the dissertation lists "hypermedia as the engine of application state" among the interface constraints.

AspectREST (resource over HTTP)RPC and gRPCGraphQL
ContractOpenAPI document (optional).proto file (required, typed)schema (required, typed)
Unitresource: /orders/42method: OrderService.Trackquery/mutation against one endpoint
TransportHTTP/1.1, HTTP/2HTTP/2 + Protocol BuffersHTTP POST (usually) + JSON
CachingHTTP caches, CDN (via GET)none by defaulthard: one URL, POST
Over-fetch / under-fetchcommonfixed per methodsolved by the client choosing fields
StreamingSSE, WebSocket on the sidenative: 4 call types (unary, server, client, bidirectional)subscriptions (usually WebSocket)
Browser friendlyyesneeds gRPC-Webyes
Best forpublic APIs, CRUD, cacheable readsinternal service-to-service, low latency, polyglot teamsmany client types with different data needs (mobile + web)
Main riskchatty clients, verbs hidden in URLstight coupling to generated code, harder to debug with curlN+1 resolvers, query cost abuse, caching

gRPC's four call types and its deadline rule come from the official core concepts: "gRPC allows clients to specify how long they are willing to wait for an RPC to complete before the RPC is terminated with a DEADLINE_EXCEEDED error." (saved text: grpc-core). The details are in REST API Design, GraphQL and gRPC & Protocol Buffers; this chapter only places them as connector choices inside the client-server style. A common combination: REST or GraphQL at the edge for browsers and partners, gRPC between services, a Backend-for-Frontend in between.

Peer-to-peer, the contrast {#p2p} Good to know ​

In plain words: In client-server the roles are fixed and unequal. In peer-to-peer every node plays both roles and talks to other nodes directly.

Common misunderstanding: "P2P means no server at all." Most real P2P systems keep a server for discovery or coordination: BitTorrent uses trackers (and a DHT), WebRTC needs a signalling server and STUN/TURN, and Bitcoin nodes bootstrap from DNS seeds.

AspectClient-serverPeer-to-peer
Rolesfixedevery node is both
Control and datacentral, authoritativespread across nodes
Scalingadd servers (you pay)capacity grows with participants (they pay)
Failurethe server is a single point (replicate it)no single point, but churn and partitions
Security and trustone place to secureevery peer is untrusted
Consistencyeasy: one authorityhard: needs gossip, CRDTs or consensus (CRDTs)
Examplesweb, email, databasesBitTorrent, WebRTC calls, blockchain, Git between clones

The two mix: a hybrid keeps the control plane client-server (login, matchmaking, billing) and moves the data plane peer-to-peer (a video call). A modern microservice mesh is not peer-to-peer: roles per call are still fixed.

Rendering models: SPA, SSR, server-driven UI, hypermedia {#rendering} Important ​

In plain words: Who builds the HTML the user sees: the browser from JSON (SPA), the server per page (SSR), or the server in small pieces that the browser swaps in (hypermedia)?

Common misunderstanding: "Server-rendered means old-fashioned and slow." A server-rendered page can be faster to first paint than an SPA (one request, no JavaScript bundle to run first), and tools like Inertia, Livewire and HTMX give it interactivity.

ModelHTML built byClient-server contractExamplesStrengthWeakness
Classic SSRserver, full page per navigationHTML pages and formsLaravel Blade, Go html/templateSimple, SEO-friendly, little JavaScriptFull reload per action
SPAbrowser, from JSONJSON APIReact or Vue + Laravel/Go API with SanctumRich interaction, offline possible, one API for web and mobileLarge bundle, SEO and first paint need work, two codebases
SSR + hydrationserver first, then browser takes overHTML + JSONNext.js, NuxtFirst paint fast, rich laterComplex build, two runtimes
Server-driven UI with a thin protocolserver picks the component and propsInertia protocol (JSON page object)Inertia (Vue/React/Svelte) with LaravelKeep routing, controllers, auth on the server, write the page in Vue or React, no separate APITied to your own server; mobile still needs a real API
Server-driven UI over WebSocketserver holds component state, sends HTML diffsHTML fragmentsLivewireInteractivity in PHP, no JavaScript to writeServer round trip per interaction; component state is per-session (stateful)
Hypermediaserver returns HTML fragments, hx-* attributes drive swapsHTML over HTTPHTMX, TurboClose to Fielding's REST, minimal JavaScriptNot for heavy offline or canvas apps

Inertia's own site lists "Server-based routing" first: you keep routing, controllers, middleware, auth, data fetching and state on the server (saved text: inertia, paraphrased). The key architectural point: Inertia and Livewire are thin-client styles that keep the server authoritative; a separate SPA plus API is a thick-client style that creates a public contract. Choose by the audience of the contract: if only your own web UI will ever call it, Inertia saves you an API; if mobile, partners or other services will call it, build the API first. See Interaction and Presentation (MVC, MVP, MVVM).

Mobile clients and offline-first {#offline} Important ​

In plain words: A phone loses the network in elevators, tunnels and villages. An offline-first app treats the local database as the main store and syncs with the server when it can.

Common misunderstanding: "Offline support means caching GET responses." That covers reading. Writing offline needs a queue of mutations, a way to replay them safely, and a plan for when two devices edited the same thing.

Definition: Offline-first splits the client into a UI, a local store (SQLite, Room, Core Data, IndexedDB) and a sync engine; the server exposes a sync endpoint that is idempotent and detects conflicts.

text
     Offline write and later sync
1    phone (offline): user edits order 42 note   -> local DB + queue [{id:m1, base_version:3, note:"gate B"}]
2    phone (offline): user edits again           -> queue [m1, m2 (base_version:3)]
3    network returns: POST /sync [m1, m2]        ->
4    server: m1 base_version 3 == current 3      -> applied, version 4
5    server: m2 base_version 3 != current 4      -> conflict, returns the server copy
6    phone: shows "this changed elsewhere", user or rule merges, new mutation m3 (base_version:4)
7    lost response? phone resends m1             -> server sees id m1 already stored -> duplicate, same answer
Conflict strategyHowGood forCost
Last write winsnewest timestamp or version overwritescounters you can lose, preferencesSilently drops edits; clock skew
Reject on conflict (compare-and-set)base_version must match, else 409/conflictorders, inventory, moneyUser must resolve
Field-level mergemerge changed fields onlyprofile formsNeeds per-field versions
CRDTdata types that merge by designcollaborative text, countersComplexity; see CRDTs
Operation logsend intents ("add item"), not statescarts, ledgersServer replays and validates each

Mobile adds more constraints: radios save battery by batching traffic (so push channels are expensive: use the platform's push service, APNs and FCM, to wake the app instead of keeping a socket open), tokens must live in the OS keychain, and old app versions live for years (see Evolution). Go: syncapi/main.go. Laravel: SyncController.

Security at the boundary {#security} Must-know ​

In plain words: Everything a client sends is untrusted, because the client is outside your control. The server boundary is where you check who is calling, what they may do, and whether the data is sane.

Common misunderstanding: "The mobile app hides the admin button, so users cannot call admin endpoints." The app is a convenience; anyone can call your API with curl. Authorization must be re-checked on the server for every request.

ConcernMechanismWhere it livesChapter
Authentication (who)Session cookie, Bearer token (Sanctum, JWT), OAuth 2.0 / OIDCGateway or app server middlewareAuthentication, JWT, OAuth2/OIDC
Authorization (what)Policies, RBAC, abilities (token scopes)App server, per resourceAuthorization models
TransportTLS (HTTPS), HSTS; mTLS between servicesEdge and service meshCryptography and TLS, mTLS
Cross-originCORS: the browser asks the server whether a page from another origin may read the responseServer response headersWeb sessions, cookies, CORS
CSRFA malicious site makes the browser send your cookie: defend with SameSite cookies and a CSRF tokenCookie-based apps onlyOWASP Top 10
Input validationValidate type, size, range on the server (Laravel Form Requests)ServerSecurity by Design
AbuseRate limiting (429 + Retry-After), payload size caps, timeoutsGateway and serverRate limiting
WebSocket specificsCheck Origin on the upgrade; authenticate on connect; browsers do not apply CORS to socketsServerRFC 6455 §10

Two facts people mix up. CORS is a browser rule, not a server defence: it stops a page from reading a cross-origin response; it does not stop curl, and it does not stop a cross-site form POST (that is CSRF). MDN's CORS guide describes it as "an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources" (saved text: mdn-cors). Cookies and tokens split the threat: a cookie is sent automatically (so you need CSRF protection and HttpOnly, Secure, SameSite); a Bearer token in JavaScript memory is sent only by your code (no CSRF, but an XSS bug can steal it). Laravel's Sanctum handles both: cookie sessions for your first-party SPA, tokens for mobile and third parties ("Laravel Sanctum exists to solve two separate problems", Sanctum docs, saved text: laravel-sanctum).

Load balancing and session affinity {#lb} Important ​

In plain words: A load balancer stands in front of many identical servers and hands each request to one of them. Session affinity ("sticky sessions") pins a user to one server.

Common misunderstanding: "Sticky sessions are a harmless convenience." They quietly turn a stateless system into a stateful one: load is uneven, a deploy or crash logs people out, and autoscaling stops helping existing users.

Algorithm / featureHowFitsNote
Round robineach server in turnidentical, short requestsignores load
Least connectionsserver with fewest open connectionslong requests, SSE, WebSocketthe usual choice for push
Weightedproportional to capacitymixed hardware
Consistent hashing on a keysame key, same servercache locality, shard-like workloadsrebalancing on change
Cookie or IP affinitypin by cookie or source IPlegacy stateful appsavoid; use a shared store
L4 versus L7TCP level versus HTTP level (path, header, cookie)L7 for routing and TLS terminationsee Load Balancing
Health checksactive probes remove a bad nodeallreadiness endpoint must test dependencies, liveness must not
Connection drainingstop new requests, let in-flight finishdeployspair with Go's http.Server.Shutdown
text
     Rolling deploy of a stateless service behind an L7 balancer
1    replica A: SIGTERM -> readiness fails -> balancer stops sending new requests
2    A: srv.Shutdown(ctx) waits for in-flight handlers (<= 15 s)
3    SSE/WebSocket clients on A: connection closed -> client reconnects (Last-Event-ID) -> lands on B
4    A exits; replica A' starts, passes readiness, receives traffic
5    repeat for B, C. Users saw a reconnect, not an error

For WebSocket and SSE use least-connections, set balancer idle timeouts above your heartbeat interval, and make reconnects cheap. More in Scaling Strategies, Load Balancing and Forward vs Reverse Proxies.

Client-server inside microservices {#micro-cs} Must-know ​

In plain words: In a system of services, almost every box is a server for the ones that call it and a client of the ones it calls. The style does not disappear; it repeats at every hop.

Common misunderstanding: "Inside the datacenter the network is reliable, so internal calls need no timeouts." Every client-server hop needs a deadline, a retry rule and a failure plan; an unbounded call in service A holds a thread while B is slow and the stall spreads (a cascading failure).

Definition: A service-to-service call has the same parts as a browser call, plus a contract owned by the called service and relied on by every caller.

text
     One user click, four client-server hops
1    browser  -> gateway        GET /checkout/summary                 (deadline 3 s)
2    gateway  -> orders         GET /v1/orders/42                     (deadline 2.5 s: parent budget minus gateway time)
3    orders   -> pricing        POST /v1/quote                        (deadline 1.5 s)
4    orders   -> inventory      GET /v1/stock/9 (gRPC unary)          (deadline 1.5 s, in parallel with 3)
5    each hop: authenticate caller (mTLS or token), propagate X-Request-Id / traceparent
6    if pricing is slow: orders returns a degraded answer (cached price) instead of waiting
Rule for every service-as-clientWhyWhere
Set connect and total timeouts; propagate the caller's deadlinePrevent thread pile-upTimeouts, Retries & Jitter
Retry only idempotent calls, with jitter and a budgetRetries multiply loadAPI Idempotency
Circuit breaker around each dependencyStop calling a dead serviceCircuit Breaker
Pass identity and trace idsAuthorization and debuggingmTLS
Version the contract; add fields, do not change meaningCallers deploy later than the serverEvolution
Prefer fewer, coarser callsChatty clients pay latency per callService Communication

Who finds whom is Service Discovery; the single entrance for outside clients is the API Gateway. The style as a whole appears again in Service-Oriented Architecture and Microservices Architecture.

Evolution: API versioning and backward compatibility {#evolution} Important ​

In plain words: You can redeploy your server tonight; you cannot redeploy every phone. So the server must keep understanding old clients while new ones arrive.

Common misunderstanding: "Version the URL (/v2) and the problem is solved." A new version number only moves the problem; two versions double the testing and the support. Most change should be additive inside one version.

ChangeBackward compatible?Rule
Add an optional response fieldyesClients must ignore unknown fields (tolerant reader)
Add an optional request field with a defaultyesThe default keeps old behaviour
Add a new endpointyes
Remove or rename a fieldnoAdd the new one, deprecate the old, remove after the sunset date
Change a field's type or meaningnoNew field name
Tighten validationno (for old clients)Introduce behind a flag, or in the next version
Change status codes or error shapenoTreat error format as part of the contract
Versioning approachExampleProsCons
URL path/api/v1/ordersVisible, easy to route and cacheVersion proliferation
Header or media typeAccept: application/vnd.shop.v2+jsonClean URLsHidden, harder to test by hand
Query parameter?version=2Easy to tryCaches and logs need care
Date-pinned (per account)Stripe-Version: 2024-06-20Gradual upgrades per clientNeeds a compatibility layer on the server
Additive only + feature flagsno version at allLeast workNeeds discipline and contract tests

Deprecation can be announced in headers: Deprecation (RFC 9745) and Sunset (RFC 8594), both response headers. Details and consumer-driven contract tests in API Versioning & Evolution.

Mechanics ​

What happens during one request ​

text
     Phase                      Knob (Go net/http)                  Failure it prevents
1    DNS lookup                 resolver, cache                     slow first byte
2    TCP connect                net.Dialer.Timeout                  hang on unreachable host
3    TLS handshake              Transport.TLSHandshakeTimeout       hang in negotiation
4    send request               (write deadline)                    stuck upload
5    wait for first byte        Transport.ResponseHeaderTimeout     server accepted, never answers
6    read body                  Client.Timeout (covers 1-6)         endless body
7    reuse connection           Transport.IdleConnTimeout,          keep-alive: skip 1-3 next time
                                MaxIdleConnsPerHost

Server side (Go http.Server): ReadHeaderTimeout (slow-header attacks), ReadTimeout (whole request), WriteTimeout (whole response, do not use it on SSE/WebSocket routes), IdleTimeout (keep-alive wait), MaxHeaderBytes, and Shutdown(ctx) for graceful stop. Defaults are no timeout at all, which is why a bare http.ListenAndServe is not a production server. Per-response deadlines on streaming routes: http.NewResponseController(w).SetWriteDeadline(...).

Keep-alive, multiplexing and connection reuse ​

ProtocolBehaviourConsequence
HTTP/1.0one request per TCP connectionhandshake cost every time
HTTP/1.1persistent by default (keep-alive); one request at a time per connectionbrowsers open about six connections per host
HTTP/2many streams over one connection, header compressionone connection per host is enough; SSE limit disappears; head-of-line blocking at TCP level remains
HTTP/3QUIC over UDPno TCP head-of-line blocking; faster connection start

In Go, a response body that is not read to the end and closed keeps the connection out of the pool: always defer resp.Body.Close() and drain small bodies (io.Copy(io.Discard, resp.Body)).

Errors, retries, back-off ​

SituationRetry?How
Connect error, DNS erroryes (idempotent or not: nothing was sent)jittered exponential back-off
Timeout after sendingonly if idempotent or keyedsame request, same Idempotency-Key
429 or 503 with Retry-Afteryes, after that delayhonour the header
500, 502, 504 on idempotent callyes, boundedat most 2-3 tries
400, 401, 403, 404, 422nofix the request
409, 412after re-readingmerge and resend

Rules: put a budget on the whole operation (a context deadline), not just per try; add jitter so clients do not retry in lockstep; retry at one layer (retrying in the client, the gateway and the service multiplies attempts by 3 x 3 x 3). Deep treatment in Timeouts, Retries & Jitter.

Solving the classic problems ​

Problem 1: replicas that forget you ​

SolutionHowAdvantageCost or limitation
Shared session storeSESSION_DRIVER=redis (Laravel), session id in a cookieRevocable, small cookieRedis becomes critical; one lookup per request
Signed tokenSanctum token or JWT in AuthorizationNo store hit (JWT)Revocation and size; rotate keys
Sticky sessionsbalancer pins by cookieQuick fix for legacy appsUneven load, logout on deploy
Client-held stateURL, signed hidden fieldZero server memorySize, tampering (sign it)

Problem 2: polling that melts the server ​

SolutionHowAdvantageCost or limitation
Conditional GETETag + If-None-Match → 304Tiny responses, shared CDN cacheStill one request per tick
Adaptive intervalslow down when idle, speed up after a changeFewer requestsMore client code
Server hintRetry-After or a field next_poll_inServer controls loadNeeds client cooperation
Switch to SSEone stream per userNear real time, fewer requestsConnections to hold (capacity)
Push through a brokerserver publishes to Redis/NATS; web tier fans outScales fan-outOne more system

Problem 3: the retry that charges twice ​

SolutionHowAdvantageCost or limitation
Idempotency-Key headerstore key + result for 24 hSafe retries of POSTStorage, key scope per user
Natural idempotencyPUT /orders/42/status with the full stateNo extra storageNot every action fits
Unique constraintUNIQUE (client_request_id)Database guarantees itError handling for the duplicate
Version checkIf-Match / WHERE version = ?Stops lost updates tooClient must re-read on 412

Problem 4: slow clients and giant responses ​

SolutionHowAdvantageCost or limitation
Paginationcursor or keyset (see Pagination)Bounded payloadClient complexity
CompressionAccept-Encoding: gzip, br70-90% smaller JSONCPU (cache compressed assets)
Field selection?fields=id,status, GraphQLLess over-fetchCache keys multiply
StreamingNDJSON, SSE, gRPC server streamFirst byte earlyResume logic
Async job202 Accepted + Location: /jobs/7 to pollLong work without long requestsJob store needed

Problem 5: the thundering herd on reconnect ​

When a load balancer restarts, 100,000 SSE or WebSocket clients reconnect in the same second. Solutions: client back-off with full jitter (sleep = random(0, min(cap, base * 2^n))), server-side connection limits per instance, Retry-After on 503, gradual deploys (a few replicas at a time) and a retry: field spread by the server.

Choosing ​

Push versus pull, one table.

NeedChooseWhyWatch out
Status updated every minute or slowerShort polling with ETagZero new infrastructureInterval times users equals load
Updates in seconds, one direction, browsersSSEReconnect and resume built in; plain HTTPSix-connection limit on HTTP/1.1; proxy buffering
Updates in seconds, hostile proxy or old browserLong pollingWorks everywhereParked requests count as capacity
Chat, presence, collaborative editingWebSocket (Laravel Reverb, Go coder/websocket)Two-way, low overheadCheck Origin, authenticate, scale with a pub/sub backplane
Internal real-time between servicesgRPC streamingTyped, deadlines, flow controlNot for browsers without gRPC-Web
A third party tells you something happenedWebhookNo pollingVerify signature, dedupe, accept reordering
Wake a sleeping phoneAPNs / FCM pushOS-level, battery-friendlyNot guaranteed delivery; send data via the API
Low-latency telemetry up (device to server)WebSocket or gRPC client streamOne connection, many framesBackpressure
Does the client need updates sooner than ~30 s?noShort polling + ETag/304cheapest, cacheable, CDN-friendlyyesDoes the client send a stream too?yesBrowser, or service-to-service?WebSocketchat, games, cursorsgRPC bidiinternalnoCan you keep an open connection per user?no (proxy, mobile)Long pollingworks through anythingyesSSEnotifications, progressdefault to the simplest option that meets the latency need

Architecture variant, one table.

SituationChooseReason
Internal admin tool, one team, web onlyInertia or Livewire or BladeNo separate API to design and version
Public product with web, iOS, AndroidAPI first (REST or GraphQL) + SPA/native clientsOne contract, many clients
Content site, SEO mattersSSR or hypermediaFast first paint, crawlable
Field workers, bad networkOffline-first thick client + sync APIWorks without connection
High-fan-out feedsPush through a pub/sub backplaneSee Feeds
Services calling servicesgRPC or REST with deadlines + contractsTyped, timed, versioned

Go ​

Go's standard library is a complete client-server toolkit: net/http for the server and the client, context for deadlines, http.ResponseController for flushing and per-response deadlines. Only WebSocket needs a library (github.com/coder/websocket, the maintained continuation of nhooyr.io/websocket; the older gorilla/websocket also works). Layout of the snippets: docs/snippets/architecture/client-server/go/, module academy/client-server, gofmt and go vet clean.

Three tiers in one process ​

The handler (presentation) calls a service (logic) that calls a repository interface (data). Replace memRepo with a database/sql or pgx implementation and nothing above changes.

go
// Three tiers in one process: presentation (HTTP handler), logic (Service),
// data (Repository). Each tier knows only the one below it, through an
// interface, so the same Service runs behind HTTP, gRPC or a CLI.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"sync"
	"time"
)

// ---- data tier ------------------------------------------------------

type Order struct {
	ID      string `json:"id"`
	Status  string `json:"status"`
	Version int    `json:"version"`
}

var ErrNotFound = errors.New("order not found")

type Repository interface {
	Find(ctx context.Context, id string) (Order, error)
}

type memRepo struct {
	mu   sync.RWMutex
	data map[string]Order
}

func (m *memRepo) Find(_ context.Context, id string) (Order, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	o, ok := m.data[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	return o, nil
}

// ---- logic tier -----------------------------------------------------

type Service struct{ repo Repository }

// Track holds the business rules (who may see what, which fields are public).
func (s Service) Track(ctx context.Context, id string) (Order, error) {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second) // budget for the tier below
	defer cancel()
	return s.repo.Find(ctx, id)
}

// ---- presentation tier ----------------------------------------------

type Handler struct{ svc Service }

func (h Handler) get(w http.ResponseWriter, r *http.Request) {
	o, err := h.svc.Track(r.Context(), r.PathValue("id"))
	switch {
	case errors.Is(err, ErrNotFound):
		http.Error(w, "not found", http.StatusNotFound)
	case err != nil:
		http.Error(w, "internal error", http.StatusInternalServerError)
	default:
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(o)
	}
}

func main() {
	repo := &memRepo{data: map[string]Order{"42": {ID: "42", Status: "shipped", Version: 3}}}
	h := Handler{svc: Service{repo: repo}}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", h.get)
	log.Fatal((&http.Server{Addr: ":8081", Handler: mux, ReadHeaderTimeout: 5 * time.Second}).ListenAndServe())
}

Where state lives: session or signed token ​

Both middlewares keep the server stateless in the sense that matters: any replica can answer. The session needs a shared store; the token needs a shared key.

go
// Where does state live when the server is stateless? Two answers:
// a server-side session (state in a store, id in a cookie) and a signed
// token (state in the client, verified by any server that knows the key).
package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"net/http"
	"strings"
	"sync"
	"time"
)

// ---- A: server-side session. The store must be shared (Redis, DB). ----

type SessionStore interface {
	Get(id string) (userID string, ok bool)
	Put(id, userID string, ttl time.Duration)
}

type memStore struct {
	mu sync.Mutex
	m  map[string]string
}

func (s *memStore) Get(id string) (string, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	u, ok := s.m[id]
	return u, ok
}
func (s *memStore) Put(id, u string, _ time.Duration) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.m[id] = u
}

func sessionAuth(store SessionStore, next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c, err := r.Cookie("sid")
		if err != nil {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		if _, ok := store.Get(c.Value); !ok { // one network call to the store per request
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		next(w, r)
	}
}

func newSessionCookie(id string) *http.Cookie {
	return &http.Cookie{
		Name: "sid", Value: id, Path: "/",
		HttpOnly: true,                 // JavaScript cannot read it
		Secure:   true,                 // HTTPS only
		SameSite: http.SameSiteLaxMode, // basic CSRF defence
		MaxAge:   int((2 * time.Hour).Seconds()),
	}
}

// ---- B: signed token. No store lookup; revocation is the price. ----

var key = []byte("replace-with-32-random-bytes-from-a-secret-store")

func sign(userID string, exp time.Time) string {
	payload := fmt.Sprintf("%s.%d", userID, exp.Unix())
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(payload))
	return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + hex.EncodeToString(mac.Sum(nil))
}

func verify(token string) (userID string, ok bool) {
	p, sig, found := strings.Cut(token, ".")
	if !found {
		return "", false
	}
	raw, err := base64.RawURLEncoding.DecodeString(p)
	if err != nil {
		return "", false
	}
	mac := hmac.New(sha256.New, key)
	mac.Write(raw)
	want := hex.EncodeToString(mac.Sum(nil))
	if !hmac.Equal([]byte(sig), []byte(want)) { // constant-time compare
		return "", false
	}
	var exp int64
	user, expStr, _ := strings.Cut(string(raw), ".")
	if _, err := fmt.Sscanf(expStr, "%d", &exp); err != nil || time.Now().Unix() > exp {
		return "", false
	}
	return user, true
}

func tokenAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tok, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
		if _, ok := verify(tok); !found || !ok {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		next(w, r) // no shared store: any replica can answer
	}
}

func randomID() string {
	b := make([]byte, 32)
	_, _ = rand.Read(b)
	return base64.RawURLEncoding.EncodeToString(b)
}

func main() {
	store := &memStore{m: map[string]string{}}
	id := randomID()
	store.Put(id, "u1", 2*time.Hour)

	mux := http.NewServeMux()
	mux.HandleFunc("GET /me/session", sessionAuth(store, func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "ok (session)") }))
	mux.HandleFunc("GET /me/token", tokenAuth(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "ok (token)") }))
	fmt.Println("example token:", sign("u1", time.Now().Add(15*time.Minute)))
	_ = (&http.Server{Addr: ":8082", Handler: mux, ReadHeaderTimeout: 5 * time.Second}).ListenAndServe()
}

The client side: timeouts, keep-alive, retry ​

The zero http.Client has no timeout and http.DefaultTransport is shared by the whole process; build one tuned client and reuse it.

go
// A production-shaped HTTP client: one shared *http.Client, explicit
// timeouts, a context per call, connection reuse, retry only when safe.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"time"
)

// newClient builds the client once and shares it. The zero-value
// http.Client has NO timeout and http.DefaultTransport is shared by
// every library in the process, so build your own.
func newClient() *http.Client {
	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   2 * time.Second,  // TCP connect
			KeepAlive: 30 * time.Second, // TCP keep-alive probes
		}).DialContext,
		TLSHandshakeTimeout:   3 * time.Second,
		ResponseHeaderTimeout: 3 * time.Second, // server accepted but never answers
		MaxIdleConns:          100,
		MaxIdleConnsPerHost:   20, // default is 2: too low for a busy service
		IdleConnTimeout:       90 * time.Second,
		ForceAttemptHTTP2:     true,
	}
	return &http.Client{
		Transport: tr,
		Timeout:   10 * time.Second, // total budget incl. reading the body
	}
}

type status struct {
	OrderID string `json:"order_id"`
	Seq     int    `json:"seq"`
	Status  string `json:"status"`
}

// getStatus does a conditional GET. etag is what the caller stored last time.
func getStatus(ctx context.Context, c *http.Client, url, etag string) (st status, newETag string, changed bool, err error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return st, etag, false, err
	}
	req.Header.Set("Accept", "application/json")
	if etag != "" {
		req.Header.Set("If-None-Match", etag)
	}
	resp, err := c.Do(req)
	if err != nil {
		return st, etag, false, err
	}
	defer resp.Body.Close()
	defer io.Copy(io.Discard, resp.Body) // drain so the connection returns to the pool

	switch resp.StatusCode {
	case http.StatusNotModified:
		return st, etag, false, nil
	case http.StatusOK:
		if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&st); err != nil {
			return st, etag, false, err
		}
		return st, resp.Header.Get("ETag"), true, nil
	default:
		return st, etag, false, fmt.Errorf("unexpected status %s", resp.Status)
	}
}

// withRetry retries only idempotent calls (GET, PUT, DELETE) and only on
// failures that may be transient. POST needs an Idempotency-Key first.
func withRetry(ctx context.Context, attempts int, fn func(context.Context) error) error {
	var err error
	for i := 0; i < attempts; i++ {
		attemptCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
		err = fn(attemptCtx)
		cancel()
		if err == nil || errors.Is(err, context.Canceled) {
			return err
		}
		select {
		case <-time.After(time.Duration(100<<i) * time.Millisecond): // 100, 200, 400 ms
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	return err
}

func main() {
	c := newClient()
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	etag := ""
	err := withRetry(ctx, 3, func(ctx context.Context) error {
		st, tag, changed, err := getStatus(ctx, c, "http://localhost:8080/orders/42/status", etag)
		if err != nil {
			return err
		}
		etag = tag
		log.Printf("changed=%v status=%+v etag=%s", changed, st, etag)
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}

Offline-first sync endpoint ​

Idempotency by mutation id and conflict detection by base version, as in the offline section.

go
// Offline-first sync endpoint. The mobile app queues mutations while offline
// and replays them later. Each mutation carries a client-generated id (so a
// replay is harmless) and the version the client edited (so conflicts show).
package main

import (
	"encoding/json"
	"net/http"
	"sync"
	"time"
)

type Mutation struct {
	ID          string `json:"id"` // uuid made on the device: idempotency key
	OrderID     string `json:"order_id"`
	BaseVersion int    `json:"base_version"` // version the client last saw
	Note        string `json:"note"`
}

type Result struct {
	ID         string `json:"id"`
	Outcome    string `json:"outcome"` // applied | duplicate | conflict
	Version    int    `json:"version"`
	ServerNote string `json:"server_note,omitempty"`
}

type store struct {
	mu      sync.Mutex
	seen    map[string]Result // mutation id -> first result
	version map[string]int
	note    map[string]string
}

func (s *store) apply(m Mutation) Result {
	s.mu.Lock()
	defer s.mu.Unlock()
	if prev, ok := s.seen[m.ID]; ok {
		prev.Outcome = "duplicate" // same answer, no second write
		return prev
	}
	cur := s.version[m.OrderID]
	var res Result
	if m.BaseVersion != cur {
		// Someone else wrote first. Do not overwrite: return the server copy
		// and let the client merge (last-write-wins, field merge, or ask the user).
		res = Result{ID: m.ID, Outcome: "conflict", Version: cur, ServerNote: s.note[m.OrderID]}
	} else {
		s.version[m.OrderID] = cur + 1
		s.note[m.OrderID] = m.Note
		res = Result{ID: m.ID, Outcome: "applied", Version: cur + 1}
	}
	s.seen[m.ID] = res
	return res
}

func main() {
	s := &store{seen: map[string]Result{}, version: map[string]int{}, note: map[string]string{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /sync", func(w http.ResponseWriter, r *http.Request) {
		var batch []Mutation
		if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&batch); err != nil {
			http.Error(w, "bad json", http.StatusBadRequest)
			return
		}
		out := make([]Result, 0, len(batch))
		for _, m := range batch { // in order: the device queue is ordered
			out = append(out, s.apply(m))
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(out)
	})
	_ = (&http.Server{Addr: ":8083", Handler: mux, ReadHeaderTimeout: 5 * time.Second}).ListenAndServe()
}

The Go angle in short. One goroutine per connection makes holding 10,000 SSE streams cheap; Server.Shutdown drains in-flight requests; contexts carry cancellation from the client's disconnect (r.Context()) to every downstream call. Fuller coverage in net/http: Server, Client, HTTP/2, HTTPS, TLS & mTLS in Go and gRPC in Go.

Laravel ​

Laravel 13 is a three-tier server framework with first-class tools for each variant in this chapter. Source: Routing, Sanctum, Responses (event streams), Broadcasting, Reverb, HTTP Client.

API routes. php artisan install:api installs Sanctum and creates routes/api.php; the docs state: "The routes in routes/api.php are stateless and are assigned to the api middleware group", with the /api prefix applied automatically (saved text: laravel-routing). In Laravel 13 you register the abilities and ability middleware aliases yourself in bootstrap/app.php (the Sanctum docs show how).

php
<?php

// routes/api.php (created by `php artisan install:api`, which installs Sanctum).
// Routes in this file are stateless and get the /api prefix and the `api` middleware group.

use App\Http\Controllers\Api\OrderStatusController;
use App\Http\Controllers\Api\SyncController;
use App\Http\Controllers\Api\TokenController;
use App\Http\Middleware\ConditionalGet;
use Illuminate\Support\Facades\Route;

Route::post('/tokens', [TokenController::class, 'store'])->middleware('throttle:10,1');

Route::middleware('auth:sanctum')->group(function () {
    Route::delete('/tokens/current', [TokenController::class, 'destroy']);

    // 1. short polling: cheap because of ETag/304
    Route::get('/orders/{order}/status', [OrderStatusController::class, 'show'])
        ->middleware([ConditionalGet::class, 'ability:orders:read']);

    // 2. SSE: one long GET, text/event-stream
    Route::get('/orders/{order}/events', [OrderStatusController::class, 'stream'])
        ->middleware('ability:orders:read');

    // offline-first batch sync from the mobile app
    Route::post('/sync', [SyncController::class, 'store']);
});

// 3. WebSocket needs no route: the event implements ShouldBroadcast and
// the client subscribes to the private channel through Reverb (see OrderStatusUpdated).

Sanctum has two modes (docs: "SPA Authentication" and "API tokens"): cookie-based session authentication for a first-party SPA on a configured stateful domain (CSRF cookie first, then login), and bearer tokens for mobile apps and third parties. Tokens are stored hashed (SHA-256) and carry abilities.

php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class TokenController extends Controller
{
    /** Mobile or third-party client trades credentials for a bearer token. */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
            'device_name' => ['required', 'string', 'max:100'],
        ]);

        $user = User::where('email', $data['email'])->first();
        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages(['email' => ['The credentials are incorrect.']]);
        }

        // Abilities limit what this token may do, whatever the user may do.
        // Sanctum stores a SHA-256 hash; the plain text exists only in this response.
        $token = $user->createToken($data['device_name'], ['orders:read']);

        return response()->json(['token' => $token->plainTextToken], 201);
    }

    /** Logout = delete the token row; the next request with it gets 401. */
    public function destroy(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(null, 204);
    }
}

Conditional GET as middleware: Symfony's Response::setEtag() and isNotModified() do the header work.

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Adds a validator to GET responses and turns "unchanged" into 304.
 * The body is still built (cheap here); for an expensive query compare
 * a version column BEFORE building the body instead.
 */
class ConditionalGet
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var Response $response */
        $response = $next($request);

        if (! $request->isMethodSafe() || ! $response->isSuccessful()) {
            return $response;
        }

        $response->setEtag(md5((string) $response->getContent()));
        $response->headers->set('Cache-Control', 'private, no-cache'); // store, but revalidate
        $response->isNotModified($request); // sets 304 and drops the body on a match

        return $response;
    }
}

SSE. Laravel documents response()->eventStream(): "The eventStream method may be used to return a server-sent events (SSE) streamed response using the text/event-stream content type" (Responses docs, saved text: laravel-responses). A generator yields values; StreamedEvent names the event.

php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\StreamedEvent;
use Symfony\Component\HttpFoundation\StreamedResponse;

class OrderStatusController extends Controller
{
    /** Short polling endpoint. */
    public function show(Request $request, Order $order): JsonResponse
    {
        abort_unless($request->user()->can('view', $order), 403);

        return response()->json([
            'order_id' => $order->id,
            'seq' => $order->status_seq,
            'status' => $order->status,
        ]);
    }

    /**
     * Server-Sent Events. Laravel's response()->eventStream() sends
     * text/event-stream and flushes each yielded value.
     * Each open stream occupies one PHP worker (php-fpm) for its whole life:
     * run this under Octane/Swoole/FrankenPHP, or prefer Reverb for many users.
     */
    public function stream(Request $request, Order $order): StreamedResponse
    {
        abort_unless($request->user()->can('view', $order), 403);

        $lastSeq = (int) $request->header('Last-Event-ID', 0);
        $deadline = now()->addMinutes(5); // let the client reconnect: bounded lifetime

        return response()->eventStream(function () use ($order, $lastSeq, $deadline) {
            while (now()->lessThan($deadline)) {
                $fresh = Order::query()->whereKey($order->id)->first(['id', 'status', 'status_seq']);

                if ($fresh && $fresh->status_seq > $lastSeq) {
                    $lastSeq = $fresh->status_seq;
                    yield new StreamedEvent(
                        event: 'status',
                        data: ['seq' => $fresh->status_seq, 'status' => $fresh->status],
                    );
                }

                if (connection_aborted()) {
                    return; // client left; stop polling the database
                }
                sleep(2); // a real system waits on a Redis channel instead of the table
            }
        });
    }
}

Broadcasting with Reverb (WebSocket): "Laravel Reverb brings blazing-fast and scalable real-time WebSocket communication directly to your Laravel application" (Reverb docs). An event that implements ShouldBroadcast is queued and sent to Reverb; the client listens with Laravel Echo on a private channel authorised in routes/channels.php.

php
<?php

namespace App\Events;

use App\Models\Order;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * Fired after the status changes. Because it implements ShouldBroadcast,
 * Laravel queues a broadcast job that pushes it to Reverb (WebSocket server).
 */
class OrderStatusUpdated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(public Order $order) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel('orders.'.$this->order->id)];
    }

    public function broadcastAs(): string
    {
        return 'status.updated';
    }

    public function broadcastWith(): array
    {
        return ['seq' => $this->order->status_seq, 'status' => $this->order->status];
    }
}
php
<?php

// routes/channels.php: authorizes who may subscribe to a private channel.
// The browser asks POST /broadcasting/auth first; Reverb accepts the socket only after it passes.

use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});
php
<?php

namespace App\Services;

use App\Events\OrderStatusUpdated;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

class OrderService
{
    /** The write side: one UPDATE, then one event. Polling, SSE and WebSocket all read from this. */
    public function advance(Order $order, string $status): Order
    {
        DB::transaction(function () use ($order, $status) {
            $order->forceFill(['status' => $status, 'status_seq' => $order->status_seq + 1])->save();
        });

        // dispatch AFTER the commit, or the socket client may re-fetch stale data
        OrderStatusUpdated::dispatch($order->refresh());

        return $order;
    }
}

Offline-first sync (idempotent by mutation id, compare-and-set on version; see Optimistic vs Pessimistic Locking):

php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\SyncedMutation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SyncController extends Controller
{
    /**
     * Offline-first batch sync. Mutation ids are made on the device, so a replay
     * after a lost response is detected (duplicate) instead of applied twice.
     */
    public function store(Request $request): JsonResponse
    {
        $batch = $request->validate([
            'mutations' => ['required', 'array', 'max:200'],
            'mutations.*.id' => ['required', 'uuid'],
            'mutations.*.order_id' => ['required', 'integer'],
            'mutations.*.base_version' => ['required', 'integer'],
            'mutations.*.note' => ['required', 'string', 'max:500'],
        ])['mutations'];

        $results = [];
        foreach ($batch as $m) {
            $results[] = DB::transaction(function () use ($m, $request) {
                // SyncedMutation: uuid primary key, `result` cast to array in the model
                if ($prior = SyncedMutation::find($m['id'])) {
                    return [...$prior->result, 'outcome' => 'duplicate'];
                }

                // compare-and-set on the version the client edited
                $updated = Order::whereKey($m['order_id'])
                    ->where('user_id', $request->user()->id)
                    ->where('version', $m['base_version'])
                    ->update(['note' => $m['note'], 'version' => DB::raw('version + 1')]);

                $current = Order::whereKey($m['order_id'])->first(['version', 'note']);
                $result = $updated
                    ? ['id' => $m['id'], 'outcome' => 'applied', 'version' => $current->version]
                    : ['id' => $m['id'], 'outcome' => 'conflict', 'version' => $current->version, 'server_note' => $current->note];

                SyncedMutation::create(['id' => $m['id'], 'result' => $result]);

                return $result;
            });
        }

        return response()->json($results);
    }
}

Laravel as a client of another service: the Http facade with explicit timeouts and a bounded retry.

php
<?php

namespace App\Clients;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

/**
 * Service-to-service: this Laravel app is a SERVER for browsers and a CLIENT
 * of the inventory service. Timeouts and retries belong here, not at call sites.
 */
class InventoryClient
{
    private function http(): PendingRequest
    {
        return Http::baseUrl(config('services.inventory.url'))
            ->acceptJson()
            ->withToken(config('services.inventory.token'))
            ->connectTimeout(1)       // seconds to open the TCP/TLS connection
            ->timeout(3)              // seconds for the whole call
            ->retry(3, 200, function (\Throwable $e) {
                // retry only network failures; a 4xx or 5xx response is not retried here
                return $e instanceof ConnectionException;
            }, throw: false)
            ->withHeaders(['X-Request-Id' => request()->header('X-Request-Id', (string) str()->uuid())]);
    }

    public function stock(int $sku): int
    {
        return $this->http()->get("/v1/stock/{$sku}")->throw()->json('available');
    }
}

Inertia versus API. Inertia keeps the controller and returns a page object; the React or Vue page gets props. An API controller returns JSON. Same model, different contract owner:

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Same data, two client-server shapes. Inertia keeps routing, auth and data
 * fetching on the server; the Vue/React page just receives props.
 * An API controller returns JSON for a separate SPA or a mobile app.
 */
class InertiaOrderController extends Controller
{
    public function show(Request $request, Order $order): Response
    {
        Gate::authorize('view', $order); // Laravel 13's base Controller has no authorize() helper

        return Inertia::render('Orders/Show', [
            'order' => $order->only('id', 'status', 'status_seq'),
        ]);
    }
}
QuestionInertiaSeparate API (Sanctum)
Who calls it?Only your own web UIWeb SPA, mobile, partners, other services
AuthSession cookie (normal Laravel)Cookie for first-party SPA, tokens for the rest
RoutingServer (Laravel routes)Server for API; client router for pages
Versioning burdenNone (UI and server deploy together)Real: old apps and partners
OfflineNoPossible (thick client)
Real-timeEcho/Reverb alongsideSame
Choose whenOne team, web only, speed mattersMore than one kind of client

The Laravel angle in short. A PHP-FPM worker handles one request at a time, so an SSE stream holds a whole worker for its life: for more than a handful of streams use Laravel Octane (Swoole, RoadRunner, FrankenPHP), or move push to Reverb, a separate long-running process. Sessions default to files or database in a fresh app; behind more than one replica use redis or database.

Worked example: order tracking three ways ​

Requirement. The customer opens "Where is my order?". The status moves placed → packed → shipped → delivered, a few changes per hour. 50,000 customers have the page open at peak. Build it with polling, SSE and WebSocket in both stacks.

Variant 1: short polling with ETag. Browser: every 10 s call fetch on the status URL with an If-None-Match header holding the last ETag; the server answers 304 when unchanged.

go
package main

import (
	"encoding/json"
	"net/http"
	"strconv"
	"time"
)

// poll answers short polling. The client repeats this call every few
// seconds; If-None-Match turns "nothing changed" into a body-less 304.
func (a *app) poll(w http.ResponseWriter, r *http.Request) {
	ev, ok := a.hub.Latest(r.PathValue("id"))
	if !ok {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("ETag", ev.ETag())
	w.Header().Set("Cache-Control", "no-cache") // store it, but always revalidate
	if r.Header.Get("If-None-Match") == ev.ETag() {
		w.WriteHeader(http.StatusNotModified)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(ev)
}

// longPoll holds the request open until something newer than ?seq= exists,
// or 25 seconds pass (below most proxy idle timeouts), then answers 204.
func (a *app) longPoll(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	seen, _ := strconv.Atoi(r.URL.Query().Get("seq"))

	ch, cancel := a.hub.Subscribe(id) // subscribe first, then read history: no gap
	defer cancel()
	if missed := a.hub.Since(id, seen); len(missed) > 0 {
		writeJSON(w, missed[len(missed)-1])
		return
	}

	timer := time.NewTimer(25 * time.Second)
	defer timer.Stop()
	select {
	case ev := <-ch:
		writeJSON(w, ev)
	case <-timer.C:
		w.WriteHeader(http.StatusNoContent) // client re-issues immediately
	case <-r.Context().Done():
		// client went away; the handler just returns
	}
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(v)
}

Variant 2: SSE. Server writes id:/event:/data:; the browser uses new EventSource(url) and resumes by Last-Event-ID.

go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"
)

// sse streams text/event-stream. The browser's EventSource reconnects by
// itself and sends the last id it saw in the Last-Event-ID header.
func (a *app) sse(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	rc := http.NewResponseController(w)

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("X-Accel-Buffering", "no") // tell nginx not to buffer
	fmt.Fprint(w, "retry: 3000\n\n")          // reconnect delay in milliseconds

	ch, cancel := a.hub.Subscribe(id) // subscribe first, then replay: no gap
	defer cancel()

	last, _ := strconv.Atoi(r.Header.Get("Last-Event-ID"))
	for _, ev := range a.hub.Since(id, last) {
		writeEvent(w, ev.Seq, "status", ev)
	}
	if err := rc.Flush(); err != nil {
		return
	}

	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()
	for {
		select {
		case ev := <-ch:
			writeEvent(w, ev.Seq, "status", ev)
		case <-heartbeat.C:
			fmt.Fprint(w, ": keep-alive\n\n") // a comment line keeps proxies awake
		case <-r.Context().Done():
			return
		}
		if err := rc.Flush(); err != nil {
			return
		}
	}
}

func writeEvent(w http.ResponseWriter, id int, name string, payload any) {
	b, _ := json.Marshal(payload)
	fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", id, name, b)
}
js
// Browser, SSE (EventSource cannot set headers: use a cookie session or a signed URL token)
const es = new EventSource('/orders/42/events');
es.addEventListener('status', (e) => render(JSON.parse(e.data)));
es.onerror = () => { /* the browser reconnects by itself and sends Last-Event-ID */ };

Variant 3: WebSocket. Go with coder/websocket, Laravel with Reverb and Echo.

go
package main

import (
	"context"
	"net/http"
	"strconv"
	"time"

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

// websocket upgrades the connection and pushes JSON frames. Unlike SSE the
// client can also send frames (here: {"ack": <seq>} to resume).
func (a *app) websocket(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
		OriginPatterns: []string{"app.example.com"}, // browsers do not enforce CORS here: check Origin yourself
	})
	if err != nil {
		return // Accept already wrote the HTTP error
	}
	defer c.CloseNow()

	ctx := c.CloseRead(r.Context()) // drains control frames, cancels ctx on close
	ch, cancel := a.hub.Subscribe(id)
	defer cancel()

	since, _ := strconv.Atoi(r.URL.Query().Get("seq"))
	for _, ev := range a.hub.Since(id, since) {
		if err := send(ctx, c, ev); err != nil {
			return
		}
	}
	ping := time.NewTicker(25 * time.Second)
	defer ping.Stop()
	for {
		select {
		case ev := <-ch:
			if err := send(ctx, c, ev); err != nil {
				return
			}
		case <-ping.C:
			pctx, pcancel := context.WithTimeout(ctx, 5*time.Second)
			err := c.Ping(pctx) // dead peers are found by a missing pong
			pcancel()
			if err != nil {
				return
			}
		case <-ctx.Done():
			_ = c.Close(websocket.StatusNormalClosure, "bye")
			return
		}
	}
}

func send(ctx context.Context, c *websocket.Conn, v any) error {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	return wsjson.Write(ctx, c, v)
}
js
// Browser, Laravel Echo + Reverb (private channel authorised by routes/channels.php)
window.Echo.private(`orders.${orderId}`)
  .listen('.status.updated', (e) => render(e));

And the server wiring plus the long-polling variant:

go
// Order tracking served four ways from one server: polling with ETag,
// long polling, Server-Sent Events and WebSocket.
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os/signal"
	"syscall"
	"time"

	"academy/client-server/internal/orders"
)

type app struct{ hub *orders.Hub }

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	a := &app{hub: orders.NewHub()}
	a.hub.Publish("42", "placed")

	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}/status", a.poll)     // 1. short polling + ETag
	mux.HandleFunc("GET /orders/{id}/wait", a.longPoll)   // 2. long polling
	mux.HandleFunc("GET /orders/{id}/events", a.sse)      // 3. Server-Sent Events
	mux.HandleFunc("GET /orders/{id}/ws", a.websocket)    // 4. WebSocket
	mux.HandleFunc("POST /orders/{id}/status", a.advance) // the write side

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,  // slowloris guard
		ReadTimeout:       10 * time.Second, // whole request incl. body
		IdleTimeout:       60 * time.Second, // keep-alive connections
		// No WriteTimeout: it would kill SSE and WebSocket streams.
		// Per-response deadlines use http.ResponseController instead.
	}

	go func() {
		<-ctx.Done()
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
		defer cancel()
		_ = srv.Shutdown(shutdownCtx) // stops accepting, waits for handlers
	}()

	log.Printf("listening on %s", srv.Addr)
	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}
}

func (a *app) advance(w http.ResponseWriter, r *http.Request) {
	status := r.URL.Query().Get("to")
	if status == "" {
		http.Error(w, "missing ?to=", http.StatusBadRequest)
		return
	}
	ev := a.hub.Publish(r.PathValue("id"), status)
	w.WriteHeader(http.StatusAccepted)
	_, _ = w.Write([]byte(ev.ETag()))
}

Comparison at 50,000 viewers (numbers are a worked estimate, not a benchmark; they assume 10 s polling, 5 events per order per day, and a 400-byte JSON status):

MeasurePolling (10 s, ETag)SSEWebSocket
Requests per second at peakabout 5,000 (most are 304)near 0 after connectnear 0 after connect
Open connectionsfew (keep-alive churn)50,00050,000
Time to see a changeup to 10 s, average 5 swell under 1 swell under 1 s
Bytes per idle minute per userabout 6 x 300 B = 1.8 KBheartbeat only, about 3 x 15 Bping/pong, about 2 x 10 B
Server memorysmall, short-livedtens of KB per streamtens of KB per socket
Works through CDNyes (cache the 304/200 for seconds)no (stream)no
Reconnect and resumenot neededbuilt in (Last-Event-ID)you write it (?seq=, ack)
Authnormal cookie or tokencookie or URL token (EventSource has no headers)Origin check + token on connect or channel auth
Laravel implementationConditionalGet + controllerresponse()->eventStream (needs Octane at scale)ShouldBroadcast + Reverb
Go implementationpoll.gosse.go (one goroutine per stream)ws.go (coder/websocket)
Best fitstatus page that changes rarelyone-way live statustwo-way or very high rate
Failure modestale for up to 10 sherd on reconnectherd + stuck sockets without ping

Decision. For a status that changes five times a day, polling with 304 is the right answer and the cheapest to run; ship SSE when "within a second" becomes a requirement; keep WebSocket for features where the client also sends (chat with support). Resist the upgrade because it is fashionable: every step up adds connections to operate.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Example (everyday). A Laravel or Go monolith with PostgreSQL, server-rendered pages and a session in the database. Client-server appears as browser to app server; polling with 304 or Livewire's own polling covers the live parts. One process means no replica problem: in-memory state works until you run a second instance, so start with SESSION_DRIVER=database or redis anyway. Retries are rare because there is no internal network.

Modular monolith and multiple databases ​

Example. The same codebase split into modules (orders, billing, notifications) with an internal in-process API between them, and a read replica for reports. The browser to server boundary is still the only network contract. Inside the process, modules call each other as function calls shaped like client calls (an interface, DTOs, no shared tables), so that a module can later become a service without changing callers. See Modular Monolith and Layered Monolithic Architecture. Push goes through an in-process event bus first, Reverb or a Go hub second.

Microservices ​

Example (production). A marketplace checkout: browser → API gateway (TLS, auth, rate limit) → BFF → orders, pricing, inventory, payments. Each arrow is a client-server hop with its own timeout and contract; payments exposes POST /v1/charges with Idempotency-Key; orders publishes OrderShipped events and a notification service turns them into push messages (SSE or APNs/FCM) for the customer. What survives a service boundary: HTTP semantics (idempotency, status codes, Retry-After), identity (propagated token or mTLS), a trace id. What does not: transactions (use sagas and outbox), shared memory, and "the call always returns". The contract is the product: Service Communication, Data Ownership, Microservices Architecture.

Distributed data: replicas, caches, multi-region ​

Example. The order-tracking page reads from a replica or a cache. A customer pays, is redirected to "My orders" and sees nothing: replica lag. Fixes: route that user's reads to the primary for a short time after a write (read-your-writes by session flag), return the created resource in the write response, or use a version token (seq) the client passes back and the server waits on. A CDN in front of status endpoints (Cache-Control: max-age=5, stale-while-revalidate=30) turns 50,000 polls into a handful of origin requests, at the price of up to five seconds of staleness. Multi-region: clients connect to the nearest region (GeoDNS), writes go to a home region, and WebSocket and SSE connections are regional, so a pub/sub backplane must fan events out across regions. See Replication & Failover, Redis, CDNs and Caching.

Scaling path: 1x, 10x, 100x ​

LoadShapeWhat changes in the client-server design
1x (hundreds of users)One app server, one database, polling every 10-30 sNothing special; add timeouts and ETag early because they are free
10xTwo or more replicas behind a load balancer, Redis for sessions and cache, a read replicaStatelessness becomes mandatory; remove sticky sessions; CDN for static assets; connection pooling (Connection Pooling)
100xGateway, autoscaled stateless tier, dedicated real-time tier (Reverb or Go hub) with a pub/sub backplane, queue for slow work, rate limiting and load sheddingSeparate the connection-holding tier from the request tier (different scaling signal: connections versus CPU); 429/503 with Retry-After; capacity per Capacity Estimation and SLOs per SLA, SLO, SLI
BeyondMulti-region, BFFs per client type, gRPC internally, cell-based isolationContracts and versioning dominate; ownership per team (Service Boundaries)

Lab ​

Goal. See the cost of polling, the effect of 304, the resume property of SSE and the stateless property, with the Go snippets. No database needed.

Setup (two terminals):

bash
cd docs/snippets/architecture/client-server/go
go run ./tracking          # terminal A: server on :8080 (order 42 starts as "placed")
  1. Short polling and 304. In terminal B:
    bash
    curl -si localhost:8080/orders/42/status | head -n 8      # 200, ETag: "42-1"
    curl -si -H 'If-None-Match: "42-1"' localhost:8080/orders/42/status | head -n 3   # expect: HTTP/1.1 304 Not Modified
  2. A change flips the validator.
    bash
    curl -s -X POST 'localhost:8080/orders/42/status?to=packed'      # prints "42-2"
    curl -si -H 'If-None-Match: "42-1"' localhost:8080/orders/42/status | head -n 1   # expect: 200 again (tag changed)
  3. Long polling. Terminal B: curl -s 'localhost:8080/orders/42/wait?seq=2' hangs. Terminal C: curl -s -X POST 'localhost:8080/orders/42/status?to=shipped'. Terminal B returns the shipped event at once. Without a change it returns 204 after 25 s.
  4. SSE and resume. curl -N localhost:8080/orders/42/events prints the history (ids 1..3) then waits. Change the status from another terminal and watch a new id: line appear. Stop curl, then resume: curl -N -H 'Last-Event-ID: 2' localhost:8080/orders/42/events prints only events with id greater than 2.
  5. Graceful shutdown. Start the SSE curl, press Ctrl-C in terminal A: the server stops accepting, waits up to 15 s for handlers, and the curl stream ends (the handler returns on r.Context().Done()).
  6. Stateless token. go run ./state prints a signed token. curl -i -H "Authorization: Bearer <token>" localhost:8082/me/token returns 200; change one character and it returns 401. Restart the process: the same token still works (the key is in code here; in production it comes from a secret store), unlike the in-memory session cookie, which dies with the process.

Expected: steps 1-2 show 304 then 200; step 3 shows an instant answer after the change; step 4 shows id: 3 onward only on resume; step 6 shows the token surviving a restart and the session not.

Common misconceptions ​

BeliefReality
"Client-server means web browser and web server"It is a style of roles; mobile apps, CLIs and services are clients too
"Stateless means the system has no state"The server process has none between requests; the state moved to the client or a shared store
"Sticky sessions give me stateless scaling"They hide state in server memory and break on deploys and crashes
"JWT is stateless so I never need a lookup"True until you need logout or revocation; then you add state (a deny list) or keep tokens short-lived
"WebSocket is the modern replacement for polling"SSE or polling with 304 is simpler and enough for one-way updates
"The server pushes to the browser"The browser opened the connection; the server writes into it
"CORS protects my API"CORS only constrains browsers reading responses; curl and server-side callers ignore it
"POST is for everything that changes data"Idempotent changes belong on PUT/DELETE; POST needs an idempotency key to be retried
"A 200 with {error: ...} is fine"Caches, retries, monitors and clients rely on status codes
"REST must be JSON"REST is a set of constraints; the representation can be HTML, JSON or anything
"Internal calls do not need timeouts"Unbounded internal calls cause cascading failures
"Thick clients are always better UX"They move complexity and security risk to the device and need an API contract and sync
"Inertia is just an SPA"It keeps routing, auth and data fetching on the server and needs no separate API
"Add a version number and compatibility is solved"Additive change inside one version is cheaper; each version doubles the test surface

Cheat sheet ​

TopicWhat to remember
The styleClient asks, server owns data and rules; separation of concerns lets both evolve (Fielding)
TiersTier = deploy boundary with a network call; layer = code grouping; add a tier only for a named reason
Thin vs thickRules on the server always; the client predicts, the server decides
StatelessAny replica can answer from the request plus a shared store; kill a server, lose nobody
State placesCookie, token, URL, local storage (client); Redis, database, cache, queue (shared)
PollingETag + If-None-Match turns waste into 304
Long pollingPark the request about 25 s, answer on change or 204, re-ask
SSEOne-way, text/event-stream, id: + Last-Event-ID resume, heartbeat comment, no WriteTimeout
WebSocketTwo-way, own protocol, check Origin, ping/pong, you write resume
gRPCTyped, HTTP/2, four call types, deadlines on every call
HTTP promisesSafe = read-only; idempotent = GET, PUT, DELETE; POST needs Idempotency-Key
Status codes401 who are you, 403 not allowed, 409/412 version clash, 429 slow down, 503 retry later
Security boundaryAuthenticate, authorize per resource, validate input, TLS, CSRF for cookies, CORS is browser-only
Load balancingLeast-connections for streams; no sticky sessions; drain on deploy
MicroservicesEvery service is both; deadlines, retries on idempotent calls only, contracts versioned
EvolutionAdditive changes, tolerant readers, Deprecation and Sunset headers
GoOwn http.Client with timeouts; http.Server with ReadHeaderTimeout; Shutdown(ctx)
Laravelroutes/api.php stateless; Sanctum cookie or token; eventStream for SSE; Reverb for WebSocket

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What two constraints does Fielding's client-server style add, and what does the separation buy? Important ​

Answer

Answer: A client that initiates and a server that owns data and rules, communicating over a connector. Separation of concerns simplifies the server (scalability) and lets both sides evolve independently as long as the interface stays stable.

2 — A three-layer Laravel app on one server: how many tiers is it, and why? Must-know ​

Answer

Answer: Server side it is one tier (layers are code groups inside one process); with the browser and the database the system is three-tier. Layers and tiers differ: a tier boundary means a network call.

3 — A user is logged out after every deploy. Name two likely causes and the fixes. Must-know ​

Answer

Answer: Sessions stored in server memory or local files, or sticky sessions pinned to a replaced server. Fix by using a shared session store (Redis or database) or signed tokens, so any replica can read the session.

4 — Why is PUT safe to retry but POST not, and how do you make POST retryable? Must-know ​

Answer

Answer: RFC 9110 defines PUT and DELETE as idempotent: repeating has the same effect as once. POST has no such guarantee. Send an Idempotency-Key; the server stores the first result and returns it for repeats.

5 — How does a conditional GET reduce load, and what are the two headers? Must-know ​

Answer

Answer: The server returns an ETag; the client sends it back as If-None-Match; if unchanged, the server answers 304 Not Modified with no body, saving bandwidth and serialization work.

6 — When would you pick SSE over WebSocket? Must-know ​

Answer

Answer: When updates flow one way (server to client): SSE is plain HTTP, reconnects automatically and resumes with Last-Event-ID. WebSocket is for two-way, high-rate traffic.

7 — What is the SSE gotcha over HTTP/1.1 in browsers, and how do you avoid it? Important ​

Answer

Answer: A browser allows about six connections per host, so many tabs exhaust them. Use HTTP/2 (many streams per connection) or share one stream per tab group.

8 — Why must a Go server that serves SSE not set WriteTimeout? Important ​

Answer

Answer: WriteTimeout bounds the whole response, so it kills long-lived streams. Use http.NewResponseController(w).SetWriteDeadline per write or no global write timeout on streaming routes.

9 — CORS is configured correctly yet an attacker's site can still make your user's browser change data. Why? Must-know ​

Answer

Answer: CORS restricts reading cross-origin responses, not sending requests; a cross-site form POST with the user's cookie is CSRF. Defend with SameSite cookies and CSRF tokens (or use Bearer tokens instead of cookies).

10 — Your service calls three others and each retries 3 times. What is the worst-case amplification, and what do you do? Must-know ​

Answer

Answer: Retries multiply across layers (3 x 3 x 3 = 27 calls to the deepest service). Retry at one layer, use a retry budget and jitter, and propagate deadlines.

11 — Inertia or a Sanctum API: how do you choose? Important ​

Answer

Answer: If only your own web UI calls the server, Inertia avoids designing and versioning an API. If mobile apps, partners or other services will call it, build the API first.

12 — Two phones edit the same order offline. Describe a safe sync protocol. Good to know ​

Answer

Answer: Each mutation has a client-generated id (dedupe) and the base_version it edited. The server compares and sets: apply if the version matches, otherwise return a conflict with the server copy for the client to merge.

Glossary ​

TermMeaning
ClientComponent that initiates requests
ServerComponent that owns resources and answers requests
ConnectorThe mechanism joining components (HTTP, gRPC, SQL wire protocol)
TierDeployment boundary with a network call between sides
LayerCode-level grouping inside one program
Two-tier / three-tier / n-tierClient + database; client + app server + database; more intermediate servers
Thin clientClient with little logic; server renders and decides
Thick (fat, rich) clientClient holding significant logic and data
Stateless serverServer that keeps no per-client memory between requests
SessionServer-side record of a logged-in user, found by an id in a cookie
Bearer tokenCredential sent in the Authorization header; whoever holds it can use it
Sticky session / session affinityBalancer pins a client to one server
Short pollingClient repeats a request on a timer
Long pollingRequest parked on the server until data or timeout
SSE (Server-Sent Events)One-way HTTP stream, text/event-stream, with automatic reconnect
WebSocketTwo-way framed protocol after an HTTP upgrade (RFC 6455)
gRPC streamingServer, client or bidirectional streams over HTTP/2
WebhookServer-to-server callback POST on an event
IdempotentRepeating gives the same effect as once
Safe methodA method not expected to change server state
ETagOpaque version tag of a representation
Conditional requestRequest with If-None-Match, If-Match or If-Modified-Since
304 Not Modified"Use your cached copy"
Content negotiationClient and server agree on format and language through Accept* headers
CORSBrowser mechanism by which a server permits cross-origin reads
CSRFAttack that makes a browser send an authenticated request from another site
SPASingle-page application: the browser builds HTML from JSON
SSRServer-side rendering of HTML
Hypermedia / HATEOASResponses carry the next possible actions as links or forms
InertiaProtocol and adapters letting a server-routed app render Vue/React pages without an API
LivewireLaravel framework for server-rendered interactive components
HTMXLibrary that drives HTML fragment swaps with attributes
Offline-firstDesign in which the local store is primary and the network is a sync channel
BackplaneShared pub/sub that lets many real-time servers deliver to each other's clients
Thundering herdMany clients retrying or reconnecting at the same instant
DeadlineAbsolute time by which a call must finish, propagated to callees
Tolerant readerClient that ignores unknown fields
BFFBackend-for-Frontend: a server tailored to one kind of client

References ​

Primary sources read and saved for this chapter (saved under scratchpad/sources/client-server/):

Built by Morteza Negahi