The Client-Server Model
"HTTP is a stateless request/response protocol for exchanging "messages" across a connection." — RFC 9110, HTTP Semantics, section 3.4 (IETF, June 2022)
Summary: Almost every system on the internet is a client asking and a server answering, and almost every scaling, caching and reliability problem is a question about one of the five things that sit between the two: who holds the state, who owns the connection, what one connection costs the server, what the client may remember, and what happens when a request is lost or repeated. Focus: Roles and request/response, thin and thick clients, stateless and stateful servers and sessions, two-, three- and n-tier layouts (presentation, application and data tier, reverse proxy, API server, BFF), the journey of one request (DNS, TCP, TLS, HTTP, application, database), the server side under load (prefork, worker pools, event loops, goroutines; Apache, NGINX, PHP-FPM, Octane with Swoole, FrankenPHP and RoadRunner, Go net/http), connection handling (keep-alive, connection pools, limits, the C10K problem, epoll and kqueue), client-side caching with ETag, If-None-Match and 304, push versus pull, mobile clients (idempotent retry, backoff, offline-first), and peer-to-peer and hybrid models (BitTorrent, WebRTC signalling), with Go and Laravel 13 code. Learning goal: For any feature, say which side owns which state, trace the request from the name lookup to the database and back with a number on every hop, size a worker pool with arithmetic instead of hope, make a response cacheable with a validator, and make a client retry without making an outage worse.
This is the first chapter of the Networking & Protocols group. It owns the system-design mechanics and numbers of the style. The style itself, with Fielding's constraints and the variants, is in Client-Server Architecture and Its Variants. Each layer of the journey has a deeper page that this one links instead of repeating: IP, DNS & GeoDNS, TCP & UDP, HTTP/1.1, HTTP/2, HTTP/3 & Keep-Alive, Forward vs Reverse Proxies, Web Sessions, Cookies & CORS, Real-Time Communication, Scaling Strategies and Load Balancing. On the foundations side: Network Models and What Happens When You Open a URL, DNS Resolution for Developers, Ports, Sockets & Connections and TLS in Practice.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in four tables | Everything in one minute |
| Why a split into two programs exists, and what it costs | Why it exists |
| RFC 9110, C10K, WebRTC, where the numbers come from | Where it comes from |
| Client, server, request, response | Roles |
| Thin client versus thick client | Thin and thick clients |
| Stateless versus stateful, sessions | Stateless and stateful, Sessions |
| Two-tier, three-tier, n-tier, BFF, API server | Tiers |
| DNS to TCP to TLS to HTTP to database | The journey of a request |
| prefork, worker pool, event loop, goroutine | Server concurrency models |
| PHP-FPM, Octane, Swoole, FrankenPHP | PHP servers |
| Keep-alive, pools, limits, backlog | Connection handling |
| C10K, epoll, kqueue | C10K and readiness notification |
| ETag, If-None-Match, 304 | Client-side caching |
| Polling, SSE, WebSocket versus request/response | Push versus pull |
| Retries, backoff, offline-first | Mobile and flaky clients |
| BitTorrent, WebRTC, signalling | Peer-to-peer and hybrid |
| Knobs, defaults, error messages | Mechanics |
| Code | Go, Laravel |
| Real failures and fixes | Solving the classic problems |
| Which model for which workload | Choosing |
| One process to a fleet | In architecture |
| Reproduce the numbers | Lab |
| Beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The pattern. A client starts every exchange; a server waits for it. The same program can be a client on one connection and a server on another (RFC 9110 says exactly that), so "client" and "server" are roles of a connection, not kinds of machine.
| Term | In plain words | Tiny example | What it owns |
|---|---|---|---|
| Client | The side that opens the connection and sends the request | A browser, a mobile app, a Laravel service calling a payment API | The user's screen, its own cache, retry decisions |
| Server | The side that accepts connections and answers | NGINX, a Go net/http process, PHP-FPM behind NGINX | The data, the rules, the connection limits |
| Request | One message: method, target, headers, optional body | GET /catalog with If-None-Match: "a1b2" | Intent and validators |
| Response | One message back: status, headers, optional body | 304 Not Modified, or 200 with ETag | Result and cache instructions |
| Reverse proxy | A server that forwards to other servers | NGINX or AWS ALB in front of the app | TLS ending, buffering, routing, limits |
| BFF | A server shaped for one kind of client | A mobile-only API that returns exactly the mobile screen | Aggregation and trimming |
State and where it lives.
| Choice | Meaning | Example | Scaling effect |
|---|---|---|---|
| Stateless server | Every request carries what the server needs | JWT or a session id looked up in Redis | Any replica can answer; add boxes freely |
| Stateful server | The process remembers between requests | In-memory session map, a WebSocket room in RAM | Requests must reach the same box (affinity) or the state is lost |
| Thin client | Little logic, server renders | Server-rendered Laravel Blade page | Cheap devices, server does the work |
| Thick client | Real logic and local state | Mobile app with local database, SPA | Fast UI and offline use, harder updates and trust |
One server, four ways to hold connections.
| Model | One connection costs | Typical products | Limit knob | Weak spot |
|---|---|---|---|---|
| Process per request | A whole OS process while busy | Apache prefork, PHP-FPM | MaxRequestWorkers, pm.max_children | RAM per process, slow clients pin a process |
| Thread pool plus listener | A thread only while a request runs | Apache event MPM | MaxRequestWorkers, ThreadsPerChild | Thread-safe code needed |
| Event loop | A few kilobytes of state | NGINX, Node.js, Swoole, Octane workers | worker_connections | One blocking call stalls every connection on that loop |
| Goroutine per connection | A goroutine (small stack) parked by the runtime | Go net/http | Your own limits (LimitListener, timeouts) | Unbounded unless you bound it |
The request, hop by hop (fresh connection, same data centre, orders of magnitude).
| Hop | What happens | Cost on a fresh connection | Cost on a reused one |
|---|---|---|---|
| DNS | Name to IP address | 0 ms cached, tens of ms on a miss | 0 |
| TCP | Three-way handshake | 1 round trip | 0 |
| TLS 1.3 | Key exchange, certificate | 1 more round trip (RFC 8446) | 0 |
| HTTP | Request out, response back | 1 round trip plus server time | 1 round trip plus server time |
| Application | Routing, validation, business rules | CPU time, often 1-50 ms | same |
| Database | Query over a pooled connection | 0.2-5 ms in one data centre | same |
Every row is unpacked below. The rest of the page is about moving cost from the left column of that last table to the right column.
Why it exists
Two programs on one machine can share memory. Two programs on different machines cannot, so something has to say who speaks first and who keeps the truth. The client-server split answers both: the server keeps the truth and waits; the client asks, shows and decides what to do when the answer does not come. The alternatives all exist (mainframe terminals, peer-to-peer, a shared network file), and each one gives something up.
| Gain from the split | Cost of the split |
|---|---|
| One place to secure, audit, update and bill | The server is a shared bottleneck and a single target |
| Clients stay simple and replaceable | Every interaction is a network call that can be slow, lost or repeated |
| Data stays consistent because one party writes it | The server must absorb every client's peak at once |
| Server and client change and scale independently | Two versions of the contract live at the same time in production |
| Failure is local: a client can crash alone | A server crash is everyone's outage |
An everyday picture. A restaurant. Guests (clients) order; the kitchen (server) cooks and keeps the stock. A waiter is a reverse proxy: guests never walk into the kitchen. The kitchen has a fixed number of cooks (workers); more guests than cooks means a queue at the door (the listen backlog). A guest who leaves the table with a half-eaten plate still occupies the seat (a slow client holds a connection). Takeaway orders (HTTP caching) save the kitchen a trip when the dish has not changed.
Three common misunderstandings, up front
- "A server is a big machine." It is a role. A phone can serve; a data-centre box can be a client of a hundred services in the same minute.
- "Stateless means the system has no state." It means the server process does not keep the per-user state between requests; the state is in the request, a database, Redis or a signed token.
- "More workers always means more throughput." Workers are bounded by RAM, CPU and the database behind them; past the knee, more workers only lengthen queues.
Where it comes from
HTTP's own specification defines the vocabulary used here: RFC 9110 describes HTTP as "a family of stateless, application-level, request/response protocols" and says one program can be a client on some connections and a server on others. Roy Fielding's dissertation derives the client-server constraint as a separation of concerns; that argument is told in the architecture chapter and not repeated.
The scaling story that shaped today's server designs is Dan Kegel's C10K page. It opens with the question "It's time for web servers to handle ten thousand clients simultaneously, don't you think?" and surveys the options of its time: one thread per client, many clients per thread with nonblocking I/O and readiness notification (select, poll, epoll, kqueue), and asynchronous I/O. The dated notes on the page are from 2001 (it mentions "As of 2001" and an epoll proposal of 11 July 2001), so its hardware numbers belong to that era; the ideas did not age. The readiness-notification route won on Linux and the BSD family, which is why NGINX documents epoll and kqueue as its efficient connection-processing methods.
Peer-to-peer is the older and the contrasting idea. BitTorrent's specification (BEP 3) describes it as "a protocol for distributing files" whose advantage over plain HTTP is that "the downloaders upload to each other", so the file source supports very large numbers of downloaders "with only a modest increase in its load". WebRTC takes the hybrid route: browsers exchange media directly, but, as the MDN signalling guide puts it, "A form of discovery and media format negotiation must take place", and that part needs a server.
What this page does not claim: dates for Apache's MPMs, NGINX's first release or PHP-FPM's merge into PHP are not stated here because they were not in the sources read for this chapter.
The concept catalogue
Client, server, request and response Must-know
In plain words: The client opens the connection and asks; the server answers. One question, one answer, then both sides forget everything about it unless something stored it.
Common misunderstanding: "The server is the powerful machine and the client is the user's device." The roles are per connection. Your API server is a client of PostgreSQL, of Redis, and of the payment provider.
Definition: In HTTP a client sends a request message (method, request target, headers, optional content); a server returns a response message (status code, headers, optional content). RFC 9110 defines the protocol as stateless: "each request message's semantics can be understood in isolation", and connections have no bearing on meaning.
Client Server
1 open connection ------------------------> accept()
2 GET /orders/42 HTTP/1.1 -----------------> parse, route, authorise
3 <------------------------ 200 OK + body (or 404, 503)
4 next request on the same connection ------> (keep-alive)
5 close (or idle timeout fires on a side)Real scenario: A mobile app calls GET /orders/42. The same Laravel process, while answering, is a client of the database (SQL over a pooled connection) and of a shipping API (Laravel HTTP client). Three client-server pairs in one request.
What provides it: Every HTTP stack: NGINX, Apache httpd, Go net/http, PHP-FPM behind a web server, Laravel Octane.
How to use it: Think per arrow. For every arrow draw the client side's timeout and retry rule, and the server side's limit and duplicate rule. Most outages are a missing line on one of those.
Thin and thick clients Important
In plain words: A thin client shows what the server prepared; a thick client does real work itself and keeps its own data.
Common misunderstanding: "Thick means a native app and thin means a website." A single-page application is a thick client in a browser; a native app that only renders server-driven screens is thin.
Definition: Thin: rendering and logic on the server, the client displays (server-rendered HTML, terminal, remote desktop). Thick (also called fat or rich): significant logic, validation, caching and state on the client (SPA, mobile app with local database, game).
| Dimension | Thin client | Thick client |
|---|---|---|
| Where logic runs | Server | Client, plus the server for truth |
| Update path | Deploy once, everyone is updated | App stores, cache busting, old versions in the wild for months |
| Offline | Does not work | Can work (offline-first) |
| Trust | Server decides | The client cannot be trusted; the server re-validates everything |
| Payload | Rendered pages | Data (JSON) |
| Latency feel | Each click is a round trip | Instant locally, sync later |
| Typical stack | Laravel Blade, Livewire | React or Vue SPA, Flutter, Swift or Kotlin apps |
Thin: click -> request -> server renders HTML -> response -> repaint (1 round trip per click)
Thick: click -> local state changes -> repaint -> background sync request (0 round trips to feel it)Real scenarios: A banking back office on server-rendered pages (thin: audit and updates are simple). A chat app that shows your message instantly and marks it "sending" until the server acknowledges (thick). A map app that downloads tiles for offline use.
Fix / how to choose: Start thin unless offline, latency feel or device capabilities force thick. Thick clients need the server to validate everything again and need a version policy (see API Versioning).
Stateless and stateful servers Must-know
In plain words: A stateless server forgets you between requests, so any copy of it can serve your next one. A stateful server remembers, so only that copy can.
Common misunderstanding: "My app is stateless because I use sessions." Sessions are state. The app server is stateless only if the session lives outside the process (Redis, database, signed cookie).
Definition: Stateless: the server holds no per-client data between requests that a different replica could not obtain. Stateful: a process holds data that other replicas lack (in-memory sessions, WebSocket connections and their rooms, an open transaction, a local file).
Stateful: client -> LB -> server A (holds session) next request lands on B -> "logged out"
Stateless: client -> LB -> server A ----+
+--> Redis: session 8f2c... <- any server reads it
client -> LB -> server B ----+| Where state can live | Example | Scales how | Cost |
|---|---|---|---|
| Client (cookie, token) | Signed JWT, Laravel encrypted cookie session | Perfectly (the server stores nothing) | Size limits, revocation is hard |
| Shared store | Redis, Memcached, database sessions | Needs the store to scale | One extra hop, a new dependency |
| Server memory | PHP file sessions on one box, Go map | Only with sticky routing | Lost on restart, lost on scale-out |
| Database | Orders, carts, balances | Per database chapters | Latency, contention |
| Connection | A WebSocket subscribed to rooms | Needs fan-out between boxes (see realtime) | Reconnect storms after a deploy |
Real scenarios: The autoscaler adds two replicas and half the users are logged out (sessions in process memory). A deploy restarts all workers and every in-memory shopping cart vanishes. A WebSocket server holds 200 000 sockets; draining it for a deploy takes ten minutes.
Fix: Move per-user state out of the process by default; if a connection must be stateful, make that tier small, drain it gently and let clients reconnect with jitter. The scaling consequences are in Scaling Strategies.
Sessions Must-know
In plain words: HTTP does not remember you; a session is the trick that makes it look as if it does: the client sends the same small identifier every time, and the server (or the identifier itself) supplies the memory.
Common misunderstanding: "A session is a server-side object." It is an identifier plus wherever the data lives. Laravel's docs open with exactly this: "Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests."
Definition: A session ties several requests to one user through an identifier (usually a cookie), with data in a backend: Laravel supports file, cookie, database, Memcached, Redis, DynamoDB and array drivers.
1 POST /login (credentials) ---> server creates session s123 in Redis
2 <--- Set-Cookie: laravel_session=s123; HttpOnly; Secure
3 GET /cart Cookie: s123 ---> server loads s123 from Redis, answersThe cookie attributes, CORS, CSRF and token-versus-session trade-offs are owned by Web Sessions, Cookies, Serialization & CORS and Authentication; this page only fixes where the state sits. A database session table looks like this:
-- Laravel's database session driver stores one row per session.
CREATE TABLE sessions (
id VARCHAR(255) PRIMARY KEY,
user_id BIGINT NULL,
ip_address VARCHAR(45) NULL,
user_agent TEXT NULL,
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);Fix / how to use it: In Laravel set SESSION_DRIVER=redis for a fleet, and know that session blocking (a lock per session, needs an atomic-lock cache driver) serialises parallel requests of one user.
Tiers: two-tier, three-tier, n-tier Must-know
In plain words: A tier is a group of machines or processes that does one kind of job, so you can scale and secure it on its own. Two tiers: client and database. Three: client, application server, database. More than three: add proxies, BFFs, caches, queues.
Common misunderstanding: "Tier and layer are the same." Layers are code organisation inside one program (Fowler's presentation, domain logic, data access); tiers are where those parts run. One three-layer Laravel app can run in a single tier.
Definition: The presentation tier is what the user touches (browser, app); the application tier runs business logic (the API server); the data tier stores state (PostgreSQL, Redis). Fowler's bliki describes the usual split as "presentation (UI), domain logic (aka business logic), and data access". An n-tier design inserts further tiers: a reverse proxy, an API gateway, a backend-for-frontend (BFF), caches, search and queue systems.
| Layout | What talks to the database | Strength | Weakness | Seen today |
|---|---|---|---|---|
| Two-tier | The client itself | Fewest moving parts | Credentials and rules on every device; every client opens its own DB connection | Internal tools, desktop apps of the 1990s, some mobile "backend as a service" setups |
| Three-tier | Only the application server | Rules in one place; DB reachable only from the app network | The app tier scales with the slowest query | Default for web applications |
| n-tier | Domain services behind proxies and BFFs | Each tier scales and fails separately; tailored APIs | More hops, more deadlines, more to monitor | Large systems and microservices |
A BFF is an API server owned by one front end (web, mobile): it aggregates calls to several services and trims fields so the client makes one request. An API server is any server whose product is data, not pages. A reverse proxy sits in front of either, ends TLS, and forwards; its detail is in Forward vs Reverse Proxies, and the BFF and gateway trade-offs are in API Gateway, BFF & Service Mesh.
Real scenarios: A Laravel monolith behind NGINX is three-tier (browser, NGINX plus PHP-FPM, MySQL). Adding Redis and a queue worker makes it n-tier without any microservice. A mobile client that needs 9 calls to render the home screen gets a BFF that does the 9 calls server-side and returns one payload.
Fix / how to choose: Add a tier only when you can name what it removes: a trust boundary, a scaling unit, a client-specific contract. Each tier costs a hop, a timeout and a failure mode (Cascading Failures).
The journey of a request Must-know
In plain words: Before your code runs, the client has to find the server, open a connection and agree on encryption. After your code runs, the answer takes the same road back.
Common misunderstanding: "A request is one round trip." On a fresh connection it is at least three: TCP, TLS, then HTTP, plus DNS; keep-alive and connection reuse are what bring it back to one.
Definition: The standard path: name resolution (DNS), transport connection (TCP), optional TLS handshake, HTTP request, proxy, application, database, then the response on the reverse path.
t=0 ms DNS lookup api.example.com -> 203.0.113.10 (cached: 0 ms)
t=+1 RTT TCP SYN / SYN-ACK / ACK -> connection open (RFC 9293)
t=+1 RTT TLS 1.3 ClientHello / ServerHello -> encrypted channel (RFC 8446)
t=+1 RTT GET /orders/42 HTTP/1.1 ------------> reverse proxy
proxy picks a worker, forwards on a kept-alive upstream connection
worker: route -> auth -> controller -> SELECT ... (pooled DB connection)
t=+server 200 OK + body <------------ same path back| Layer | Owns | Failure you see | Where it is taught |
|---|---|---|---|
| DNS | Name to address, TTL, GeoDNS | NXDOMAIN, stale record after a move | IP, DNS & GeoDNS, DNS for developers |
| TCP | Reliable byte stream, congestion | connection refused, timeout, reset | TCP & UDP, Ports & sockets |
| TLS | Encryption, server identity | Certificate errors, handshake failures | TLS in Practice |
| HTTP | Methods, status codes, caching | 4xx, 5xx, 304 | HTTP evolution |
| Proxy / LB | Routing, limits, TLS ending | 502, 503, 504 | Load Balancing |
| Application | Business rules | 500, 422, 409 | the rest of this chapter |
| Database | Truth | Timeouts, deadlocks, pool exhaustion | Connection Pooling |
The latency budget of this whole path, geography and the p99 are in Latency Budgets & Tail Latency. Here, the point is the shape: DNS, TCP and TLS cost round trips only on a fresh connection, so the cheapest request is one that reuses a connection.
Server concurrency models: prefork, worker pools, event loops, goroutines Must-know
In plain words: A server needs a plan for many clients at once. It can give each client its own process, share a pool of threads, run one loop that watches thousands of sockets, or start a cheap goroutine per client.
Common misunderstanding: "An event loop is faster than threads." It uses less memory per idle connection. For CPU-heavy requests it is the same CPU; and one blocking call (a slow DNS lookup, a synchronous disk read) stalls every connection on that loop.
Definition: Four models. (1) Process per request: a pool of worker processes, each handling one request at a time. (2) Thread pool, optionally with an event-driven listener. (3) Event loop: a small number of threads multiplex many nonblocking sockets through the OS readiness API. (4) Goroutine per connection: blocking-style code, with the Go runtime parking goroutines on its network poller.
| Product | Model | What the vendor docs say | The limit you tune |
|---|---|---|---|
| Apache httpd, prefork MPM | Process per request | "A single control process is responsible for launching child processes which listen for connections and serve them when they arrive"; it keeps spare idle processes ready so clients "do not need to wait for a new child processes to be forked" | MaxRequestWorkers, StartServers, MinSpareServers, MaxSpareServers |
| Apache httpd, event MPM | Threads plus listener | "designed to allow more requests to be served simultaneously by passing off some processing work to the listeners threads, freeing up the worker threads" | MaxRequestWorkers, ThreadsPerChild, ServerLimit |
| NGINX | Event loop in a few worker processes | Chooses a connection processing method per platform: epoll on Linux 2.6+, kqueue on FreeBSD, OpenBSD, NetBSD and macOS | worker_processes, worker_connections (default 512), worker_rlimit_nofile |
| PHP-FPM | Process pool, one request at a time per child | pm.max_children "sets the limit on the number of simultaneous requests that will be served" | pm, pm.max_children, pm.start_servers, spare servers |
| Laravel Octane | Long-lived workers on Swoole, FrankenPHP or RoadRunner | "Octane boots your application once, keeps it in memory, and then feeds it requests" | --workers, --max-requests, --task-workers |
Go net/http | Goroutine per connection | Serve accepts connections "creating a new service goroutine for each" | ReadHeaderTimeout, IdleTimeout, your own connection limit |
| Node.js | Single-threaded event loop | (not a source read for this chapter) | worker threads or cluster |
Process per request (PHP-FPM, pm = dynamic, max_children = 3)
t0 A B C all three busy
t1 D arrives -> no free child -> waits in the listen backlog (accept queue)
t2 A finishes -> D starts
A slow client or a slow query holds its child the whole time.
Event loop (NGINX worker)
epoll_wait() -> [fd 14 readable, fd 90 writable, fd 311 readable] -> handle each without blocking -> epoll_wait()Real scenarios: A PHP site fine at 50 users whose p99 goes from 80 ms to 12 s at 300 users: all pm.max_children workers are in a slow query, the rest queue. A Go service that handles 50 000 idle WebSocket-like connections on one box and then falls over because nothing limits the number of requests per connection. NGINX in front of both, absorbing slow clients so the app workers never see them.
What provides it: The table above, per product. PHP's classic model is shared-nothing: each request boots the framework and ends; Octane gives that up for speed and in exchange asks you to write long-lived-safe code (see PHP servers).
Fix / how to use it: Put an event-driven proxy (NGINX, HAProxy, Envoy, a cloud load balancer) in front of a worker-pool server so slow clients are buffered there. Size the pool with the formula in Mechanics.
PHP servers: FPM, Octane, Swoole, FrankenPHP, RoadRunner Important
In plain words: PHP-FPM starts the framework fresh for every request and throws it away; Octane starts it once and reuses it, which is much faster and much easier to get subtly wrong.
Common misunderstanding: "Octane is just a faster FPM." It is a different lifecycle. Static properties, singletons that captured the first request, and growing arrays now survive between requests.
Definition: PHP-FPM (FastCGI Process Manager) is a pool manager: a web server such as NGINX hands requests to it over FastCGI, and each child process runs one request at a time (pm = static, dynamic or ondemand). Laravel Octane serves the app through Swoole, Open Swoole, FrankenPHP or RoadRunner; by default it "will start an application request worker for each CPU core" and "gracefully restarts any worker once it has handled 500 requests" (--max-requests).
| Aspect | PHP-FPM (+ NGINX or Apache) | Octane on Swoole / Open Swoole | Octane on FrankenPHP | Octane on RoadRunner |
|---|---|---|---|---|
| Process model | Pool of processes, one request each | Workers with a Swoole event loop and coroutines | Workers inside the Caddy-based server | Go server managing PHP workers |
| App boot | Every request | Once per worker | Once per worker | Once per worker |
| Memory between requests | None | Kept | Kept | Kept |
| Extra Octane features | n/a | Concurrent tasks, ticks, Octane cache and tables | Basic | Basic |
| Typical failure | pm.max_children reached, 502 or 504 at the proxy | Memory growth, state leaking across requests | Same | Same |
# FPM status page (pm.status_path) when the pool is too small
pool: www
active processes: 40
max active processes: 40
max children reached: 187 <- every increment is a request that waited or failed
listen queue: 63 <- connections waiting for a free childThe leak rules for a long-lived worker are in the Laravel section below. The question "Octane or FPM?" is answered in Choosing.
Connection handling: keep-alive, pools, limits, backlog Must-know
In plain words: Opening a connection is expensive, so both sides keep them open and reuse them, within limits so nobody runs out of sockets or memory.
Common misunderstanding: "A bigger connection pool is a faster pool." A pool larger than the database or server can use just moves the queue into a worse place (the database's lock manager, the server's memory).
Definition: HTTP/1.1 connections are persistent by default: RFC 9112 says HTTP/1.1 defaults to the use of "persistent connections", allowing multiple requests and responses to be carried over a single connection, and a Connection: close header ends it. Keep-alive is that reuse; an idle timeout (keepalive_timeout in NGINX, IdleTimeout in Go, KeepAliveTimeout in Apache) closes idle ones. A connection pool is a bounded set of reusable connections held by a client (HTTP to another service, SQL to a database). The listen backlog is the kernel queue of connections completed by TCP but not yet accepted by the process.
| Where | Knob | Default (from the docs read) | What it bounds |
|---|---|---|---|
| NGINX | worker_connections | 512 per worker | All connections of a worker, client and upstream together |
| NGINX | keepalive_timeout, keepalive_requests | set per server | Idle time and requests per client connection |
| NGINX upstream | keepalive | off unless set | Idle connections cached to the app per worker |
| Apache httpd | MaxRequestWorkers, ListenBacklog | MPM dependent | Simultaneous requests, accept queue |
| PHP-FPM | listen.backlog | 511 on Linux, -1 on BSD | The accept queue of the FPM socket |
| Go server | IdleTimeout, ReadHeaderTimeout | no timeout if zero | Idle and slow-header clients |
| Go client | Transport.MaxIdleConnsPerHost | 2 (DefaultMaxIdleConnsPerHost) | Idle connections reused per destination |
| Laravel HTTP client | connectTimeout | 10 seconds | Time to open the connection |
| Linux | ulimit -n, net.core.somaxconn | system dependent | File descriptors per process; the cap on the backlog |
Without keep-alive, 4 requests: 4 x (TCP + TLS handshake + request) = 4 connections
With keep-alive, 4 requests: 1 x (TCP + TLS handshake) + 4 requests = 1 connection
Go pool, MaxIdleConnsPerHost = 2, 10 parallel callers to one host:
8 connections are opened, used, then CLOSED on return (only 2 may stay idle) -> constant reconnectsReal scenarios: A Go client that never drains resp.Body cannot reuse its connections: each request opens a new one. A service whose pool is 200 per replica, times 50 replicas, asks PostgreSQL for 10 000 connections. NGINX proxying to PHP-FPM over a new upstream connection per request because proxy_http_version 1.1 and the Connection "" header were not set.
What provides it / fix: In Go, create one http.Client and share it (client.go); configure Transport pool limits. In NGINX, enable upstream keepalive (snippet under Mechanics). In Laravel, remember each PHP-FPM worker has its own connection, so total connections are workers times replicas; use a pooler as described in Connection Pooling. The HTTP/2 and HTTP/3 side (many requests multiplexed on one connection) is in HTTP evolution.
The C10K problem, epoll and kqueue Important
In plain words: In the late 1990s a server that gave one thread to each client could not reach ten thousand clients; the fix was to stop asking each socket "anything yet?" and to let the kernel say which sockets are ready.
Common misunderstanding: "C10K is solved, so it does not matter." The OS part is solved; the application part is not: ten thousand idle connections are cheap, ten thousand slow requests to a database that allows 100 connections are not.
Definition: C10K is the problem of handling ten thousand simultaneous connections on one server. Readiness-notification APIs make it practical: select and poll scan every descriptor on each call (cost grows with the number of connections), epoll (Linux 2.6+) and kqueue (FreeBSD, NetBSD, OpenBSD, macOS) report only the descriptors that changed. Kegel's page also lists the per-process file descriptor limit (ulimit, setrlimit) as a constraint to raise.
poll(): for each of 10 000 fds: is it ready? -> O(connections) per wake-up
epoll(): kernel keeps a ready list; epoll_wait returns 3 fds -> O(ready) per wake-up| Mechanism | OS | Cost per wake-up | Used by |
|---|---|---|---|
select | everywhere, fd limit (FD_SETSIZE) | scans all | legacy |
poll | everywhere | scans all | legacy, small fd sets |
epoll | Linux 2.6+ | only ready fds | NGINX on Linux, Go runtime netpoller on Linux, Swoole, Node.js (libuv) |
kqueue | FreeBSD, OpenBSD, NetBSD, macOS | only changed fds | NGINX on BSD and macOS, Go on macOS |
Real scenarios: A chat gateway with 100 000 mostly idle sockets: event-driven is the only sane choice. The Go lab in this chapter opens 500 idle connections to net/http and reports about 500 extra goroutines.
Fix: Pick a runtime built on epoll or kqueue; raise ulimit -n; set idle timeouts; cap connections per client. The socket-level tools (ss, lsof) are in Ports, Sockets & Connections.
Client-side caching: ETag, If-None-Match and 304 Must-know
In plain words: The server stamps a response with a fingerprint. Next time the client shows the fingerprint and asks "has it changed?"; if not, the server answers with a tiny "no" and the client reuses its copy.
Common misunderstanding: "304 means the cache is stale." It means the server confirmed the client's copy is still good. The request still happened; only the body was saved.
Definition: An ETag is "an opaque validator for differentiating between multiple representations of the same resource" (RFC 9110, 8.8.3). A client stores the response with its ETag and sends it back as If-None-Match. The 304 (Not Modified) status code "indicates that a conditional GET or HEAD request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition evaluated to false". If-None-Match uses the weak comparison function, and * matches any current representation. Freshness (Cache-Control: max-age) decides whether to ask at all; validators decide how cheap asking is. The full caching model is RFC 9111 and, for CDNs, CDNs.
1 GET /catalog ->
2 <- 200 OK, ETag: "a1b2", Cache-Control: no-cache, body (480 KB)
3 GET /catalog, If-None-Match: "a1b2" ->
4 <- 304 Not Modified (no body)
5 (data changes on the server)
6 GET /catalog, If-None-Match: "a1b2" ->
7 <- 200 OK, ETag: "c3d4", new body| Header | Direction | Meaning |
|---|---|---|
ETag | response | Validator for this representation (strong "x" or weak W/"x") |
If-None-Match | request | "Send the body only if the current ETag is not one of these" |
If-Match | request | "Apply this change only if the current ETag matches" (optimistic concurrency on PUT, see Optimistic Locking) |
Last-Modified, If-Modified-Since | both | The date-based, coarser validator pair |
Cache-Control: no-cache | response | Store it, but revalidate before every reuse |
Cache-Control: max-age=N | response | Fresh for N seconds without asking |
304 | response | Revalidation succeeded; reuse your copy |
Vary | response | Which request headers also select the representation |
Real scenarios: An app polls the catalogue every 5 seconds: with ETag, 95% of polls become bodiless 304s. A PUT with If-Match stops two editors silently overwriting each other (412 Precondition Failed). A JSON endpoint with Accept-Language negotiation must send Vary, or one language is cached for everyone.
Fix / how to use it: Go middleware that hashes the body and answers 304 is in server.go. In Laravel the cache.headers middleware does it when etag is in the list (it sets an xxh128 hash of the content), or use the custom middleware shown below. Note that computing the ETag from the body still makes the server do the work; the saving is bandwidth and client parsing. For real server savings, derive the validator from a version column or updated_at before building the body.
Push versus pull Important
In plain words: Pull means the client asks again and again. Push means the server speaks when it has something.
Common misunderstanding: "Push means the server connects to the client." The client opens the connection and the server writes to it later; clients behind NAT or a mobile network cannot be dialled from outside.
Definition: HTTP request/response is pull. Push-like options over the same client-initiated connection: long polling (the server holds the request until there is data), Server-Sent Events (one long response of events), WebSocket (a bidirectional channel after an upgrade). On mobile the OS push channels (APNs, FCM) wake the app so it can pull.
| Technique | Latency to new data | Server cost | Works through proxies | Fits |
|---|---|---|---|---|
| Short polling | Up to one interval | A request per poll, mostly 304 or empty | Everywhere | Dashboards, low urgency |
| Long polling | Near real time | One held connection per client | Mostly | Fallback, simple notifications |
| SSE | Near real time, server to client only | One held connection per client | Mostly (needs no buffering) | Feeds, progress, notifications |
| WebSocket | Real time, both ways | One stateful connection per client | Needs proxy support for upgrades | Chat, games, collaboration |
| Mobile push (APNs, FCM) | Seconds, app may be closed | Provider's gateway | Not applicable | Wake-ups, alerts |
All the scaling work (fan-out between servers, presence, reconnect storms) is in Real-Time Communication. The choice here is between "the client asks again, with a validator so it is cheap" and "the connection stays open, so the server is stateful".
Mobile and flaky clients: idempotent retry, backoff, offline-first Must-know
In plain words: Phones lose signal in lifts and tunnels. The app must expect a request to fail, try again sensibly and keep working with what it has.
Common misunderstanding: "If the request timed out, it failed." It may have succeeded and only the answer was lost. Retrying a non-idempotent request then charges the card twice.
Definition: An idempotent request has the same intended effect whether sent once or many times; RFC 9110 lists PUT, DELETE and the safe methods as idempotent, and notes such requests can be repeated automatically "if a communication failure occurs before the client is able to read the server's response". POST is not idempotent by default; an Idempotency-Key header with server-side deduplication makes it so (see API Idempotency). Exponential backoff waits longer after each failure; jitter randomises the wait so clients do not retry in lockstep. Marc Brooker's Builders' Library article on timeouts, retries and backoff with jitter is the source for the full-jitter formula. Offline-first means the app works from local storage and syncs when it can.
attempt 1 t=0.0 s send POST /charges Idempotency-Key: k-7f3 -> timeout (answer lost)
attempt 2 t=0.4 s same key -> 503, Retry-After: 2
attempt 3 t=2.4 s same key -> 201 (server: seen k-7f3 before? return the first result)| Failure | Client should | Why |
|---|---|---|
| Connection refused, DNS failure | Retry with backoff | The server never saw it |
| Timeout on GET, PUT, DELETE | Retry with backoff | Idempotent |
Timeout on POST with Idempotency-Key | Retry with the same key | The server deduplicates |
| Timeout on POST without a key | Do not retry blindly; ask the user or reconcile | May have been processed |
429 or 503 with Retry-After | Wait at least that long | The server told you |
| 4xx other than 408, 429 | Do not retry | The request is wrong |
| Offline | Queue locally, show "pending", sync on reconnect | Offline-first |
Real scenarios: A ride app queues "cancel trip" while in a tunnel and sends it on reconnect. After a 5-minute outage 2 million apps reconnect in the same second (a retry storm) unless backoff has jitter. A "pay" button tapped twice on slow 3G: the second tap carries the same idempotency key.
Fix: Go retry code with deadline awareness is in client.go; Laravel's Http::retry with a closure for delay and a when callback is in PaymentsClient. Retry policy at fleet level (budgets, hedging, storms) is the topic of Timeouts, Retries & Jitter.
Peer-to-peer and hybrid models Good to know
In plain words: In peer-to-peer every participant is both client and server. In a hybrid, a server helps peers find each other and then steps aside.
Common misunderstanding: "WebRTC is serverless." Media flows between peers, but peers must first exchange descriptions and network candidates through a signalling server (and often a STUN or TURN server too).
Definition: Peer-to-peer (P2P): peers exchange data directly; capacity grows with the number of peers. BitTorrent identifies content by URL and metainfo, uses a tracker or other discovery to find peers, and has downloaders upload to each other. WebRTC is the browser API for real-time audio, video and data between peers. Signalling is the discovery and negotiation step; MDN describes it as "A connection is established through a discovery and negotiation process called signaling" involving "a third, mutually agreed-upon server". The offer and answer (session descriptions) and ICE candidates travel over that channel; STUN servers help each peer learn its public address, TURN servers relay when a direct path is impossible.
Alice signalling server Bob
1 createOffer() --- offer ---------------------->
2 ------- offer ------>
3 <------ answer ------ setRemoteDescription, createAnswer
4 <-- answer --------
5 ICE candidates <-------- exchanged both ways via the server ------->
6 ============ media / data channel flows directly, peer to peer ============| Model | Who stores data | Scaling | Strength | Weakness | Example |
|---|---|---|---|---|---|
| Client-server | Server | Add servers | Control, consistency, billing | Server is cost and bottleneck | Web apps, APIs |
| Pure P2P | Peers | Grows with peers | No central cost | Discovery, NAT, trust, churn | BitTorrent swarms |
| Hybrid | Server for coordination, peers for payload | Server scales with sessions, not bytes | Cheap bandwidth, central control of identity | Needs TURN relays for hard NATs | WebRTC calls, some game matchmaking |
Real scenarios: A video call with 2 participants goes peer to peer; with 20 it usually goes through a media server (an SFU), because 20 peers each uploading 19 streams does not fit a laptop's uplink. That last part is architecture knowledge, not a claim from the sources read here.
Fix / how to choose: Use client-server unless peers' bandwidth is the thing you need or latency to the server is the problem; when you use WebRTC, plan for a signalling service (a WebSocket server) and TURN capacity from day one.
Mechanics
Sizing a worker pool: Little's law
For a pool of N workers each handling one request at a time, with mean time W seconds per request, the throughput ceiling is N / W requests per second (Little's law: concurrency = arrival rate x time in system). The pool size is also bounded by memory.
| Quantity | Example | Result |
|---|---|---|
| RAM for PHP | 8 GB box, 2 GB for OS, NGINX, Redis agent | 6 GB |
Resident memory per FPM child (measure it with ps) | 60 MB | 100 children fit |
| Mean request time | 50 ms | 100 / 0.05 = 2000 requests/s ceiling |
| If 30% of requests wait 1 s on a slow API | mean time 0.35 s | 100 / 0.35 = about 285 requests/s |
| Database connections | 100 children x 5 replicas | 500 connections needed from PostgreSQL |
These are illustrative back-of-envelope numbers, not measurements of a product: the method is the point. The collapse in the fourth row is why slow dependencies, not CPU, are the usual way a worker pool dies.
Knobs and defaults
| Product | Knob | Default (as documented) | Effect when too low | Effect when too high |
|---|---|---|---|---|
| NGINX | worker_processes | 1 (auto = one per core) | Idle cores | Little benefit |
| NGINX | worker_connections | 512 | worker_connections are not enough in the error log | Memory, descriptor limit |
| PHP-FPM | pm.max_children | mandatory, no default | Requests queue, 502/504 | Out-of-memory kill |
| PHP-FPM | pm.max_requests | 0 (never recycle) | Workers recycled often | Leaks accumulate |
| PHP-FPM | request_terminate_timeout | 0 (off) | Legit slow requests killed | Stuck workers hold slots |
| PHP-FPM | listen.backlog | 511 on Linux | Connections refused under bursts | Longer queues, stale requests |
| Apache | MaxRequestWorkers | MPM specific | Requests wait | RAM exhaustion |
| Octane | --workers | one per CPU core | Under-use | Memory |
| Octane | --max-requests | 500 | Frequent restarts | Leaks live longer |
| Octane | max_execution_time | 30 seconds | Killed long requests | Stuck workers |
| Go server | ReadHeaderTimeout | none | Valid slow clients dropped | Slow-loris holds goroutines |
| Go client | MaxIdleConnsPerHost | 2 | Constant reconnects | Idle descriptors |
NGINX with an upstream keep-alive pool, PHP-FPM and Apache configuration live in the snippets:
# NGINX as reverse proxy in front of an application upstream.
worker_processes auto; # one worker per CPU core
worker_rlimit_nofile 65535; # raise the per-worker file-descriptor limit
events {
use epoll; # Linux; NGINX picks the best method itself (kqueue on BSD and macOS)
worker_connections 4096; # per worker; includes upstream connections (default 512)
}
http {
keepalive_timeout 65s; # idle client connections
keepalive_requests 1000; # requests per client connection before it is closed
upstream app {
server 192.0.2.11:8080; # documentation-range addresses
server 192.0.2.12:8080;
keepalive 32; # idle upstream connections cached per worker
}
server {
listen 80 backlog=4096;
location / {
proxy_pass http://app;
proxy_http_version 1.1; # required for upstream keep-alive
proxy_set_header Connection ""; # do not forward "close"
proxy_read_timeout 30s;
}
}
}; /etc/php/8.4/fpm/pool.d/www.conf (excerpt). One pool = one worker-process pool.
[www]
listen = /run/php/php-fpm.sock
listen.backlog = 511 ; accept queue; default 511 on Linux
pm = dynamic ; static | dynamic | ondemand
pm.max_children = 40 ; hard cap on simultaneous requests = RAM / memory per worker
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
pm.max_requests = 500 ; recycle a worker after N requests (limits leaks)
request_terminate_timeout = 30s
pm.status_path = /fpm-status ; exposes "listen queue" and "max children reached"# Apache httpd 2.4: choose exactly one MPM, then size it.
# LoadModule mpm_prefork_module modules/mod_mpm_prefork.so # one process per request, no threads
LoadModule mpm_event_module modules/mod_mpm_event.so # threads, with an event listener for idle keep-alive
<IfModule mpm_event_module>
StartServers 3
ThreadsPerChild 25
MaxRequestWorkers 400 # simultaneous requests: must fit in RAM and in the upstream's limits
ServerLimit 16 # processes: MaxRequestWorkers / ThreadsPerChild
MaxConnectionsPerChild 0
ListenBacklog 511
</IfModule>
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100Messages you will actually see
| Where | Message or status | Meaning | First thing to check |
|---|---|---|---|
| NGINX error log | worker_connections are not enough | A worker hit worker_connections | The limit counts upstream connections too |
| NGINX error log | connect() failed (111: Connection refused) while connecting to upstream | App not listening or backlog full | Is PHP-FPM or the Go process up |
| NGINX | 502 Bad Gateway | Upstream closed or sent garbage | Crashed worker, killed by OOM |
| NGINX | 504 Gateway Time-out | Upstream too slow | proxy_read_timeout, slow query |
| NGINX error log | upstream timed out (110: Connection timed out) while reading response header from upstream | Same as 504, in the log | Slow dependency |
| PHP-FPM log | server reached pm.max_children setting (40), consider raising it | Pool exhausted | RAM budget, slow dependency |
| PHP-FPM log | WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers) | Spare servers too few | Spare settings |
| Go client | net/http: request canceled (Client.Timeout exceeded while awaiting headers) | Client timeout fired | Timeout versus server p99 |
| Go server log | http: Accept error: accept tcp ...: accept4: too many open files; retrying in 5ms | Process out of descriptors | ulimit -n, connection leak |
| Browser / client | ERR_CONNECTION_REFUSED | Nothing listens or firewall | Port, process, security group |
| HTTP | 429 Too Many Requests with Retry-After | Rate limit | Honour the header |
| HTTP | 503 Service Unavailable with Retry-After | Overloaded or draining | Retry with backoff |
| HTTP | 412 Precondition Failed | If-Match did not match | Re-read, re-apply |
The exact wording of log lines varies by version; treat them as typical, and check your own logs. Status code semantics are RFC 9110.
Go
The Go module is academy/client-server-model, standard library only. before/ is the first version; server/ and client/ are the fixed halves; lab/ holds two single-process programs whose output is quoted in the Lab.
Before
A typical first version: http.ListenAndServe with no timeouts, a global map for sessions with no lock, the full catalogue rebuilt on every request, and a client that retries a POST forever with a fixed sleep.
// Before: the first version of an API server and its client.
// Every line is common, and every line is a production incident waiting.
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
)
// Session state lives in this process only: a second replica never sees it,
// a restart wipes it, and concurrent requests race on the map.
var sessions = map[string]string{}
func catalog(w http.ResponseWriter, r *http.Request) {
// Reads the whole body with no size limit.
body, _ := io.ReadAll(r.Body)
sessions[r.Header.Get("X-Session")] = string(body)
// Rebuilds and resends the full catalogue on every request: no ETag,
// so a client that polls every 5 seconds re-downloads identical bytes.
items := make([]map[string]any, 0, 5000)
for i := 0; i < 5000; i++ {
items = append(items, map[string]any{"id": i, "name": fmt.Sprintf("item-%d", i)})
}
_ = json.NewEncoder(w).Encode(items)
}
func main() {
http.HandleFunc("/catalog", catalog)
// http.ListenAndServe has no ReadHeaderTimeout, no IdleTimeout and no
// connection limit: one slow client holds a goroutine and a socket forever.
log.Fatal(http.ListenAndServe(":8080", nil))
}
// fetchWithRetry is the client half: the default client has no timeout, the
// loop retries immediately and forever on any error, and it replays a POST
// that may already have been processed.
func fetchWithRetry(url string, payload io.Reader) (*http.Response, error) {
for {
resp, err := http.Post(url, "application/json", payload)
if err == nil {
return resp, nil
}
time.Sleep(100 * time.Millisecond) // fixed pause: every client wakes together
}
}After
The server half. New sets every timeout and a body cap; ETag makes GET and HEAD conditional (strong validator from the body, weak comparison for If-None-Match, * and lists handled); LimitListener caps open connections so the rest wait in the kernel's accept queue; ConnStats counts connection-state transitions through http.Server.ConnState.
// Package server holds the server-side pieces of the chapter: a hardened
// http.Server, a conditional-GET (ETag / 304) middleware, a connection limit
// and a connection-state counter.
package server
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"net"
"net/http"
"strings"
"sync/atomic"
"time"
)
// New returns an http.Server with every timeout set. The zero value of each
// field means "no limit", which is the default of http.ListenAndServe.
func New(addr string, h http.Handler, stats *ConnStats) *http.Server {
srv := &http.Server{
Addr: addr,
Handler: http.MaxBytesHandler(h, 1<<20), // 1 MiB request body cap
ReadHeaderTimeout: 5 * time.Second, // slow-loris defence
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second, // how long a keep-alive connection may sit idle
MaxHeaderBytes: 16 << 10,
}
if stats != nil {
srv.ConnState = stats.Hook
}
return srv
}
// ConnStats counts connection-state transitions reported by http.Server.
type ConnStats struct {
New, Active, Idle, Closed atomic.Int64
}
// Hook is meant for http.Server.ConnState.
func (c *ConnStats) Hook(_ net.Conn, s http.ConnState) {
switch s {
case http.StateNew:
c.New.Add(1)
case http.StateActive:
c.Active.Add(1)
case http.StateIdle:
c.Idle.Add(1)
case http.StateClosed, http.StateHijacked:
c.Closed.Add(1)
}
}
// ETag makes GET and HEAD responses conditional. It buffers the handler's
// output, derives a strong validator from the bytes and answers 304 with no
// body when the client already holds that representation (RFC 9110 section 13.1.2).
func ETag(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
next.ServeHTTP(w, r)
return
}
rec := &bufferedWriter{header: http.Header{}, status: http.StatusOK}
next.ServeHTTP(rec, r)
if rec.status != http.StatusOK {
copyHeader(w.Header(), rec.header)
w.WriteHeader(rec.status)
_, _ = w.Write(rec.body.Bytes())
return
}
sum := sha256.Sum256(rec.body.Bytes())
tag := `"` + hex.EncodeToString(sum[:8]) + `"`
copyHeader(w.Header(), rec.header)
w.Header().Set("ETag", tag)
w.Header().Set("Cache-Control", "no-cache") // store it, but revalidate every time
if matches(r.Header.Get("If-None-Match"), tag) {
w.WriteHeader(http.StatusNotModified)
return
}
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodGet {
_, _ = w.Write(rec.body.Bytes())
}
})
}
// matches implements the weak comparison used by If-None-Match.
func matches(header, tag string) bool {
for _, part := range strings.Split(header, ",") {
p := strings.TrimSpace(part)
if p == "*" || strings.TrimPrefix(p, "W/") == tag {
return true
}
}
return false
}
type bufferedWriter struct {
header http.Header
body bytes.Buffer
status int
}
func (b *bufferedWriter) Header() http.Header { return b.header }
func (b *bufferedWriter) Write(p []byte) (int, error) { return b.body.Write(p) }
func (b *bufferedWriter) WriteHeader(code int) { b.status = code }
func copyHeader(dst, src http.Header) {
for k, v := range src {
dst[k] = append([]string(nil), v...)
}
}
// LimitListener caps the number of simultaneously open connections. Accept
// blocks while the cap is reached, so further clients wait in the kernel
// accept queue (the listen backlog) instead of consuming goroutines.
func LimitListener(l net.Listener, n int) net.Listener {
return &limitListener{Listener: l, sem: make(chan struct{}, n)}
}
type limitListener struct {
net.Listener
sem chan struct{}
}
func (l *limitListener) Accept() (net.Conn, error) {
l.sem <- struct{}{} // acquire a slot before accepting
c, err := l.Listener.Accept()
if err != nil {
<-l.sem
return nil, err
}
return &limitConn{Conn: c, release: func() { <-l.sem }}, nil
}
type limitConn struct {
net.Conn
release func()
closed atomic.Bool
}
func (c *limitConn) Close() error {
err := c.Conn.Close()
if c.closed.CompareAndSwap(false, true) {
c.release()
}
return err
}The tests cover the 304 round trip (including W/ prefixes, lists and *), POST untouched, the connection limit releasing a slot on close, and the non-zero timeouts:
package server
import (
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func catalogue() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `[{"id":1},{"id":2}]`)
})
}
func TestETagRoundTrip(t *testing.T) {
ts := httptest.NewServer(ETag(catalogue()))
defer ts.Close()
first, err := http.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(first.Body)
first.Body.Close()
tag := first.Header.Get("ETag")
if first.StatusCode != 200 || tag == "" || len(body) == 0 {
t.Fatalf("first: status=%d etag=%q bytes=%d", first.StatusCode, tag, len(body))
}
req, _ := http.NewRequest(http.MethodGet, ts.URL, nil)
req.Header.Set("If-None-Match", tag)
second, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer second.Body.Close()
rest, _ := io.ReadAll(second.Body)
if second.StatusCode != http.StatusNotModified || len(rest) != 0 {
t.Fatalf("revalidation: status=%d bytes=%d, want 304 and 0", second.StatusCode, len(rest))
}
for _, h := range []string{`W/` + tag, `"other", ` + tag, `*`} {
req.Header.Set("If-None-Match", h)
r, _ := http.DefaultClient.Do(req)
r.Body.Close()
if r.StatusCode != http.StatusNotModified {
t.Errorf("If-None-Match %q gave %d, want 304", h, r.StatusCode)
}
}
req.Header.Set("If-None-Match", `"stale"`)
r, _ := http.DefaultClient.Do(req)
r.Body.Close()
if r.StatusCode != http.StatusOK {
t.Errorf("stale validator gave %d, want 200", r.StatusCode)
}
}
func TestETagLeavesPostAlone(t *testing.T) {
h := ETag(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", nil))
if rec.Code != http.StatusCreated || rec.Header().Get("ETag") != "" {
t.Fatalf("POST: code=%d etag=%q", rec.Code, rec.Header().Get("ETag"))
}
}
func TestLimitListener(t *testing.T) {
base, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
l := LimitListener(base, 1)
defer l.Close()
accepted := make(chan net.Conn, 2)
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
accepted <- c
}
}()
c1, _ := net.Dial("tcp", base.Addr().String())
defer c1.Close()
c2, _ := net.Dial("tcp", base.Addr().String())
defer c2.Close()
first := <-accepted // the first connection takes the only slot
select {
case <-accepted:
t.Fatal("second connection accepted while the limit of 1 was reached")
case <-time.After(150 * time.Millisecond):
}
first.Close() // release the slot
select {
case second := <-accepted:
second.Close()
case <-time.After(2 * time.Second):
t.Fatal("second connection not accepted after the slot was released")
}
}
func TestNewSetsTimeouts(t *testing.T) {
s := New(":0", catalogue(), nil)
if s.ReadHeaderTimeout == 0 || s.IdleTimeout == 0 || s.WriteTimeout == 0 || s.MaxHeaderBytes == 0 {
t.Fatalf("a timeout or limit is zero: %+v", s)
}
}The client half. One shared http.Client with a bounded Transport; Do retries only when the request is safe to replay (idempotent method or Idempotency-Key), honours Retry-After, uses full jitter, rewinds the body with GetBody, and stops when the next wait would overrun the context deadline.
// Package client is the well-behaved caller: one shared Transport with a
// bounded connection pool, a per-call deadline, and retries that obey the rules
// in RFC 9110 (only idempotent requests, honour Retry-After) with full jitter.
package client
import (
"context"
"errors"
"io"
"math/rand/v2"
"net"
"net/http"
"strconv"
"time"
)
// NewHTTPClient returns a client meant to be created once and shared.
func NewHTTPClient() *http.Client {
return &http.Client{
Timeout: 10 * time.Second, // whole exchange, including reading the body
Transport: &http.Transport{
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20, // the stdlib default is only 2
MaxConnsPerHost: 50, // hard cap: further callers wait for a connection
IdleConnTimeout: 90 * time.Second,
},
}
}
// Policy describes one retry schedule.
type Policy struct {
MaxAttempts int
Base, Cap time.Duration
}
// DefaultPolicy is three attempts, 200 ms base, 5 s cap.
var DefaultPolicy = Policy{MaxAttempts: 3, Base: 200 * time.Millisecond, Cap: 5 * time.Second}
// Safe reports whether replaying the request cannot do harm: the method is
// idempotent (RFC 9110 section 9.2.2) or the caller attached an Idempotency-Key
// that the server deduplicates.
func Safe(r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
return true
}
return r.Header.Get("Idempotency-Key") != ""
}
// Delay is "full jitter": a random value between 0 and min(cap, base*2^n).
func (p Policy) Delay(attempt int) time.Duration {
ceiling := p.Base << attempt
if ceiling <= 0 || ceiling > p.Cap {
ceiling = p.Cap
}
return time.Duration(rand.Int64N(int64(ceiling) + 1))
}
// Do sends req, retrying 429, 502, 503, 504 and transport errors while the
// request is safe to replay and the context still has time left.
func Do(ctx context.Context, c *http.Client, req *http.Request, p Policy) (*http.Response, error) {
var lastErr error
for attempt := 0; attempt < p.MaxAttempts; attempt++ {
if attempt > 0 {
if req.GetBody != nil { // rewind the body for a replay
b, err := req.GetBody()
if err != nil {
return nil, err
}
req.Body = b
}
}
resp, err := c.Do(req.WithContext(ctx))
wait := p.Delay(attempt)
switch {
case err == nil && !retryableStatus(resp.StatusCode):
return resp, nil
case err == nil:
if ra := retryAfter(resp); ra > 0 {
wait = ra // the server's instruction beats our guess
}
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
lastErr = errors.New("server answered " + resp.Status)
default:
lastErr = err
}
if !Safe(req) || attempt == p.MaxAttempts-1 {
break
}
if dl, ok := ctx.Deadline(); ok && time.Until(dl) < wait {
break // the next attempt cannot fit inside the deadline
}
select {
case <-time.After(wait):
case <-ctx.Done():
return nil, ctx.Err()
}
}
return nil, lastErr
}
func retryableStatus(code int) bool {
return code == http.StatusTooManyRequests || code == http.StatusBadGateway ||
code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout
}
// retryAfter parses the delta-seconds form of Retry-After.
func retryAfter(resp *http.Response) time.Duration {
if s, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && s >= 0 {
return time.Duration(s) * time.Second
}
return 0
}package client
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
var fast = Policy{MaxAttempts: 3, Base: time.Millisecond, Cap: 5 * time.Millisecond}
func flaky(failures int32) (*httptest.Server, *atomic.Int32) {
var hits atomic.Int32
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) <= failures {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})), &hits
}
func TestGetIsRetried(t *testing.T) {
ts, hits := flaky(2)
defer ts.Close()
req, _ := http.NewRequest(http.MethodGet, ts.URL, nil)
resp, err := Do(context.Background(), NewHTTPClient(), req, fast)
if err != nil || resp.StatusCode != 200 || hits.Load() != 3 {
t.Fatalf("err=%v hits=%d", err, hits.Load())
}
resp.Body.Close()
}
func TestPostWithoutKeyIsNotRetried(t *testing.T) {
ts, hits := flaky(2)
defer ts.Close()
req, _ := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader("x"))
if _, err := Do(context.Background(), NewHTTPClient(), req, fast); err == nil {
t.Fatal("expected an error after one failed attempt")
}
if hits.Load() != 1 {
t.Fatalf("POST was sent %d times, want 1", hits.Load())
}
}
func TestPostWithKeyIsRetriedWithBody(t *testing.T) {
var bodies atomic.Int32
var hits atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b := make([]byte, 8)
n, _ := r.Body.Read(b)
if string(b[:n]) == "payload" {
bodies.Add(1)
}
if hits.Add(1) == 1 {
w.WriteHeader(http.StatusBadGateway)
return
}
w.WriteHeader(http.StatusCreated)
}))
defer ts.Close()
req, _ := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader("payload"))
req.Header.Set("Idempotency-Key", "k-1")
resp, err := Do(context.Background(), NewHTTPClient(), req, fast)
if err != nil || resp.StatusCode != 201 {
t.Fatalf("err=%v", err)
}
resp.Body.Close()
if bodies.Load() != 2 {
t.Fatalf("the full body reached the server %d times, want 2", bodies.Load())
}
}
func TestDeadlineStopsRetries(t *testing.T) {
ts, hits := flaky(100)
defer ts.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
req, _ := http.NewRequest(http.MethodGet, ts.URL, nil)
slow := Policy{MaxAttempts: 10, Base: time.Second, Cap: time.Second}
start := time.Now()
_, _ = Do(ctx, NewHTTPClient(), req, slow)
if time.Since(start) > time.Second || hits.Load() > 3 {
t.Fatalf("kept retrying past the deadline: %v, %d hits", time.Since(start), hits.Load())
}
}
func TestDelayStaysUnderCap(t *testing.T) {
for a := 0; a < 40; a++ {
if d := DefaultPolicy.Delay(a); d < 0 || d > DefaultPolicy.Cap {
t.Fatalf("attempt %d: delay %v outside [0, %v]", a, d, DefaultPolicy.Cap)
}
}
}The Go angle
net/httpis goroutine-per-connection by design:Serveaccepts connections "creating a new service goroutine for each". Because the runtime parks goroutines on its network poller (epoll on Linux, kqueue on macOS and BSD), blocking-style handler code scales like an event loop. The price: nothing bounds the number of goroutines except you. UseLimitListener-style caps,http.MaxBytesHandler, and per-requestcontextdeadlines.- Zero means "no limit" in
http.Server.ReadHeaderTimeoutis the slow-loris defence;IdleTimeoutends idle keep-alive connections (if zero,ReadTimeoutis used);WriteTimeoutbounds the response. The documentation says most users will preferReadHeaderTimeoutoverReadTimeoutbecause the handler can decide what is too slow for the body. - The client side: "Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used."
DefaultMaxIdleConnsPerHostis 2, so a service that calls one host from many goroutines silently reconnects unless you raise it. Always drain and closeresp.Body, or the connection cannot return to the pool (the keep-alive lab shows 1 connection versus 200). - HTTP/2 is automatic for HTTPS on
ServerandDefaultTransport; a customTransportneedsForceAttemptHTTP2or the protocol fields (see HTTP evolution). - For graceful deploys call
Server.Shutdown(ctx): it stops accepting, lets in-flight requests finish and closes idle keep-alive connections.
Laravel
The Laravel snippets are Laravel 13 application files (namespaced, one class per file, php -l clean). Version notes: the Laravel 13 docs for the HTTP client, sessions, middleware, responses and Octane were read for this chapter.
Before
State in a static property (harmless under PHP-FPM, a leak and a data-bleed under Octane), Product::all() returned in full on every poll, and a payment call with a short fixed retry and no idempotency key.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
// Before: state in a static property, no validator, no deadline, blind retries.
class CatalogControllerBefore
{
// Under PHP-FPM this resets on every request. Under Octane (Swoole,
// FrankenPHP, RoadRunner) it lives as long as the worker: a memory leak
// and, worse, one user's data visible to the next request.
private static array $seen = [];
public function index(Request $request): JsonResponse
{
self::$seen[] = $request->user()?->id;
// Rebuilt and resent in full on every poll: no ETag, no 304.
return response()->json(Product::all());
}
public function charge(Request $request): array
{
// Default timeout is long, retries replay a POST that may have been
// processed, and every client wakes at the same instant (fixed sleep).
$response = Http::retry(5, 100)->post('https://payments.example.test/charges', [
'order_id' => $request->input('order_id'),
]);
return $response->json();
}
}After
A conditional GET, two ways. The first uses the built-in cache.headers middleware: with etag in the directive list, Laravel sets an xxh128 hash of the response content as the ETag, and private;max_age=0;must_revalidate forces a revalidation each time. The second is a small middleware that sets the ETag itself and lets Symfony's isNotModified turn the response into a 304.
<?php
use App\Http\Controllers\CatalogController;
use App\Http\Middleware\ConditionalGet;
use Illuminate\Support\Facades\Route;
// Option 1: the built-in middleware. With `etag` in the list Laravel sets an
// xxh128 hash of the response content as the ETag (Laravel 13 responses docs).
Route::get('/catalog', [CatalogController::class, 'index'])
->middleware('cache.headers:private;max_age=0;must_revalidate;etag');
// Option 2: our own middleware, which also answers 304 itself.
Route::get('/catalog-v2', [CatalogController::class, 'index'])
->middleware(ConditionalGet::class);
Route::post('/charges', [CatalogController::class, 'charge'])
->middleware('throttle:30,1');<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
// Turns any GET/HEAD response into a conditional one: strong ETag from the body,
// 304 and no body when the client sent a matching If-None-Match.
class ConditionalGet
{
public function handle(Request $request, Closure $next): Response
{
/** @var Response $response */
$response = $next($request);
if (! $request->isMethodCacheable() || $response->getStatusCode() !== 200) {
return $response;
}
$response->setEtag(hash('xxh128', (string) $response->getContent()));
$response->headers->set('Cache-Control', 'private, no-cache'); // store, but always revalidate
// Symfony compares If-None-Match with the ETag and rewrites the
// response to 304 Not Modified with an empty body.
$response->isNotModified($request);
return $response;
}
}A controller with no per-process state, and a bounded outbound call. connectTimeout(3) and timeout(8) set deadlines; retry takes the attempt count, a closure that returns the delay in milliseconds (full jitter here) and a when callback so only connection errors and 429, 502, 503 and 504 are retried; the Idempotency-Key header is what makes retrying a POST legitimate.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Services\PaymentsClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
// After: no per-process state, a conditional GET, a bounded outbound call.
class CatalogController
{
public function index(): JsonResponse
{
// Safe under Octane: nothing is stored on the class or in statics.
return response()->json(Product::query()->orderBy('id')->get(['id', 'name', 'price_cents']));
}
public function charge(Request $request, PaymentsClient $payments): JsonResponse
{
$data = $request->validate(['order_id' => ['required', 'integer']]);
// The client key is generated once per user action and reused on retry.
$key = $request->header('Idempotency-Key') ?? (string) \Illuminate\Support\Str::uuid();
return response()->json($payments->charge($data['order_id'], $key));
}
}<?php
namespace App\Services;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
// A bounded outbound call: connect and total timeouts, jittered backoff,
// retry only on connection errors and 429/502/503/504, and only because the
// POST carries an Idempotency-Key the provider deduplicates.
class PaymentsClient
{
public function charge(int $orderId, string $idempotencyKey): array
{
$response = Http::baseUrl(config('services.payments.url'))
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->connectTimeout(3)
->timeout(8)
->retry(
3,
// Full jitter: random between 0 and min(cap, base * 2^attempt) milliseconds.
fn (int $attempt, Exception $e): int => random_int(0, min(5000, 200 * (2 ** $attempt))),
function (Exception $e, PendingRequest $request): bool {
if ($e instanceof ConnectionException) {
return true;
}
return $e instanceof RequestException
&& in_array($e->response->status(), [429, 502, 503, 504], true);
},
throw: false,
)
->post('/charges', ['order_id' => $orderId]);
return $response->throw()->json();
}
}Long-lived worker rules (Octane).
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
// Three rules for a long-lived worker (Octane on Swoole, FrankenPHP or RoadRunner).
class OctaneSafety
{
// WRONG under Octane: survives between requests.
// private static array $perUser = [];
// WRONG under Octane: a singleton that captured the first request.
// public function __construct(private Request $request) {}
public function show(Request $request): array
{
// Rule 1: take the request as a method argument, never in a constructor
// of a singleton.
$userId = $request->user()->id;
// Rule 2: shared mutable state belongs in a store (cache, Redis, database),
// not in a static property.
$hits = Cache::increment("hits:{$userId}");
// Rule 3: anything that must not outlive the request is created inside it.
return ['user' => $userId, 'hits' => $hits];
}
}Starting Octane with a fixed worker count and a restart limit, as documented:
# Laravel Octane: start N workers, recycle each after M requests.
php artisan octane:install --server=frankenphp
php artisan octane:start --server=frankenphp --workers=4 --max-requests=500 --host=0.0.0.0 --port=8000The Laravel angle
- Under PHP-FPM every request boots the framework, so "stateless" is free; the web server (NGINX or Apache) owns keep-alive and slow clients, and
pm.max_childrenis your concurrency limit. Under Octane the framework boots once per worker; Laravel's Octane documentation warns that "adding data to a statically maintained array will result in a memory leak" and says not to inject the request or the container into singletons' constructors. - Sessions:
SESSION_DRIVERselects file, cookie, database, memcached, redis, dynamodb or array. For more than one server use redis, database, dynamodb or cookie. Session blocking (theblockoption on a route) needs a cache driver with atomic locks and serialises requests of one session. - The HTTP client (a Guzzle wrapper):
connectTimeoutdefaults to 10 seconds;retry($times, $sleep, $when, $throw)accepts a closure for the sleep, an array of delays, and awhencallable; withthrow: falsea final failure does not throw, though aConnectionExceptionstill can.Http::poolsends requests concurrently, which is how a BFF fans out. - Octane extras on Swoole: concurrent tasks, ticks, the Octane cache and tables; on FrankenPHP and RoadRunner you get the faster boot but not those. Real-time push from Laravel is Reverb (a WebSocket server) with broadcasting; see Real-Time Communication.
- Sanctum covers SPA and mobile authentication; the token or cookie it issues is what lets the application tier stay stateless.
Solving the classic problems
The 502 or 504 at peak: worker pool exhausted
| Cause | Symptom | Fix | Cost or limit |
|---|---|---|---|
pm.max_children too small for the slow-request mix | server reached pm.max_children, listen queue above 0 | Raise it to what RAM allows (Little's law above) | RAM; more DB connections |
| One slow dependency pins every worker | Everything slow, CPU idle | Timeouts on every outbound call, circuit breaker (Circuit Breaker), bulkheads | Needs a degraded response |
| Slow clients pin workers | Many workers in "reading request" | Put NGINX (buffering) in front; client_body_timeout | One more hop |
| No spare capacity | Latency cliff at a certain load | Autoscale on queue depth or concurrency, shed load (Load Shedding) | Cold-start lag |
FPM pool = 40, mean request 50 ms -> ceiling 800 req/s
Dependency slows to 2 s for 10% of requests -> mean 0.245 s -> ceiling 163 req/s
Incoming load 300 req/s -> queue grows without bound -> 504s from the proxy after proxy_read_timeoutSlow-loris and slow clients
A client that sends one header byte every few seconds holds a connection, and in a process-per-request server, a worker. Fix: a header-read timeout (ReadHeaderTimeout in Go, client_header_timeout in NGINX), limits per client IP at the edge (DDoS Protection), and an event-driven front end.
Reconnect storm after a deploy or outage
All clients drop at once and return at once. Fix: jittered backoff on the client (full jitter, cap), Retry-After from the server, connection draining on deploy (Shutdown, nginx -s quit, FPM graceful reload), and a retry budget (Timeouts, Retries & Jitter).
Stale or wasted downloads
Clients re-download unchanged data. Fix: ETag and If-None-Match for 304s, Cache-Control: max-age for no request at all, Vary for negotiated content. Cost: the server must compute a validator cheaply, otherwise it is doing the work anyway.
State lost on scale-out or deploy
Fix: externalise sessions (Redis, database, signed cookie), make workers disposable, keep stateful tiers (WebSocket gateways) small and drain them. See Scaling Strategies.
Octane leaks and cross-request data bleed
Symptoms: memory grows until --max-requests recycles the worker; one user sees another's data. Fix: no statics, no request in singleton constructors, a store for shared state, --max-requests as a safety net not a cure.
Double submit from a flaky mobile network
Fix: client generates one Idempotency-Key per user intent and reuses it on every retry; server stores key and result; see API Idempotency.
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Typical Laravel site, moderate traffic, simple ops | NGINX plus PHP-FPM, pm = dynamic | pm.max_requests, pm.status_path | Isolation per request, forgiving of sloppy state |
| Laravel API where boot time dominates latency | Octane on FrankenPHP, Swoole or RoadRunner | --max-requests, leak review, load test | Boot once, 1 worker per core |
| Need concurrent tasks, ticks, in-memory tables in PHP | Octane on Swoole | Task workers | Swoole-only features |
| Many idle connections (chat, push) | Event loop or Go (or Reverb for Laravel) | ulimit -n, idle timeouts, drain on deploy | Cheap idle connection |
| CPU-bound, simple deploys | Go net/http behind a proxy | ReadHeaderTimeout, LimitListener | One binary, goroutines |
| Legacy PHP app needing mod_php semantics | Apache with a documented MPM choice | prefork for non-thread-safe libraries | Compatibility |
| Many clients, one cheap read endpoint | Conditional GET + CDN | max-age, stale-while-revalidate | Fewer bytes and fewer workers |
| Real-time updates, bidirectional | WebSocket | Fan-out layer | See realtime chapter |
| Real-time one-way updates | SSE | Last-Event-ID resume | Simpler than WebSocket |
| Voice, video, large P2P transfers | WebRTC or BitTorrent-style | Signalling service, TURN | Server cost scales with sessions, not bytes |
| Mobile app on bad networks | Thick client, local store | Idempotency keys, backoff with jitter, sync queue | Works offline |
| Question | If yes | If no |
|---|---|---|
| Does a request often wait on slow I/O? | Event loop, goroutines, or a big enough pool with timeouts | A small pool is fine |
| Can the app tolerate shared mutable process state? | Octane, Go | PHP-FPM |
| Do clients poll the same data? | Validators and 304s | Skip |
| Must a user keep one server for state? | Fix the state; sticky routing is a stopgap | Stateless, any replica |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One NGINX, one PHP-FPM pool (or one Go binary) and one PostgreSQL on a single machine. The client-server model is two arrows: browser to NGINX, app to database. Sessions can sit in files or in the database; ETag middleware gives the cheap wins; pm.max_children and the database connection limit are the only capacity knobs. Example: a 4-core, 8 GB server runs 60 FPM children (60 MB each, 3.6 GB), NGINX with worker_processes auto, PostgreSQL with max_connections = 100. The ceiling is workers divided by mean time per request; the first thing to fail is the database or the pool, not NGINX.
Modular monolith: boundaries without the network
Several modules, still one process and one deployment, maybe separate database schemas. Client-server shows up inside: modules call each other through interfaces, and the HTTP boundary is a BFF-style controller per client type (web, mobile, admin). Keep each module's data behind its interface so a module can later become a service without changing callers. The caller-side habits (deadlines, no hidden shared state) are practised in process before they are needed on the network.
Microservices: every arrow is a client-server pair
Each service is a server to its callers and a client of its dependencies. All of this chapter repeats per arrow: connection pool and keep-alive on the HTTP client, a deadline that shrinks per hop, retries only for idempotent calls or with idempotency keys, a worker-pool or event-loop limit on the server, and validators where reads dominate. An API gateway or BFF per client type terminates TLS and aggregates. A call chain of five services at 99.9% availability each is about 99.5% together, and every hop adds a timeout to coordinate; the contract and failure-policy mechanics are in Service Communication and the service-to-service security in mTLS.
Distributed data: replicas, caches, regions
The client's cache (ETag), a CDN, Redis, a read replica: each is a copy with its own staleness. A 304 only says "unchanged since the validator"; a CDN may answer without asking; a replica may lag, so a client that just wrote and immediately reads can miss its own write (read-your-writes, see Replication). Regional deployments move the server closer to the client (DNS routing, GeoDNS) so the TCP and TLS round trips shrink; the data-consistency price is in Consistency Models.
Scaling path: 1x, 10x, 100x
| Load | Shape | What changes | First bottleneck |
|---|---|---|---|
| 1x (about 50 req/s) | One box: NGINX, FPM, PostgreSQL | Nothing special; add ETag, keep-alive, timeouts | Slow queries |
| 10x (about 500 req/s) | Reverse proxy or load balancer, 2-4 app replicas, shared Redis session store, read replica, CDN for static files | Stateless app tier, externalised sessions, connection pooler | Database connections, worker pools |
| 100x (about 5000 req/s) | Autoscaled app fleet across zones, CDN with conditional GETs, BFFs, queues for slow work, Octane or Go for hot paths | Retry budgets, load shedding, connection draining, regional routing | Fan-out latency, the data tier |
The request rates are scenario numbers for illustration; capacity estimation method is in Capacity Estimation.
Lab
Two single-process Go programs were run on the author's machine (macOS, Apple silicon, Go 1.27) to produce the numbers below; the NGINX and FPM experiments are written with commands and expected output and are labelled "expected, not run".
Lab 1 (run): connections with and without keep-alive.
// Lab 1: how many TCP connections do 200 sequential requests need with and
// without keep-alive? The server counts connection-state transitions itself.
package main
import (
"fmt"
"io"
"net"
"net/http"
"time"
"academy/client-server-model/server"
)
func run(disableKeepAlives bool, requests int) (conns int64, elapsed time.Duration) {
var stats server.ConnStats
ln, _ := net.Listen("tcp", "127.0.0.1:0")
srv := server.New("", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "ok")
}), &stats)
go srv.Serve(ln)
defer srv.Close()
c := &http.Client{Transport: &http.Transport{DisableKeepAlives: disableKeepAlives}}
start := time.Now()
for i := 0; i < requests; i++ {
resp, err := c.Get("http://" + ln.Addr().String())
if err != nil {
panic(err)
}
_, _ = io.Copy(io.Discard, resp.Body) // drain, or the connection cannot be reused
resp.Body.Close()
}
return stats.New.Load(), time.Since(start)
}
func main() {
const n = 200
on, tOn := run(false, n)
off, tOff := run(true, n)
fmt.Printf("keep-alive on : %3d requests, %3d TCP connections, %v\n", n, on, tOn.Round(time.Millisecond))
fmt.Printf("keep-alive off: %3d requests, %3d TCP connections, %v\n", n, off, tOff.Round(time.Millisecond))
}$ cd docs/snippets/system-design/client-server-model/go && go run ./lab/keepalive
keep-alive on : 200 requests, 1 TCP connections, 11ms
keep-alive off: 200 requests, 200 TCP connections, 28msSame 200 requests, 1 connection versus 200. On loopback the time difference is small (no network latency, no TLS); across a real network each extra connection adds a TCP round trip and, with TLS, a handshake.
Lab 2 (run): what an idle connection costs a goroutine-per-connection server.
// Lab 2: what does one idle client connection cost a goroutine-per-connection
// server? Opens N idle TCP connections to net/http and reports goroutines and heap.
package main
import (
"fmt"
"net"
"net/http"
"runtime"
"time"
)
func heap() uint64 {
runtime.GC()
var m runtime.MemStats
runtime.ReadMemStats(&m)
return m.HeapAlloc + m.StackInuse
}
func main() {
const n = 500
ln, _ := net.Listen("tcp", "127.0.0.1:0")
srv := &http.Server{Handler: http.NotFoundHandler(), IdleTimeout: time.Minute}
go srv.Serve(ln)
defer srv.Close()
baseG, baseM := runtime.NumGoroutine(), heap()
conns := make([]net.Conn, 0, n)
for i := 0; i < n; i++ {
c, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
fmt.Println("dial failed at", i, "(raise ulimit -n):", err)
break
}
conns = append(conns, c)
// One byte of a request line puts the connection in the server's read loop.
_, _ = c.Write([]byte("G"))
}
time.Sleep(300 * time.Millisecond)
g, m := runtime.NumGoroutine()-baseG, int64(heap())-int64(baseM)
fmt.Printf("%d open connections -> %d extra goroutines, about %d KiB per connection\n",
len(conns), g, m/int64(len(conns))/1024)
for _, c := range conns {
c.Close()
}
}$ go run ./lab/idleconns
500 open connections -> 500 extra goroutines, about 14 KiB per connectionOne goroutine per connection, as the documentation says. The 14 KiB per connection includes the client side, because both ends live in one process, so treat it as an upper bound; the server's share is smaller.
Lab 3 (expected, not run): the pool wall. Prerequisites: NGINX, PHP-FPM with pm = static, pm.max_children = 4, a PHP file that calls sleep(1), and wrk or hey.
$ hey -z 10s -c 4 http://127.0.0.1/slow.php # 4 concurrent = pool size
Requests/sec: ~4.0 latency p50: ~1.0 s
$ hey -z 10s -c 16 http://127.0.0.1/slow.php # 16 concurrent, pool of 4
Requests/sec: ~4.0 latency p50: ~4.0 s # same throughput, 4x the latency (waiting in the listen queue)
$ curl -s http://127.0.0.1/fpm-status | grep -E 'max children|listen queue'
max children reached: 1
listen queue: 12(expected, not run)
Lab 4 (expected, not run): conditional GET.
$ curl -si http://127.0.0.1:8080/catalog | sed -n '1p;/^ETag/p;/^Content-Length/p'
HTTP/1.1 200 OK
Etag: "9f3c0a1d5b2e4f67"
Content-Length: 148893
$ curl -si -H 'If-None-Match: "9f3c0a1d5b2e4f67"' http://127.0.0.1:8080/catalog | sed -n '1p'
HTTP/1.1 304 Not Modified(expected, not run: the tag value and length will differ)
Lab 5 (expected, not run): see the connection reuse yourself.
$ curl -v --http1.1 http://example.test/a http://example.test/b 2>&1 | grep -E 'Connected to|Re-using'
* Connected to example.test (203.0.113.10) port 80
* Re-using existing connection with host example.test(expected, not run)
Common misconceptions
| Belief | Reality |
|---|---|
| A server is a big computer | It is a role in a connection; any process that accepts requests |
| Stateless means no state anywhere | No per-user state in the process; the state moves to the client, Redis or the database |
| More workers is always faster | Throughput is workers divided by time per request, capped by RAM, CPU and the database |
| An event loop is always faster than threads | It uses less memory per idle connection; CPU work and blocking calls still hurt |
| 304 means the cache is broken | It means the validator matched; the body was saved |
| A timeout means the request failed | It may have succeeded; replaying a non-idempotent request can duplicate it |
| Keep-alive keeps the connection forever | Idle timeouts close it, and either side may send Connection: close |
| WebRTC needs no server | It needs signalling, and often STUN or TURN |
| Octane is FPM but faster | It is a different lifecycle: state persists between requests |
| C10K is a solved problem | The OS limit is solved; your database, locks and downstream calls still cap concurrency |
| A bigger connection pool is better | Past the knee it just moves the queue |
| Thick clients are native apps only | A single-page application is a thick client in a browser |
Cheat sheet
| Topic | Remember |
|---|---|
| Roles | Client starts, server answers; roles are per connection |
| Stateless | State lives in the request, a store or a token; any replica can serve |
| Tiers | Presentation, application, data; add a tier only for a named reason |
| Request path | DNS, TCP, TLS, HTTP, proxy, app, DB; reuse connections to skip the first three |
| Worker pool | Throughput ceiling = workers / mean time; RAM caps workers |
| FPM | pm.max_children is the concurrency limit; watch listen queue |
| Octane | Boot once; no statics, no request in singleton constructors; --max-requests is a net |
| Event loop | epoll or kqueue; never block the loop |
| Go server | Set ReadHeaderTimeout and IdleTimeout; bound connections |
| Go client | Share one client; raise MaxIdleConnsPerHost; drain bodies |
| ETag | ETag out, If-None-Match in, 304 back; cheap validators save CPU too |
| Retry | Only idempotent or keyed; backoff with full jitter; honour Retry-After |
| Offline-first | Local store, queue writes, sync with idempotency keys |
| P2P and hybrid | Peers move payload, a signalling server introduces them |
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 — Why can one program be both a client and a server? Must-know
Answer
Answer: The roles belong to a connection: a Laravel app is a server to browsers and a client of PostgreSQL, Redis and a payment API at the same time (RFC 9110).
2 — A PHP-FPM pool has pm.max_children = 50 and the mean request takes 100 ms. What is the throughput ceiling, and what happens at 800 requests per second? Important
Answer
Answer: 50 / 0.1 = 500 requests per second. At 800 the excess waits in the listen queue; latency grows and the proxy eventually returns 504 or 502.
3 — Why does a Go client talking to one host from 20 goroutines reconnect constantly with default settings? Important
Answer
Answer: MaxIdleConnsPerHost defaults to 2, so 18 of the 20 connections are closed after use instead of pooled. Raise it and always drain resp.Body.
4 — What is the difference between Cache-Control: no-cache and no-store, and which pairs with ETag for always-fresh data? Must-know
Answer
Answer: no-cache allows storing but requires revalidation before reuse, which is what ETag and If-None-Match make cheap; no-store forbids storing at all.
5 — A POST timed out. When may the client retry it? Must-know
Answer
Answer: Only when the server deduplicates, for example with an Idempotency-Key; PUT and DELETE are idempotent by definition, a bare POST is not.
6 — Why does a stateful WebSocket tier make deploys harder than a stateless HTTP tier? Must-know
Answer
Answer: Connections and room state live in the process; restarting drops them and clients reconnect together, so drain gradually and reconnect with jitter.
7 — Name two things that go wrong when a Laravel app moves from FPM to Octane unchanged. Important
Answer
Answer: Static properties and singletons keep data across requests (leaks and cross-user data), and a constructor-injected request is the first request forever.
8 — What does epoll improve over poll? Important
Answer
Answer: poll scans every descriptor on each wake-up; epoll returns only the ready ones, so cost follows activity, not connection count.
9 — Which parts of a WebRTC call still need a server? Important
Answer
Answer: Signalling (offer, answer, candidates), STUN for discovering public addresses, and TURN as a relay when a direct path fails.
10 — What is the difference between a tier and a layer? Must-know
Answer
Answer: Layers organise code inside a program; tiers are separately deployed groups of machines or processes.
Glossary
| Term | Meaning |
|---|---|
| Client | The side that opens the connection and sends requests |
| Server | The side that accepts connections and answers |
| Request / response | The two HTTP message types of one exchange |
| Thin client | Client that mostly displays what the server rendered |
| Thick client | Client with real logic, state and often offline storage |
| Stateless | The server keeps no per-client data between requests |
| Stateful | The process holds data other replicas lack |
| Session | An identifier (usually a cookie) tying requests to stored user data |
| Two-tier | Client talks straight to the data tier |
| Three-tier | Presentation, application and data tiers |
| n-tier | More than three tiers: proxies, BFFs, caches, queues |
| Presentation tier | What the user touches: browser or app |
| Application tier | The servers running business logic (API server) |
| Data tier | Databases and stores holding state |
| API server | A server whose product is data and operations rather than pages |
| BFF | Backend-for-frontend: an API server shaped for one client type |
| Reverse proxy | A server that forwards client requests to backends (NGINX, HAProxy, ALB) |
| DNS | System that maps names to IP addresses |
| TCP | Reliable byte-stream transport (RFC 9293) |
| TLS | Encryption and server identity for a connection (RFC 8446) |
| HTTP | The request/response application protocol (RFC 9110, 9112) |
| Keep-alive | Reusing one connection for several requests (persistent connection) |
| Connection pool | A bounded set of reusable connections held by a client |
| Listen backlog | Kernel queue of completed connections waiting for accept |
| Event loop | One thread multiplexing many nonblocking sockets |
| Prefork | Apache model with a pool of single-request child processes |
| Worker pool | A fixed set of workers each handling one request at a time |
| PHP-FPM | PHP FastCGI Process Manager, a pool of PHP worker processes |
| Octane | Laravel package serving the app from long-lived workers |
| Swoole | PHP extension with an event loop and coroutines, one Octane server |
| FrankenPHP | PHP application server built on Caddy, an Octane server |
| RoadRunner | Go-based PHP application server, an Octane server |
| Goroutine | Go's lightweight thread, one per connection in net/http |
| C10K | The problem of serving ten thousand concurrent connections |
| epoll | Linux readiness-notification API |
| kqueue | BSD and macOS readiness-notification API |
| ETag | Opaque validator identifying a representation of a resource |
| If-None-Match | Request header making a GET conditional on a changed ETag |
| 304 Not Modified | Status meaning the client's copy is still valid |
| Idempotent retry | Replaying a request whose repeated effect equals one effect |
| Backoff | Waiting longer after each failure |
| Jitter | Randomising the wait to avoid synchronised retries |
| Offline-first | Design where the app works from local data and syncs later |
| Peer-to-peer | Participants exchange data directly, each acting as client and server |
| WebRTC | Browser API for peer-to-peer audio, video and data |
| Signalling | The server-assisted exchange of offers, answers and candidates |
| STUN / TURN | Servers that reveal public addresses / relay media when direct paths fail |
| Little's law | Concurrency equals arrival rate times time in system |
References
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.html
- RFC 9111, HTTP Caching: https://www.rfc-editor.org/rfc/rfc9111.html
- RFC 9112, HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112.html
- NGINX, connection processing methods: https://nginx.org/en/docs/events.html
- NGINX core module (
worker_processes,worker_connections): https://nginx.org/en/docs/ngx_core_module.html - NGINX upstream module (
keepalive): https://nginx.org/en/docs/http/ngx_http_upstream_module.html - Apache httpd MPMs: https://httpd.apache.org/docs/2.4/mpm.html
- Apache prefork MPM: https://httpd.apache.org/docs/2.4/mod/prefork.html
- Apache event MPM: https://httpd.apache.org/docs/2.4/mod/event.html
- PHP manual, FPM configuration: https://www.php.net/manual/en/install.fpm.configuration.php
- PHP manual, FPM: https://www.php.net/manual/en/install.fpm.php
- Laravel 13 Octane: https://laravel.com/docs/13.x/octane
- Laravel 13 HTTP client: https://laravel.com/docs/13.x/http-client
- Laravel 13 session: https://laravel.com/docs/13.x/session
- Laravel 13 responses (cache control middleware): https://laravel.com/docs/13.x/responses
- Laravel 13 middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13 Sanctum: https://laravel.com/docs/13.x/sanctum
- Laravel 13 Reverb: https://laravel.com/docs/13.x/reverb
- Go
net/http: https://pkg.go.dev/net/http - Dan Kegel, The C10K problem: https://www.kegel.com/c10k.html
- W3C, WebRTC 1.0: https://www.w3.org/TR/webrtc/
- MDN, WebRTC signalling and video calling: https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling
- MDN,
ETag: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag - BitTorrent BEP 3: https://www.bittorrent.org/beps/bep_0003.html
- Martin Fowler, Presentation Domain Data Layering: https://martinfowler.com/bliki/PresentationDomainDataLayering.html
- Marc Brooker, Timeouts, retries, and backoff with jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/