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 for | Go to |
|---|---|
| The whole page in a few tables | Everything in one minute |
| Why the style exists and what it costs | Why it exists |
| Fielding, Shaw and Garlan, Tanenbaum, HTTP | Where it comes from |
| Roles, request-response, separation of concerns | The style |
| Two-tier, three-tier, n-tier | Tiers |
| Thick versus thin clients | Thick and thin clients |
| Sessions, tokens, where state lives | Stateless servers |
| Polling, long polling, SSE, WebSocket, gRPC streams | Request-response vs push |
| Methods, idempotency, ETag, 304, Accept | Client-server over HTTP |
| REST, gRPC, GraphQL | API styles |
| The opposite style | Peer-to-peer |
| SPA, SSR, Inertia, Livewire, HTMX | Rendering models |
| Mobile, sync, conflicts | Mobile and offline-first |
| Authentication, TLS, CORS, CSRF | Security at the boundary |
| Replicas, sticky sessions | Load balancing |
| Services calling services | Inside microservices |
| Versioning, compatibility | Evolution |
| Retry, timeouts, 429, 503 | Mechanics and Solving the classic problems |
| Which option when | Choosing |
| Go server and client | Go |
| Laravel API, Sanctum, SSE, Reverb | Laravel |
| Order tracking three ways | Worked example |
| Monolith to distributed | In architecture |
| Hands-on exercise | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked later.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Client | The side that starts a conversation | Browser, mobile app, another service | Nobody knows who may initiate |
| Server | The side that waits and answers; owns the data and the rules | GET /orders/42 handler | Rules scattered across every client |
| Request-response | One question, one answer, then the exchange is over | HTTP GET returns 200 | Fine for fetching; wrong for "tell me when it changes" |
| Tier | A deployable layer of the system | Browser, app server, database | Logic mixed with storage or UI |
| Thin client | Little logic; the server decides and renders | Server-rendered page | Slow UI on poor networks |
| Thick client | Much logic runs on the device | Mobile app with local database | Logic duplicated and hard to update |
| Stateless server | Needs nothing remembered from the previous request | Bearer token carries the identity | Cannot add replicas freely |
| Push | The server sends without being asked each time | SSE, WebSocket | Clients hammer the server with polling |
| Idempotent | Repeating it has the same effect as doing it once | PUT, DELETE, GET | A retry charges the card twice |
| Conditional request | "Send it only if it changed" | If-None-Match then 304 | Full payload every poll |
| API style | The shape of the contract | REST, gRPC, GraphQL | Contract arguments in every code review |
| Offline-first | The app works without a connection and syncs later | Notes app on a train | Lost data and "no network" screens |
The style in one table.
| Question | Answer |
|---|---|
| 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.
| Option | Direction | Connection | Typical latency | Typical use |
|---|---|---|---|---|
| Short polling | client asks repeatedly | new request each time | up to one interval | order status every 10 s |
| Long polling | client asks, server holds | request parked up to ~25 s | near real time | chat on hostile networks |
| SSE (Server-Sent Events) | server to client | one long GET | near real time | notifications, progress, LLM tokens |
| WebSocket | both ways | one upgraded TCP connection | near real time | chat, collaborative editing, games |
| gRPC server streaming | server to client | one HTTP/2 stream | near real time | internal feeds |
| gRPC bidirectional streaming | both ways | one HTTP/2 stream | near real time | internal real-time pipelines |
| Webhook | server to a server URL | one POST per event | seconds | payment 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 files | One source of truth; every client sees the same order |
| Updating means reinstalling everywhere | Fix the server once; clients stay the same |
| Security is the user's laptop | Secrets and checks live on a machine you control |
| Free from network failure | A network sits in the middle: latency and partial failure are now part of design |
| Scales by buying bigger desks | Scales 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
- "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.
- "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.
- "Push needs WebSocket." No. For one-way updates SSE is simpler, cheaper to operate and reconnects by itself; plain polling with
304is 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).
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 interactivityThe 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.
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 gives | How | What it costs |
|---|---|---|
| Independent evolution | Contract between sides stays stable | The contract becomes a public API with compatibility duty |
| Server simplicity and scale | UI moved away from the server | Latency on every interaction |
| Central control | Rules and data in one place | Single place that must be available (and replicated) |
| Client variety | Web, iOS, Android, CLI share one server | Every 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.
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.
| Shape | Typical stack | Strength | Weakness | Still seen in |
|---|---|---|---|---|
| Two-tier | Desktop app speaks SQL to PostgreSQL, SQL Server or Oracle | Simple, fast to build, rich UI | Business rules in every client; database exposed; every client holds a connection; updating means redeploying clients | Internal tools, point-of-sale, legacy ERP |
| Three-tier | Browser or app, Laravel or Go server, PostgreSQL or MySQL | Rules in one place; database private; clients stay thin | The app server is the bottleneck and single point to replicate | Most web applications |
| N-tier | Client, CDN, load balancer, gateway, services, cache, databases | Each tier scales and is secured on its own | Latency adds up, more to operate, partial failures | Large platforms |
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 hopsReal 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.
| Property | Thin client | Thick client |
|---|---|---|
| Logic lives in | server | device (and duplicated on the server for safety) |
| Update | deploy the server; every user gets it | app store review, or code-on-demand in the browser |
| Works offline | no | yes, if it holds data |
| Server load | higher (renders, decides) | lower per interaction |
| Network sensitivity | high: every click is a round trip | low after the first load |
| Security | rules cannot be bypassed | rules on the device can be bypassed; the server must re-check |
| Examples | classic Laravel Blade, Livewire, HTMX, terminal | SPA with React, native iOS app, desktop IDE |
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 differFix / 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.
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).
| Where | Example | Pros | Cons | Revocation |
|---|---|---|---|---|
| Client, signed token (JWT, Sanctum token) | Authorization: Bearer ... | No lookup (JWT); easy to scale | Size on every request; leaked token works until expiry | Hard for self-contained JWT; easy for a database token |
| Client, cookie with session id | Set-Cookie: laravel_session=... | Browser handles it; HttpOnly hides it from JavaScript | CSRF risk; cookies only for same site | Delete the server row |
| Client, URL or hidden field | ?page=3&cursor=... | Linkable, cacheable, back button works | Visible and tamperable: validate | n/a |
| Server memory | in-process session | Fastest | Dies with the process; forces sticky sessions | Restart loses everyone |
| Shared store | Redis, Memcached, database | Any replica can read; revocable; TTL | One more dependency, one more hop | Delete the key |
| Database | sessions, personal_access_tokens tables | Durable, queryable | Load on the primary for every request | Delete the row |
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 outReal 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.
-- 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.
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).
| Technique | Mechanism | Strengths | Weaknesses | Browser support and proxy notes |
|---|---|---|---|---|
| Short polling | GET every N seconds; If-None-Match makes unchanged answers a body-less 304 | Simplest; cacheable; CDN-friendly; stateless | Latency up to N; wasted requests; load grows with users times rate | Everywhere |
| Long polling | GET held until data or timeout (~25 s), then re-issued | Near real time; works through nearly every proxy | One parked request per user; each answer costs a full request; ordering and gaps need care | Everywhere |
| SSE | One GET, Content-Type: text/event-stream, server writes id:, event:, data: lines; EventSource reconnects and sends Last-Event-ID | Simple; automatic reconnect and resume; plain HTTP; text only | One 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+) |
| WebSocket | HTTP Upgrade handshake then framed TCP messages (RFC 6455) | Both directions; low overhead per message; binary | Own protocol: no HTTP caching, no automatic resume, must check Origin, harder load balancing and auth; every connection is state | All current browsers |
| gRPC streaming | HTTP/2 stream with Protocol Buffers messages; server, client or bidirectional | Typed contract; deadlines; backpressure via HTTP/2 flow control | Browsers need gRPC-Web or a proxy; internal use mostly | Services, mobile SDKs |
| Webhook | Provider POSTs to your URL when an event happens | No polling by you | You must be reachable, verify signatures, accept duplicates and reordering | Server 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).
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 streamReal 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).
| Method | Safe | Idempotent | Cacheable | Typical use | Retry after a timeout? |
|---|---|---|---|---|---|
GET | yes | yes | yes | read a resource | yes |
HEAD | yes | yes | yes | headers only (existence, size, ETag) | yes |
OPTIONS | yes | yes | no | CORS preflight, capabilities | yes |
PUT | no | yes | no | replace a resource at a known URL | yes |
DELETE | no | yes | no | remove a resource | yes |
POST | no | no | rarely | create, run an action | only with an Idempotency-Key |
PATCH | no | not guaranteed | no | partial update | only if you make it idempotent (version check) |
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 chargeStatus codes you must know:
| Code | Meaning | Client should |
|---|---|---|
| 200 / 201 / 204 | OK / created (send Location) / success, no body | proceed |
| 301 / 308 | moved permanently (308 keeps the method) | update the link |
| 304 | not modified: use your cached copy | reuse cache |
| 400 / 422 | malformed request / valid syntax but invalid data (Laravel validation returns 422) | fix input, do not retry as-is |
| 401 | not authenticated (no or bad credentials) | log in or refresh the token |
| 403 | authenticated but not allowed | do not retry |
| 404 / 410 | not found / gone | stop |
| 409 | conflict with current state (version mismatch) | re-read, merge, retry |
| 412 | precondition failed (If-Match did not match) | re-read, retry |
| 429 | too many requests (honour Retry-After) | back off |
| 500 / 502 / 503 / 504 | server error / bad gateway / unavailable / gateway timeout | retry 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.
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)| Header | Direction | Purpose |
|---|---|---|
Cache-Control: max-age=N, no-cache, no-store, private, public, s-maxage, stale-while-revalidate | response | how long and by whom it may be reused. no-cache means "store it, but revalidate", no-store means "never store" |
ETag / If-None-Match | response / request | opaque version tag; 304 when equal |
Last-Modified / If-Modified-Since | response / request | time-based validator, one-second resolution |
If-Match | request | write only if the version still matches; 412 otherwise (optimistic concurrency over HTTP) |
Vary: Accept-Encoding, Accept-Language | response | which request headers the cached copy depends on |
Accept, Accept-Language, Accept-Encoding | request | content negotiation: the client states what it can take |
Content-Type, Content-Encoding, Content-Language | response | what the server actually chose |
Retry-After | response | seconds or date to wait after 429/503 |
Idempotency-Key | request | client-chosen key to deduplicate POST (an IETF draft convention; Stripe popularised it) |
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.
| Aspect | REST (resource over HTTP) | RPC and gRPC | GraphQL |
|---|---|---|---|
| Contract | OpenAPI document (optional) | .proto file (required, typed) | schema (required, typed) |
| Unit | resource: /orders/42 | method: OrderService.Track | query/mutation against one endpoint |
| Transport | HTTP/1.1, HTTP/2 | HTTP/2 + Protocol Buffers | HTTP POST (usually) + JSON |
| Caching | HTTP caches, CDN (via GET) | none by default | hard: one URL, POST |
| Over-fetch / under-fetch | common | fixed per method | solved by the client choosing fields |
| Streaming | SSE, WebSocket on the side | native: 4 call types (unary, server, client, bidirectional) | subscriptions (usually WebSocket) |
| Browser friendly | yes | needs gRPC-Web | yes |
| Best for | public APIs, CRUD, cacheable reads | internal service-to-service, low latency, polyglot teams | many client types with different data needs (mobile + web) |
| Main risk | chatty clients, verbs hidden in URLs | tight coupling to generated code, harder to debug with curl | N+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.
| Aspect | Client-server | Peer-to-peer |
|---|---|---|
| Roles | fixed | every node is both |
| Control and data | central, authoritative | spread across nodes |
| Scaling | add servers (you pay) | capacity grows with participants (they pay) |
| Failure | the server is a single point (replicate it) | no single point, but churn and partitions |
| Security and trust | one place to secure | every peer is untrusted |
| Consistency | easy: one authority | hard: needs gossip, CRDTs or consensus (CRDTs) |
| Examples | web, email, databases | BitTorrent, 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.
| Model | HTML built by | Client-server contract | Examples | Strength | Weakness |
|---|---|---|---|---|---|
| Classic SSR | server, full page per navigation | HTML pages and forms | Laravel Blade, Go html/template | Simple, SEO-friendly, little JavaScript | Full reload per action |
| SPA | browser, from JSON | JSON API | React or Vue + Laravel/Go API with Sanctum | Rich interaction, offline possible, one API for web and mobile | Large bundle, SEO and first paint need work, two codebases |
| SSR + hydration | server first, then browser takes over | HTML + JSON | Next.js, Nuxt | First paint fast, rich later | Complex build, two runtimes |
| Server-driven UI with a thin protocol | server picks the component and props | Inertia protocol (JSON page object) | Inertia (Vue/React/Svelte) with Laravel | Keep routing, controllers, auth on the server, write the page in Vue or React, no separate API | Tied to your own server; mobile still needs a real API |
| Server-driven UI over WebSocket | server holds component state, sends HTML diffs | HTML fragments | Livewire | Interactivity in PHP, no JavaScript to write | Server round trip per interaction; component state is per-session (stateful) |
| Hypermedia | server returns HTML fragments, hx-* attributes drive swaps | HTML over HTTP | HTMX, Turbo | Close to Fielding's REST, minimal JavaScript | Not 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.
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 strategy | How | Good for | Cost |
|---|---|---|---|
| Last write wins | newest timestamp or version overwrites | counters you can lose, preferences | Silently drops edits; clock skew |
| Reject on conflict (compare-and-set) | base_version must match, else 409/conflict | orders, inventory, money | User must resolve |
| Field-level merge | merge changed fields only | profile forms | Needs per-field versions |
| CRDT | data types that merge by design | collaborative text, counters | Complexity; see CRDTs |
| Operation log | send intents ("add item"), not states | carts, ledgers | Server 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.
| Concern | Mechanism | Where it lives | Chapter |
|---|---|---|---|
| Authentication (who) | Session cookie, Bearer token (Sanctum, JWT), OAuth 2.0 / OIDC | Gateway or app server middleware | Authentication, JWT, OAuth2/OIDC |
| Authorization (what) | Policies, RBAC, abilities (token scopes) | App server, per resource | Authorization models |
| Transport | TLS (HTTPS), HSTS; mTLS between services | Edge and service mesh | Cryptography and TLS, mTLS |
| Cross-origin | CORS: the browser asks the server whether a page from another origin may read the response | Server response headers | Web sessions, cookies, CORS |
| CSRF | A malicious site makes the browser send your cookie: defend with SameSite cookies and a CSRF token | Cookie-based apps only | OWASP Top 10 |
| Input validation | Validate type, size, range on the server (Laravel Form Requests) | Server | Security by Design |
| Abuse | Rate limiting (429 + Retry-After), payload size caps, timeouts | Gateway and server | Rate limiting |
| WebSocket specifics | Check Origin on the upgrade; authenticate on connect; browsers do not apply CORS to sockets | Server | RFC 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 / feature | How | Fits | Note |
|---|---|---|---|
| Round robin | each server in turn | identical, short requests | ignores load |
| Least connections | server with fewest open connections | long requests, SSE, WebSocket | the usual choice for push |
| Weighted | proportional to capacity | mixed hardware | |
| Consistent hashing on a key | same key, same server | cache locality, shard-like workloads | rebalancing on change |
| Cookie or IP affinity | pin by cookie or source IP | legacy stateful apps | avoid; use a shared store |
| L4 versus L7 | TCP level versus HTTP level (path, header, cookie) | L7 for routing and TLS termination | see Load Balancing |
| Health checks | active probes remove a bad node | all | readiness endpoint must test dependencies, liveness must not |
| Connection draining | stop new requests, let in-flight finish | deploys | pair with Go's http.Server.Shutdown |
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 errorFor 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.
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-client | Why | Where |
|---|---|---|
| Set connect and total timeouts; propagate the caller's deadline | Prevent thread pile-up | Timeouts, Retries & Jitter |
| Retry only idempotent calls, with jitter and a budget | Retries multiply load | API Idempotency |
| Circuit breaker around each dependency | Stop calling a dead service | Circuit Breaker |
| Pass identity and trace ids | Authorization and debugging | mTLS |
| Version the contract; add fields, do not change meaning | Callers deploy later than the server | Evolution |
| Prefer fewer, coarser calls | Chatty clients pay latency per call | Service 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.
| Change | Backward compatible? | Rule |
|---|---|---|
| Add an optional response field | yes | Clients must ignore unknown fields (tolerant reader) |
| Add an optional request field with a default | yes | The default keeps old behaviour |
| Add a new endpoint | yes | |
| Remove or rename a field | no | Add the new one, deprecate the old, remove after the sunset date |
| Change a field's type or meaning | no | New field name |
| Tighten validation | no (for old clients) | Introduce behind a flag, or in the next version |
| Change status codes or error shape | no | Treat error format as part of the contract |
| Versioning approach | Example | Pros | Cons |
|---|---|---|---|
| URL path | /api/v1/orders | Visible, easy to route and cache | Version proliferation |
| Header or media type | Accept: application/vnd.shop.v2+json | Clean URLs | Hidden, harder to test by hand |
| Query parameter | ?version=2 | Easy to try | Caches and logs need care |
| Date-pinned (per account) | Stripe-Version: 2024-06-20 | Gradual upgrades per client | Needs a compatibility layer on the server |
| Additive only + feature flags | no version at all | Least work | Needs 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
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
MaxIdleConnsPerHostServer 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
| Protocol | Behaviour | Consequence |
|---|---|---|
| HTTP/1.0 | one request per TCP connection | handshake cost every time |
| HTTP/1.1 | persistent by default (keep-alive); one request at a time per connection | browsers open about six connections per host |
| HTTP/2 | many streams over one connection, header compression | one connection per host is enough; SSE limit disappears; head-of-line blocking at TCP level remains |
| HTTP/3 | QUIC over UDP | no 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
| Situation | Retry? | How |
|---|---|---|
| Connect error, DNS error | yes (idempotent or not: nothing was sent) | jittered exponential back-off |
| Timeout after sending | only if idempotent or keyed | same request, same Idempotency-Key |
429 or 503 with Retry-After | yes, after that delay | honour the header |
| 500, 502, 504 on idempotent call | yes, bounded | at most 2-3 tries |
| 400, 401, 403, 404, 422 | no | fix the request |
| 409, 412 | after re-reading | merge 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
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
| Shared session store | SESSION_DRIVER=redis (Laravel), session id in a cookie | Revocable, small cookie | Redis becomes critical; one lookup per request |
| Signed token | Sanctum token or JWT in Authorization | No store hit (JWT) | Revocation and size; rotate keys |
| Sticky sessions | balancer pins by cookie | Quick fix for legacy apps | Uneven load, logout on deploy |
| Client-held state | URL, signed hidden field | Zero server memory | Size, tampering (sign it) |
Problem 2: polling that melts the server
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
| Conditional GET | ETag + If-None-Match → 304 | Tiny responses, shared CDN cache | Still one request per tick |
| Adaptive interval | slow down when idle, speed up after a change | Fewer requests | More client code |
| Server hint | Retry-After or a field next_poll_in | Server controls load | Needs client cooperation |
| Switch to SSE | one stream per user | Near real time, fewer requests | Connections to hold (capacity) |
| Push through a broker | server publishes to Redis/NATS; web tier fans out | Scales fan-out | One more system |
Problem 3: the retry that charges twice
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
Idempotency-Key header | store key + result for 24 h | Safe retries of POST | Storage, key scope per user |
| Natural idempotency | PUT /orders/42/status with the full state | No extra storage | Not every action fits |
| Unique constraint | UNIQUE (client_request_id) | Database guarantees it | Error handling for the duplicate |
| Version check | If-Match / WHERE version = ? | Stops lost updates too | Client must re-read on 412 |
Problem 4: slow clients and giant responses
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
| Pagination | cursor or keyset (see Pagination) | Bounded payload | Client complexity |
| Compression | Accept-Encoding: gzip, br | 70-90% smaller JSON | CPU (cache compressed assets) |
| Field selection | ?fields=id,status, GraphQL | Less over-fetch | Cache keys multiply |
| Streaming | NDJSON, SSE, gRPC server stream | First byte early | Resume logic |
| Async job | 202 Accepted + Location: /jobs/7 to poll | Long work without long requests | Job 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.
| Need | Choose | Why | Watch out |
|---|---|---|---|
| Status updated every minute or slower | Short polling with ETag | Zero new infrastructure | Interval times users equals load |
| Updates in seconds, one direction, browsers | SSE | Reconnect and resume built in; plain HTTP | Six-connection limit on HTTP/1.1; proxy buffering |
| Updates in seconds, hostile proxy or old browser | Long polling | Works everywhere | Parked requests count as capacity |
| Chat, presence, collaborative editing | WebSocket (Laravel Reverb, Go coder/websocket) | Two-way, low overhead | Check Origin, authenticate, scale with a pub/sub backplane |
| Internal real-time between services | gRPC streaming | Typed, deadlines, flow control | Not for browsers without gRPC-Web |
| A third party tells you something happened | Webhook | No polling | Verify signature, dedupe, accept reordering |
| Wake a sleeping phone | APNs / FCM push | OS-level, battery-friendly | Not guaranteed delivery; send data via the API |
| Low-latency telemetry up (device to server) | WebSocket or gRPC client stream | One connection, many frames | Backpressure |
Architecture variant, one table.
| Situation | Choose | Reason |
|---|---|---|
| Internal admin tool, one team, web only | Inertia or Livewire or Blade | No separate API to design and version |
| Public product with web, iOS, Android | API first (REST or GraphQL) + SPA/native clients | One contract, many clients |
| Content site, SEO matters | SSR or hypermedia | Fast first paint, crawlable |
| Field workers, bad network | Offline-first thick client + sync API | Works without connection |
| High-fan-out feeds | Push through a pub/sub backplane | See Feeds |
| Services calling services | gRPC or REST with deadlines + contracts | Typed, 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.
// 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.
// 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.
// 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.
// 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
// 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
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
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
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
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
// 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
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
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
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
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'),
]);
}
}| Question | Inertia | Separate API (Sanctum) |
|---|---|---|
| Who calls it? | Only your own web UI | Web SPA, mobile, partners, other services |
| Auth | Session cookie (normal Laravel) | Cookie for first-party SPA, tokens for the rest |
| Routing | Server (Laravel routes) | Server for API; client router for pages |
| Versioning burden | None (UI and server deploy together) | Real: old apps and partners |
| Offline | No | Possible (thick client) |
| Real-time | Echo/Reverb alongside | Same |
| Choose when | One team, web only, speed matters | More 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.
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.
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)
}// 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.
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)
}// 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:
// 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):
| Measure | Polling (10 s, ETag) | SSE | WebSocket |
|---|---|---|---|
| Requests per second at peak | about 5,000 (most are 304) | near 0 after connect | near 0 after connect |
| Open connections | few (keep-alive churn) | 50,000 | 50,000 |
| Time to see a change | up to 10 s, average 5 s | well under 1 s | well under 1 s |
| Bytes per idle minute per user | about 6 x 300 B = 1.8 KB | heartbeat only, about 3 x 15 B | ping/pong, about 2 x 10 B |
| Server memory | small, short-lived | tens of KB per stream | tens of KB per socket |
| Works through CDN | yes (cache the 304/200 for seconds) | no (stream) | no |
| Reconnect and resume | not needed | built in (Last-Event-ID) | you write it (?seq=, ack) |
| Auth | normal cookie or token | cookie or URL token (EventSource has no headers) | Origin check + token on connect or channel auth |
| Laravel implementation | ConditionalGet + controller | response()->eventStream (needs Octane at scale) | ShouldBroadcast + Reverb |
| Go implementation | poll.go | sse.go (one goroutine per stream) | ws.go (coder/websocket) |
| Best fit | status page that changes rarely | one-way live status | two-way or very high rate |
| Failure mode | stale for up to 10 s | herd on reconnect | herd + 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
| Load | Shape | What changes in the client-server design |
|---|---|---|
| 1x (hundreds of users) | One app server, one database, polling every 10-30 s | Nothing special; add timeouts and ETag early because they are free |
| 10x | Two or more replicas behind a load balancer, Redis for sessions and cache, a read replica | Statelessness becomes mandatory; remove sticky sessions; CDN for static assets; connection pooling (Connection Pooling) |
| 100x | Gateway, autoscaled stateless tier, dedicated real-time tier (Reverb or Go hub) with a pub/sub backplane, queue for slow work, rate limiting and load shedding | Separate 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 |
| Beyond | Multi-region, BFFs per client type, gRPC internally, cell-based isolation | Contracts 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):
cd docs/snippets/architecture/client-server/go
go run ./tracking # terminal A: server on :8080 (order 42 starts as "placed")- 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 - 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) - 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 theshippedevent at once. Without a change it returns204after 25 s. - SSE and resume.
curl -N localhost:8080/orders/42/eventsprints the history (ids 1..3) then waits. Change the status from another terminal and watch a newid:line appear. Stop curl, then resume:curl -N -H 'Last-Event-ID: 2' localhost:8080/orders/42/eventsprints only events with id greater than 2. - 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()). - Stateless token.
go run ./stateprints a signed token.curl -i -H "Authorization: Bearer <token>" localhost:8082/me/tokenreturns 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| The style | Client asks, server owns data and rules; separation of concerns lets both evolve (Fielding) |
| Tiers | Tier = deploy boundary with a network call; layer = code grouping; add a tier only for a named reason |
| Thin vs thick | Rules on the server always; the client predicts, the server decides |
| Stateless | Any replica can answer from the request plus a shared store; kill a server, lose nobody |
| State places | Cookie, token, URL, local storage (client); Redis, database, cache, queue (shared) |
| Polling | ETag + If-None-Match turns waste into 304 |
| Long polling | Park the request about 25 s, answer on change or 204, re-ask |
| SSE | One-way, text/event-stream, id: + Last-Event-ID resume, heartbeat comment, no WriteTimeout |
| WebSocket | Two-way, own protocol, check Origin, ping/pong, you write resume |
| gRPC | Typed, HTTP/2, four call types, deadlines on every call |
| HTTP promises | Safe = read-only; idempotent = GET, PUT, DELETE; POST needs Idempotency-Key |
| Status codes | 401 who are you, 403 not allowed, 409/412 version clash, 429 slow down, 503 retry later |
| Security boundary | Authenticate, authorize per resource, validate input, TLS, CSRF for cookies, CORS is browser-only |
| Load balancing | Least-connections for streams; no sticky sessions; drain on deploy |
| Microservices | Every service is both; deadlines, retries on idempotent calls only, contracts versioned |
| Evolution | Additive changes, tolerant readers, Deprecation and Sunset headers |
| Go | Own http.Client with timeouts; http.Server with ReadHeaderTimeout; Shutdown(ctx) |
| Laravel | routes/api.php stateless; Sanctum cookie or token; eventStream for SSE; Reverb for WebSocket |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Client | Component that initiates requests |
| Server | Component that owns resources and answers requests |
| Connector | The mechanism joining components (HTTP, gRPC, SQL wire protocol) |
| Tier | Deployment boundary with a network call between sides |
| Layer | Code-level grouping inside one program |
| Two-tier / three-tier / n-tier | Client + database; client + app server + database; more intermediate servers |
| Thin client | Client with little logic; server renders and decides |
| Thick (fat, rich) client | Client holding significant logic and data |
| Stateless server | Server that keeps no per-client memory between requests |
| Session | Server-side record of a logged-in user, found by an id in a cookie |
| Bearer token | Credential sent in the Authorization header; whoever holds it can use it |
| Sticky session / session affinity | Balancer pins a client to one server |
| Short polling | Client repeats a request on a timer |
| Long polling | Request parked on the server until data or timeout |
| SSE (Server-Sent Events) | One-way HTTP stream, text/event-stream, with automatic reconnect |
| WebSocket | Two-way framed protocol after an HTTP upgrade (RFC 6455) |
| gRPC streaming | Server, client or bidirectional streams over HTTP/2 |
| Webhook | Server-to-server callback POST on an event |
| Idempotent | Repeating gives the same effect as once |
| Safe method | A method not expected to change server state |
| ETag | Opaque version tag of a representation |
| Conditional request | Request with If-None-Match, If-Match or If-Modified-Since |
| 304 Not Modified | "Use your cached copy" |
| Content negotiation | Client and server agree on format and language through Accept* headers |
| CORS | Browser mechanism by which a server permits cross-origin reads |
| CSRF | Attack that makes a browser send an authenticated request from another site |
| SPA | Single-page application: the browser builds HTML from JSON |
| SSR | Server-side rendering of HTML |
| Hypermedia / HATEOAS | Responses carry the next possible actions as links or forms |
| Inertia | Protocol and adapters letting a server-routed app render Vue/React pages without an API |
| Livewire | Laravel framework for server-rendered interactive components |
| HTMX | Library that drives HTML fragment swaps with attributes |
| Offline-first | Design in which the local store is primary and the network is a sync channel |
| Backplane | Shared pub/sub that lets many real-time servers deliver to each other's clients |
| Thundering herd | Many clients retrying or reconnecting at the same instant |
| Deadline | Absolute time by which a call must finish, propagated to callees |
| Tolerant reader | Client that ignores unknown fields |
| BFF | Backend-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/):
- Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapters 3 and 5: net_arch_styles, rest_arch_style
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110; RFC 9111, HTTP Caching: https://www.rfc-editor.org/rfc/rfc9111
- RFC 6455, The WebSocket Protocol: https://www.rfc-editor.org/rfc/rfc6455
- RFC 9745 (Deprecation header): https://www.rfc-editor.org/rfc/rfc9745; RFC 8594 (Sunset header): https://www.rfc-editor.org/rfc/rfc8594
- WHATWG HTML Standard, Server-sent events: https://html.spec.whatwg.org/multipage/server-sent-events.html
- MDN: HTTP overview, CORS, Conditional requests, Content negotiation, Using server-sent events
- gRPC core concepts: https://grpc.io/docs/what-is-grpc/core-concepts/
- Laravel 13: Routing, Sanctum, Responses, Broadcasting, Reverb, HTTP Client, CSRF
- Inertia: https://inertiajs.com/; Livewire: https://livewire.laravel.com/docs/quickstart
- Go:
go doc net/http(Server, Client, Transport, ResponseController);github.com/coder/websocket - Secondary (not fetched, cited from memory of the books, no quotation): Shaw and Garlan, Software Architecture: Perspectives on an Emerging Discipline (1996); Tanenbaum and van Steen, Distributed Systems: Principles and Paradigms.