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 for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why distribution needs design, and the analogy | Why it exists |
| Waldo 1994, the fallacies, Fowler's First Law, Dean's numbers, SWEBOK | Where it comes from |
| Local vs remote calls: latency, partial failure, memory, serialization, versioning | Local vs remote |
| All eight fallacies, each with its design consequence | The eight fallacies |
| "don't distribute your objects" and what it does and does not forbid | First Law |
| Remote Facade, DTO, coarse-grained interfaces | Coarse-grained design |
| Component vs service vs process vs deployment boundary | Boundaries |
| Data gravity, team ownership, scaling, failure isolation: what to distribute | Choosing what to distribute |
| In-process, separate process, separate host, separate region | The distribution ladder |
| Timeouts, retries, idempotency, backpressure as design inputs | Network as a design input |
| Location transparency and why it fails | Location transparency |
| RPC vs messaging vs REST | Interaction styles |
| Contracts, JSON vs Protobuf, schema evolution | Contracts and serialization |
| Latency budgets, tail latency, hedging | Budgets and tail latency |
| N+1 across the network, caching, consistency | Chatty calls, caching, consistency |
| Correlation ids, tracing, contract tests, consumer-driven contracts | Observability and testability |
Exact knobs: Go net/http, gRPC, Laravel HTTP client, Octane | Mechanics |
| Working code | Go, Laravel |
| Chatty clients, retry storms, version skew, the distributed monolith | Solving the classic problems |
| Which rung of the ladder for which situation | Choosing |
| Monolith, modular monolith, microservices, distributed data, scaling | In architecture |
| Measure in-process vs localhost vs +50 ms, and chatty vs coarse | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, 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.
| Dimension | Local (in-process) call | Remote call | Design consequence |
|---|---|---|---|
| Latency | Nanoseconds (about 100 ns to reach main memory) | 0.5 ms in a datacenter, about 150 ms across continents | Count calls; make them coarse; set a latency budget |
| Failure | Fails with the caller (or throws) | Can fail on its own, or be slow, or half-succeed | Timeouts, bounded retries, idempotency, classified errors |
| Memory | One address space, pass a pointer | No shared memory, data is copied | Pass values (DTOs), never references |
| Serialization | None | Encode and decode on every call | Choose a format, budget the CPU, cap payload size |
| Versioning | Compiler checks both sides together | Caller and callee deploy at different times | Explicit contract, additive changes, tolerant readers |
| Concurrency | Same locks, same scheduler | Two machines, no shared lock | Idempotency, optimistic concurrency, no distributed locks by default |
| Ownership | One team, one release | Often two teams, two releases | Contracts, ownership, deprecation policy |
| Debugging | One stack trace | Many logs, many clocks | Correlation id, distributed tracing |
Numbers to carry in your head (Jeff Dean, LADIS 2009 keynote, "Numbers Everyone Should Know").
| Operation | Time | Relative to a memory reference |
|---|---|---|
| Main memory reference | 100 ns | 1x |
| Mutex lock/unlock | 25 ns | 0.25x |
| Send 2K bytes over 1 Gbps network | 20 us | 200x |
| Read 1 MB sequentially from memory | 250 us | 2,500x |
| Round trip within same datacenter | 500 us | 5,000x |
| Disk seek | 10 ms | 100,000x |
| Send packet CA to Netherlands and back | 150 ms | 1,500,000x |
The eight fallacies in one line each. All are unpacked in the fallacies section.
| # | Fallacy | One-line design consequence |
|---|---|---|
| 1 | The network is reliable | Timeouts, bounded retries, idempotency |
| 2 | Latency is zero | Coarse calls, a latency budget |
| 3 | Bandwidth is infinite | Small payloads, pagination, compression |
| 4 | The network is secure | TLS or mTLS, authentication at every hop |
| 5 | Topology does not change | Service discovery, no hard-coded addresses |
| 6 | There is one administrator | Contracts, versioning, ownership |
| 7 | Transport cost is zero | Budget serialization and egress, batch |
| 8 | The network is homogeneous | Open formats, tolerant readers |
Where the pieces live in your tools.
| Concern | Go | Laravel |
|---|---|---|
| Per-call deadline | context.WithTimeout, http.Client.Timeout, gRPC deadlines | Http::timeout(), Http::connectTimeout() |
| Bounded retry | A small loop with jittered backoff (this page's Client), gRPC retryPolicy | Http::retry($times, $sleep, $when) |
| Coarse call | One method taking a slice, one DTO | One endpoint, a readonly DTO |
| Parallel fan-out | errgroup, goroutines | Http::pool() |
| Correlation id | X-Request-ID header + context | Context::add() + withHeaders() |
| Fake the network in tests | httptest.NewServer + a sleep handler | Http::fake(), Http::sequence(), Http::preventStrayRequests() |
| Gateway to gRPC | google.golang.org/grpc | RoadRunner 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 local | Distribute it |
|---|---|
| A call costs nanoseconds | A call costs microseconds to hundreds of milliseconds |
| Failure is all-or-nothing for the process | Failure is partial: one side can be down, slow or confused |
| Refactor across the boundary with the IDE | Changing the boundary is a migration with a deprecation window |
| One deploy, one rollback | Independent deploys, independent rollbacks, version skew |
| One database transaction | Eventual consistency, sagas, idempotency |
| Debug with one stack trace | Debug with correlation ids and traces |
| Scale the whole thing together | Scale a hot part alone; isolate a failing part |
| Risk: the big ball of mud | Risk: the distributed big ball of mud |
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
- "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.
- "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.
- "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.
| Difference | What it means | What the design must contain |
|---|---|---|
| Latency | Round trips are 4 to 5 orders of magnitude slower (Waldo 1994) | A call-count budget and a time budget |
| Partial failure | One side fails, the other keeps running | Timeouts, retries, idempotency, fallbacks |
| No shared memory | No pointers, no shared objects, no shared locks | Values in messages (DTOs), explicit ownership of state |
| Serialization | Every call encodes and decodes | A format, a size cap, a CPU budget |
| Concurrency | Two machines make progress independently | Optimistic concurrency, idempotency keys |
| Versioning | The two ends are deployed at different times | An evolvable contract, tolerant readers |
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-onlyReal 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.
| Tool | What it gives you |
|---|---|
Go context | A deadline and a cancel signal that travel with the call |
| gRPC deadlines | A deadline propagated to downstream calls (default in Go and Java) |
Laravel Http::timeout() | Maximum seconds to wait (default 30 s) |
| Idempotency keys | Safe retry of writes |
| Circuit breaker, bulkhead | Stop 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 really happens | Design consequence | Page that goes deeper |
|---|---|---|---|---|
| 1 | The network is reliable | Packets drop, connections reset, peers crash mid-request | Timeouts on every call; bounded retries with jitter; idempotent operations; classify errors | Timeouts, Retries & Jitter, Error handling |
| 2 | Latency is zero | 0.5 ms in a datacenter, 150 ms across continents, plus queuing | Coarse calls; latency budget; parallelise independent calls; cache | Latency Budget & Tail Latency |
| 3 | Bandwidth is infinite | Links saturate; big payloads starve small ones | Pagination, field selection, compression, no blobs in messages | Claim check in message design |
| 4 | The network is secure | Anything on the path can read or alter traffic | TLS or mTLS between services, authentication at every hop, validate every input | mTLS & service security |
| 5 | Topology does not change | Pods move, IPs change, regions fail over | Service discovery, DNS with short TTL, no hard-coded addresses | Service Discovery |
| 6 | There is one administrator | Other teams, other clouds, other release schedules | Explicit contracts, versioning, deprecation policy, ownership | Service Boundaries |
| 7 | Transport cost is zero | Encoding CPU, bytes on the wire, cloud egress fees | Budget serialization time and egress; batch; binary format when it matters | Serialization formats |
| 8 | The network is homogeneous | Different languages, OSes, endianness, library versions | Open wire formats (JSON, Protobuf), tolerant readers, no language-bound types | Contracts |
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 arrivingReal 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:
| Fallacy | Go | Laravel |
|---|---|---|
| 1 | context.WithTimeout, retry loop with jitter | Http::timeout()->retry() |
| 2 | One slice-taking method, errgroup for fan-out | One endpoint, Http::pool() |
| 3 | io.LimitReader, http.MaxBytesReader | max: validation rules, pagination |
| 4 | tls.Config, mTLS | Http::withOptions(['cert' => ...]) |
| 5 | DNS name, resolver, gRPC dns:/// target | A config value per environment; service discovery in the platform |
| 6 | Versioned paths, reserved proto fields | Versioned routes, API resources |
| 7 | Reuse connections (MaxIdleConnsPerHost) | Octane keeps the process warm; keep-alive in Guzzle |
| 8 | JSON or Protobuf, not encoding/gob | JSON, 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.
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 callReal 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.
| Era | Approach | What went wrong |
|---|---|---|
| Late 1990s | Distributed objects with transparent middleware (DCOM, CORBA, Java RMI) | Chatty fine-grained calls, no failure model in the interface |
| 2000s | SOAP web services, coarse documents | Heavy envelopes, but the right granularity |
| 2010s | REST over HTTP, JSON, then gRPC and messaging | Right granularity; the new risk is too many services |
| Today | Explicit remote APIs, async messaging, modular monoliths first | Distribution 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.
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 exposedReal 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.
| Rule | Why |
|---|---|
| One use case per call, shaped by what the caller needs | Avoids both chatty calls and "return the whole database" |
| DTOs have wire names, not domain names | The domain model can change without breaking the wire |
| Money is integer minor units, never float | No rounding drift between languages |
| DTOs contain data only, no behaviour | They 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 rules | One 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:
| Boundary | What it is | Failure and speed across it | Typical example |
|---|---|---|---|
| Class / function | Language-level unit | Same as local call | Engine.UnitPrice |
| Module / package | A unit of code with a public API and hidden internals | Same as local call; the compiler enforces visibility | Go internal/pricing, Laravel module folder |
| Component | A replaceable part with a stated interface (UML component) | Depends on where it is wired | PriceQuoter and its implementations |
| Process | An operating system process with its own address space | Serialization, IPC, independent crash | A PHP-FPM worker, a Go binary |
| Deployable | What you ship and roll back as one | Independent release | A container image |
| Service | A component reachable over the network, owned by a team | Network failure, version skew | pricing service |
| Host / pod / node | A machine or scheduling unit | Machine failure, shared resources | A Kubernetes pod |
| Region | A group of datacenters | Partition, 100+ ms RTT | eu-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.
| Driver | Meaning | Distribute when | Do not distribute when |
|---|---|---|---|
| Data gravity | Compute should live where the data is, because moving data costs time and money | The component reads a large dataset it alone owns (search index, ML features, analytics) | The "dataset" is a few rows another module already has |
| Team ownership | Conway's law: boundaries follow communication | A separate team owns the roadmap, release train and on-call | The same five people change both sides every week |
| Scaling needs | Parts of a system need different resources | One 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 isolation | A bug or overload in one part must not take down another | A flaky third-party integration, a batch job that eats memory | The "isolation" is just a different log file |
| Compliance and residency | Data must stay in a region or under certain controls | PCI card handling, EU-resident personal data | Convenience |
| Technology fit | A part needs a different runtime | A Python ML model beside a Go API | Preference only |
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 growsReal 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.
| Rung | Example | Typical round trip | New in this rung | What you must add | Typical trigger |
|---|---|---|---|---|---|
| 1. In-process module | Go package, Laravel module | ~100 ns | nothing (the baseline) | Interface, tests | Default |
| 2. Separate process, same host | Sidecar, 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 skew | DTOs, health checks, restart policy, contract | Isolate a crashy or heavy component; different runtime |
| 3. Separate hosts, same datacenter | Service per host, pod per service | ~500 us (Dean) | Partial failure, loss and reordering, discovery, TLS, load balancing | Timeouts, retries, idempotency, circuit breaker, mTLS | Independent scaling, team ownership |
| 4. Separate regions | Active-active or follower in another region | ~150 ms across continents (Dean) | Partitions as the normal case, clock skew, replication lag, data residency | Consistency choice, conflict handling, regional failover | Latency to users, disaster recovery, compliance |
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 anythingReal 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.
| Input | Question it answers | Design rule | Deeper page |
|---|---|---|---|
| Timeout / deadline | How long may this call take in total? | Set on every call; derive from the latency budget; propagate downstream | Timeouts, Retries & Jitter |
| Retry | Is a second attempt safe and useful? | Only for transient errors; bounded; jittered exponential backoff; within the remaining deadline; with a retry budget | Cascading Failures, Circuit Breaker |
| Idempotency | Can the callee see the same request twice? | Reads are naturally safe; writes need an idempotency key | API Idempotency, Idempotent Consumers |
| Backpressure | What happens when the callee is slower than the caller? | Bounded queues, concurrency limits, shed load, return 429 or 503 with Retry-After | Backpressure & Flow Control, Load Shedding |
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:
| Mechanism | Go | Laravel |
|---|---|---|
| Total deadline | context.WithTimeout(ctx, d) | A queue job timeout, Http::timeout() |
| Per-attempt timeout | context.WithTimeout per attempt | Http::timeout() (applies per attempt) |
| Retry with backoff | Loop with rand.Int64N jitter | Http::retry($times, $sleepClosure, $whenClosure) |
| Retry only transient errors | Inspect status and error type | The third retry argument |
| Idempotency key | Idempotency-Key header | Http::withHeaders(['Idempotency-Key' => ...]) |
| Concurrency limit | Buffered channel as a semaphore, x/sync/semaphore | Http::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 transparency | Useful? | Why |
|---|---|---|
| Access transparency (same syntax) | Mixed | Hides the cost, so people write chatty loops |
| Location transparency (address abstracted) | Yes | Needed for discovery, scaling, failover |
| Failure transparency (errors hidden) | No | The callee may have acted; the caller must be told "unknown" |
| Performance transparency | No | A 100x difference cannot be abstracted |
| Concurrency transparency | Partial | Idempotency and versioning must be explicit |
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 sReal 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.
| Dimension | RPC (gRPC, JSON-RPC, Thrift) | REST over HTTP (JSON) | Messaging (RabbitMQ, Kafka, SQS) |
|---|---|---|---|
| Model | Call a method on a remote service | Operate on resources with GET/POST/PUT/DELETE | Publish a message; a consumer handles it later |
| Coupling in time | Tight: caller waits | Tight: caller waits | Loose: producer does not wait |
| Coupling to location | Service name | URL | Topic or queue name |
| Contract | .proto or IDL, generated clients | OpenAPI (optional), conventions | Message schema (Avro, Protobuf, JSON Schema) |
| Typical payload | Binary (Protobuf) | JSON | Any, usually Avro, Protobuf or JSON |
| Streaming | Built in (gRPC streams) | Server-Sent Events, WebSockets, chunking | The broker is the stream |
| Failure model | Status codes, deadlines | HTTP status, timeouts | Acks, redelivery, dead-letter queues |
| Caching | Hard | Native (HTTP cache, ETag) | Not applicable |
| Browser-friendly | Needs gRPC-Web | Yes | No |
| Best for | Internal, high-volume, strongly typed calls | Public APIs, CRUD, cacheable reads | Events, workflows, absorbing bursts, decoupling |
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:
| Change | Backward compatible? (new server, old client) | Forward compatible? (old server, new client) | Safe action |
|---|---|---|---|
| Add an optional field | Yes | Yes if readers ignore unknown fields | Do it |
| Add a required field | No (old clients do not send it) | Yes | Avoid; make it optional with a default |
| Remove a field | Yes only if no client reads it | Yes | Deprecate, wait, then remove; Protobuf: reserved |
| Rename a field | No | No | Add the new name, keep the old one for a window |
| Change a field's type | No | No | New field |
| Change meaning, keep name | Silent bug | Silent bug | New name |
| Reuse a Protobuf field number | Corrupts data | Corrupts data | Never 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.
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 numberReal 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.
| Format | Size | Encode/decode cost | Schema | Human-readable | Evolution | Typical use |
|---|---|---|---|---|---|---|
| JSON | Larger (names repeated, numbers as text) | Moderate | Optional (JSON Schema, OpenAPI) | Yes | Easy to add fields; types are loose | Public REST APIs, browser, Laravel |
| Protobuf | Small (field numbers, varints) | Low | Required (.proto) | No (needs tooling) | Strong rules: field numbers, reserved | gRPC, internal high-volume, Kafka values |
| Avro | Small | Low | Required, schema travels or registry | No | Reader/writer schema resolution | Kafka with Schema Registry |
| MessagePack, CBOR | Smaller than JSON | Low | None | No | As loose as JSON | Compact JSON-like |
| XML/SOAP | Large | High | XSD | Yes | Heavy | Legacy enterprise |
PHP serialize(), Go encoding/gob | Language-specific | Low | Implicit in the class or type | No | Breaks across versions and languages | Never 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 parallel | P(at least one is in the slowest 1%) | Meaning |
|---|---|---|
| 1 | 1.0% | One user in 100 sees the slow case |
| 10 | 9.6% | One user in 10 |
| 20 | 18.2% | The chatty basket from the lab, if it were parallel |
| 100 | 63.4% | The Dean and Barroso example |
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 itReal 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:
| Tool | Where |
|---|---|
| Per-call deadline | context.WithTimeout; gRPC deadline propagation (default in Go); Laravel Http::timeout() |
| Parallel independent calls | Go errgroup; Laravel Http::pool() |
| Percentile metrics | Prometheus histograms; see Observability |
| Hedging | gRPC hedging policy; manual in Go with two goroutines and a cancel |
| Budget tests | The 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.
-- 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.
| Remedy | What it does | Cost |
|---|---|---|
Batch endpoint (POST /quotes with many lines) | One round trip, one failure mode | Bigger payload; partial success needs a convention |
Join or expand parameter (?include=lines) | Server assembles the answer | Server does more work per call |
| Field selection or GraphQL | Caller says what it needs | A query language to secure and cost-limit |
| Pipelining (Redis, HTTP/2) | Multiple requests in flight on one connection | The server still does N operations |
Parallel fan-out (Http::pool, errgroup) | Wall-clock win only | Load unchanged; tail risk multiplied |
| Local read model or cache | Avoid the call | Staleness |
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 location | Latency | Staleness | Failure behaviour |
|---|---|---|---|
In-process (Go sync.Map, Laravel Cache::store('array')) | ns | Per process, differs between instances | Lost on restart |
| Shared (Redis, Memcached) | ~0.5 ms | One copy, TTL-bound | A new dependency; stampede on expiry |
| HTTP cache / CDN | Near the user | max-age, stale-while-revalidate | Serves stale when origin is down (stale-if-error) |
| Read model (own table) | DB latency | Event-driven, eventually consistent | Needs events and rebuild |
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 = TTLReal 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.
| Situation | What can go wrong | Design response | Where it is taught |
|---|---|---|---|
| Two services update their own databases for one business action | One succeeds, the other fails | Saga with compensations, or transactional outbox | Designing for Failure & Reliable Messaging |
| Read replica behind the primary | Read-your-writes violation | Read from primary after a write, session stickiness | Eventual Consistency in Database Systems |
| Cache in front of a service | Stale reads | TTL, event invalidation | Caching |
| Multi-region replicas | Conflicts, lag | Choose CP or AP per datum, conflict resolution | CAP & PACELC, Consistency Models |
| Duplicate delivery | Effect applied twice | Idempotent consumer, inbox | Idempotent 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.
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| Practice | Go | Laravel |
|---|---|---|
| Accept or create the id at the edge | Correlate middleware in this chapter | CorrelationId middleware with Context::add() |
| Forward it on every outgoing call | Header from context | withHeaders(['X-Request-ID' => Context::get('request_id')]) |
| Put it in every log line | slog with request_id attribute | Context is added to log records automatically |
| Standard tracing | OpenTelemetry, traceparent | OpenTelemetry PHP, traceparent |
| Latency metrics per dependency | Histogram around the client call | Same, 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:
| Test | What it checks | Speed | Catches |
|---|---|---|---|
| Unit test | One module in isolation | ms | Logic bugs |
| Contract test (provider) | The provider honours the documented shape and status codes | ms to s | Provider breaking the contract |
| Consumer-driven contract test | The provider still satisfies what each actual consumer uses | s | Breaking a field somebody depends on |
| Latency-budget test | Call count and time against injected latency | s | Chatty regressions, missing timeouts |
| Resilience test | Behaviour under injected failure (Toxiproxy, chaos) | s to min | Missing retries, bad fallbacks |
| End-to-end test | The system as a whole | min | Wiring 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."
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 brokenReal 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.
| Knob | Where | Default | Advice |
|---|---|---|---|
http.Client.Timeout | Client | none | A safety net; prefer a context per call |
context.WithTimeout | Per request | none | The primary tool; http.NewRequestWithContext |
http.Transport.MaxIdleConnsPerHost | Transport | 2 | Raise for service-to-service traffic so connections are reused |
http.Transport.IdleConnTimeout | Transport | 90 s in DefaultTransport | Keep below the load balancer's idle timeout |
Transport.TLSHandshakeTimeout; dial timeout via net.Dialer.Timeout | Transport | 10 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, IdleTimeout | Server | none | Always set; protects from slow clients (slowloris) |
http.MaxBytesReader | Handler | none | Cap request bodies |
| gRPC deadline | context.WithTimeout on the call | none | "should always explicitly set a realistic deadline" |
gRPC retryPolicy | Service config | none | maxAttempts, initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodes |
| gRPC deadline propagation | Automatic in Go | on | Pass 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
| Feature | Call | Notes |
|---|---|---|
| Total timeout | Http::timeout(2) | Seconds; default 30 |
| Connect timeout | Http::connectTimeout(1) | Seconds to establish the connection |
| Retry | Http::retry(3, 100) | 3 attempts, 100 ms apart; second argument can be a closure fn (int $attempt, Exception $e) => ... |
| Retry only some failures | third argument closure | e.g. $e instanceof ConnectionException |
| Do not throw after retries | retry(3, 100, throw: false) | A ConnectionException is still thrown for connection failures |
| Concurrent requests | Http::pool(fn (Pool $pool) => [...], concurrency: 5) | A failed entry is a ConnectionException instance |
| Fake in tests | Http::fake(), Http::sequence()->pushStatus(503) | |
| Forbid real calls in tests | Http::preventStrayRequests() | |
| Count calls | Http::assertSentCount($n) | |
| Share data with logs and jobs | Context::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
| Failure | HTTP | gRPC status | Retry? | Meaning for the caller |
|---|---|---|---|---|
| Request rejected (validation) | 400 / 422 | INVALID_ARGUMENT | No | The request is wrong; fix it |
| Not found / unknown sku | 404 / 422 | NOT_FOUND | No | Business answer |
| Unauthenticated / forbidden | 401 / 403 | UNAUTHENTICATED / PERMISSION_DENIED | No | Credentials |
| Rate limited | 429 | RESOURCE_EXHAUSTED | Yes, after Retry-After | Back off |
| Server error | 500 | INTERNAL | Maybe | Often a bug; retry once at most |
| Bad gateway / unavailable / gateway timeout | 502 / 503 / 504 | UNAVAILABLE | Yes, bounded | Transient |
| Client deadline hit | none (client side) | DEADLINE_EXCEEDED | Only if idempotent | Outcome unknown |
| Connection refused / reset | none | UNAVAILABLE | Yes, bounded | Callee 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.
// 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
// 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
// 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
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
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:
// 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:
// 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
// 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.Localand*after.Clientboth satisfyQuoterwithout declaring it. The consumer owns the interface, which is why the remote and local versions can be swapped inmain. context.Contextis 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 checksctx.Err().net/httphas no default deadline:http.Client.Timeoutis zero ("no timeout") and theTransportreuses at most two idle connections per host.after.NewClientraisesMaxIdleConnsPerHost, because opening a connection costs extra round trips.- The standard library is enough for the first rung:
httptest.NewServerpicks a free port, which makes budget tests parallel-safe, andnet/http'sServeMuxsupports method and path patterns such asPOST /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
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
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
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
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
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
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
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
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.
PricingServiceProviderbindsPriceQuoterto 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 awhenclosure (for transient-only retries), andretry(..., throw: false)still throwsConnectionExceptionfor connection-level failures. Http::pool()runs requests concurrently and returns aConnectionExceptioninstance for a failed entry instead of throwing; it shortens wall-clock time but does not reduce the number of requests.Contextcarries 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,
reservednumbers) 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)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Batch endpoint | Take a list, return a list (POST /v1/quotes) | One round trip | Partial-failure convention needed |
| Remote Facade + DTO | Coarse method over fine-grained domain | Hides the object graph | Another layer to maintain |
include / field selection | Caller states the shape | Flexible | Query cost control |
| Read model | Local copy updated by events | No call at read time | Staleness, rebuild tooling |
| Cache | Keep the last answer | Skips the call | TTL staleness |
Do the first one first. The lab shows 40 calls become 1, and the after package proves the totals are identical.
Retry storm
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Retry in one layer only | Only the outermost caller retries | No multiplication | Policy must be agreed across teams |
| Jittered exponential backoff | rand(0, min(max, base * 2^n)) | De-synchronises clients | Longer tail for retried calls |
| Retry budget | At most X retries per minute or Y% of traffic | Caps amplification (SRE book) | Some failures are not retried |
| Deadline check | Stop if remaining time is less than backoff | No work after the user left | Needs deadline propagation |
| Circuit breaker | Fail fast while the callee is down | Lets it recover | State and tuning; see Circuit Breaker |
| Load shedding at the callee | Return 503 early | Protects the callee | Clients must handle it |
Unknown outcome after a timeout
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Make the operation a read | Reads are safely repeatable | Trivial | Only some operations |
| Idempotency key | Client sends a unique key; server stores the result | Safe retry for writes | Key storage, TTL |
| Query before retry | Ask "did my request apply?" | Works without keys | Extra call and race |
| Outbox + idempotent consumer | Message-based exactly-once effect | Robust | Infrastructure |
| Compensate | Undo with a reverse action | Handles long flows | Design effort (saga) |
Version skew
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Additive changes only | New optional fields | No coordination | Contract grows |
| Expand and contract | Old and new together, remove later | Safe rollout | Needs usage metrics |
| Tolerant reader | Ignore unknown fields | Forward compatibility | Typos pass silently |
| Consumer-driven contract tests | Provider CI replays consumer expectations | Finds who depends on what | Needs a broker or shared repo |
| Version in the path or media type | /v2 | Explicit | Two versions to run |
The distributed monolith
| Symptom | Cause | Fix |
|---|---|---|
| Every release needs three services deployed together | Shared database or chatty synchronous chains | Merge them back into one deployable, or give each its own data and an async boundary |
| One service down means everything down | Synchronous call chain on the critical path | Fallbacks, caches, queues; see Service Boundaries |
| Cannot test one service alone | Hidden runtime dependencies | Contract tests, fakes |
| Latency grows with each new service | Call depth | Flatten, batch, cache, move to events |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New product, one team, unclear boundaries | Modular monolith, in-process modules | Interfaces designed coarse; module tests | Cheapest place to find the right boundaries (Fowler's Monolith First) |
| One part needs very different CPU/memory | Separate worker on its own host | Queue between them | Independent scaling without a synchronous dependency |
| A different team owns the capability and releases independently | Service with an explicit contract | Consumer-driven contract tests, versioning policy | Ownership is the strongest driver |
| Flaky third-party integration | Isolate behind an adapter, maybe a separate process | Timeout, circuit breaker, queue for retries | Failure isolation |
| User waits for the answer | Synchronous call with deadline | Cache, parallel fan-out, hedged reads | Latency budget |
| User does not wait for the result | Message or job | Idempotent consumer, outbox | Absorbs bursts and downtime |
| Many small reads of reference data | Local cache or replicated read model | Event-driven refresh, TTL | Avoid the call entirely |
| Data must be near users in another continent | Regional replica or edge cache | Explicit consistency choice per datum | 150 ms is physics |
| Public API for browsers and partners | REST + JSON | OpenAPI, versioning, rate limits | Tooling and caching |
| Internal, high-volume, strongly typed calls | gRPC + Protobuf | Deadlines, reserved, retry policy | Performance and generated clients |
| Call depth is already 4+ services | Collapse or go async | Tracing, budget per hop | Latency 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.
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).
| Module | Public interface | Owns | Allowed to read |
|---|---|---|---|
| pricing | PriceQuoter | prices, discounts | nothing else |
| orders | OrderService | orders, order_lines | pricing via PriceQuoter |
| inventory | StockService | stock | nothing 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.
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 budgetProduction 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).
| Datum | Where it lives | Allowed staleness | Rule |
|---|---|---|---|
| Product title | CDN + cache | minutes | Cache aggressively |
| Display price | Service cache | 60 s | Re-validate at order |
| Charged price | Pricing service (source of truth) | 0 | Always call, with idempotency key |
| Stock level | Inventory service | seconds | Reserve, do not read-then-write |
| Order | Orders DB primary | 0 | Read 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×
| Scale | Typical design | What distribution adds | What to watch |
|---|---|---|---|
| 1x (hundreds of requests per day to a few per second) | Modular monolith, in-process pricing | Nothing | Keep 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 work | Queue between web and workers | Connection 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 events | Deadlines, retry budgets, circuit breakers, contracts, tracing | Call depth, retry amplification, per-dependency p99, cost of egress |
| Multi-region | Regional read models, one write owner per datum | Replication lag and conflict rules | Staleness 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.
cd docs/snippets/design/distribution-of-components/go
go vet ./... && go test ./... # the budget tests must pass firstExperiment 1: run the measurement.
go run ./labOutput measured on the authoring machine (macOS, arm64, Go 1.27, loopback network). Your numbers will differ, the ratios will not:
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| Reading | Value | Lesson |
|---|---|---|
| In-process vs coarse localhost | 440 ns vs 169 us, about 380x | Even loopback is not "local" (Fowler) |
| Chatty vs coarse on localhost | 5.4 ms vs 0.17 ms, about 32x | Call count dominates before the network is even slow |
| Chatty with +50 ms | 2.08 s = 40 x 50 ms + overhead | Latency is multiplied by call count |
| Coarse with +50 ms | 52.3 ms = 1 x 50 ms + 2 ms | One 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:
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 afterwardsOn 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Local vs remote | Latency, partial failure, no shared memory, serialization, concurrency, versioning |
| Numbers | Memory 100 ns, datacenter RTT 0.5 ms, cross-continent 150 ms (Dean) |
| First Law | Do not distribute objects; design the remote interface coarse first |
| Remote Facade + DTO | One call, one message, no business logic in the facade, data only in the DTO |
| Fallacy 1 | Timeout + bounded retry + idempotency on every call |
| Fallacy 2 | Count calls; budget the milliseconds |
| Fallacies 3 and 7 | Bound payloads; budget serialization and egress |
| Fallacies 4 to 6, 8 | TLS or mTLS; discovery; contracts and owners; open formats |
| Boundaries | Module, component, process, deployable, service, region are different lines |
| What to distribute | Data gravity, team ownership, scaling needs, failure isolation (and compliance) |
| Ladder | In-process, same host, same datacenter, other region; each adds failures, none removes any |
| Retry rules | Only transient errors, only safe operations, jitter, budget, inside the deadline |
| Deadline | Set on every call; propagate downstream; stop retrying when time is short |
| Contracts | Additive changes, tolerant reader, reserved, expand and contract |
| Protobuf vs JSON | Protobuf: small, strict, tooling; JSON: readable, universal |
| Tail latency | 1 - 0.99^N slow requests; hedge idempotent reads with care |
| Chatty | Loop around a remote call is a defect; batch or cache |
| Caching | A cache is a replica with TTL-sized staleness |
| Observability | Correlation id on every hop, histograms per dependency |
| Testing | Call-count test, timeout test, consumer-driven contract test |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — 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
| Term | Meaning |
|---|---|
| Distribution of components | Deciding how software components are spread over processes, hosts and regions and how they communicate (SWEBOK §3.4) |
| Local call | A call within one address space |
| Remote call | A call across a process or network boundary; copies arguments, can fail independently |
| Latency | Time for a request and its response; round-trip time (RTT) when both directions are counted |
| Tail latency | A high percentile of latency (p95, p99, p99.9) |
| Percentile (p50, p99) | The value below which that percent of observations fall |
| Partial failure | One part of a system fails while the rest keeps running; the caller cannot tell which |
| Address space | The memory a process can address; not shared between processes |
| Serialization (marshalling) | Encoding an in-memory structure as bytes for transport |
| Versioning | Managing changes to a contract while old and new code run together |
| Version skew | Caller and callee running different versions at the same time |
| Fallacies of distributed computing | Eight false assumptions about networks, attributed to Deutsch and Gosling |
| First Law of Distributed Object Design | Fowler: "don't distribute your objects" |
| Distributed objects | Objects used identically in-process or remotely via middleware (DCOM, CORBA, RMI) |
| Coarse-grained interface | Few calls that each do a lot; suited to remote use |
| Fine-grained interface | Many small calls; suited to in-process use |
| Remote Facade | A 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 |
| Assembler | Code that maps between DTOs and domain objects |
| Component | A replaceable part with a stated interface |
| Service | A component reachable over a network, usually owned by one team |
| Process | An OS process with its own address space |
| Deployable | The unit you ship and roll back |
| Data gravity | The pull of computation toward large datasets because moving data is costly |
| Team ownership / Conway's law | System boundaries follow the communication structure of the organisation |
| Failure isolation | Containing the damage of a fault inside one component |
| Bulkhead | Separate resource pools per dependency so one failure cannot exhaust shared capacity |
| Cookie-cutter scaling | Scaling by running more identical copies of the whole application |
| Distributed monolith | Services that must be changed and deployed together |
| Distribution ladder | In-process, separate process, separate hosts, separate regions |
| Location transparency | Callers do not know where the callee runs; useful for addressing, a myth for failure and speed |
| Timeout / deadline | The maximum time to wait; a deadline is an absolute point in time |
| Deadline propagation | Passing the remaining time to downstream calls |
| Retry | Repeating a failed call; safe only for transient failures on idempotent operations |
| Exponential backoff | Waiting longer after each failed attempt |
| Jitter | Randomness added to backoff so clients do not retry in lock step |
| Retry budget | A cap on retries per time window or per request fraction |
| Retry storm | Retries that amplify an overload |
| Idempotency | An operation that has the same effect when applied once or many times |
| Idempotency key | A unique token that lets the server detect a repeated request |
| Backpressure | A signal that makes producers slow down when a consumer cannot keep up |
| Circuit breaker | A guard that fails fast while a dependency is failing |
| Load shedding | Rejecting excess work early to protect a service |
| Hedged request | Sending a duplicate request to another replica after a short wait and using the first answer |
| Latency budget | The time allotted to each step of a request so the total meets the target |
| Chatty interface | An interface that needs many small remote calls to do one task |
| N+1 | One call for a list plus one per item |
| RPC | Remote procedure call: invoke a method on a remote service (gRPC, Thrift) |
| REST | Resource-oriented API style over HTTP |
| Messaging | Asynchronous communication through a broker (queues, topics) |
| gRPC | RPC framework on HTTP/2 with Protobuf contracts and deadlines |
| Protobuf | Binary serialization format with numbered fields and a schema |
| JSON | Text serialization format; no mandatory schema |
| Schema evolution | Changing a contract without breaking existing readers and writers |
| Backward / forward compatibility | New readers accept old data; old readers accept new data |
| Tolerant reader | A reader that ignores unknown fields and defaults missing optional ones |
| Expand and contract | Add the new shape, migrate users, then remove the old shape |
| Consumer-driven contract | A contract recorded from a consumer's expectations and replayed against the provider |
| Contract test | A test of the interface agreement between two components |
| Correlation id | An identifier carried through all calls of one request to join logs |
| traceparent | The W3C Trace Context header that carries trace and span ids |
| Eventual consistency | Replicas converge if updates stop; reads may be stale meanwhile |
| Read-your-writes | A user always sees their own updates |
| Saga | A sequence of local transactions with compensations, replacing a distributed transaction |
| Transactional outbox | Writing an event to a table in the same transaction as the data, then relaying it |
| Toxiproxy | A TCP proxy that injects latency and failures for tests |
| tc netem | Linux traffic control tool that adds delay and loss to an interface |
| Octane | Laravel's long-lived application server (FrankenPHP, Swoole, RoadRunner) |
| RoadRunner | A Go application server for PHP with a gRPC plugin |
References
- Jim Waldo, Geoff Wyant, Ann Wollrath, Sam Kendall, "A Note on Distributed Computing", Sun Microsystems Laboratories TR-94-29, November 1994. Archived PDF (Harvard scholar copy)
- Peter Deutsch, "The Eight Fallacies of Distributed Computing" (Sun page). Archived copy; Arnon Rotem-Gal-Oz, "Fallacies of Distributed Computing Explained" (the 1994/1997 history). Archived PDF; Wikipedia, Fallacies of distributed computing (secondary source, same list)
- Martin Fowler, "Microservices and the First Law of Distributed Objects", 13 August 2014. martinfowler.com
- Martin Fowler, Patterns of Enterprise Application Architecture (2002), chapter 7; catalog pages Remote Facade and Data Transfer Object
- Martin Fowler, Monolith First; James Lewis and Martin Fowler, Microservices
- Jeff Dean, "Designs, Lessons and Advice from Building Large Distributed Systems", LADIS 2009 keynote ("Numbers Everyone Should Know"). PDF; Peter Norvig, Teach Yourself Programming in Ten Years (timing table, read but not quoted)
- Jeffrey Dean and Luiz Andre Barroso, "The Tail at Scale", Communications of the ACM 56(2), 2013. PDF
- IEEE Computer Society, SWEBOK Guide v4.0a, Software Design KA, section 3.4 Distribution of Components
- gRPC: Deadlines, Retry; Protocol Buffers: Encoding, Language Guide (proto3)
- Google SRE book, Addressing Cascading Failures
- Go:
net/httpdocumentation (read throughgo doc net/http.Client),google.golang.org/grpc(read throughgo doc), Cloudflare, The complete guide to Go net/http timeouts - Laravel 13: HTTP Client, Context, Octane; RoadRunner, gRPC plugin
- Pact, Documentation; W3C, Trace Context; Shopify, Toxiproxy; tc-netem(8)
- Sam Newman, Building Microservices (not read for this page; listed as further reading only)