Skip to content

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 forGo to
The whole chapter in four tablesEverything in one minute
Why a split into two programs exists, and what it costsWhy it exists
RFC 9110, C10K, WebRTC, where the numbers come fromWhere it comes from
Client, server, request, responseRoles
Thin client versus thick clientThin and thick clients
Stateless versus stateful, sessionsStateless and stateful, Sessions
Two-tier, three-tier, n-tier, BFF, API serverTiers
DNS to TCP to TLS to HTTP to databaseThe journey of a request
prefork, worker pool, event loop, goroutineServer concurrency models
PHP-FPM, Octane, Swoole, FrankenPHPPHP servers
Keep-alive, pools, limits, backlogConnection handling
C10K, epoll, kqueueC10K and readiness notification
ETag, If-None-Match, 304Client-side caching
Polling, SSE, WebSocket versus request/responsePush versus pull
Retries, backoff, offline-firstMobile and flaky clients
BitTorrent, WebRTC, signallingPeer-to-peer and hybrid
Knobs, defaults, error messagesMechanics
CodeGo, Laravel
Real failures and fixesSolving the classic problems
Which model for which workloadChoosing
One process to a fleetIn architecture
Reproduce the numbersLab
Beliefs, summary, quiz, termsMisconceptions, 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.

TermIn plain wordsTiny exampleWhat it owns
ClientThe side that opens the connection and sends the requestA browser, a mobile app, a Laravel service calling a payment APIThe user's screen, its own cache, retry decisions
ServerThe side that accepts connections and answersNGINX, a Go net/http process, PHP-FPM behind NGINXThe data, the rules, the connection limits
RequestOne message: method, target, headers, optional bodyGET /catalog with If-None-Match: "a1b2"Intent and validators
ResponseOne message back: status, headers, optional body304 Not Modified, or 200 with ETagResult and cache instructions
Reverse proxyA server that forwards to other serversNGINX or AWS ALB in front of the appTLS ending, buffering, routing, limits
BFFA server shaped for one kind of clientA mobile-only API that returns exactly the mobile screenAggregation and trimming

State and where it lives.

ChoiceMeaningExampleScaling effect
Stateless serverEvery request carries what the server needsJWT or a session id looked up in RedisAny replica can answer; add boxes freely
Stateful serverThe process remembers between requestsIn-memory session map, a WebSocket room in RAMRequests must reach the same box (affinity) or the state is lost
Thin clientLittle logic, server rendersServer-rendered Laravel Blade pageCheap devices, server does the work
Thick clientReal logic and local stateMobile app with local database, SPAFast UI and offline use, harder updates and trust

One server, four ways to hold connections.

ModelOne connection costsTypical productsLimit knobWeak spot
Process per requestA whole OS process while busyApache prefork, PHP-FPMMaxRequestWorkers, pm.max_childrenRAM per process, slow clients pin a process
Thread pool plus listenerA thread only while a request runsApache event MPMMaxRequestWorkers, ThreadsPerChildThread-safe code needed
Event loopA few kilobytes of stateNGINX, Node.js, Swoole, Octane workersworker_connectionsOne blocking call stalls every connection on that loop
Goroutine per connectionA goroutine (small stack) parked by the runtimeGo net/httpYour own limits (LimitListener, timeouts)Unbounded unless you bound it

The request, hop by hop (fresh connection, same data centre, orders of magnitude).

HopWhat happensCost on a fresh connectionCost on a reused one
DNSName to IP address0 ms cached, tens of ms on a miss0
TCPThree-way handshake1 round trip0
TLS 1.3Key exchange, certificate1 more round trip (RFC 8446)0
HTTPRequest out, response back1 round trip plus server time1 round trip plus server time
ApplicationRouting, validation, business rulesCPU time, often 1-50 mssame
DatabaseQuery over a pooled connection0.2-5 ms in one data centresame

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 splitCost of the split
One place to secure, audit, update and billThe server is a shared bottleneck and a single target
Clients stay simple and replaceableEvery interaction is a network call that can be slow, lost or repeated
Data stays consistent because one party writes itThe server must absorb every client's peak at once
Server and client change and scale independentlyTwo versions of the contract live at the same time in production
Failure is local: a client can crash aloneA 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).

DimensionThin clientThick client
Where logic runsServerClient, plus the server for truth
Update pathDeploy once, everyone is updatedApp stores, cache busting, old versions in the wild for months
OfflineDoes not workCan work (offline-first)
TrustServer decidesThe client cannot be trusted; the server re-validates everything
PayloadRendered pagesData (JSON)
Latency feelEach click is a round tripInstant locally, sync later
Typical stackLaravel Blade, LivewireReact 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 liveExampleScales howCost
Client (cookie, token)Signed JWT, Laravel encrypted cookie sessionPerfectly (the server stores nothing)Size limits, revocation is hard
Shared storeRedis, Memcached, database sessionsNeeds the store to scaleOne extra hop, a new dependency
Server memoryPHP file sessions on one box, Go mapOnly with sticky routingLost on restart, lost on scale-out
DatabaseOrders, carts, balancesPer database chaptersLatency, contention
ConnectionA WebSocket subscribed to roomsNeeds 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, answers

The 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:

sql
-- 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.

Two-tierThick clientDatabaselogic in the client;DB credentials on devicesThree-tierPresentation tierApplication tierData tierlogic on servers you control;the default web shapen-tierClientReverse proxy / BFFAPI serverDataWeb clientBFF (web)Domain servicesCache + DBMobile clientBFF (mobile)Domain servicesQueue + DBeach extra tier adds a hop, a deadline and a failure mode;add one only for a reason you can name
LayoutWhat talks to the databaseStrengthWeaknessSeen today
Two-tierThe client itselfFewest moving partsCredentials and rules on every device; every client opens its own DB connectionInternal tools, desktop apps of the 1990s, some mobile "backend as a service" setups
Three-tierOnly the application serverRules in one place; DB reachable only from the app networkThe app tier scales with the slowest queryDefault for web applications
n-tierDomain services behind proxies and BFFsEach tier scales and fails separately; tailored APIsMore hops, more deadlines, more to monitorLarge 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.

Clientbrowser or appDNS resolvername to IPReverse proxyNGINX, HAProxy, ALBTLS ends hereApp workerPHP-FPM, Octane,Go net/httpDatabasepooled connections1 DNS2 TCP SYN3 TLS handshake456Where time goes (typical, order of magnitude)1 DNS: 0 ms when cached, tens of ms on a miss. 2-3 TCP + TLS 1.3: 2 round trips on a fresh connection, 0 on a reused one.4 HTTP request over the kept-alive connection: 1 round trip. 5 query: 0.2-5 ms inside one data centre.6 Response bytes back. Keep-alive and pools exist to skip steps 2-3 and the database handshake on most requests.Round-trip times depend on distance; see the latency chapter for numbers.
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
LayerOwnsFailure you seeWhere it is taught
DNSName to address, TTL, GeoDNSNXDOMAIN, stale record after a moveIP, DNS & GeoDNS, DNS for developers
TCPReliable byte stream, congestionconnection refused, timeout, resetTCP & UDP, Ports & sockets
TLSEncryption, server identityCertificate errors, handshake failuresTLS in Practice
HTTPMethods, status codes, caching4xx, 5xx, 304HTTP evolution
Proxy / LBRouting, limits, TLS ending502, 503, 504Load Balancing
ApplicationBusiness rules500, 422, 409the rest of this chapter
DatabaseTruthTimeouts, deadlocks, pool exhaustionConnection 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.

Process per requestApache prefork, PHP-FPMpm.max_childrenprocess 1: request Aprocess 2: request Bprocess 3: request Cno free process: waitcost: RAM per processgain: isolation, no shared stateThreads + listenerApache event MPMMaxRequestWorkersworker threads runonly active requestslistener thread parksidle keep-alive socketscost: thread-safe codegain: many idle sockets, few threadsEvent loopNGINX, Node.js, Swooleworker_connectionsone thread per workerepoll / kqueue wakes itthousands of sockets,non-blocking I/Ocost: never block the loopgain: tiny memory per connectionGoroutine per connGo net/httpruntime netpoller (epoll)1 goroutine perconnection, blocking stylescheduler parks it onepoll, not on a threadcost: unbounded unless limitedgain: simple code, event-loop scaleAll four answer the same question: what does an idle or slow connection cost, and who runs when data arrives?Limit knobs differ, the failure is the same: workers exhausted, new connections queue in the listen backlog.Laravel Octane keeps the app booted inside Swoole, FrankenPHP or RoadRunner workers instead of per-request FPM processes.
ProductModelWhat the vendor docs sayThe limit you tune
Apache httpd, prefork MPMProcess 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 MPMThreads 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
NGINXEvent loop in a few worker processesChooses a connection processing method per platform: epoll on Linux 2.6+, kqueue on FreeBSD, OpenBSD, NetBSD and macOSworker_processes, worker_connections (default 512), worker_rlimit_nofile
PHP-FPMProcess pool, one request at a time per childpm.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 OctaneLong-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/httpGoroutine per connectionServe accepts connections "creating a new service goroutine for each"ReadHeaderTimeout, IdleTimeout, your own connection limit
Node.jsSingle-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).

AspectPHP-FPM (+ NGINX or Apache)Octane on Swoole / Open SwooleOctane on FrankenPHPOctane on RoadRunner
Process modelPool of processes, one request eachWorkers with a Swoole event loop and coroutinesWorkers inside the Caddy-based serverGo server managing PHP workers
App bootEvery requestOnce per workerOnce per workerOnce per worker
Memory between requestsNoneKeptKeptKept
Extra Octane featuresn/aConcurrent tasks, ticks, Octane cache and tablesBasicBasic
Typical failurepm.max_children reached, 502 or 504 at the proxyMemory growth, state leaking across requestsSameSame
# 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 child

The 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.

WhereKnobDefault (from the docs read)What it bounds
NGINXworker_connections512 per workerAll connections of a worker, client and upstream together
NGINXkeepalive_timeout, keepalive_requestsset per serverIdle time and requests per client connection
NGINX upstreamkeepaliveoff unless setIdle connections cached to the app per worker
Apache httpdMaxRequestWorkers, ListenBacklogMPM dependentSimultaneous requests, accept queue
PHP-FPMlisten.backlog511 on Linux, -1 on BSDThe accept queue of the FPM socket
Go serverIdleTimeout, ReadHeaderTimeoutno timeout if zeroIdle and slow-header clients
Go clientTransport.MaxIdleConnsPerHost2 (DefaultMaxIdleConnsPerHost)Idle connections reused per destination
Laravel HTTP clientconnectTimeout10 secondsTime to open the connection
Linuxulimit -n, net.core.somaxconnsystem dependentFile 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 reconnects

Real 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
MechanismOSCost per wake-upUsed by
selecteverywhere, fd limit (FD_SETSIZE)scans alllegacy
polleverywherescans alllegacy, small fd sets
epollLinux 2.6+only ready fdsNGINX on Linux, Go runtime netpoller on Linux, Swoole, Node.js (libuv)
kqueueFreeBSD, OpenBSD, NetBSD, macOSonly changed fdsNGINX 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.

Client cacheServer1 GET /catalog2 200 OK, ETag: "a1b2", body 480 KBclient stores body + validator3 GET /catalog, If-None-Match: "a1b2"4 304 Not Modified, no body (about 300 bytes)5 GET /catalog, If-None-Match: "a1b2" (resource changed)6 200 OK, ETag: "c3d4", new body
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
HeaderDirectionMeaning
ETagresponseValidator for this representation (strong "x" or weak W/"x")
If-None-Matchrequest"Send the body only if the current ETag is not one of these"
If-Matchrequest"Apply this change only if the current ETag matches" (optimistic concurrency on PUT, see Optimistic Locking)
Last-Modified, If-Modified-SincebothThe date-based, coarser validator pair
Cache-Control: no-cacheresponseStore it, but revalidate before every reuse
Cache-Control: max-age=NresponseFresh for N seconds without asking
304responseRevalidation succeeded; reuse your copy
VaryresponseWhich 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.

TechniqueLatency to new dataServer costWorks through proxiesFits
Short pollingUp to one intervalA request per poll, mostly 304 or emptyEverywhereDashboards, low urgency
Long pollingNear real timeOne held connection per clientMostlyFallback, simple notifications
SSENear real time, server to client onlyOne held connection per clientMostly (needs no buffering)Feeds, progress, notifications
WebSocketReal time, both waysOne stateful connection per clientNeeds proxy support for upgradesChat, games, collaboration
Mobile push (APNs, FCM)Seconds, app may be closedProvider's gatewayNot applicableWake-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)
FailureClient shouldWhy
Connection refused, DNS failureRetry with backoffThe server never saw it
Timeout on GET, PUT, DELETERetry with backoffIdempotent
Timeout on POST with Idempotency-KeyRetry with the same keyThe server deduplicates
Timeout on POST without a keyDo not retry blindly; ask the user or reconcileMay have been processed
429 or 503 with Retry-AfterWait at least that longThe server told you
4xx other than 408, 429Do not retryThe request is wrong
OfflineQueue locally, show "pending", sync on reconnectOffline-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.

Client-serverserverone place to secure, bill, update;the server is the bottleneckPeer-to-peercapacity grows with peers (BitTorrent);discovery, NAT and trust are hardHybrid (WebRTC)signalling servermedia flows peer to peerserver only introduces peers(offer, answer, ICE candidates)
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 ============
ModelWho stores dataScalingStrengthWeaknessExample
Client-serverServerAdd serversControl, consistency, billingServer is cost and bottleneckWeb apps, APIs
Pure P2PPeersGrows with peersNo central costDiscovery, NAT, trust, churnBitTorrent swarms
HybridServer for coordination, peers for payloadServer scales with sessions, not bytesCheap bandwidth, central control of identityNeeds TURN relays for hard NATsWebRTC 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.

QuantityExampleResult
RAM for PHP8 GB box, 2 GB for OS, NGINX, Redis agent6 GB
Resident memory per FPM child (measure it with ps)60 MB100 children fit
Mean request time50 ms100 / 0.05 = 2000 requests/s ceiling
If 30% of requests wait 1 s on a slow APImean time 0.35 s100 / 0.35 = about 285 requests/s
Database connections100 children x 5 replicas500 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 ​

ProductKnobDefault (as documented)Effect when too lowEffect when too high
NGINXworker_processes1 (auto = one per core)Idle coresLittle benefit
NGINXworker_connections512worker_connections are not enough in the error logMemory, descriptor limit
PHP-FPMpm.max_childrenmandatory, no defaultRequests queue, 502/504Out-of-memory kill
PHP-FPMpm.max_requests0 (never recycle)Workers recycled oftenLeaks accumulate
PHP-FPMrequest_terminate_timeout0 (off)Legit slow requests killedStuck workers hold slots
PHP-FPMlisten.backlog511 on LinuxConnections refused under burstsLonger queues, stale requests
ApacheMaxRequestWorkersMPM specificRequests waitRAM exhaustion
Octane--workersone per CPU coreUnder-useMemory
Octane--max-requests500Frequent restartsLeaks live longer
Octanemax_execution_time30 secondsKilled long requestsStuck workers
Go serverReadHeaderTimeoutnoneValid slow clients droppedSlow-loris holds goroutines
Go clientMaxIdleConnsPerHost2Constant reconnectsIdle descriptors

NGINX with an upstream keep-alive pool, PHP-FPM and Apache configuration live in the snippets:

nginx
# 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;
        }
    }
}
ini
; /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
# 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 100

Messages you will actually see ​

WhereMessage or statusMeaningFirst thing to check
NGINX error logworker_connections are not enoughA worker hit worker_connectionsThe limit counts upstream connections too
NGINX error logconnect() failed (111: Connection refused) while connecting to upstreamApp not listening or backlog fullIs PHP-FPM or the Go process up
NGINX502 Bad GatewayUpstream closed or sent garbageCrashed worker, killed by OOM
NGINX504 Gateway Time-outUpstream too slowproxy_read_timeout, slow query
NGINX error logupstream timed out (110: Connection timed out) while reading response header from upstreamSame as 504, in the logSlow dependency
PHP-FPM logserver reached pm.max_children setting (40), consider raising itPool exhaustedRAM budget, slow dependency
PHP-FPM logWARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers)Spare servers too fewSpare settings
Go clientnet/http: request canceled (Client.Timeout exceeded while awaiting headers)Client timeout firedTimeout versus server p99
Go server loghttp: Accept error: accept tcp ...: accept4: too many open files; retrying in 5msProcess out of descriptorsulimit -n, connection leak
Browser / clientERR_CONNECTION_REFUSEDNothing listens or firewallPort, process, security group
HTTP429 Too Many Requests with Retry-AfterRate limitHonour the header
HTTP503 Service Unavailable with Retry-AfterOverloaded or drainingRetry with backoff
HTTP412 Precondition FailedIf-Match did not matchRe-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.

go
// 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.

go
// 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:

go
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.

go
// 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
}
go
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/http is goroutine-per-connection by design: Serve accepts 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. Use LimitListener-style caps, http.MaxBytesHandler, and per-request context deadlines.
  • Zero means "no limit" in http.Server. ReadHeaderTimeout is the slow-loris defence; IdleTimeout ends idle keep-alive connections (if zero, ReadTimeout is used); WriteTimeout bounds the response. The documentation says most users will prefer ReadHeaderTimeout over ReadTimeout because 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." DefaultMaxIdleConnsPerHost is 2, so a service that calls one host from many goroutines silently reconnects unless you raise it. Always drain and close resp.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 Server and DefaultTransport; a custom Transport needs ForceAttemptHTTP2 or 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
<?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
<?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
<?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
<?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
<?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
<?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:

sh
# 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=8000

The 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_children is 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_DRIVER selects file, cookie, database, memcached, redis, dynamodb or array. For more than one server use redis, database, dynamodb or cookie. Session blocking (the block option on a route) needs a cache driver with atomic locks and serialises requests of one session.
  • The HTTP client (a Guzzle wrapper): connectTimeout defaults to 10 seconds; retry($times, $sleep, $when, $throw) accepts a closure for the sleep, an array of delays, and a when callable; with throw: false a final failure does not throw, though a ConnectionException still can. Http::pool sends 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 ​

CauseSymptomFixCost or limit
pm.max_children too small for the slow-request mixserver reached pm.max_children, listen queue above 0Raise it to what RAM allows (Little's law above)RAM; more DB connections
One slow dependency pins every workerEverything slow, CPU idleTimeouts on every outbound call, circuit breaker (Circuit Breaker), bulkheadsNeeds a degraded response
Slow clients pin workersMany workers in "reading request"Put NGINX (buffering) in front; client_body_timeoutOne more hop
No spare capacityLatency cliff at a certain loadAutoscale 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_timeout

Slow-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 ​

SituationChooseExtra techniqueReason
Typical Laravel site, moderate traffic, simple opsNGINX plus PHP-FPM, pm = dynamicpm.max_requests, pm.status_pathIsolation per request, forgiving of sloppy state
Laravel API where boot time dominates latencyOctane on FrankenPHP, Swoole or RoadRunner--max-requests, leak review, load testBoot once, 1 worker per core
Need concurrent tasks, ticks, in-memory tables in PHPOctane on SwooleTask workersSwoole-only features
Many idle connections (chat, push)Event loop or Go (or Reverb for Laravel)ulimit -n, idle timeouts, drain on deployCheap idle connection
CPU-bound, simple deploysGo net/http behind a proxyReadHeaderTimeout, LimitListenerOne binary, goroutines
Legacy PHP app needing mod_php semanticsApache with a documented MPM choiceprefork for non-thread-safe librariesCompatibility
Many clients, one cheap read endpointConditional GET + CDNmax-age, stale-while-revalidateFewer bytes and fewer workers
Real-time updates, bidirectionalWebSocketFan-out layerSee realtime chapter
Real-time one-way updatesSSELast-Event-ID resumeSimpler than WebSocket
Voice, video, large P2P transfersWebRTC or BitTorrent-styleSignalling service, TURNServer cost scales with sessions, not bytes
Mobile app on bad networksThick client, local storeIdempotency keys, backoff with jitter, sync queueWorks offline
QuestionIf yesIf no
Does a request often wait on slow I/O?Event loop, goroutines, or a big enough pool with timeoutsA small pool is fine
Can the app tolerate shared mutable process state?Octane, GoPHP-FPM
Do clients poll the same data?Validators and 304sSkip
Must a user keep one server for state?Fix the state; sticky routing is a stopgapStateless, 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 ​

LoadShapeWhat changesFirst bottleneck
1x (about 50 req/s)One box: NGINX, FPM, PostgreSQLNothing special; add ETag, keep-alive, timeoutsSlow queries
10x (about 500 req/s)Reverse proxy or load balancer, 2-4 app replicas, shared Redis session store, read replica, CDN for static filesStateless app tier, externalised sessions, connection poolerDatabase 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 pathsRetry budgets, load shedding, connection draining, regional routingFan-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.

go
// 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, 28ms

Same 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.

go
// 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 connection

One 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 ​

BeliefReality
A server is a big computerIt is a role in a connection; any process that accepts requests
Stateless means no state anywhereNo per-user state in the process; the state moves to the client, Redis or the database
More workers is always fasterThroughput is workers divided by time per request, capped by RAM, CPU and the database
An event loop is always faster than threadsIt uses less memory per idle connection; CPU work and blocking calls still hurt
304 means the cache is brokenIt means the validator matched; the body was saved
A timeout means the request failedIt may have succeeded; replaying a non-idempotent request can duplicate it
Keep-alive keeps the connection foreverIdle timeouts close it, and either side may send Connection: close
WebRTC needs no serverIt needs signalling, and often STUN or TURN
Octane is FPM but fasterIt is a different lifecycle: state persists between requests
C10K is a solved problemThe OS limit is solved; your database, locks and downstream calls still cap concurrency
A bigger connection pool is betterPast the knee it just moves the queue
Thick clients are native apps onlyA single-page application is a thick client in a browser

Cheat sheet ​

TopicRemember
RolesClient starts, server answers; roles are per connection
StatelessState lives in the request, a store or a token; any replica can serve
TiersPresentation, application, data; add a tier only for a named reason
Request pathDNS, TCP, TLS, HTTP, proxy, app, DB; reuse connections to skip the first three
Worker poolThroughput ceiling = workers / mean time; RAM caps workers
FPMpm.max_children is the concurrency limit; watch listen queue
OctaneBoot once; no statics, no request in singleton constructors; --max-requests is a net
Event loopepoll or kqueue; never block the loop
Go serverSet ReadHeaderTimeout and IdleTimeout; bound connections
Go clientShare one client; raise MaxIdleConnsPerHost; drain bodies
ETagETag out, If-None-Match in, 304 back; cheap validators save CPU too
RetryOnly idempotent or keyed; backoff with full jitter; honour Retry-After
Offline-firstLocal store, queue writes, sync with idempotency keys
P2P and hybridPeers move payload, a signalling server introduces them

Self-check: questions & answers ​

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

1 — 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 ​

TermMeaning
ClientThe side that opens the connection and sends requests
ServerThe side that accepts connections and answers
Request / responseThe two HTTP message types of one exchange
Thin clientClient that mostly displays what the server rendered
Thick clientClient with real logic, state and often offline storage
StatelessThe server keeps no per-client data between requests
StatefulThe process holds data other replicas lack
SessionAn identifier (usually a cookie) tying requests to stored user data
Two-tierClient talks straight to the data tier
Three-tierPresentation, application and data tiers
n-tierMore than three tiers: proxies, BFFs, caches, queues
Presentation tierWhat the user touches: browser or app
Application tierThe servers running business logic (API server)
Data tierDatabases and stores holding state
API serverA server whose product is data and operations rather than pages
BFFBackend-for-frontend: an API server shaped for one client type
Reverse proxyA server that forwards client requests to backends (NGINX, HAProxy, ALB)
DNSSystem that maps names to IP addresses
TCPReliable byte-stream transport (RFC 9293)
TLSEncryption and server identity for a connection (RFC 8446)
HTTPThe request/response application protocol (RFC 9110, 9112)
Keep-aliveReusing one connection for several requests (persistent connection)
Connection poolA bounded set of reusable connections held by a client
Listen backlogKernel queue of completed connections waiting for accept
Event loopOne thread multiplexing many nonblocking sockets
PreforkApache model with a pool of single-request child processes
Worker poolA fixed set of workers each handling one request at a time
PHP-FPMPHP FastCGI Process Manager, a pool of PHP worker processes
OctaneLaravel package serving the app from long-lived workers
SwoolePHP extension with an event loop and coroutines, one Octane server
FrankenPHPPHP application server built on Caddy, an Octane server
RoadRunnerGo-based PHP application server, an Octane server
GoroutineGo's lightweight thread, one per connection in net/http
C10KThe problem of serving ten thousand concurrent connections
epollLinux readiness-notification API
kqueueBSD and macOS readiness-notification API
ETagOpaque validator identifying a representation of a resource
If-None-MatchRequest header making a GET conditional on a changed ETag
304 Not ModifiedStatus meaning the client's copy is still valid
Idempotent retryReplaying a request whose repeated effect equals one effect
BackoffWaiting longer after each failure
JitterRandomising the wait to avoid synchronised retries
Offline-firstDesign where the app works from local data and syncs later
Peer-to-peerParticipants exchange data directly, each acting as client and server
WebRTCBrowser API for peer-to-peer audio, video and data
SignallingThe server-assisted exchange of offers, answers and candidates
STUN / TURNServers that reveal public addresses / relay media when direct paths fail
Little's lawConcurrency equals arrival rate times time in system

References ​

Built by Morteza Negahi