Skip to content

Distribution of Components: Local vs Remote, Latency & Failure as Design Inputs ​

"We argue that objects that interact in a distributed system need to be dealt with in ways that are intrinsically different from objects that interact in a single address space." — Jim Waldo, Geoff Wyant, Ann Wollrath, Sam Kendall, A Note on Distributed Computing, Sun Microsystems Laboratories TR-94-29, November 1994

Summary: Moving a component to another process or machine does not just add a wire: it adds latency, partial failure, serialization, version skew and a second owner. A good design treats those as inputs from the first sketch, decides what to distribute for a reason, and shapes the interface for the remote case before anything is distributed. Focus: Local vs remote calls, the eight fallacies and their design consequences, the First Law of Distributed Object Design, coarse-grained interfaces (Remote Facade, DTO), component vs service vs process boundaries, the distribution ladder, RPC vs messaging vs REST, serialization and schema evolution, latency budgets and tail latency, chatty interfaces, caching, consistency, observability and contract testing, in Go and Laravel. Learning goal: Take an in-process module, decide whether it should move behind a network, redesign its interface as one coarse call with a deadline, bounded retries and a correlation id, and prove with a test that the call count and the latency budget hold.

This page is the design-level view of distribution, the SWEBOK "distribution of components" concern. It is deliberately not a networking course and not a microservices tutorial. How to survive failures is in Error & Exception Handling and Fault Tolerance; how to pick synchronous or asynchronous communication between services is in Service Communication; where the lines between services go is in Service Boundaries; the full retry, timeout and jitter treatment is in Timeouts, Retries & Jitter, and the end-to-end latency arithmetic is in Latency Budget & Tail Latency. Here we answer the question that comes first: should this component be remote at all, and what must change in its design if it is?

Page map ​

If you are looking forGo to
The whole chapter in a few tablesEverything in one minute
Why distribution needs design, and the analogyWhy it exists
Waldo 1994, the fallacies, Fowler's First Law, Dean's numbers, SWEBOKWhere it comes from
Local vs remote calls: latency, partial failure, memory, serialization, versioningLocal vs remote
All eight fallacies, each with its design consequenceThe eight fallacies
"don't distribute your objects" and what it does and does not forbidFirst Law
Remote Facade, DTO, coarse-grained interfacesCoarse-grained design
Component vs service vs process vs deployment boundaryBoundaries
Data gravity, team ownership, scaling, failure isolation: what to distributeChoosing what to distribute
In-process, separate process, separate host, separate regionThe distribution ladder
Timeouts, retries, idempotency, backpressure as design inputsNetwork as a design input
Location transparency and why it failsLocation transparency
RPC vs messaging vs RESTInteraction styles
Contracts, JSON vs Protobuf, schema evolutionContracts and serialization
Latency budgets, tail latency, hedgingBudgets and tail latency
N+1 across the network, caching, consistencyChatty calls, caching, consistency
Correlation ids, tracing, contract tests, consumer-driven contractsObservability and testability
Exact knobs: Go net/http, gRPC, Laravel HTTP client, OctaneMechanics
Working codeGo, Laravel
Chatty clients, retry storms, version skew, the distributed monolithSolving the classic problems
Which rung of the ladder for which situationChoosing
Monolith, modular monolith, microservices, distributed data, scalingIn architecture
Measure in-process vs localhost vs +50 ms, and chatty vs coarseLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

A local call and a remote call are different operations. Every row is unpacked in the concepts.

DimensionLocal (in-process) callRemote callDesign consequence
LatencyNanoseconds (about 100 ns to reach main memory)0.5 ms in a datacenter, about 150 ms across continentsCount calls; make them coarse; set a latency budget
FailureFails with the caller (or throws)Can fail on its own, or be slow, or half-succeedTimeouts, bounded retries, idempotency, classified errors
MemoryOne address space, pass a pointerNo shared memory, data is copiedPass values (DTOs), never references
SerializationNoneEncode and decode on every callChoose a format, budget the CPU, cap payload size
VersioningCompiler checks both sides togetherCaller and callee deploy at different timesExplicit contract, additive changes, tolerant readers
ConcurrencySame locks, same schedulerTwo machines, no shared lockIdempotency, optimistic concurrency, no distributed locks by default
OwnershipOne team, one releaseOften two teams, two releasesContracts, ownership, deprecation policy
DebuggingOne stack traceMany logs, many clocksCorrelation id, distributed tracing

Numbers to carry in your head (Jeff Dean, LADIS 2009 keynote, "Numbers Everyone Should Know").

OperationTimeRelative to a memory reference
Main memory reference100 ns1x
Mutex lock/unlock25 ns0.25x
Send 2K bytes over 1 Gbps network20 us200x
Read 1 MB sequentially from memory250 us2,500x
Round trip within same datacenter500 us5,000x
Disk seek10 ms100,000x
Send packet CA to Netherlands and back150 ms1,500,000x

The eight fallacies in one line each. All are unpacked in the fallacies section.

#FallacyOne-line design consequence
1The network is reliableTimeouts, bounded retries, idempotency
2Latency is zeroCoarse calls, a latency budget
3Bandwidth is infiniteSmall payloads, pagination, compression
4The network is secureTLS or mTLS, authentication at every hop
5Topology does not changeService discovery, no hard-coded addresses
6There is one administratorContracts, versioning, ownership
7Transport cost is zeroBudget serialization and egress, batch
8The network is homogeneousOpen formats, tolerant readers

Where the pieces live in your tools.

ConcernGoLaravel
Per-call deadlinecontext.WithTimeout, http.Client.Timeout, gRPC deadlinesHttp::timeout(), Http::connectTimeout()
Bounded retryA small loop with jittered backoff (this page's Client), gRPC retryPolicyHttp::retry($times, $sleep, $when)
Coarse callOne method taking a slice, one DTOOne endpoint, a readonly DTO
Parallel fan-outerrgroup, goroutinesHttp::pool()
Correlation idX-Request-ID header + contextContext::add() + withHeaders()
Fake the network in testshttptest.NewServer + a sleep handlerHttp::fake(), Http::sequence(), Http::preventStrayRequests()
Gateway to gRPCgoogle.golang.org/grpcRoadRunner gRPC plugin (see Laravel angle)

Why it exists ​

A program is a set of components that cooperate. When they live in one process, cooperation costs a function call and the compiler keeps both sides in sync. When they live in different processes, on different machines or in different regions, the same cooperation crosses a network, and the network brings its own physics and its own failures. The question "which components go where" is therefore not a deployment detail you can fix at the end. It changes the interfaces (they must be coarser), the error model (it must include "I don't know what happened"), the data model (copies diverge) and the team model (two teams, two release trains).

Keep it localDistribute it
A call costs nanosecondsA call costs microseconds to hundreds of milliseconds
Failure is all-or-nothing for the processFailure is partial: one side can be down, slow or confused
Refactor across the boundary with the IDEChanging the boundary is a migration with a deprecation window
One deploy, one rollbackIndependent deploys, independent rollbacks, version skew
One database transactionEventual consistency, sagas, idempotency
Debug with one stack traceDebug with correlation ids and traces
Scale the whole thing togetherScale a hot part alone; isolate a failing part
Risk: the big ball of mudRisk: the distributed big ball of mud
1. Same processmodule call~100 ns (memory)2. Same hostseparate process~100 us (localhostHTTP, measured)+ serialization+ own lifecycle+ version skew3. Separate hostssame datacenter~500 us round trip+ partial failure+ timeouts, retries+ discovery, TLS+ bandwidth, load+ independent scaling+ failure isolation4. Separate regionsother continent~150 ms round trip+ partitions are normal+ clocks disagree+ replication lag+ data residency+ consistency is a choice+ cost of egress+ regional failureisolation, closerto usersEach step right buys independence and costs latency and new failure modesRound-trip figures: Dean (2009) for datacenter and cross-continent, this page's lab for localhost

The picture is the ladder this chapter keeps returning to: four rungs from a module call to a separate region. Moving right buys independence (separate deploys, scaling, failure isolation) and costs latency and new failure modes. The latency figures are Dean's 2009 numbers for the datacenter and the transcontinental rungs, and this page's own lab for localhost.

The analogy we reuse on this page: cooking in your own kitchen vs ordering from a restaurant across town. Reaching for the salt in your own kitchen takes a second and never fails halfway. Phoning a restaurant takes minutes, the line can be busy, they can say "yes" and then never deliver, the courier can be stuck, and when you phone back you do not know whether they already started your dish. So you stop ordering one ingredient at a time: you place one order with everything in it, you agree how long you will wait, and you write down your order number in case you must ask what happened. That order is the coarse-grained call; the order number is the correlation id; "how long you will wait" is the deadline.

Three common misunderstandings, up front ​

  1. "A remote call is a function call that happens to be slow." Slowness is the visible difference, and the least fundamental one. A remote call can also half succeed, return a result you cannot trust, or never return. The interface has to be designed for that.
  2. "The First Law says never use microservices." It says do not hide the remote/in-process distinction behind transparent distributed objects. Fowler himself explains in 2014 why coarse-grained services over HTTP or messaging do not violate it.
  3. "We can put everything behind interfaces now and move it out later for free." The interface of a component that may go remote must already be coarse, carry a context or deadline, and return classifiable errors. Retro-fitting that is a rewrite of every caller.

Where it comes from ​

Waldo, Wyant, Wollrath and Kendall, 1994. The Sun Labs note argued against the idea that objects should look the same whether they are local or remote. Their abstract says the differences are that "distributed systems require that the programmer be aware of latency, have a different model of memory access, and take into account issues of concurrency and partial failure." The text puts a number on latency, which has aged less than you might expect:

"The difference between the two is currently between four and five orders of magnitude" — Waldo et al., A Note on Distributed Computing, section 4.1 (1994)

and names the failure property that cannot be hidden:

"In a distributed system, the failure of a network link is indistinguishable from the failure of a processor on the other side of that link." — Waldo et al., A Note on Distributed Computing, section 4.3 (1994)

They also call the unified local/remote view of objects "mistaken". That is the intellectual root of everything on this page.

Deutsch and Gosling, the fallacies. Sun's list of eight false assumptions is attributed to Peter Deutsch (seven in 1994) and James Gosling (the eighth, around 1997). We could not read a 1994 original; the two sources we read are Deutsch's own short page (archived copy) and Arnon Rotem-Gal-Oz's whitepaper, which gives the 1994/1997 history:

"Essentially everyone, when they first build a distributed application, makes the following eight assumptions. All prove to be false in the long run and all cause big trouble and painful learning experiences." — Peter Deutsch, The Eight Fallacies of Distributed Computing (Sun Microsystems page, archived copy)

Fowler, 2002. In Patterns of Enterprise Application Architecture (chapter 7, "Distribution Strategies") Fowler coined what he calls the First Law of Distributed Object Design: "don't distribute your objects". The same book gives the two patterns that make a remote interface workable, Remote Facade and Data Transfer Object. The Remote Facade page states the physics bluntly:

"The brutal truth is that any inter-process call is orders of magnitude more expensive than an in-process call - even if both processes are on the same machine." — Martin Fowler, Remote Facade, PoEAA catalog (2003)

Fowler, 2014. In "Microservices and the First Law of Distributed Objects" he explains that the law targeted a fashion, distributed objects with transparent middleware (DCOM, CORBA), and why microservices do not violate it, while keeping his wariness:

"you can't encapsulate the remote/in-process distinction" — Martin Fowler, Microservices and the First Law of Distributed Objects, 13 August 2014

"I do think distribution is a complexity booster." — the same article

Dean, 2009 and Dean and Barroso, 2013. Jeff Dean's LADIS 2009 keynote popularised the "Numbers Everyone Should Know" table (table above) and the skill of estimating a design's performance "without actually having to build it". The Tail at Scale (CACM, 2013) showed that tail latency dominates in fan-out systems, see Budgets and tail latency.

SWEBOK v4, 2024. The Software Design knowledge area lists "Distribution of Components" among the key design issues:

"Distribution concerns how software components are distributed across hardware (including computers, networks and other devices) and how those components communicate while meeting performance, reliability, scalability, availability, monitorability, business continuity and other expectations." — IEEE Computer Society, SWEBOK Guide v4.0a, Software Design KA §3.4

Newman. Sam Newman's Building Microservices covers remote calls and their failure modes in depth; we did not read the book for this page and make no claim attributed to it. See the sibling pages for the microservices material.

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a call timeline where it helps, real scenarios, how it shows up in the tools, and the fix.

Local vs remote calls Must-know ​

In plain words: a local call is the same program talking to itself. A remote call is two programs talking through a wire that can be slow, can drop messages and can break without telling both sides.

Common misunderstanding: "If both services run on the same machine the call is basically local." Fowler: any inter-process call is orders of magnitude more expensive "even if both processes are on the same machine". In this page's lab, a coarse localhost HTTP call is between 250 and 380 times slower than the same work in-process (two runs: 110 and 169 microseconds against 440 nanoseconds; see Lab); no physical network is involved.

Definition: a call is remote if caller and callee do not share an address space, so arguments and results must be copied across a boundary and either side can fail independently. The six differences below are the design inputs.

DifferenceWhat it meansWhat the design must contain
LatencyRound trips are 4 to 5 orders of magnitude slower (Waldo 1994)A call-count budget and a time budget
Partial failureOne side fails, the other keeps runningTimeouts, retries, idempotency, fallbacks
No shared memoryNo pointers, no shared objects, no shared locksValues in messages (DTOs), explicit ownership of state
SerializationEvery call encodes and decodesA format, a size cap, a CPU budget
ConcurrencyTwo machines make progress independentlyOptimistic concurrency, idempotency keys
VersioningThe two ends are deployed at different timesAn evolvable contract, tolerant readers
text
     Caller (checkout)                        Callee (pricing)
1    quote(basket)  ---------------------->   (request in flight, 0.5 ms in a datacenter)
2                                             compute price           (4 microseconds)
3                   <---- response lost -----  (switch drops the packet)
4    ... waiting ...
5    timeout after 300 ms
6    did pricing run? unknown -- the caller cannot tell "never arrived" from "arrived, answer lost"
7    retry is safe ONLY because quote() is read-only

Real scenario: a checkout calls a tax service and the tax service answers in 8 s because of a garbage-collection pause. Without a deadline the checkout thread waits 8 s and the checkout page times out; with a 300 ms deadline it falls back to a cached rate. A payment call that times out after the bank charged the card is the classic "did it happen?" problem: see API Idempotency.

What provides it / what prevents it: nothing removes the difference; you can only design around it.

ToolWhat it gives you
Go contextA deadline and a cancel signal that travel with the call
gRPC deadlinesA deadline propagated to downstream calls (default in Go and Java)
Laravel Http::timeout()Maximum seconds to wait (default 30 s)
Idempotency keysSafe retry of writes
Circuit breaker, bulkheadStop calling a failing dependency; give each dependency its own limited pool of connections or workers so one slow dependency cannot use them all (Bulkhead & Graceful Degradation)

Fix / how to use it: every example in Go and Laravel shows the same shape: a Quote call that takes a context (or has a timeout), returns typed errors, and sends one coarse message.

The eight fallacies, each with its consequence Must-know ​

In plain words: eight things everyone believes the first time they build something distributed, and all eight are false.

Common misunderstanding: "These are about the internet, not about our private datacenter or our Kubernetes cluster." They hold inside a cluster too: pods restart, DNS caches go stale, a noisy neighbour saturates a NIC, a node loses a switch.

Definition: the Deutsch/Gosling list, in order: the network is reliable; latency is zero; bandwidth is infinite; the network is secure; topology does not change; there is one administrator; transport cost is zero; the network is homogeneous.

Fallacy (what we wrongly assume) to design consequence (what we do instead)1 The network is reliabletimeouts, bounded retries, idempotency2 Latency is zerocoarse calls, latency budget, async where possible3 Bandwidth is infinitesmall payloads, pagination, compression4 The network is secureTLS or mTLS, authn at every hop, validate input5 Topology does not changeservice discovery, no hard-coded addresses6 There is one administratorexplicit contracts, versioning, ownership7 Transport cost is zerobudget for serialization and egress; batch8 The network is homogeneousopen formats, tolerant readers, no language-bound types
#FallacyWhat really happensDesign consequencePage that goes deeper
1The network is reliablePackets drop, connections reset, peers crash mid-requestTimeouts on every call; bounded retries with jitter; idempotent operations; classify errorsTimeouts, Retries & Jitter, Error handling
2Latency is zero0.5 ms in a datacenter, 150 ms across continents, plus queuingCoarse calls; latency budget; parallelise independent calls; cacheLatency Budget & Tail Latency
3Bandwidth is infiniteLinks saturate; big payloads starve small onesPagination, field selection, compression, no blobs in messagesClaim check in message design
4The network is secureAnything on the path can read or alter trafficTLS or mTLS between services, authentication at every hop, validate every inputmTLS & service security
5Topology does not changePods move, IPs change, regions fail overService discovery, DNS with short TTL, no hard-coded addressesService Discovery
6There is one administratorOther teams, other clouds, other release schedulesExplicit contracts, versioning, deprecation policy, ownershipService Boundaries
7Transport cost is zeroEncoding CPU, bytes on the wire, cloud egress feesBudget serialization time and egress; batch; binary format when it mattersSerialization formats
8The network is homogeneousDifferent languages, OSes, endianness, library versionsOpen wire formats (JSON, Protobuf), tolerant readers, no language-bound typesContracts
text
     Fallacy 1 in motion: a retry that makes things worse
1    t=0      service A calls B, B is slow (overloaded)
2    t=300ms  A's timeout fires, A retries (attempt 2)      -> B now has 2 requests from A
3    t=600ms  attempt 2 times out, A retries (attempt 3)    -> B now has 3
4    each of A's 3 layers of callers also retries 3 times   -> 3 x 3 x 3 = 27 requests per user request
5    B falls over; recovery is slower because the retries keep arriving

Real scenario: the retry storm above is the classic cascading failure; the Google SRE book recommends "randomized exponential backoff when scheduling retries" and "a server-wide retry budget", for example only allowing 60 retries per minute in a process. A tax service that goes down for 40 seconds takes the checkout with it because nobody set a timeout: fallacy 1 and fallacy 2 together.

What provides it:

FallacyGoLaravel
1context.WithTimeout, retry loop with jitterHttp::timeout()->retry()
2One slice-taking method, errgroup for fan-outOne endpoint, Http::pool()
3io.LimitReader, http.MaxBytesReadermax: validation rules, pagination
4tls.Config, mTLSHttp::withOptions(['cert' => ...])
5DNS name, resolver, gRPC dns:/// targetA config value per environment; service discovery in the platform
6Versioned paths, reserved proto fieldsVersioned routes, API resources
7Reuse connections (MaxIdleConnsPerHost)Octane keeps the process warm; keep-alive in Guzzle
8JSON or Protobuf, not encoding/gobJSON, not PHP serialize()

Fix / how to use it: keep the eight rows as a design review checklist. For every remote call on the whiteboard ask "which row does this call violate if I do nothing?".

The First Law of Distributed Object Design Must-know ​

In plain words: do not take a program designed for one process and split it into remote pieces without redesigning the interfaces. Fowler's law is "don't distribute your objects".

Common misunderstanding: "It bans distributed systems." Fowler's 2014 article says the law is about distributed objects: the idea that "you could design objects and choose to use these same objects either in-process or remote". Microservice advocates, he writes, "advocated coarse-grained interactions with documents over HTTP or lightweight messaging", so they do not violate it. He still treats distribution as a cost: "my default inclination is to prefer a monolithic design".

Definition: an object interface designed for in-process use (many small calls, shared references, no failure besides exceptions) becomes unusable when the object is put behind a network. The fix is not better middleware; it is a different, coarser interface designed for the remote case.

text
     Fine-grained, designed in-process          Coarse-grained, designed for remote
1    price = catalog.unitPrice(sku)             quote = pricing.quote({lines: [...]})
2    pct   = catalog.discount(qty)              -- one call, one response, one failure mode
3    ... repeated for each of 100 lines ...
4    100 x 2 calls, each a round trip           1 call

Real scenario: Fowler's own example: "if you want 100 product prices and availabilities, you can happily make 100 calls to your product price function and another 100 for the availabilities. But if that function is a remote call, you're usually better off to batch all that into a single call". Java RMI, CORBA and DCOM generated stubs that made catalog.unitPrice(sku) remote with no visible change; the results were systems that were slow and that failed in ways no caller handled.

EraApproachWhat went wrong
Late 1990sDistributed objects with transparent middleware (DCOM, CORBA, Java RMI)Chatty fine-grained calls, no failure model in the interface
2000sSOAP web services, coarse documentsHeavy envelopes, but the right granularity
2010sREST over HTTP, JSON, then gRPC and messagingRight granularity; the new risk is too many services
TodayExplicit remote APIs, async messaging, modular monoliths firstDistribution is chosen deliberately

What provides it: the discipline of designing the remote interface first; see Coarse-grained design.

Fix / how to use it: write the interface for the remote case, then implement it in-process. The reverse (write in-process, then make remote) is the mistake the law warns against.

Coarse-grained interfaces, Remote Facade and DTO Must-know ​

In plain words: instead of asking ten small questions across the network, send one message with everything you need and get one answer with everything you asked for.

Common misunderstanding: "A Remote Facade is a place for business logic." Fowler: "None of the fine-grained objects have a remote interface, and the Remote Facade contains no domain logic. All the Remote Facade does is translate coarse-grained methods onto the underlying fine-grained objects."

Definition: Remote Facade is a coarse-grained facade over a web of fine-grained objects, there to reduce round trips. Data Transfer Object (DTO) is an object that carries data between processes: "The solution is to create a Data Transfer Object that can hold all the data for the call." Fowler adds that DTOs also "encapsulate the serialization mechanism" and give "a clear point to change serialization". Fowler's catalog notes that an assembler usually maps between the DTO and domain objects.

Chatty (left) vs Remote Facade with DTOs (right)Clientloops over linesprice(sku)discount(qty)price(sku)discount(qty)network boundary: 2 x N round tripsClientone DTORemoteFacadeno rulesEnginePricesDiscountsRoundingnetwork boundary: 1 round triprequest DTOresponse DTO
text
     Client                    Remote Facade (pricing service)       Domain objects (in-process)
1    POST /v1/quotes  ------>  decode QuoteRequest DTO
2                              validate (1..100 lines, qty 1..10000)
3                              ------------------------------------>  Engine.Basket(lines)
4                                                                      UnitPrice, Discount, rounding
5                              <------------------------------------  total + per-line
6    <------ 200 QuoteResponse DTO (total_cents, lines[])
     one round trip; the domain objects were never exposed

Real scenario: a mobile app's "order summary" screen needs the order, its lines, the customer name and the shipping status. One GET /orders/42/summary that returns a DTO beats four calls over a 4G link, and it is a place to add caching and authorisation once. A GraphQL query or a gRPC method with a field mask solves the same problem with a different surface.

RuleWhy
One use case per call, shaped by what the caller needsAvoids both chatty calls and "return the whole database"
DTOs have wire names, not domain namesThe domain model can change without breaking the wire
Money is integer minor units, never floatNo rounding drift between languages
DTOs contain data only, no behaviourThey are copied, not shared
Explicit limits (max lines, max size)The server protects itself, and the limit is part of the contract
The facade holds no business rulesOne place for rules, and the facade stays replaceable

What provides it: Go struct with JSON tags; Protobuf message; Laravel readonly class or API Resource. See Go and Laravel.

Fix / how to use it: start from the screen or the use case, list the data it needs, and define one DTO pair for it. Link the DTO to Data Persistence in Design: DTOs are not entities, and sharing entities across a process boundary couples two databases through a class.

Component vs service vs process vs deployment unit Important ​

In plain words: "component", "service", "process" and "deployable" are four different boundaries that people use as if they were one.

Common misunderstanding: "One service equals one process equals one container." Fowler's microservices article: "services map to runtime processes, but that is only a first approximation. A service may consist of multiple processes that will always be developed and deployed together, such as an application process and a database that's only used by that service."

Definition:

BoundaryWhat it isFailure and speed across itTypical example
Class / functionLanguage-level unitSame as local callEngine.UnitPrice
Module / packageA unit of code with a public API and hidden internalsSame as local call; the compiler enforces visibilityGo internal/pricing, Laravel module folder
ComponentA replaceable part with a stated interface (UML component)Depends on where it is wiredPriceQuoter and its implementations
ProcessAn operating system process with its own address spaceSerialization, IPC, independent crashA PHP-FPM worker, a Go binary
DeployableWhat you ship and roll back as oneIndependent releaseA container image
ServiceA component reachable over the network, owned by a teamNetwork failure, version skewpricing service
Host / pod / nodeA machine or scheduling unitMachine failure, shared resourcesA Kubernetes pod
RegionA group of datacentersPartition, 100+ ms RTTeu-west, us-east

Real scenario: a Laravel app and its queue worker are two processes, one deployable, one codebase; that is not a service boundary. Two Go binaries in one repo with a shared database are two deployables, one data owner; changes to the schema still need both released together.

What provides it: modules (compile-time boundaries), processes (runtime boundaries), contracts (the interface), ownership (CODEOWNERS and team). See Modular Monolith and Design Quality Principles for coupling and cohesion at the module level.

Fix / how to use it: draw the four boundaries separately on the design. Distribute at the weakest one that meets your goal: often a module boundary plus a queue, not a new service.

Choosing what to distribute Must-know ​

In plain words: distribute a component only when a concrete need outweighs the cost of the network. Four needs are legitimate: data gravity, team ownership, different scaling needs, and failure isolation.

Common misunderstanding: "Microservices are the modern default, a monolith is a smell." Fowler's Monolith First: "By building a monolith first, you can figure out what the right boundaries are". Most teams get boundaries wrong early and moving behaviour across a process boundary is much harder than across a module.

Definition: a decision rule. Distribute when at least one of the following is true and the cost is accepted.

DriverMeaningDistribute whenDo not distribute when
Data gravityCompute should live where the data is, because moving data costs time and moneyThe component reads a large dataset it alone owns (search index, ML features, analytics)The "dataset" is a few rows another module already has
Team ownershipConway's law: boundaries follow communicationA separate team owns the roadmap, release train and on-callThe same five people change both sides every week
Scaling needsParts of a system need different resourcesOne part needs 50x the CPU, GPU or memory of the rest (image resizing, PDF rendering)The load profile is the same everywhere (use cookie-cutter scaling: more copies of the whole thing)
Failure isolationA bug or overload in one part must not take down anotherA flaky third-party integration, a batch job that eats memoryThe "isolation" is just a different log file
Compliance and residencyData must stay in a region or under certain controlsPCI card handling, EU-resident personal dataConvenience
Technology fitA part needs a different runtimeA Python ML model beside a Go APIPreference only
text
     Decision walk for "should pricing be a separate service?"
1    Does it own a large dataset others should not copy?     no  -> data gravity: no
2    Does a different team own it and release on its own?    yes -> ownership: yes
3    Does it need very different scaling?                    no
4    Would a failure there be contained by the boundary?     partly (checkout would still need a price)
5    Result: one real driver, so try a MODULE with an interface first; split later if ownership pain grows

Real scenario: an image-thumbnailing function needs 8 vCPUs for short bursts while the web app needs 0.5. Scaling the whole app to 8 vCPUs wastes money; a separate worker fed by a queue scales alone. By contrast, "customer" and "address" logic called together on every request, owned by the same team, gains nothing from a network between them.

What provides it: Monolith vs Microservices vs Modular Monolith is the full decision page; Service Boundaries covers Conway's law and the distributed monolith; Microservices Data Ownership covers data gravity from the database side.

Fix / how to use it: write the driver on the ADR (see Architecture Decisions). If you cannot name a driver, the answer is "not yet".

The distribution ladder Must-know ​

In plain words: you do not choose between "monolith" and "microservices". You climb a ladder one rung at a time, and each rung has a price.

Common misunderstanding: "Going from one process to two is a small step." The step from in-process to a separate process on the same host is the most expensive one in design terms, because it introduces serialization, an independent lifecycle and version skew; the later steps add physics but few new concepts.

Definition: four rungs. Look at the picture in Why it exists.

RungExampleTypical round tripNew in this rungWhat you must addTypical trigger
1. In-process moduleGo package, Laravel module~100 nsnothing (the baseline)Interface, testsDefault
2. Separate process, same hostSidecar, local worker, PHP-FPM + queue worker, Unix socket, localhost gRPC~100 us (measured here: 110 to 170 us for localhost HTTP)Serialization, independent crash and restart, version skewDTOs, health checks, restart policy, contractIsolate a crashy or heavy component; different runtime
3. Separate hosts, same datacenterService per host, pod per service~500 us (Dean)Partial failure, loss and reordering, discovery, TLS, load balancingTimeouts, retries, idempotency, circuit breaker, mTLSIndependent scaling, team ownership
4. Separate regionsActive-active or follower in another region~150 ms across continents (Dean)Partitions as the normal case, clock skew, replication lag, data residencyConsistency choice, conflict handling, regional failoverLatency to users, disaster recovery, compliance
text
     What changes at each step for one call: checkout -> pricing.quote(basket)
1    Rung 1   function call, 440 ns, error = return value or panic
2    Rung 2   POST over loopback, 170 us, error = timeout | refused | 5xx | bad JSON
3    Rung 3   POST across hosts, ~0.6 ms, error = above + lost response | reset | slow node
4    Rung 4   POST to another continent, ~150 ms, error = above + partition | stale replica | regional outage
     each rung ADDS to the error list; none removes anything

Real scenario: a PHP monolith offloads PDF generation to a Go worker on the same host over a Unix socket (rung 2): the PHP app keeps its database, the worker has no state, the contract is one JSON message. Later the worker moves to separate hosts (rung 3) with only a base URL and timeout change, because the interface was already coarse and idempotent.

What provides it: the interface discipline in Coarse-grained design and Network as a design input. The same Quoter interface in the Go section has an in-process and an HTTP implementation, so moving between rung 1 and 3 is a wiring change.

Fix / how to use it: move one rung at a time, and ship the safety rails (deadline, retries, metrics) before the move, not after the first outage.

Network as a design input Must-know ​

In plain words: timeouts, retries, idempotency and backpressure are not "error handling added later"; they are parameters of the design, like a database index.

Common misunderstanding: "The HTTP client library takes care of timeouts." Go's http.Client has Timeout zero by default, which "means no timeout"; gRPC "does not set a deadline" by default, so "it is possible for a client to end up waiting for a response effectively forever"; Laravel's HTTP client times out after 30 seconds, which is usually longer than your user's patience.

Definition: four inputs every remote call needs, and where each is taught.

InputQuestion it answersDesign ruleDeeper page
Timeout / deadlineHow long may this call take in total?Set on every call; derive from the latency budget; propagate downstreamTimeouts, Retries & Jitter
RetryIs a second attempt safe and useful?Only for transient errors; bounded; jittered exponential backoff; within the remaining deadline; with a retry budgetCascading Failures, Circuit Breaker
IdempotencyCan the callee see the same request twice?Reads are naturally safe; writes need an idempotency keyAPI Idempotency, Idempotent Consumers
BackpressureWhat happens when the callee is slower than the caller?Bounded queues, concurrency limits, shed load, return 429 or 503 with Retry-AfterBackpressure & Flow Control, Load Shedding
text
     One call with a deadline budget of 800 ms
1    t=0       caller sets deadline = now + 800 ms
2    t=0       attempt 1, per-attempt timeout 300 ms
3    t=300     timeout; remaining 500 ms; jittered backoff 0..25 ms
4    t=320     attempt 2, per-attempt timeout 300 ms
5    t=620     timeout; remaining 180 ms; backoff would leave less than one attempt
6    t=620     stop: return ErrTimeout (do NOT start attempt 3 that cannot finish)

Real scenario: the Go Client in this chapter stops retrying when time.Until(deadline) <= wait; the gRPC retry guide shows the same idea with maxAttempts, initialBackoff, maxBackoff and retryableStatusCodes, and a retry throttling policy that "prevents server overload due to retries".

What provides it:

MechanismGoLaravel
Total deadlinecontext.WithTimeout(ctx, d)A queue job timeout, Http::timeout()
Per-attempt timeoutcontext.WithTimeout per attemptHttp::timeout() (applies per attempt)
Retry with backoffLoop with rand.Int64N jitterHttp::retry($times, $sleepClosure, $whenClosure)
Retry only transient errorsInspect status and error typeThe third retry argument
Idempotency keyIdempotency-Key headerHttp::withHeaders(['Idempotency-Key' => ...])
Concurrency limitBuffered channel as a semaphore, x/sync/semaphoreHttp::pool(..., concurrency: 5), queue worker count

Fix / how to use it: the rule "retry only reads or idempotent writes" is the one that prevents duplicate charges. The quote call here is a read, so it retries; a payment call needs an idempotency key first.

Location transparency and why it fails Important ​

In plain words: location transparency is the promise "you call it the same way whether it is local or remote". The promise is attractive and wrong.

Common misunderstanding: "Good middleware (gRPC, a service mesh, a smart proxy) hides the network from the developer." It hides addressing and plumbing (discovery, TLS, load balancing), which is valuable. It cannot hide latency, partial failure or version skew, because those are properties of the situation, not of the plumbing: Waldo's argument is that "the failure of a network link is indistinguishable from the failure of a processor on the other side of that link".

Definition: transparency of access (same call syntax), location (the caller does not know where the callee is), and failure (the caller does not see network errors). The first two are useful; the last is a myth.

Kind of transparencyUseful?Why
Access transparency (same syntax)MixedHides the cost, so people write chatty loops
Location transparency (address abstracted)YesNeeded for discovery, scaling, failover
Failure transparency (errors hidden)NoThe callee may have acted; the caller must be told "unknown"
Performance transparencyNoA 100x difference cannot be abstracted
Concurrency transparencyPartialIdempotency and versioning must be explicit
text
     A "transparent" remote property access
1    total = basket.getTotal()          -- looks like a getter
2    -> hidden: HTTP GET, 40 ms, may throw 503, may return a stale value
3    for (line in basket.lines) line.getPrice()   -- 100 hidden round trips = 4 s

Real scenario: an ORM's lazy loading inside a loop is a milder cousin (N+1 queries over the network to the database; see ORM Pitfalls); a Java RMI stub that implements the same interface as the local class is the severe case.

What provides it / what to do instead: make the remote nature visible in the type: a distinct interface (Quoter) that takes a context.Context or has a timeout, returns a typed error and accepts a DTO. Hide how it is implemented (in-process, HTTP, gRPC) but not that it may be remote.

Fix / how to use it: the same Quoter interface can have a local and a remote implementation (see Go); this is not transparency, because the interface itself was designed for the remote case.

RPC vs messaging vs REST Must-know ​

In plain words: three ways for components to talk. RPC asks a question and waits. REST addresses resources with HTTP verbs. Messaging drops a note in a mailbox and moves on.

Common misunderstanding: "gRPC is faster, so it is better than REST", or "messaging is more decoupled, so use it everywhere". Format and style are separate decisions: you can run REST over HTTP/2 and RPC over JSON, and asynchronous messaging brings its own costs (ordering, duplicates, eventual consistency, debugging).

Definition: a design-level comparison.

DimensionRPC (gRPC, JSON-RPC, Thrift)REST over HTTP (JSON)Messaging (RabbitMQ, Kafka, SQS)
ModelCall a method on a remote serviceOperate on resources with GET/POST/PUT/DELETEPublish a message; a consumer handles it later
Coupling in timeTight: caller waitsTight: caller waitsLoose: producer does not wait
Coupling to locationService nameURLTopic or queue name
Contract.proto or IDL, generated clientsOpenAPI (optional), conventionsMessage schema (Avro, Protobuf, JSON Schema)
Typical payloadBinary (Protobuf)JSONAny, usually Avro, Protobuf or JSON
StreamingBuilt in (gRPC streams)Server-Sent Events, WebSockets, chunkingThe broker is the stream
Failure modelStatus codes, deadlinesHTTP status, timeoutsAcks, redelivery, dead-letter queues
CachingHardNative (HTTP cache, ETag)Not applicable
Browser-friendlyNeeds gRPC-WebYesNo
Best forInternal, high-volume, strongly typed callsPublic APIs, CRUD, cacheable readsEvents, workflows, absorbing bursts, decoupling
text
     Order placed: three designs
1    RPC:       checkout --Reserve()--> inventory --(waits)--> checkout --Charge()--> payment
2    REST:      checkout --POST /reservations--> inventory (201) ; --POST /payments--> payment (201)
3    Messaging: checkout --OrderPlaced--> broker ; inventory and payment each consume and react
     RPC/REST: simple to reason about, availability = product of availabilities
     Messaging: resilient to downtime, but results arrive later (eventual consistency)

Real scenario: a pricing quote on the checkout critical path is a synchronous call (RPC or REST) because the user waits for the price. Sending the order confirmation email is messaging because nobody waits. An analytics feed of "price viewed" events is messaging with Kafka. Choosing messaging for the first or RPC for the last is the usual mistake.

What provides it: Integration Styles & Channels compares file, shared database, RPC and messaging; REST API Design and gRPC & Protobuf cover the two synchronous styles; Messaging Fundamentals the third; Service Communication the architectural decision.

Fix / how to use it: default rule: synchronous for queries the user is waiting on, asynchronous for commands whose result need not be immediate, events for facts other components may care about.

Contracts, schema evolution and versioning Must-know ​

In plain words: the contract is the promise about what messages look like. Both sides will change; the contract must allow one side to change first.

Common misunderstanding: "We version with /v2 when we change something, so we are safe." Versions in the URL do not help if the old and new versions must both run at the same time for months, or if consumers you do not know about depend on fields you never documented.

Definition: an evolvable contract follows compatibility rules:

ChangeBackward compatible? (new server, old client)Forward compatible? (old server, new client)Safe action
Add an optional fieldYesYes if readers ignore unknown fieldsDo it
Add a required fieldNo (old clients do not send it)YesAvoid; make it optional with a default
Remove a fieldYes only if no client reads itYesDeprecate, wait, then remove; Protobuf: reserved
Rename a fieldNoNoAdd the new name, keep the old one for a window
Change a field's typeNoNoNew field
Change meaning, keep nameSilent bugSilent bugNew name
Reuse a Protobuf field numberCorrupts dataCorrupts dataNever reuse; "Field numbers should never be reused"

Tolerant reader: a reader ignores fields it does not know and uses defaults for missing optional fields. The Go facade above decodes without DisallowUnknownFields, and the Laravel controller reads only the keys it validates.

text
     Rolling a field change across two services (expand and contract)
1    deploy server v2: accepts "currency" (optional), still accepts old requests
2    deploy clients one by one: start sending "currency"
3    observe: no client sends the old shape for 14 days
4    deploy server v3: stop accepting the old shape; reserve the removed Protobuf number

Real scenario: the .proto snippet reserves field 3 (coupon) and its name after the field was removed so that nobody can reuse the number for a different type. The message-side equivalent is in Message Design & Schema Evolution; the HTTP-side policy is in API Versioning.

What provides it: Protobuf's rules for field numbers and reserved; JSON Schema or OpenAPI for JSON; consumer-driven contract tests to find out who depends on what.

Fix / how to use it: make every change additive; when you must break, run the old and new shape in parallel (expand and contract) and measure usage before deleting.

Serialization formats: JSON vs Protobuf and friends Important ​

In plain words: serialization turns an in-memory object into bytes for the wire. The format decides the size, the speed and how easily the contract can evolve.

Common misunderstanding: "Protobuf is always faster so we should use it everywhere." For a few hundred bytes at 100 requests per second the format is not your bottleneck; the round trip is. Binary formats pay off with high volume, large payloads or mobile bandwidth, and cost debuggability.

Definition: the design trade-offs.

FormatSizeEncode/decode costSchemaHuman-readableEvolutionTypical use
JSONLarger (names repeated, numbers as text)ModerateOptional (JSON Schema, OpenAPI)YesEasy to add fields; types are loosePublic REST APIs, browser, Laravel
ProtobufSmall (field numbers, varints)LowRequired (.proto)No (needs tooling)Strong rules: field numbers, reservedgRPC, internal high-volume, Kafka values
AvroSmallLowRequired, schema travels or registryNoReader/writer schema resolutionKafka with Schema Registry
MessagePack, CBORSmaller than JSONLowNoneNoAs loose as JSONCompact JSON-like
XML/SOAPLargeHighXSDYesHeavyLegacy enterprise
PHP serialize(), Go encoding/gobLanguage-specificLowImplicit in the class or typeNoBreaks across versions and languagesNever as a service contract (fallacy 8)

The Protobuf encoding guide explains why it is compact: each field on the wire is "a tag" made of the field number and a wire type, followed by the value. That is also why renumbering a field is a breaking change: the receiver identifies fields by number, not by name.

Real scenario: a service that sends 20 kB JSON bodies at 5,000 requests per second spends measurable CPU in encode/decode and 100 MB/s of bandwidth; switching to Protobuf with compression typically helps, but you should measure with your payloads. For a 300-byte quote at 50 requests per second the choice is irrelevant; pick the one your team debugs faster.

What provides it: Go encoding/json, google.golang.org/protobuf; Laravel json() and response()->json(), and Protobuf via the RoadRunner gRPC plugin or google/protobuf PHP library.

Fix / how to use it: start with JSON for external and low-volume APIs, choose Protobuf when you adopt gRPC or when profiling shows serialization cost; always keep payloads bounded and money in integer minor units.

Latency budgets and tail latency Must-know ​

In plain words: a latency budget is how many milliseconds each step may spend so that the whole request still feels fast. Tail latency is the slow few percent of requests that dominate what users notice.

Common misunderstanding: "Our average latency is 20 ms, we are fine." Dean and Barroso's example: "consider a system where each server typically responds in 10ms but with a 99th-percentile latency of one second... If a user request must collect responses from 100 such servers in parallel, then 63% of user requests will take more than one second". Averages hide the tail, and fan-out multiplies it.

Definition: a latency budget divides a user-facing target (say 300 ms at the 99th percentile) among the steps of a request; tail latency is a high percentile (p95, p99, p99.9) of the latency distribution. For one call with probability p of being slow, N parallel independent calls are all fast with probability (1 - p) to the power N.

Calls in parallelP(at least one is in the slowest 1%)Meaning
11.0%One user in 100 sees the slow case
109.6%One user in 10
2018.2%The chatty basket from the lab, if it were parallel
10063.4%The Dean and Barroso example
text
     A 300 ms budget for "show checkout" (p99 target)
1    gateway + auth                       20 ms
2    cart service call                    40 ms
3    pricing.quote (coarse)               60 ms     <- deadline for this call = 60 ms, not 300
4    tax + shipping in parallel           80 ms     (the slower of the two sets the time)
5    render                               40 ms
6    headroom                             60 ms
     sum of serial parts must fit; each remote call gets a deadline, and retries must fit inside it

Real scenario: the Tail at Scale paper recommends tail-tolerant techniques such as hedged requests: "A simple way to curb latency variability is to issue the same request to multiple replicas and use the results from whichever replica responds first". Use only for idempotent reads, and with a budget (send the second request after the 95th-percentile expected latency), or you double your load. gRPC also supports hedging as "a complementary feature to retries".

What provides it:

ToolWhere
Per-call deadlinecontext.WithTimeout; gRPC deadline propagation (default in Go); Laravel Http::timeout()
Parallel independent callsGo errgroup; Laravel Http::pool()
Percentile metricsPrometheus histograms; see Observability
HedginggRPC hedging policy; manual in Go with two goroutines and a cancel
Budget testsThe budget_test.go in this chapter

Fix / how to use it: write the budget on the design page, give every remote call a deadline smaller than the remaining budget, measure p99 not the mean, and test the call count in CI (see Go and Laravel). The arithmetic is expanded in Latency Budget & Tail Latency.

Chatty interfaces and N+1 across the network Must-know ​

In plain words: a chatty interface makes many small calls where one would do. N+1 is the classic form: one call to get a list, then one more call per item.

Common misunderstanding: "Parallelising the calls fixes it." Concurrency shortens the wall clock but not the load: 40 parallel requests still cost 40 requests on the server, 40 connections or streams, and 40 chances to hit the tail. The fix is fewer calls.

Definition: N+1 across the network: a loop containing a remote call. It exists in every layer: HTTP between services, SQL between app and database, Redis between app and cache.

sql
-- PostgreSQL: chatty, one round trip per line (N+1)
SELECT unit_cents FROM prices WHERE sku = 'A';
SELECT unit_cents FROM prices WHERE sku = 'B';
SELECT unit_cents FROM prices WHERE sku = 'C';

-- coarse: one round trip for the whole basket
SELECT sku, unit_cents FROM prices WHERE sku = ANY ('{A,B,C}');

-- find the chatty queries in production: very high "calls", tiny mean_exec_time
SELECT calls, round(mean_exec_time::numeric, 3) AS mean_ms, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 5;

The same fix exists in each product: PostgreSQL = ANY(array) or a join, MySQL IN (...), MongoDB $in, Redis MGET or pipelining, Elasticsearch _mget, and over HTTP a batch endpoint or a GraphQL query. See ORM Pitfalls for the Eloquent form and Data Persistence in Design for the repository form.

RemedyWhat it doesCost
Batch endpoint (POST /quotes with many lines)One round trip, one failure modeBigger payload; partial success needs a convention
Join or expand parameter (?include=lines)Server assembles the answerServer does more work per call
Field selection or GraphQLCaller says what it needsA query language to secure and cost-limit
Pipelining (Redis, HTTP/2)Multiple requests in flight on one connectionThe server still does N operations
Parallel fan-out (Http::pool, errgroup)Wall-clock win onlyLoad unchanged; tail risk multiplied
Local read model or cacheAvoid the callStaleness

Real scenario: see the lab: 20 lines priced chatty over localhost cost about 5 ms for 40 calls; through the Remote Facade about 0.2 ms for one call. With 50 ms of added latency the same code takes 2.08 s vs 52 ms. The chatty version is not "a bit slower", it is unusable.

What provides it: the coarse Quoter interface; a call-count test (Http::assertSentCount(1) in Laravel, Hits() == 1 in Go).

Fix / how to use it: count remote calls per user request; put the number in a test. Treat a loop around a remote call as a defect.

Caching as a distribution tool Important ​

In plain words: the fastest remote call is the one you do not make. A cache keeps a copy of a remote answer close to the caller.

Common misunderstanding: "Caching only improves speed." It also changes consistency (the copy can be stale) and availability (a cache can serve when the source is down). Every cache is a small replica with a replication delay equal to its TTL.

Definition: a cache stores a remote result keyed by request, with a time to live (TTL) or an invalidation rule. Common forms: in-process memory, a shared cache (Redis, Memcached), HTTP caching (Cache-Control, ETag), a CDN.

Cache locationLatencyStalenessFailure behaviour
In-process (Go sync.Map, Laravel Cache::store('array'))nsPer process, differs between instancesLost on restart
Shared (Redis, Memcached)~0.5 msOne copy, TTL-boundA new dependency; stampede on expiry
HTTP cache / CDNNear the usermax-age, stale-while-revalidateServes stale when origin is down (stale-if-error)
Read model (own table)DB latencyEvent-driven, eventually consistentNeeds events and rebuild
text
     Cache-aside for a price lookup, TTL 60 s
1    checkout asks the local cache for "price:A"           -> miss
2    checkout calls pricing.quote()                        -> 4999 cents
3    store "price:A" = 4999 for 60 s
4    next 59 s: hit, no remote call
5    pricing changes the price at second 10
6    checkout still shows the old price until second 60    -> staleness window = TTL

Real scenario: a price shown on a product page can be 60 s stale; the price used to charge the card must be re-validated at order time (cache the display, never the charge). When a cache entry expires under load, many callers miss at once and all call the origin (a cache stampede); a single-flight pattern or a short randomised TTL prevents it. See Caching.

What provides it: Go golang.org/x/sync/singleflight, Laravel Cache::remember() and Cache::flexible() (stale-while-revalidate), HTTP caching headers.

Fix / how to use it: decide per datum how stale it may be, write it next to the field, and never cache a value that a later write depends on being exact.

Consistency implications Important ​

In plain words: once data lives in two places, the two copies disagree for a while. Distribution turns "the truth" into "the truth, eventually".

Common misunderstanding: "A transaction across two services is just a bigger transaction." There is no shared lock manager and no shared commit; a call that times out leaves the outcome unknown. Atomicity across services needs a protocol (two-phase commit with all its costs) or a design that avoids it (sagas, outbox).

Definition: the consistency choices distribution forces, with pointers rather than re-teaching.

SituationWhat can go wrongDesign responseWhere it is taught
Two services update their own databases for one business actionOne succeeds, the other failsSaga with compensations, or transactional outboxDesigning for Failure & Reliable Messaging
Read replica behind the primaryRead-your-writes violationRead from primary after a write, session stickinessEventual Consistency in Database Systems
Cache in front of a serviceStale readsTTL, event invalidationCaching
Multi-region replicasConflicts, lagChoose CP or AP per datum, conflict resolutionCAP & PACELC, Consistency Models
Duplicate deliveryEffect applied twiceIdempotent consumer, inboxIdempotent Consumers & the Inbox Pattern

Real scenario: "reserve stock then charge the card" across inventory and payment: if the charge call times out you do not know whether the card was charged. The saga either retries the charge with the same idempotency key (safe) or compensates by releasing the stock after a bounded wait. That is a design output of the distribution decision, not an implementation detail.

What provides it: the database section for replica and isolation semantics (Isolation Levels, Distributed SQL, Consensus & 2PC), and the messaging section for delivery guarantees (Delivery Guarantees).

Fix / how to use it: keep the data that must change together in one service (one transaction), accept eventual consistency for the rest, and write the staleness window and the failure rule next to every cross-service write.

Observability across components Important ​

In plain words: when one user request touches five services, you need a thread that ties all their log lines together. That thread is the correlation id.

Common misunderstanding: "Each service logs its errors, so we can find the problem." Without a shared id you cannot tell which log line in service C belongs to the failing request in service A, and each service has its own clock.

Definition: three signals, tied by identifiers: logs (events), metrics (aggregates, including latency histograms) and traces (a tree of spans per request). The W3C Trace Context standard defines the traceparent header, which "describes the position of the incoming request in its trace graph in a portable, fixed-length format". A simpler X-Request-ID header is a correlation id; Laravel's Context feature lets you "trace execution flows throughout a distributed system" by adding data once and including it in logs and queued jobs.

text
     One request, one id, five log lines
1    gateway   X-Request-ID: 7f3a...   received GET /checkout
2    checkout  X-Request-ID: 7f3a...   calling pricing.quote (lines=20) deadline=300ms
3    pricing   X-Request-ID: 7f3a...   quote ok in 4ms
4    checkout  X-Request-ID: 7f3a...   tax.rate timeout after 300ms, using cached rate
5    gateway   X-Request-ID: 7f3a...   200 in 412ms
     grep 7f3a across all services reconstructs the story
PracticeGoLaravel
Accept or create the id at the edgeCorrelate middleware in this chapterCorrelationId middleware with Context::add()
Forward it on every outgoing callHeader from contextwithHeaders(['X-Request-ID' => Context::get('request_id')])
Put it in every log lineslog with request_id attributeContext is added to log records automatically
Standard tracingOpenTelemetry, traceparentOpenTelemetry PHP, traceparent
Latency metrics per dependencyHistogram around the client callSame, in an HTTP client macro or middleware

Real scenario: a latency regression after a deploy: the per-dependency histogram shows pricing.quote p99 went from 20 ms to 400 ms while the mean did not move; the trace shows a new N+1 inside pricing. Without the id and the histogram you would blame the database.

What provides it: Observability: Logs, Metrics & Traces is the full page; here the point is that propagating the id is part of the interface design.

Fix / how to use it: add the middleware on both sides before the first remote call exists.

Testability: contract tests and consumer-driven contracts Important ​

In plain words: you cannot run the whole company in a test. Instead each side proves it keeps its end of a written agreement.

Common misunderstanding: "End-to-end tests prove the services work together, so we need nothing else." End-to-end tests are slow, flaky and cannot cover every version combination; they tell you something broke but not which side broke the contract.

Definition:

TestWhat it checksSpeedCatches
Unit testOne module in isolationmsLogic bugs
Contract test (provider)The provider honours the documented shape and status codesms to sProvider breaking the contract
Consumer-driven contract testThe provider still satisfies what each actual consumer usessBreaking a field somebody depends on
Latency-budget testCall count and time against injected latencysChatty regressions, missing timeouts
Resilience testBehaviour under injected failure (Toxiproxy, chaos)s to minMissing retries, bad fallbacks
End-to-end testThe system as a wholeminWiring and environment errors

Pact describes the consumer-driven form: "a code-first consumer-driven contract testing tool"; the contract is generated while the consumer's tests run, and "only parts of the communication that are actually used by the consumer(s) get tested. This in turn means that any provider behaviour not used by current consumers is free to change without breaking tests."

text
     Consumer-driven contract (checkout consumes pricing)
1    checkout's test: "POST /v1/quotes {lines:[{sku:A,qty:1}]} -> 200 with total_cents (integer)"
2    that expectation is recorded as a contract file
3    pricing's CI replays the contract against the real pricing handler
4    pricing wants to rename total_cents -> total: replay fails, build is red BEFORE the release
5    pricing adds "tax_cents": replay passes, nobody is broken

Real scenario: the tests in this chapter's snippets are budget tests: the Go test uses an httptest server with an injected delay and asserts that 20 chatty requests become 1; the Laravel test uses Http::fake() and Http::assertSentCount(1). Resilience tests inject latency and failure with a proxy such as Toxiproxy (its latency toxic: toxiproxy-cli toxic add -t latency -a latency=1000 redis) or with tc qdisc ... netem delay 100ms on Linux.

What provides it: Go testing + httptest; Laravel Http::fake(), Http::sequence(), Http::preventStrayRequests(); Pact libraries for both languages (check each library's current docs before adopting).

Fix / how to use it: every remote call gets one test for the call count, one for the timeout and one contract test shared with the other side.

Mechanics ​

Go: net/http, context and gRPC Must-know ​

In plain words: Go gives you the knobs, but most are off by default.

Common misunderstanding: "http.Client.Timeout covers everything." It "includes connection time, any redirects, and reading the response body", but it is per client, and a zero value "means no timeout". Per-call deadlines belong in context.

KnobWhereDefaultAdvice
http.Client.TimeoutClientnoneA safety net; prefer a context per call
context.WithTimeoutPer requestnoneThe primary tool; http.NewRequestWithContext
http.Transport.MaxIdleConnsPerHostTransport2Raise for service-to-service traffic so connections are reused
http.Transport.IdleConnTimeoutTransport90 s in DefaultTransportKeep below the load balancer's idle timeout
Transport.TLSHandshakeTimeout; dial timeout via net.Dialer.TimeoutTransport10 s and 30 s in DefaultTransport (none in a bare Transport)Lower the dial timeout to fail fast on dead hosts
http.Server.ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeoutServernoneAlways set; protects from slow clients (slowloris)
http.MaxBytesReaderHandlernoneCap request bodies
gRPC deadlinecontext.WithTimeout on the callnone"should always explicitly set a realistic deadline"
gRPC retryPolicyService confignonemaxAttempts, initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodes
gRPC deadline propagationAutomatic in GoonPass the incoming ctx to outgoing calls

Cloudflare's guide to Go timeouts walks through the same phases (dial through net.Dialer, TLSHandshakeTimeout, ResponseHeaderTimeout, the body) and shows how to set each. The DefaultTransport values above were read with go doc net/http.DefaultTransport on Go 1.27; they can differ between Go versions.

Laravel: HTTP client, Octane and gRPC Important ​

FeatureCallNotes
Total timeoutHttp::timeout(2)Seconds; default 30
Connect timeoutHttp::connectTimeout(1)Seconds to establish the connection
RetryHttp::retry(3, 100)3 attempts, 100 ms apart; second argument can be a closure fn (int $attempt, Exception $e) => ...
Retry only some failuresthird argument closuree.g. $e instanceof ConnectionException
Do not throw after retriesretry(3, 100, throw: false)A ConnectionException is still thrown for connection failures
Concurrent requestsHttp::pool(fn (Pool $pool) => [...], concurrency: 5)A failed entry is a ConnectionException instance
Fake in testsHttp::fake(), Http::sequence()->pushStatus(503)
Forbid real calls in testsHttp::preventStrayRequests()
Count callsHttp::assertSentCount($n)
Share data with logs and jobsContext::add('request_id', $id)Included in log records and queued jobs

Octane "boots your application once, keeps it in memory", which means the HTTP client's connections and your singletons live across requests: good for latency, dangerous for static state (see Designing for Concurrency). gRPC with Laravel is not built in: the RoadRunner gRPC plugin "enables PHP applications to communicate with gRPC clients"; it consists of a protoc plugin that generates PHP classes from the .proto file and a gRPC server that proxies requests to PHP workers. We have not run it for this page and show no PHP gRPC code; the design points (deadlines, coarse messages, reserved fields) are identical.

Error vocabulary at the boundary Important ​

FailureHTTPgRPC statusRetry?Meaning for the caller
Request rejected (validation)400 / 422INVALID_ARGUMENTNoThe request is wrong; fix it
Not found / unknown sku404 / 422NOT_FOUNDNoBusiness answer
Unauthenticated / forbidden401 / 403UNAUTHENTICATED / PERMISSION_DENIEDNoCredentials
Rate limited429RESOURCE_EXHAUSTEDYes, after Retry-AfterBack off
Server error500INTERNALMaybeOften a bug; retry once at most
Bad gateway / unavailable / gateway timeout502 / 503 / 504UNAVAILABLEYes, boundedTransient
Client deadline hitnone (client side)DEADLINE_EXCEEDEDOnly if idempotentOutcome unknown
Connection refused / resetnoneUNAVAILABLEYes, boundedCallee not reachable

Go ​

The Go module academy/distribution-of-components has six packages. pricing is the in-process module; before is the location-transparent chatty version; after is the remote-ready design; latency injects delay; grpcclient shows the gRPC knobs without generated stubs; lab and budget measure and test. Every snippet passes gofmt and go vet, and go test passes.

Before: the same interface, in-process and remote ​

Fine-grained methods without a context, the remote version hidden behind the same interface, http.Get with no deadline, a swallowed error in DiscountPercent, and an N+1 loop.

go
// Package before shows "location transparency": the same fine-grained interface
// is implemented in-process and over HTTP, so callers cannot tell the difference.
// That is exactly the problem. It compiles and works, and it is slow and fragile.
package before

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"academy/distribution-of-components/pricing"
)

// PriceList is shaped for in-process use: tiny methods, no context, no timeout, no batch.
type PriceList interface {
	UnitPrice(sku string) (int64, error)
	DiscountPercent(qty int) int64
}

// Local satisfies PriceList in-process. One call costs nanoseconds.
type Local struct{ *pricing.Engine }

// Remote satisfies PriceList over HTTP. Same interface, one network round trip per call.
type Remote struct {
	BaseURL string
}

// UnitPrice hides an HTTP GET behind a method that looks free.
// Problems: no context, no deadline (http.DefaultClient has none), errors are not classified.
func (r Remote) UnitPrice(sku string) (int64, error) {
	resp, err := http.Get(r.BaseURL + "/price/" + sku)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("status %d", resp.StatusCode)
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
	var out struct {
		Cents int64 `json:"cents"`
	}
	if err := json.Unmarshal(body, &out); err != nil {
		return 0, err
	}
	return out.Cents, nil
}

// DiscountPercent is a second remote call per line. Nothing in the signature warns the caller.
func (r Remote) DiscountPercent(qty int) int64 {
	resp, err := http.Get(fmt.Sprintf("%s/discount/%d", r.BaseURL, qty))
	if err != nil {
		return 0 // swallowed: a failed call silently means "no discount"
	}
	defer resp.Body.Close()
	var out struct {
		Percent int64 `json:"percent"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return 0
	}
	return out.Percent
}

// BasketTotal is the N+1 across the network: 2 remote calls per line, one after another.
func BasketTotal(pl PriceList, lines []pricing.Line) (int64, error) {
	var total int64
	for _, l := range lines {
		unit, err := pl.UnitPrice(l.SKU)
		if err != nil {
			return 0, err
		}
		gross := unit * int64(l.Qty)
		total += gross - gross*pl.DiscountPercent(l.Qty)/100
	}
	return total, nil
}

// Handler serves the fine-grained endpoints used by Remote.
func Handler(e *pricing.Engine) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /price/{sku}", func(w http.ResponseWriter, r *http.Request) {
		p, err := e.UnitPrice(r.PathValue("sku"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		}
		_ = json.NewEncoder(w).Encode(map[string]int64{"cents": p})
	})
	mux.HandleFunc("GET /discount/{qty}", func(w http.ResponseWriter, r *http.Request) {
		var q int
		if _, err := fmt.Sscanf(r.PathValue("qty"), "%d", &q); err != nil {
			http.Error(w, "bad qty", http.StatusBadRequest)
			return
		}
		_ = json.NewEncoder(w).Encode(map[string]int64{"percent": e.DiscountPercent(q)})
	})
	return mux
}

After: the in-process module ​

go
// Package pricing is the in-process pricing module: pure rules, no I/O, no network.
// Everything else on this page is about what changes when this code moves behind a wire.
package pricing

import (
	"errors"
	"fmt"
)

// ErrUnknownSKU is a business error: the caller asked about something that does not exist.
var ErrUnknownSKU = errors.New("pricing: unknown sku")

// Line is one basket line.
type Line struct {
	SKU string
	Qty int
}

// Engine holds the price list. It is safe for concurrent use because it is read-only after New.
type Engine struct {
	unitCents map[string]int64
}

// New builds an engine from a sku -> unit price in cents table.
func New(unitCents map[string]int64) *Engine {
	cp := make(map[string]int64, len(unitCents))
	for k, v := range unitCents {
		cp[k] = v
	}
	return &Engine{unitCents: cp}
}

// UnitPrice returns the list price of one item in cents.
func (e *Engine) UnitPrice(sku string) (int64, error) {
	p, ok := e.unitCents[sku]
	if !ok {
		return 0, fmt.Errorf("%w: %q", ErrUnknownSKU, sku)
	}
	return p, nil
}

// DiscountPercent is a volume discount: 10% from 10 items, 5% from 5 items.
func (e *Engine) DiscountPercent(qty int) int64 {
	switch {
	case qty >= 10:
		return 10
	case qty >= 5:
		return 5
	default:
		return 0
	}
}

// LineTotal is the price of one line after the volume discount.
func (e *Engine) LineTotal(l Line) (int64, error) {
	unit, err := e.UnitPrice(l.SKU)
	if err != nil {
		return 0, err
	}
	gross := unit * int64(l.Qty)
	return gross - gross*e.DiscountPercent(l.Qty)/100, nil
}

// Basket prices a whole basket in one call. This is the coarse-grained operation.
func (e *Engine) Basket(lines []Line) (total int64, perLine []int64, err error) {
	perLine = make([]int64, 0, len(lines))
	for _, l := range lines {
		t, err := e.LineTotal(l)
		if err != nil {
			return 0, nil, err
		}
		perLine = append(perLine, t)
		total += t
	}
	return total, perLine, nil
}

After: DTOs, the Quoter interface and the in-process adapter ​

go
// Package after is the remote-ready design: a coarse-grained Quoter interface, explicit DTOs,
// a Remote Facade on the server, and a client that treats the network as an input
// (deadline, bounded retries, classified errors, correlation id).
package after

import (
	"context"
	"errors"
	"fmt"

	"academy/distribution-of-components/pricing"
)

// QuoteLine is one requested line. DTO fields are wire names, not domain names.
type QuoteLine struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

// QuoteRequest is the whole basket in one message (Data Transfer Object).
// Adding an optional field later is backward compatible; renaming or removing one is not.
type QuoteRequest struct {
	Lines    []QuoteLine `json:"lines"`
	Currency string      `json:"currency,omitempty"`
}

// QuotedLine is the price of one requested line.
type QuotedLine struct {
	SKU        string `json:"sku"`
	TotalCents int64  `json:"total_cents"`
}

// QuoteResponse carries everything the caller needs, so no second call is required.
type QuoteResponse struct {
	Currency   string       `json:"currency"`
	TotalCents int64        `json:"total_cents"` // money as integer cents, never float
	Lines      []QuotedLine `json:"lines"`
}

// Limits protect the server from absurd requests; they are part of the contract.
const (
	MaxLines = 100
	MaxQty   = 10_000
)

// ErrInvalid marks a request the server will never accept; retrying cannot help.
var ErrInvalid = errors.New("after: invalid quote request")

// Validate checks the contract rules once, on both sides of the wire.
func (r QuoteRequest) Validate() error {
	if n := len(r.Lines); n == 0 || n > MaxLines {
		return fmt.Errorf("%w: lines must be 1..%d, got %d", ErrInvalid, MaxLines, n)
	}
	for i, l := range r.Lines {
		if l.SKU == "" || l.Qty < 1 || l.Qty > MaxQty {
			return fmt.Errorf("%w: line %d has sku %q qty %d", ErrInvalid, i, l.SKU, l.Qty)
		}
	}
	return nil
}

// Quoter is the interface callers depend on. It is shaped by the remote case:
// one coarse call, a context for deadline and cancellation, and an error that can be classified.
// The in-process implementation obeys the same shape, so swapping is a wiring change.
type Quoter interface {
	Quote(ctx context.Context, req QuoteRequest) (QuoteResponse, error)
}

// Local is the in-process implementation of Quoter.
type Local struct{ Engine *pricing.Engine }

// Quote prices the basket in memory. It still honours ctx, because the interface promises it.
func (l Local) Quote(ctx context.Context, req QuoteRequest) (QuoteResponse, error) {
	if err := ctx.Err(); err != nil {
		return QuoteResponse{}, err
	}
	if err := req.Validate(); err != nil {
		return QuoteResponse{}, err
	}
	lines := make([]pricing.Line, len(req.Lines))
	for i, ql := range req.Lines {
		lines[i] = pricing.Line{SKU: ql.SKU, Qty: ql.Qty}
	}
	total, per, err := l.Engine.Basket(lines)
	if err != nil {
		return QuoteResponse{}, err
	}
	out := QuoteResponse{Currency: currencyOrDefault(req.Currency), TotalCents: total}
	for i, ql := range req.Lines {
		out.Lines = append(out.Lines, QuotedLine{SKU: ql.SKU, TotalCents: per[i]})
	}
	return out, nil
}

func currencyOrDefault(c string) string {
	if c == "" {
		return "EUR"
	}
	return c
}

After: the Remote Facade and correlation middleware ​

go
package after

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"

	"academy/distribution-of-components/pricing"
)

type ctxKey struct{}

// RequestID returns the correlation id stored by Correlate, or "" when there is none.
func RequestID(ctx context.Context) string {
	id, _ := ctx.Value(ctxKey{}).(string)
	return id
}

// WithRequestID stores a correlation id in ctx so outgoing calls can forward it.
func WithRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

// Correlate is middleware: reuse the caller's X-Request-ID or mint one, expose it to
// handlers through the context and echo it back so the caller can log it too.
func Correlate(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get("X-Request-ID")
		if id == "" {
			var b [8]byte
			_, _ = rand.Read(b[:])
			id = hex.EncodeToString(b[:])
		}
		w.Header().Set("X-Request-ID", id)
		next.ServeHTTP(w, r.WithContext(WithRequestID(r.Context(), id)))
	})
}

// errorBody is the wire shape of every failure: a stable machine code plus a human message.
type errorBody struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

// Facade is the Remote Facade: a coarse-grained HTTP surface over fine-grained domain objects.
// It holds no business rules; it translates a DTO into domain calls and back.
type Facade struct{ Quoter Quoter }

// Handler returns the routes of the pricing service, wrapped with correlation.
func (f Facade) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /v1/quotes", f.quote)
	return Correlate(mux)
}

func (f Facade) quote(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB cap
	var req QuoteRequest
	// Unknown fields are ignored on purpose (tolerant reader): newer clients may send more.
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeErr(w, http.StatusBadRequest, "bad_json", err.Error())
		return
	}
	resp, err := f.Quoter.Quote(r.Context(), req)
	switch {
	case err == nil:
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(resp)
	case errors.Is(err, ErrInvalid):
		writeErr(w, http.StatusBadRequest, "invalid_request", err.Error())
	case errors.Is(err, pricing.ErrUnknownSKU):
		writeErr(w, http.StatusUnprocessableEntity, "unknown_sku", err.Error())
	case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
		writeErr(w, http.StatusServiceUnavailable, "deadline", "request deadline reached")
	default:
		slog.Error("quote failed", "request_id", RequestID(r.Context()), "err", err)
		writeErr(w, http.StatusInternalServerError, "internal", "internal error")
	}
}

func writeErr(w http.ResponseWriter, status int, code, msg string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(errorBody{Code: code, Message: msg})
}

After: the client with deadline, bounded retries and classified errors ​

go
package after

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math/rand/v2"
	"net"
	"net/http"
	"time"

	"academy/distribution-of-components/pricing"
)

// Errors a caller can branch on. The network adds failure modes the in-process version never had.
var (
	ErrTimeout     = errors.New("after: pricing call timed out")
	ErrUnavailable = errors.New("after: pricing service unavailable")
)

// Config makes every network knob explicit. Zero values are filled with safe defaults.
type Config struct {
	BaseURL        string
	AttemptTimeout time.Duration // per attempt; the caller's ctx deadline bounds the total
	MaxAttempts    int           // including the first try
	BaseBackoff    time.Duration
	MaxBackoff     time.Duration
	HTTPClient     *http.Client
}

// Client is the remote implementation of Quoter.
type Client struct {
	cfg Config
	hc  *http.Client
}

// NewClient applies defaults. The http.Client has no Timeout of its own: deadlines come from ctx.
func NewClient(cfg Config) *Client {
	if cfg.AttemptTimeout == 0 {
		cfg.AttemptTimeout = 300 * time.Millisecond
	}
	if cfg.MaxAttempts == 0 {
		cfg.MaxAttempts = 3
	}
	if cfg.BaseBackoff == 0 {
		cfg.BaseBackoff = 25 * time.Millisecond
	}
	if cfg.MaxBackoff == 0 {
		cfg.MaxBackoff = 400 * time.Millisecond
	}
	hc := cfg.HTTPClient
	if hc == nil {
		hc = &http.Client{Transport: &http.Transport{
			MaxIdleConnsPerHost: 32, // reuse connections: a new TCP+TLS handshake costs round trips
			IdleConnTimeout:     90 * time.Second,
		}}
	}
	return &Client{cfg: cfg, hc: hc}
}

// Quote calls POST /v1/quotes. Retrying is safe here only because the operation is a read:
// it changes nothing on the server. A write would need an Idempotency-Key (see the links on the page).
func (c *Client) Quote(ctx context.Context, req QuoteRequest) (QuoteResponse, error) {
	if err := req.Validate(); err != nil { // fail fast, locally, for free
		return QuoteResponse{}, err
	}
	body, err := json.Marshal(req)
	if err != nil {
		return QuoteResponse{}, err
	}
	var lastErr error
	for attempt := 1; attempt <= c.cfg.MaxAttempts; attempt++ {
		resp, retryable, err := c.once(ctx, body)
		if err == nil {
			return resp, nil
		}
		lastErr = err
		if !retryable || attempt == c.cfg.MaxAttempts {
			break
		}
		wait := c.backoff(attempt)
		if dl, ok := ctx.Deadline(); ok && time.Until(dl) <= wait {
			break // not enough budget left to wait and try again
		}
		t := time.NewTimer(wait)
		select {
		case <-t.C:
		case <-ctx.Done():
			t.Stop()
			return QuoteResponse{}, classify(ctx.Err())
		}
	}
	return QuoteResponse{}, lastErr
}

// backoff is "full jitter": a random wait between 0 and an exponentially growing cap.
func (c *Client) backoff(attempt int) time.Duration {
	limit := c.cfg.BaseBackoff << (attempt - 1)
	if limit > c.cfg.MaxBackoff {
		limit = c.cfg.MaxBackoff
	}
	return time.Duration(rand.Int64N(int64(limit) + 1))
}

func (c *Client) once(ctx context.Context, body []byte) (QuoteResponse, bool, error) {
	actx, cancel := context.WithTimeout(ctx, c.cfg.AttemptTimeout)
	defer cancel()
	hreq, err := http.NewRequestWithContext(actx, http.MethodPost, c.cfg.BaseURL+"/v1/quotes", bytes.NewReader(body))
	if err != nil {
		return QuoteResponse{}, false, err
	}
	hreq.Header.Set("Content-Type", "application/json")
	if id := RequestID(ctx); id != "" {
		hreq.Header.Set("X-Request-ID", id) // correlation id travels with every hop
	}
	hresp, err := c.hc.Do(hreq)
	if err != nil {
		return QuoteResponse{}, true, classify(err)
	}
	defer hresp.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(hresp.Body, 1<<20))
	if err != nil {
		return QuoteResponse{}, true, classify(err)
	}
	switch {
	case hresp.StatusCode == http.StatusOK:
		var out QuoteResponse
		if err := json.Unmarshal(raw, &out); err != nil {
			return QuoteResponse{}, false, fmt.Errorf("after: bad response body: %w", err)
		}
		return out, false, nil
	case hresp.StatusCode == http.StatusTooManyRequests, hresp.StatusCode >= 502 && hresp.StatusCode <= 504:
		return QuoteResponse{}, true, fmt.Errorf("%w: status %d", ErrUnavailable, hresp.StatusCode)
	default:
		var eb errorBody
		_ = json.Unmarshal(raw, &eb)
		switch eb.Code {
		case "unknown_sku":
			return QuoteResponse{}, false, fmt.Errorf("%w: %s", pricing.ErrUnknownSKU, eb.Message)
		case "invalid_request":
			return QuoteResponse{}, false, fmt.Errorf("%w: %s", ErrInvalid, eb.Message)
		}
		return QuoteResponse{}, false, fmt.Errorf("after: status %d: %s", hresp.StatusCode, eb.Message)
	}
}

// classify maps transport errors onto the two errors a caller cares about.
func classify(err error) error {
	var ne net.Error
	switch {
	case errors.Is(err, context.DeadlineExceeded), errors.As(err, &ne) && ne.Timeout():
		return fmt.Errorf("%w: %v", ErrTimeout, err)
	case errors.Is(err, context.Canceled):
		return err
	default:
		return fmt.Errorf("%w: %v", ErrUnavailable, err)
	}
}

gRPC: deadlines and retries without generated code ​

The service contract, as a .proto:

proto
// The same contract as the HTTP/JSON facade, written for gRPC.
// Rules that make it evolvable: never reuse a field number, reserve removed ones,
// add new fields as optional, and keep the request coarse (the whole basket in one message).
syntax = "proto3";

package pricing.v1;

option go_package = "academy/distribution-of-components/gen/pricing/v1;pricingv1";

service Pricing {
  // Read-only, therefore safe to retry on UNAVAILABLE.
  rpc Quote(QuoteRequest) returns (QuoteResponse);
}

message QuoteLine {
  string sku = 1;
  int32 qty = 2;
}

message QuoteRequest {
  repeated QuoteLine lines = 1;
  string currency = 2;
  // Field 3 was "coupon" in v1.0 and was removed; its number must never be reused.
  reserved 3;
  reserved "coupon";
}

message QuotedLine {
  string sku = 1;
  int64 total_cents = 2;
}

message QuoteResponse {
  string currency = 1;
  int64 total_cents = 2;
  repeated QuotedLine lines = 3;
}

and the client-side knobs using only the public grpc-go API:

go
// Package grpcclient shows the gRPC side of the same design decisions using only the public
// grpc-go API (no generated stubs): a default deadline, bounded retries with jitter, and
// the retry policy expressed as service config. The service itself is described in proto/pricing.proto.
package grpcclient

import (
	"context"
	"math/rand/v2"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
)

// ServiceConfig is the declarative retry policy from the gRPC retry guide: up to 3 attempts,
// exponential backoff, only on UNAVAILABLE. gRPC applies it inside the channel.
const ServiceConfig = `{
  "methodConfig": [{
    "name": [{"service": "pricing.v1.Pricing"}],
    "timeout": "0.300s",
    "retryPolicy": {
      "maxAttempts": 3,
      "initialBackoff": "0.025s",
      "maxBackoff": "0.400s",
      "backoffMultiplier": 2,
      "retryableStatusCodes": ["UNAVAILABLE"]
    }
  }]
}`

// Dial creates a client connection with the service config above. Local development uses
// insecure credentials; production uses TLS or mTLS.
func Dial(target string) (*grpc.ClientConn, error) {
	return grpc.NewClient(target,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(ServiceConfig),
		grpc.WithChainUnaryInterceptor(DefaultDeadline(300*time.Millisecond)),
	)
}

// DefaultDeadline gives every call a deadline when the caller did not set one:
// gRPC has no default deadline, so a missing one means "wait forever".
func DefaultDeadline(d time.Duration) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		if _, ok := ctx.Deadline(); !ok {
			var cancel context.CancelFunc
			ctx, cancel = context.WithTimeout(ctx, d)
			defer cancel()
		}
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}

// Retry is a hand-written alternative to the declarative policy, for when you need custom rules.
// It retries only UNAVAILABLE, only while the deadline leaves room, with full-jitter backoff.
func Retry(maxAttempts int, base time.Duration) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		var err error
		for attempt := 1; attempt <= maxAttempts; attempt++ {
			err = invoker(ctx, method, req, reply, cc, opts...)
			if status.Code(err) != codes.Unavailable || attempt == maxAttempts {
				return err
			}
			wait := time.Duration(rand.Int64N(int64(base<<(attempt-1)) + 1))
			if dl, ok := ctx.Deadline(); ok && time.Until(dl) <= wait {
				return err
			}
			select {
			case <-time.After(wait):
			case <-ctx.Done():
				return status.FromContextError(ctx.Err()).Err()
			}
		}
		return err
	}
}

The latency-budget test ​

go
// Package budget_test is the latency-budget test: it does not assert "fast", it asserts the
// call count and a wide time budget, so it is deterministic on a loaded CI machine.
package budget_test

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
	"time"

	"academy/distribution-of-components/after"
	"academy/distribution-of-components/before"
	"academy/distribution-of-components/latency"
	"academy/distribution-of-components/pricing"
)

const injected = 50 * time.Millisecond // simulated network latency per request

func engine() *pricing.Engine {
	return pricing.New(map[string]int64{"A": 1000, "B": 250, "C": 4999})
}

func basket(n int) []pricing.Line {
	lines := make([]pricing.Line, n)
	for i := range lines {
		lines[i] = pricing.Line{SKU: []string{"A", "B", "C"}[i%3], Qty: 1 + i%12}
	}
	return lines
}

// The chatty design pays the latency 2 x N times; the facade pays it once.
func TestChattyVersusBatched(t *testing.T) {
	const n = 10
	lines := basket(n)

	chattySrv := latency.Wrap(before.Handler(engine()), injected)
	ts1 := httptest.NewServer(chattySrv)
	defer ts1.Close()
	start := time.Now()
	chattyTotal, err := before.BasketTotal(before.Remote{BaseURL: ts1.URL}, lines)
	chattyTook := time.Since(start)
	if err != nil {
		t.Fatal(err)
	}

	facade := latency.Wrap(after.Facade{Quoter: after.Local{Engine: engine()}}.Handler(), injected)
	ts2 := httptest.NewServer(facade)
	defer ts2.Close()
	client := after.NewClient(after.Config{BaseURL: ts2.URL})
	req := after.QuoteRequest{}
	for _, l := range lines {
		req.Lines = append(req.Lines, after.QuoteLine{SKU: l.SKU, Qty: l.Qty})
	}
	start = time.Now()
	resp, err := client.Quote(context.Background(), req)
	batchedTook := time.Since(start)
	if err != nil {
		t.Fatal(err)
	}

	// Call-count budget: exactly 2 requests per line versus exactly 1 in total.
	if got := chattySrv.Hits(); got != 2*n {
		t.Fatalf("chatty requests = %d, want %d", got, 2*n)
	}
	if got := facade.Hits(); got != 1 {
		t.Fatalf("batched requests = %d, want 1", got)
	}
	// Same answer from both designs.
	if chattyTotal != resp.TotalCents {
		t.Fatalf("totals differ: %d vs %d", chattyTotal, resp.TotalCents)
	}
	// Time budget with a wide margin: the lower bound is arithmetic, not a measurement.
	if min := time.Duration(2*n) * injected; chattyTook < min {
		t.Fatalf("chatty took %v, cannot be less than %v", chattyTook, min)
	}
	if budget := 8 * injected; batchedTook > budget {
		t.Fatalf("batched took %v, budget %v", batchedTook, budget)
	}
}

// A slow dependency must cost at most (attempts x timeout + backoff), never "forever".
func TestDeadlineBoundsTheWait(t *testing.T) {
	slow := latency.Wrap(after.Facade{Quoter: after.Local{Engine: engine()}}.Handler(), 2*time.Second)
	ts := httptest.NewServer(slow)
	defer ts.Close()
	client := after.NewClient(after.Config{
		BaseURL:        ts.URL,
		AttemptTimeout: 40 * time.Millisecond,
		MaxAttempts:    3,
		BaseBackoff:    5 * time.Millisecond,
		MaxBackoff:     10 * time.Millisecond,
	})
	start := time.Now()
	_, err := client.Quote(context.Background(), after.QuoteRequest{Lines: []after.QuoteLine{{SKU: "A", Qty: 1}}})
	took := time.Since(start)
	if !errors.Is(err, after.ErrTimeout) {
		t.Fatalf("err = %v, want ErrTimeout", err)
	}
	if limit := 3*40*time.Millisecond + 3*10*time.Millisecond + 500*time.Millisecond; took > limit {
		t.Fatalf("took %v, want under %v", took, limit)
	}
	if got := slow.Hits(); got != 3 {
		t.Fatalf("attempts = %d, want 3", got)
	}
}

// Retries recover from a transient 503 and stop on a permanent business error.
func TestRetryOnlyWhatCanSucceed(t *testing.T) {
	var calls atomic.Int64
	inner := after.Facade{Quoter: after.Local{Engine: engine()}}.Handler()
	flaky := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if calls.Add(1) <= 2 {
			http.Error(w, "warming up", http.StatusServiceUnavailable)
			return
		}
		inner.ServeHTTP(w, r)
	})
	ts := httptest.NewServer(flaky)
	defer ts.Close()
	client := after.NewClient(after.Config{BaseURL: ts.URL, BaseBackoff: time.Millisecond, MaxBackoff: 2 * time.Millisecond})

	if _, err := client.Quote(context.Background(), after.QuoteRequest{Lines: []after.QuoteLine{{SKU: "A", Qty: 1}}}); err != nil {
		t.Fatalf("expected success after 2 transient failures, got %v", err)
	}
	if calls.Load() != 3 {
		t.Fatalf("calls = %d, want 3", calls.Load())
	}

	calls.Store(10) // server healthy from now on
	seen := calls.Load()
	_, err := client.Quote(context.Background(), after.QuoteRequest{Lines: []after.QuoteLine{{SKU: "NOPE", Qty: 1}}})
	if !errors.Is(err, pricing.ErrUnknownSKU) {
		t.Fatalf("err = %v, want ErrUnknownSKU", err)
	}
	if calls.Load()-seen != 1 {
		t.Fatalf("a business error was retried: %d calls", calls.Load()-seen)
	}
}

The Go angle ​

  • Interfaces are satisfied implicitly, so after.Local and *after.Client both satisfy Quoter without declaring it. The consumer owns the interface, which is why the remote and local versions can be swapped in main.
  • context.Context is the carrier for deadline, cancellation and the correlation id. A function that may go remote takes a context from day one, even if the in-process version only checks ctx.Err().
  • net/http has no default deadline: http.Client.Timeout is zero ("no timeout") and the Transport reuses at most two idle connections per host. after.NewClient raises MaxIdleConnsPerHost, because opening a connection costs extra round trips.
  • The standard library is enough for the first rung: httptest.NewServer picks a free port, which makes budget tests parallel-safe, and net/http's ServeMux supports method and path patterns such as POST /v1/quotes.
  • gRPC deadlines propagate automatically in Go when you pass the incoming context to outgoing calls; the gRPC deadlines guide says this is "enabled by default (e.g. Java and Go)".
  • Errors are values, so errors.Is(err, after.ErrTimeout) lets callers branch on the failure class without string matching. The package keeps three classes: invalid (never retry), unavailable (retry, bounded), timeout (outcome unknown).

Laravel ​

The same design in Laravel 13 (PHP 8.4). The PHP snippets were reviewed, not run, because PHP is not installed on the authoring machine; every HTTP client call was checked against the Laravel 13.x HTTP client and Context docs.

Contracts: interface and DTOs ​

php
<?php

namespace App\Pricing;

use RuntimeException;

// The contract the rest of the application depends on. One class per file in a real app;
// they are shown together here so the shape is visible at a glance.

final readonly class QuoteLine
{
    public function __construct(public string $sku, public int $qty)
    {
    }
}

// DTO: the whole basket travels in one message.
final readonly class QuoteRequest
{
    /** @param list<QuoteLine> $lines */
    public function __construct(public array $lines, public string $currency = 'EUR')
    {
    }

    /** @return array{lines: list<array{sku: string, qty: int}>, currency: string} */
    public function toArray(): array
    {
        return [
            'lines' => array_map(fn (QuoteLine $l) => ['sku' => $l->sku, 'qty' => $l->qty], $this->lines),
            'currency' => $this->currency,
        ];
    }
}

final readonly class QuoteResponse
{
    /** @param array<string, int> $lineTotals sku => cents (money is integer cents, never float) */
    public function __construct(
        public string $currency,
        public int $totalCents,
        public array $lineTotals,
    ) {
    }
}

// Shaped by the remote case: one coarse call, typed DTOs, failures that can be classified.
interface PriceQuoter
{
    /**
     * @throws UnknownSku         business error, never retry
     * @throws PricingTimeout     the call may or may not have been served; safe to retry only because it is read-only
     * @throws PricingUnavailable the service could not be reached or answered 429/502/503/504
     */
    public function quote(QuoteRequest $request): QuoteResponse;
}

class UnknownSku extends RuntimeException
{
}

class PricingTimeout extends RuntimeException
{
}

class PricingUnavailable extends RuntimeException
{
}

In-process implementation ​

php
<?php

namespace App\Pricing;

// The in-process implementation: a plain method call, no network, no serialization.
final class InProcessPriceQuoter implements PriceQuoter
{
    /** @param array<string, int> $unitCents sku => unit price in cents */
    public function __construct(private readonly array $unitCents)
    {
    }

    public function quote(QuoteRequest $request): QuoteResponse
    {
        $total = 0;
        $perLine = [];

        foreach ($request->lines as $line) {
            $unit = $this->unitCents[$line->sku] ?? throw new UnknownSku("Unknown sku {$line->sku}");
            $gross = $unit * $line->qty;
            $discount = match (true) {
                $line->qty >= 10 => 10,
                $line->qty >= 5 => 5,
                default => 0,
            };
            $lineTotal = $gross - intdiv($gross * $discount, 100);

            $perLine[$line->sku] = ($perLine[$line->sku] ?? 0) + $lineTotal;
            $total += $lineTotal;
        }

        return new QuoteResponse($request->currency, $total, $perLine);
    }
}

Remote implementation: timeouts, retries, classified errors ​

php
<?php

namespace App\Pricing;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;

// The same interface over the network. Every knob is explicit: connect timeout, total timeout,
// bounded retries with jitter, error classification, correlation id.
final class HttpPriceQuoter implements PriceQuoter
{
    public function __construct(private readonly string $baseUrl)
    {
    }

    public function quote(QuoteRequest $request): QuoteResponse
    {
        try {
            $response = Http::baseUrl($this->baseUrl)
                ->acceptJson()
                ->withHeaders(['X-Request-ID' => Context::get('request_id') ?? (string) Str::uuid()])
                ->connectTimeout(1)   // seconds to establish the connection
                ->timeout(2)          // seconds for the whole attempt (Laravel's default is 30)
                // Up to 3 attempts. The second argument may be a closure: full jitter, 0..min(400, 25 * 2^(n-1)) ms.
                ->retry(
                    3,
                    fn (int $attempt, Throwable $e): int => random_int(0, min(400, 25 * (2 ** ($attempt - 1)))),
                    fn (Throwable $e): bool => $this->isTransient($e),
                )
                ->post('/v1/quotes', $request->toArray());
        } catch (ConnectionException $e) {
            // Guzzle surfaces timeouts as cURL error 28 inside a ConnectionException.
            throw str_contains($e->getMessage(), 'timed out') || str_contains($e->getMessage(), 'cURL error 28')
                ? new PricingTimeout($e->getMessage(), previous: $e)
                : new PricingUnavailable($e->getMessage(), previous: $e);
        } catch (RequestException $e) {
            $status = $e->response->status();

            if ($status === 422 && $e->response->json('code') === 'unknown_sku') {
                throw new UnknownSku((string) $e->response->json('message'), previous: $e);
            }

            throw new PricingUnavailable("pricing answered HTTP {$status}", previous: $e);
        }

        return new QuoteResponse(
            currency: (string) $response->json('currency'),
            totalCents: (int) $response->json('total_cents'),
            lineTotals: collect($response->json('lines'))->pluck('total_cents', 'sku')->all(),
        );
    }

    // Retry only what can succeed on a second try: connection failures and 429/502/503/504.
    // A 4xx business error such as 422 is final.
    private function isTransient(Throwable $e): bool
    {
        if ($e instanceof ConnectionException) {
            return true;
        }

        return $e instanceof RequestException
            && in_array($e->response->status(), [429, 502, 503, 504], true);
    }
}

Remote Facade endpoint and the switch between in-process and HTTP ​

php
<?php

namespace App\Http\Controllers;

use App\Pricing\PriceQuoter;
use App\Pricing\QuoteLine;
use App\Pricing\QuoteRequest;
use App\Pricing\UnknownSku;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

// The Remote Facade of the pricing service: coarse-grained, no business rules, DTO in and out.
final class QuotesController
{
    public function store(Request $request, PriceQuoter $quoter): JsonResponse
    {
        $data = $request->validate([
            'lines' => ['required', 'array', 'min:1', 'max:100'],
            'lines.*.sku' => ['required', 'string'],
            'lines.*.qty' => ['required', 'integer', 'min:1', 'max:10000'],
            'currency' => ['sometimes', 'string', 'size:3'],
            // Unknown extra keys are simply not read: a tolerant reader.
        ]);

        try {
            $quote = $quoter->quote(new QuoteRequest(
                array_map(fn (array $l) => new QuoteLine($l['sku'], $l['qty']), $data['lines']),
                $data['currency'] ?? 'EUR',
            ));
        } catch (UnknownSku $e) {
            return response()->json(['code' => 'unknown_sku', 'message' => $e->getMessage()], 422);
        }

        return response()->json([
            'currency' => $quote->currency,
            'total_cents' => $quote->totalCents,
            'lines' => collect($quote->lineTotals)
                ->map(fn (int $cents, string $sku) => ['sku' => $sku, 'total_cents' => $cents])
                ->values()
                ->all(),
        ]);
    }
}
php
<?php

namespace App\Providers;

use App\Pricing\HttpPriceQuoter;
use App\Pricing\InProcessPriceQuoter;
use App\Pricing\PriceQuoter;
use Illuminate\Support\ServiceProvider;

// One config switch decides where the pricing module lives. Callers type-hint PriceQuoter
// and never learn the answer. The interface is the same because it was designed coarse.
//
// config/services.php:
//   'pricing' => ['driver' => env('PRICING_DRIVER', 'local'), 'url' => env('PRICING_URL')],
final class PricingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(PriceQuoter::class, function () {
            return config('services.pricing.driver') === 'http'
                ? new HttpPriceQuoter((string) config('services.pricing.url'))
                : new InProcessPriceQuoter(['A' => 1000, 'B' => 250, 'C' => 4999]);
        });
    }
}

Correlation id middleware ​

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

// Reuse the caller's X-Request-ID or mint one. Context is added to every log line and to
// queued jobs dispatched during the request, and HttpPriceQuoter forwards it on outgoing calls.
final class CorrelationId
{
    public function handle(Request $request, Closure $next): Response
    {
        $id = $request->header('X-Request-ID') ?: (string) Str::uuid();
        Context::add('request_id', $id);

        $response = $next($request);
        $response->headers->set('X-Request-ID', $id);

        return $response;
    }
}

Chatty vs pooled vs batched ​

php
<?php

namespace App\Pricing;

use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;

// Three ways to price N basket lines against a remote pricing service.
final class ChattyVsBatched
{
    public function __construct(private readonly string $baseUrl)
    {
    }

    // 1. N+1 across the network: 2 sequential requests per line. Latency = 2 x N x round trip.
    /** @param list<QuoteLine> $lines */
    public function sequential(array $lines): int
    {
        $total = 0;
        foreach ($lines as $line) {
            $unit = (int) Http::get("{$this->baseUrl}/price/{$line->sku}")->json('cents');
            $percent = (int) Http::get("{$this->baseUrl}/discount/{$line->qty}")->json('percent');
            $gross = $unit * $line->qty;
            $total += $gross - intdiv($gross * $percent, 100);
        }

        return $total;
    }

    // 2. Concurrent but still chatty: the wall clock shrinks, the load on the service does not.
    //    N price requests still hit the service, and a failed entry arrives as a ConnectionException.
    /** @param list<QuoteLine> $lines */
    public function pooled(array $lines): array
    {
        return Http::pool(
            fn (Pool $pool) => array_map(
                fn (QuoteLine $l) => $pool->get("{$this->baseUrl}/price/{$l->sku}"),
                $lines,
            ),
            concurrency: 10,
        );
    }

    // 3. Coarse-grained: one request, one round trip, one failure to handle.
    /** @param list<QuoteLine> $lines */
    public function batched(array $lines): QuoteResponse
    {
        return (new HttpPriceQuoter($this->baseUrl))->quote(new QuoteRequest($lines));
    }
}

The latency-budget test ​

php
<?php

namespace Tests\Feature;

use App\Pricing\HttpPriceQuoter;
use App\Pricing\PricingUnavailable;
use App\Pricing\QuoteLine;
use App\Pricing\QuoteRequest;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

// Latency-budget tests: assert the number of network calls and a wide time budget, not a tight p95.
final class PricingLatencyBudgetTest extends TestCase
{
    private const OK = [
        'currency' => 'EUR',
        'total_cents' => 14_900,
        'lines' => [['sku' => 'A', 'total_cents' => 14_900]],
    ];

    public function test_a_basket_costs_exactly_one_remote_call(): void
    {
        Http::preventStrayRequests();
        Http::fake(function () {
            usleep(50_000); // simulated 50 ms network latency

            return Http::response(self::OK, 200);
        });

        $lines = array_map(fn (int $i) => new QuoteLine('A', $i + 1), range(0, 19)); // 20 lines
        $start = hrtime(true);

        (new HttpPriceQuoter('http://pricing.test'))->quote(new QuoteRequest($lines));

        $elapsedMs = (hrtime(true) - $start) / 1_000_000;

        Http::assertSentCount(1);                  // call-count budget: 1, not 40
        $this->assertLessThan(400, $elapsedMs);    // time budget with a wide margin (8 x the injected latency)
        Http::assertSent(fn (Request $r) => $r->hasHeader('X-Request-ID'));
    }

    public function test_transient_503_is_retried_then_succeeds(): void
    {
        Http::preventStrayRequests();
        Http::fake([
            'pricing.test/*' => Http::sequence()
                ->pushStatus(503)
                ->pushStatus(503)
                ->push(self::OK, 200),
        ]);

        $quote = (new HttpPriceQuoter('http://pricing.test'))
            ->quote(new QuoteRequest([new QuoteLine('A', 1)]));

        $this->assertSame(14_900, $quote->totalCents);
        Http::assertSentCount(3);
    }

    public function test_persistent_failure_is_bounded_and_classified(): void
    {
        Http::preventStrayRequests();
        Http::fake(['pricing.test/*' => Http::response([], 503)]);

        $this->expectException(PricingUnavailable::class);

        try {
            (new HttpPriceQuoter('http://pricing.test'))->quote(new QuoteRequest([new QuoteLine('A', 1)]));
        } finally {
            Http::assertSentCount(3); // bounded: 3 attempts, never an infinite loop
        }
    }
}

The Laravel angle ​

  • The container is the switch. PricingServiceProvider binds PriceQuoter to an in-process or HTTP implementation from one config key. Callers type-hint the interface. That is access to the service, not transparency: the interface itself is coarse, typed and failure-aware.
  • The HTTP client is Guzzle behind a fluent API. timeout() defaults to 30 seconds, connectTimeout() is separate, retry() accepts a sleep closure (for jitter) and a when closure (for transient-only retries), and retry(..., throw: false) still throws ConnectionException for connection-level failures.
  • Http::pool() runs requests concurrently and returns a ConnectionException instance for a failed entry instead of throwing; it shortens wall-clock time but does not reduce the number of requests.
  • Context carries the request id into log records and queued jobs automatically; add it to outgoing headers yourself.
  • Octane keeps the application warm between requests: reuse of singletons and connections lowers per-call overhead, but any state stored in a static or singleton survives across requests.
  • gRPC needs RoadRunner's gRPC plugin and generated PHP classes; the PHP side of this design (DTOs, deadlines, reserved numbers) is unchanged, only the transport differs.
  • Queues are the Laravel face of messaging. When the caller does not need the answer, dispatch() a job instead of calling; see Control Flow & Event Handling and Messaging Fundamentals.

Solving the classic problems ​

Chatty client (N+1 across the network) ​

SolutionHowAdvantageCost / limitation
Batch endpointTake a list, return a list (POST /v1/quotes)One round tripPartial-failure convention needed
Remote Facade + DTOCoarse method over fine-grained domainHides the object graphAnother layer to maintain
include / field selectionCaller states the shapeFlexibleQuery cost control
Read modelLocal copy updated by eventsNo call at read timeStaleness, rebuild tooling
CacheKeep the last answerSkips the callTTL staleness

Do the first one first. The lab shows 40 calls become 1, and the after package proves the totals are identical.

Retry storm ​

SolutionHowAdvantageCost / limitation
Retry in one layer onlyOnly the outermost caller retriesNo multiplicationPolicy must be agreed across teams
Jittered exponential backoffrand(0, min(max, base * 2^n))De-synchronises clientsLonger tail for retried calls
Retry budgetAt most X retries per minute or Y% of trafficCaps amplification (SRE book)Some failures are not retried
Deadline checkStop if remaining time is less than backoffNo work after the user leftNeeds deadline propagation
Circuit breakerFail fast while the callee is downLets it recoverState and tuning; see Circuit Breaker
Load shedding at the calleeReturn 503 earlyProtects the calleeClients must handle it

Unknown outcome after a timeout ​

SolutionHowAdvantageCost / limitation
Make the operation a readReads are safely repeatableTrivialOnly some operations
Idempotency keyClient sends a unique key; server stores the resultSafe retry for writesKey storage, TTL
Query before retryAsk "did my request apply?"Works without keysExtra call and race
Outbox + idempotent consumerMessage-based exactly-once effectRobustInfrastructure
CompensateUndo with a reverse actionHandles long flowsDesign effort (saga)

Version skew ​

SolutionHowAdvantageCost / limitation
Additive changes onlyNew optional fieldsNo coordinationContract grows
Expand and contractOld and new together, remove laterSafe rolloutNeeds usage metrics
Tolerant readerIgnore unknown fieldsForward compatibilityTypos pass silently
Consumer-driven contract testsProvider CI replays consumer expectationsFinds who depends on whatNeeds a broker or shared repo
Version in the path or media type/v2ExplicitTwo versions to run

The distributed monolith ​

SymptomCauseFix
Every release needs three services deployed togetherShared database or chatty synchronous chainsMerge them back into one deployable, or give each its own data and an async boundary
One service down means everything downSynchronous call chain on the critical pathFallbacks, caches, queues; see Service Boundaries
Cannot test one service aloneHidden runtime dependenciesContract tests, fakes
Latency grows with each new serviceCall depthFlatten, batch, cache, move to events

Choosing ​

SituationRecommendationExtra techniqueReason
New product, one team, unclear boundariesModular monolith, in-process modulesInterfaces designed coarse; module testsCheapest place to find the right boundaries (Fowler's Monolith First)
One part needs very different CPU/memorySeparate worker on its own hostQueue between themIndependent scaling without a synchronous dependency
A different team owns the capability and releases independentlyService with an explicit contractConsumer-driven contract tests, versioning policyOwnership is the strongest driver
Flaky third-party integrationIsolate behind an adapter, maybe a separate processTimeout, circuit breaker, queue for retriesFailure isolation
User waits for the answerSynchronous call with deadlineCache, parallel fan-out, hedged readsLatency budget
User does not wait for the resultMessage or jobIdempotent consumer, outboxAbsorbs bursts and downtime
Many small reads of reference dataLocal cache or replicated read modelEvent-driven refresh, TTLAvoid the call entirely
Data must be near users in another continentRegional replica or edge cacheExplicit consistency choice per datum150 ms is physics
Public API for browsers and partnersREST + JSONOpenAPI, versioning, rate limitsTooling and caching
Internal, high-volume, strongly typed callsgRPC + ProtobufDeadlines, reserved, retry policyPerformance and generated clients
Call depth is already 4+ servicesCollapse or go asyncTracing, budget per hopLatency and availability multiply

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

Monolith: one process, one database ​

Everyday example. A Laravel shop calls PriceQuoter::quote() from CheckoutController. The implementation is InProcessPriceQuoter reading a table; the call costs microseconds, a failure is an exception in the same request, and one database transaction covers order and stock. The only design obligation: write the interface as if it may be remote (coarse, DTOs, typed errors), because that costs nothing now.

text
     Monolith request
1    CheckoutController::store()
2    -> PriceQuoter::quote(QuoteRequest)         (in-process, DTO in, DTO out)
3    -> DB::transaction { order, lines, stock }   (one commit)
4    -> response                                  (one stack trace if it fails)

Production example. A Go API with internal/pricing, internal/orders, internal/inventory as packages in one binary. Compile-time visibility (internal/) enforces the boundary, go vet and the race detector run on everything, deploy is one binary. Moving to the next rung later is a wiring change in main.

Modular monolith and multiple databases ​

Everyday example. Pricing, orders and inventory become modules with their own tables (or schemas) and a public interface each; modules call each other only through interfaces, never through each other's tables. Calls are still in-process, but the contract is explicit and enforced by tests or architecture rules (Modular Monolith).

ModulePublic interfaceOwnsAllowed to read
pricingPriceQuoterprices, discountsnothing else
ordersOrderServiceorders, order_linespricing via PriceQuoter
inventoryStockServicestocknothing else

Production example. A SaaS with 30 developers keeps a single deployable but gives each module a CODEOWNERS entry and a schema. When the pricing team wants independent releases, the interface and the DTOs already exist; extracting the module means adding a transport (HTTP or gRPC) behind the same interface and moving its schema to its own database, with a dual-run period.

Microservices: the network boundary becomes real ​

Everyday example. pricing becomes a service. Checkout calls it with a 300 ms deadline, three bounded attempts and a correlation id; pricing exposes the Remote Facade, the contract is versioned and consumer-driven contract tests run in pricing's CI.

text
     Checkout -> pricing -> (nothing) -- request flow with budgets
1    client            POST /checkout                      budget 800 ms
2    checkout          derive deadline = now + 700 ms
3    checkout -> cart  GET /carts/42                       deadline 150 ms
4    checkout -> pricing  POST /v1/quotes (20 lines)       deadline 300 ms, 3 attempts, X-Request-ID
5    pricing           validate, price 20 lines            4 ms CPU
6    checkout -> tax   POST /v1/tax  (parallel with 4)     deadline 300 ms
7    checkout          write order (own DB)                one local transaction
8    checkout          publish OrderPlaced (outbox)        async, not in the user's budget

Production example. A marketplace with 100 services: the checkout path is limited to four synchronous hops, everything else (emails, analytics, search indexing, invoicing) is event-driven. Each hop has a deadline derived from the caller's remaining time, each client has retry budgets and circuit breakers, every service logs the X-Request-ID, and the platform publishes a latency histogram per dependency. The load-bearing architectural facts are the same on any stack; see Microservices Architecture and Service Communication.

Distributed data: replicas, caches and multiple regions ​

Everyday example. Checkout caches price:A for 60 s (a replica with TTL). The product page tolerates staleness; the order total is recomputed through quote() at order time. A read replica serves browsing; after a write the user's next read goes to the primary for a few seconds (read-your-writes).

DatumWhere it livesAllowed stalenessRule
Product titleCDN + cacheminutesCache aggressively
Display priceService cache60 sRe-validate at order
Charged pricePricing service (source of truth)0Always call, with idempotency key
Stock levelInventory servicesecondsReserve, do not read-then-write
OrderOrders DB primary0Read from primary after write

Production example. A multi-region deployment with an eu and a us region: users read prices from the nearest region's read model (updated from a price-change event stream, lag typically seconds), while price changes go to a single owner region. A partition between regions leaves each side serving slightly stale prices, which is a deliberate choice documented per datum, as described in CAP & PACELC. Cross-region synchronous calls are limited to a few operations that must be exact.

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

ScaleTypical designWhat distribution addsWhat to watch
1x (hundreds of requests per day to a few per second)Modular monolith, in-process pricingNothingKeep the interface coarse; write budget tests
10x (tens to hundreds of requests per second)Same monolith, several copies behind a load balancer (cookie-cutter scaling), a queue for slow workQueue between web and workersConnection pool sizes, queue depth, p99
100x (thousands per second, several teams)Extract the components with real drivers (ownership, scaling, isolation) into services; caches and read models; async eventsDeadlines, retry budgets, circuit breakers, contracts, tracingCall depth, retry amplification, per-dependency p99, cost of egress
Multi-regionRegional read models, one write owner per datumReplication lag and conflict rulesStaleness SLOs, failover drills

Lab: in-process vs localhost HTTP vs added latency, and the cost of chatty calls ​

You will measure the same basket of 20 lines priced four ways. Everything runs in Go from this chapter's module; ports are chosen by the operating system (httptest.NewServer), so it is safe on a shared machine.

Setup.

bash
cd docs/snippets/design/distribution-of-components/go
go vet ./... && go test ./...       # the budget tests must pass first

Experiment 1: run the measurement.

bash
go run ./lab

Output measured on the authoring machine (macOS, arm64, Go 1.27, loopback network). Your numbers will differ, the ratios will not:

text
basket of 20 lines

scenario                                           time    calls
in-process, coarse (average of 1000 runs)         440ns        0
localhost, chatty (fine-grained)                5.445ms       40
localhost, coarse (remote facade)                 169µs        1
localhost +50ms, chatty (fine-grained)        2.082936s       40
localhost +50ms, coarse (remote facade)        52.342ms        1
ReadingValueLesson
In-process vs coarse localhost440 ns vs 169 us, about 380xEven loopback is not "local" (Fowler)
Chatty vs coarse on localhost5.4 ms vs 0.17 ms, about 32xCall count dominates before the network is even slow
Chatty with +50 ms2.08 s = 40 x 50 ms + overheadLatency is multiplied by call count
Coarse with +50 ms52.3 ms = 1 x 50 ms + 2 msOne call pays latency once

Experiment 2: change the injected latency. In lab/main.go change 50 * time.Millisecond to 150 * time.Millisecond (a transcontinental round trip) and run again. Expected: chatty about 6.0 s, coarse about 152 ms.

Experiment 3: break the budget on purpose. In budget_test.go, replace the single client.Quote(ctx, req) in TestChattyVersusBatched with a loop that calls it once per line (20 calls, each with a one-line request). Expected: go test ./budget fails with batched requests = 20, want 1. That failure is the signal a code review would otherwise miss.

Experiment 4: timeouts and retries. Run go test -run 'Deadline|Retry' -v ./budget. Expected: TestDeadlineBoundsTheWait passes in well under a second although the server sleeps 2 s per request (three attempts of 40 ms plus backoff), and TestRetryOnlyWhatCanSucceed shows three calls for a transient 503 sequence and exactly one call for an unknown sku.

Experiment 5 (optional, real network conditions). On Linux, add 50 ms to the loopback interface with tc and repeat Experiment 1 against a server you start manually:

bash
sudo tc qdisc add dev lo root netem delay 50ms      # every packet on lo is delayed by 50 ms
go run ./lab
sudo tc qdisc del dev lo root netem                 # always remove it afterwards

On any OS you can instead put a Toxiproxy proxy in front of the service and add its latency toxic (toxiproxy-cli toxic add -t latency -a latency=50 <proxy>). The sleep middleware in latency/latency.go is the portable way and the one the tests use. tc and Toxiproxy were not run for this page (Toxiproxy is not installed and tc is Linux-only).

Experiment 6: Laravel. In a Laravel 13 app copy the php/ snippets into app/, set PRICING_DRIVER=http and run php artisan test --filter=PricingLatencyBudgetTest. Expected: three tests pass, Http::assertSentCount(1) proves one call for a 20-line basket. This was reviewed, not run, on the authoring machine.

Common misconceptions ​

BeliefReality
"A remote call is a slow function call"It can also half-succeed, time out with unknown outcome, return stale data or run an older version
"localhost is basically local"The lab: a coarse localhost call is about 380x an in-process call; inter-process calls are "orders of magnitude" slower (Fowler)
"The First Law bans microservices"It bans transparent distributed objects; coarse-grained services are a different thing, though still a "complexity booster"
"Good middleware hides the network"It hides addressing and plumbing, never latency, partial failure or versions
"Our private network is reliable and secure"Fallacies 1 and 4 hold inside a cluster too
"Retries make calls reliable"Unbounded or layered retries cause retry storms; retry only safe operations, with jitter, budget and deadline
"Average latency tells us we are fine"Tail latency dominates fan-out: 100 calls at p99 each give 63% slow requests
"Parallel calls fix chattiness"They shorten wall-clock time, not load or tail risk; fewer calls is the fix
"Protobuf is always better than JSON"It wins on size and strictness; with small payloads the round trip dominates, and JSON is easier to debug
"URL versioning solves schema evolution"Without additive changes and usage metrics you run many versions forever
"End-to-end tests are enough"They are slow, flaky and cannot tell which side broke the contract
"More services means more scalable"Only if the driver is real; otherwise you add latency and failure modes

Cheat sheet ​

TopicWhat to remember
Local vs remoteLatency, partial failure, no shared memory, serialization, concurrency, versioning
NumbersMemory 100 ns, datacenter RTT 0.5 ms, cross-continent 150 ms (Dean)
First LawDo not distribute objects; design the remote interface coarse first
Remote Facade + DTOOne call, one message, no business logic in the facade, data only in the DTO
Fallacy 1Timeout + bounded retry + idempotency on every call
Fallacy 2Count calls; budget the milliseconds
Fallacies 3 and 7Bound payloads; budget serialization and egress
Fallacies 4 to 6, 8TLS or mTLS; discovery; contracts and owners; open formats
BoundariesModule, component, process, deployable, service, region are different lines
What to distributeData gravity, team ownership, scaling needs, failure isolation (and compliance)
LadderIn-process, same host, same datacenter, other region; each adds failures, none removes any
Retry rulesOnly transient errors, only safe operations, jitter, budget, inside the deadline
DeadlineSet on every call; propagate downstream; stop retrying when time is short
ContractsAdditive changes, tolerant reader, reserved, expand and contract
Protobuf vs JSONProtobuf: small, strict, tooling; JSON: readable, universal
Tail latency1 - 0.99^N slow requests; hedge idempotent reads with care
ChattyLoop around a remote call is a defect; batch or cache
CachingA cache is a replica with TTL-sized staleness
ObservabilityCorrelation id on every hop, histograms per dependency
TestingCall-count test, timeout test, consumer-driven contract test

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 — Name the six ways a remote call differs from a local call and give one design consequence of each. Important ​

Answer

Answer: Latency (coarse calls, a budget), partial failure (timeouts, retries, idempotency), no shared memory (pass values, DTOs), serialization (choose a format, cap sizes), concurrency (idempotency, optimistic checks) and versioning (additive contract, tolerant readers). See Local vs remote.

2 — Why does Fowler say "you can't encapsulate the remote/in-process distinction", and what does that imply for the interface? Important ​

Answer

Answer: Because a remote call is orders of magnitude slower and can fail on its own, the best interface differs: fine-grained in-process, coarse-grained remote. A class designed for one cannot be used transparently as the other. The interface must be designed for the remote case before distribution. See First Law.

3 — Does microservices architecture violate the First Law of Distributed Object Design? Good to know ​

Answer

Answer: Not the letter: microservice advocates use coarse-grained interactions with documents over HTTP or messaging and do not pretend in-process and remote are the same. Fowler still calls distribution "a complexity booster" and prefers a monolith by default. See First Law.

4 — List the eight fallacies and give the design consequence of fallacies 1, 2 and 6. Must-know ​

Answer

Answer: Reliable network, zero latency, infinite bandwidth, secure network, unchanging topology, one administrator, zero transport cost, homogeneous network. 1: timeouts, bounded retries, idempotency. 2: coarse calls and a latency budget. 6: explicit contracts, versioning and ownership. See the fallacies.

5 — A client calls a service with a 300 ms timeout and retries three times; the service it calls does the same to a third service. How many requests can the third service receive for one user request, and how do you stop it? Must-know ​

Answer

Answer: Up to 3 x 3 = 9 (27 with three layers). Retry in one layer only, use jittered backoff, a retry budget, a deadline check, a circuit breaker and load shedding. See Retry storm.

6 — Which of these should be distributed: (a) code that formats an address, (b) an image-resizing function that needs 8 vCPUs in bursts, (c) a capability owned by another team with its own releases? Important ​

Answer

Answer: (a) No: no driver, same team, trivial. (b) Yes, as a worker with a queue: scaling needs. (c) Yes, as a service with an explicit contract: team ownership. See Choosing what to distribute.

7 — A user request fans out to 50 services in parallel, each with a 99th percentile of 1 s and a typical time of 10 ms. Roughly what fraction of user requests will see a slow response? Important ​

Answer

Answer: 1 - 0.99^50, about 39.5%. Fan-out multiplies tail latency; use deadlines, hedged requests for idempotent reads, fewer calls, or caches. See Latency budgets.

8 — You must remove a field from a Protobuf message. What do you do, and what must you never do? Must-know ​

Answer

Answer: Stop writing it, deprecate, wait until usage is gone, then delete it and mark both its number and name reserved. Never reuse the number for a different field or type. See Contracts.

9 — Why is retrying quote() safe in this chapter, and what would you add before retrying a charge() call? Must-know ​

Answer

Answer: quote() is read-only, so repeating it changes nothing. A charge() needs an idempotency key so the server can recognise a repeat and return the first result instead of charging twice. See Unknown outcome.

10 — What does a consumer-driven contract test catch that an end-to-end test usually does not? Important ​

Answer

Answer: The provider's change breaks a field one specific consumer uses, found in the provider's CI before release, with the exact expectation named. End-to-end tests are slow, flaky and cover few version combinations. See Testability.

11 — In the lab, chatty vs coarse differ by 32x on localhost and 40x with 50 ms injected. Why is the ratio larger with latency? Good to know ​

Answer

Answer: Chatty pays the latency 40 times, coarse once; as latency grows it dominates the compute and the ratio approaches the call-count ratio (40 to 1). See Lab.

Glossary ​

TermMeaning
Distribution of componentsDeciding how software components are spread over processes, hosts and regions and how they communicate (SWEBOK §3.4)
Local callA call within one address space
Remote callA call across a process or network boundary; copies arguments, can fail independently
LatencyTime for a request and its response; round-trip time (RTT) when both directions are counted
Tail latencyA high percentile of latency (p95, p99, p99.9)
Percentile (p50, p99)The value below which that percent of observations fall
Partial failureOne part of a system fails while the rest keeps running; the caller cannot tell which
Address spaceThe memory a process can address; not shared between processes
Serialization (marshalling)Encoding an in-memory structure as bytes for transport
VersioningManaging changes to a contract while old and new code run together
Version skewCaller and callee running different versions at the same time
Fallacies of distributed computingEight false assumptions about networks, attributed to Deutsch and Gosling
First Law of Distributed Object DesignFowler: "don't distribute your objects"
Distributed objectsObjects used identically in-process or remotely via middleware (DCOM, CORBA, RMI)
Coarse-grained interfaceFew calls that each do a lot; suited to remote use
Fine-grained interfaceMany small calls; suited to in-process use
Remote FacadeA coarse-grained facade over fine-grained objects, with no business logic (PoEAA)
Data Transfer Object (DTO)A data-only object that carries data between processes
AssemblerCode that maps between DTOs and domain objects
ComponentA replaceable part with a stated interface
ServiceA component reachable over a network, usually owned by one team
ProcessAn OS process with its own address space
DeployableThe unit you ship and roll back
Data gravityThe pull of computation toward large datasets because moving data is costly
Team ownership / Conway's lawSystem boundaries follow the communication structure of the organisation
Failure isolationContaining the damage of a fault inside one component
BulkheadSeparate resource pools per dependency so one failure cannot exhaust shared capacity
Cookie-cutter scalingScaling by running more identical copies of the whole application
Distributed monolithServices that must be changed and deployed together
Distribution ladderIn-process, separate process, separate hosts, separate regions
Location transparencyCallers do not know where the callee runs; useful for addressing, a myth for failure and speed
Timeout / deadlineThe maximum time to wait; a deadline is an absolute point in time
Deadline propagationPassing the remaining time to downstream calls
RetryRepeating a failed call; safe only for transient failures on idempotent operations
Exponential backoffWaiting longer after each failed attempt
JitterRandomness added to backoff so clients do not retry in lock step
Retry budgetA cap on retries per time window or per request fraction
Retry stormRetries that amplify an overload
IdempotencyAn operation that has the same effect when applied once or many times
Idempotency keyA unique token that lets the server detect a repeated request
BackpressureA signal that makes producers slow down when a consumer cannot keep up
Circuit breakerA guard that fails fast while a dependency is failing
Load sheddingRejecting excess work early to protect a service
Hedged requestSending a duplicate request to another replica after a short wait and using the first answer
Latency budgetThe time allotted to each step of a request so the total meets the target
Chatty interfaceAn interface that needs many small remote calls to do one task
N+1One call for a list plus one per item
RPCRemote procedure call: invoke a method on a remote service (gRPC, Thrift)
RESTResource-oriented API style over HTTP
MessagingAsynchronous communication through a broker (queues, topics)
gRPCRPC framework on HTTP/2 with Protobuf contracts and deadlines
ProtobufBinary serialization format with numbered fields and a schema
JSONText serialization format; no mandatory schema
Schema evolutionChanging a contract without breaking existing readers and writers
Backward / forward compatibilityNew readers accept old data; old readers accept new data
Tolerant readerA reader that ignores unknown fields and defaults missing optional ones
Expand and contractAdd the new shape, migrate users, then remove the old shape
Consumer-driven contractA contract recorded from a consumer's expectations and replayed against the provider
Contract testA test of the interface agreement between two components
Correlation idAn identifier carried through all calls of one request to join logs
traceparentThe W3C Trace Context header that carries trace and span ids
Eventual consistencyReplicas converge if updates stop; reads may be stale meanwhile
Read-your-writesA user always sees their own updates
SagaA sequence of local transactions with compensations, replacing a distributed transaction
Transactional outboxWriting an event to a table in the same transaction as the data, then relaying it
ToxiproxyA TCP proxy that injects latency and failures for tests
tc netemLinux traffic control tool that adds delay and loss to an interface
OctaneLaravel's long-lived application server (FrankenPHP, Swoole, RoadRunner)
RoadRunnerA Go application server for PHP with a gRPC plugin

References ​

Built by Morteza Negahi