Skip to content

Microservices Architecture ​

"In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API." — James Lewis and Martin Fowler, Microservices, martinfowler.com, 25 March 2014

Summary: Microservices is an architecture style in which one application is built as a set of small services, each owned by one team, each with its own data, each deployable on its own; the style buys team autonomy and independent change at the price of a distributed system. Focus: The definition and the nine characteristics (Lewis and Fowler), independent deployability as the real test, granularity (Richards and Ford's disintegrators and integrators), team topology, the microservice premium and its prerequisites, cross-cutting concerns and the sidecar or mesh answer, data, communication, resilience, observability, testing, deployment and versioning, the anti-patterns, when not to use the style, and a worked ordering platform in Go and Laravel. Learning goal: Look at any "microservices" system and say whether it really is one (can each service ship alone?), what it costs, which prerequisite is missing, which anti-pattern it shows, and how to build one service correctly: owned data, timeouts, breaker, health, traces and a contract test.

This chapter is the style chapter of AR 02. It describes what a microservice architecture is and what it demands. The decisions around it have their own chapters in AR 03, and this page only summarises them and links: whether to choose the style at all (Monolith vs Microservices vs Modular Monolith), where to cut (Service Boundaries), how services talk (Service Communication), the edge and the mesh (API Gateway, BFF & Service Mesh), finding instances (Service Discovery) and data (Data Ownership in Microservices). Its neighbours in AR 02 are SOA, which it grew out of, and the Modular Monolith, which is usually the better first step.

Page map ​

If you are looking forGo to
The style in three tablesEverything in one minute
Why anyone pays for a distributed systemWhy it exists
Venice 2011, Lewis and Fowler 2014, the 2023 backlashWhere it comes from
The nine characteristics, one by oneThe nine characteristics
"Can I deploy it alone?"Independent deployability
How big should a service be?Granularity
Teams, Conway's Law, two-pizza, stream-alignedTeam topology
The cost and what you need firstPremium and prerequisites
Auth, logs, tracing, config, secrets; chassis, sidecar, meshCross-cutting concerns
Data, communication, resilience (short, with links)Data, Communication, Resilience
Logs, metrics, traces, correlation IDs, OpenTelemetryObservability
Unit, component, contract, end-to-endTesting
Containers, Kubernetes, rolling, blue/green, canaryDeployment
Changing an API without breaking callersVersioning
Distributed monolith and friendsAnti-patterns
Request path, knobs, error codesMechanics
Orders, Catalog, Billing, Notifications in Go and LaravelGo, Laravel
Each classic problem and its fixSolving the classic problems
Should we, and when notChoosing
Monolith to distributed systemIn architecture
Kill a service and watch the breakerLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The nine characteristics (Lewis and Fowler, 2014). Every row is unpacked in the nine characteristics.

#CharacteristicIn plain wordsTiny exampleWhat breaks without it
1Componentization via servicesComponents are separate processes, not librariesCatalog is its own binary with its own APIOne change redeploys everything
2Organized around business capabilitiesCut by what the business does, not by technical layerBilling, not "the database team"Every feature crosses three teams
3Products not projectsThe team that builds it runs it, for its whole lifeBilling team carries the pagerHand-off to "maintenance"; nobody learns from production
4Smart endpoints and dumb pipesLogic in services; the network only carries messagesRabbitMQ routes, the consumer decidesAn ESB becomes a second, hidden monolith
5Decentralized governanceEach team picks the tool that fitsCatalog in Go, Billing in LaravelOne stack forced on every problem
6Decentralized data managementEach service owns its data; no shared schemabilling_db is private to BillingSchema changes need every team
7Infrastructure automationBuild, test, provision and deploy by pipelineOne pipeline per serviceTwenty services, twenty manual releases
8Design for failureEvery remote call can fail; plan for it300 ms timeout + breaker on CatalogOne slow service takes down the site
9Evolutionary designExpect to split, merge and replace servicesMerge two services that always change togetherWrong boundaries frozen forever

What you buy and what you pay.

You buyYou pay (the microservice premium)
Independent deployment per teamA deployment pipeline per service, and contract tests
Strong module boundaries (hard to bypass)Remote calls: latency, serialization, partial failure
Independent scaling of hot partsEventual consistency instead of one ACID transaction
Technology choice per serviceOperational complexity: many runtimes to patch and watch
Fault isolation, if built for itObservability is mandatory, not optional
Team autonomy, fewer merge queuesRefactoring across services is slow and coordinated

Anti-patterns in one table (details in Anti-patterns).

Anti-patternSymptomFix in one line
Distributed monolithServices must be released togetherRestore independent deployability or merge them
Shared databaseTwo services write the same tablesOne owner; others use its API or events
Chatty servicesOne page makes 40 internal callsCoarser APIs, composition, replicated read data
NanoservicesA service per function; more glue than logicMerge by cohesion and change pattern
Entity servicesCustomerService, OrderService as CRUD over tablesCut by capability (Checkout, Billing), not by noun
Microservice envyMicroservices chosen for fashionMonolith first; pay the premium only when complexity demands

Why it exists ​

A single deployable has one big strength and one big weakness. The strength: everything is a function call and one database transaction. The weakness: everything ships together. When fifty developers share one deployable, the weekly release becomes a negotiation, a bug in reporting blocks a fix in checkout, and the parts that need 40 servers scale together with the parts that need one. Lewis and Fowler describe exactly this frustration: "Change cycles are tied together - a change made to a small part of the application, requires the entire monolith to be rebuilt and deployed." Microservices answer with one move: make the module boundary a process boundary, so each part can be changed, deployed and scaled on its own.

Stay one deployable (monolith or modular monolith)Split into microservices
Function calls: nanoseconds, never "partially fail"Network calls: milliseconds, time out, fail halfway
One ACID transaction across modulesSagas, eventual consistency, compensation
One pipeline, one runtime to patchOne pipeline and runtime per service
Boundaries enforced by discipline and testsBoundaries enforced by the network (hard to bypass)
Scale everything togetherScale each capability separately
Release togetherRelease independently (if designed for it)
Best for: one or a few teams, a young domainBest for: many teams, a stable domain, real scaling differences

The analogy used on this page: a restaurant kitchen vs a food court. A restaurant has one kitchen, one menu and one head chef: dishes are coordinated perfectly, but changing the menu means stopping the whole kitchen, and if the fryer breaks, nobody gets fries. A food court has independent stalls: each stall owns its stove, fridge and staff (its data), changes its menu without asking anyone, and opens late without closing the others. The price: you need shared services (cleaning, payments, signs), a customer who wants pizza and sushi walks to two stalls and may get one dish late, and if the stalls all share one fridge, you are a restaurant pretending to be a food court. We come back to the food court in every section.

Three common misunderstandings, up front ​

  1. "Microservices means small services." The name misleads. Lewis and Fowler saw sizes from a two-pizza team per service to one person per service, and say the name "does lead to an unfortunate focus on the size of service". The test is independent deployability and ownership, not lines of code.
  2. "Microservices make the system simpler." They make each piece simpler and the whole harder. Fowler: "If the components do not compose cleanly, then all you are doing is shifting complexity from inside a component to the connections between components."
  3. "Microservices are how you scale." A stateless monolith scales horizontally behind a load balancer; Lewis and Fowler say so in the same article. Microservices scale organisations and uneven load; they do not make a single request faster (they make it slower).

Where it comes from ​

Roots. Lewis and Fowler do not claim novelty: "its roots go back at least to the design principles of Unix". Service-oriented architecture in the 2000s had the same goal; the difference the 2014 article stresses is the rejection of the heavyweight Enterprise Service Bus and central governance (see SOA). Netflix, they note, called its style "fine-grained SOA".

Venice, 2011 and 2012. Footnote 1 of the article: "The term “microservice” was discussed at a workshop of software architects near Venice in May, 2011", and "In May 2012, the same group decided on “microservices” as the most appropriate name." James Lewis presented the ideas at 33rd Degree in Krakow in March 2012.

Lewis and Fowler, March 2014. Microservices: a definition of this new architectural term (published in installments, 10 to 25 March 2014) listed the nine characteristics this chapter is built on.

The warnings, 2014 and 2015. Fowler's Microservice Prerequisites (28 August 2014), Microservice Premium (13 May 2015), Monolith First (3 June 2015) and Microservice Trade-Offs (1 July 2015) turned the definition into a decision. Toby Clemson's Testing Strategies in a Microservice Architecture (18 November 2014) gave the testing vocabulary. Sam Newman's Building Microservices (first edition written in 2014, released early 2015, per his book page) became the reference book; its second edition is a full rewrite with chapters on workflow, deployment on Kubernetes, testing with consumer-driven contracts, observability and stream-aligned teams.

At scale. Netflix's Hystrix library (now in maintenance mode, per its README) packaged timeouts, bulkheads, circuit breakers and fallbacks. Amazon's two-pizza team rule shaped team size. Uber's Introducing Domain-Oriented Microservice Architecture (Adam Gluck, 23 July 2020) reports (as summarised by our fetch tool) about 2,200 critical microservices and how Uber classified them into 70 domains behind gateways.

The correction, 2023. The Prime Video team described moving an audio/video monitoring tool from a distributed serverless design to a single process and cutting cost by 90% (InfoQ coverage, May 2023; the original post's URL now redirects elsewhere). Google's HotOS 2023 paper Towards Modern Development of Cloud Applications argued that "microservices conflate logical boundaries (how code is written) with physical boundaries (how code is deployed)." Neither says "never use microservices"; both say "do not pay distribution costs you do not need".

Granularity, 2021. Ford, Richards, Sadalage and Dehghani's Software Architecture: The Hard Parts (chapter 7, free excerpt from Thoughtworks) gave names to the forces that push a service apart and pull it back together.

text
     Year      Event                                            What it changed
1    2011-12   Venice workshop names "microservices"            A word for a style already in use
2    2014-03   Lewis & Fowler: nine characteristics             A shared definition
3    2014-08   Fowler: Microservice Prerequisites               "Not without CD, monitoring, provisioning"
4    2014-11   Clemson: testing strategies                      Component and contract tests
5    2015      Newman: Building Microservices (1st ed.)         The practitioner's book
6    2015-05   Fowler: Microservice Premium                     "Only above a complexity threshold"
7    2015-06   Fowler: Monolith First                           Start modular, split later
8    2020-07   Uber: DOMA, ~2,200 services into 70 domains      Group services; gateways per domain
9    2021-10   Hard Parts (granularity chapter)                 Integrators vs disintegrators
10   2023      Prime Video (90% cheaper as one process);         Distribution is a cost to justify
               Google HotOS paper (logical vs physical)

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, what provides it in each technology, and how to apply it.

Microservice architecture (the definition) Must-know ​

In plain words: one application, built as several programs that each do one business job, each owned by one team, each with its own data, each shipped on its own.

Common misunderstanding: "We have Docker containers, so we have microservices." Containers are a packaging format. Ten containers that share one database and must be released together are one application spread over ten processes: a distributed monolith.

Definition: Lewis and Fowler: "a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery." Richardson's pattern on microservices.io: "Design an architecture that structures the application as a set of two or more independently deployable, loosely coupled, components, a.k.a. services." Newman's second edition (from its public chapter list and summary; we could not read chapter 1 itself) builds the definition on independent deployability, modelling around a business domain, and information hiding.

text
     Request: "place order for 2 x sku-1"               Where it runs
1    POST /orders -> API gateway                        edge
2    gateway -> Orders service                          orders process, orders_db
3    Orders -> GET /products/sku-1 -> Catalog           catalog process, catalog_db
4    Orders -> POST /charges -> Billing                 billing process (Laravel), billing_db
5    Orders commits order + outbox row                  orders_db only
6    relay -> bus -> Notifications sends the email      notifications process, later

Real scenario: an online shop where checkout changes daily, the catalog changes weekly and invoicing changes quarterly, owned by three teams; a bank where card authorisation must scale and stay up independently of statement generation; a ride-hailing company with thousands of engineers (Uber's ~2,200 services).

What provides it:

ConcernTypical provider
Process and packagingContainers (Docker/OCI images), one image per service
Scheduling, scaling, self-healingKubernetes Deployments, ECS, Nomad
Service-to-service callsHTTP/JSON, gRPC (grpc-go), messaging (RabbitMQ, Kafka)
EdgeAPI gateway / BFF
Finding instancesService discovery: DNS, Kubernetes Services, Consul
Gonet/http, chi, grpc-go, OpenTelemetry Go
LaravelOctane (long-lived workers), HTTP client, Sanctum tokens, queues

How to use it: treat the definition as a checklist: separate process, owned data, own pipeline, business-shaped boundary, one owning team. If any box is unticked, you have something else, which may be fine, but name it honestly.

The nine characteristics Must-know ​

In plain words: nine family resemblances. Lewis and Fowler say "not all microservice architectures have all the characteristics, but we do expect that most microservice architectures exhibit most characteristics."

Common misunderstanding: "The nine are rules you must comply with." The authors write the opposite: "we are not laying down some definition to conform to." Use them as a diagnostic: which ones does your system lack, and what does it cost you?

IndependentdeployabilityStructureAutonomyOperationsChangeThe price you pay1. Componentization via services2. Organized around businesscapabilities3. Products not projects(team owns it for its whole life)4. Smart endpoints, dumb pipes5. Decentralized governance6. Decentralized datamanagement (DB per service)(no ESB, no shared schema)7. Infrastructure automation(CI/CD, provisioning)8. Design for failure(timeouts, breakers, monitoring)Prerequisites, not options9. Evolutionary design(replaceable components,split by pattern of change)Tolerant readers, versioningonly as a last resortRemote calls, partial failure,eventual consistency, many pipelines,observability, platform work= the microservice premium

The picture groups the nine around the property they all serve, independent deployability, and puts the price you pay underneath.

#CharacteristicWhat Lewis and Fowler say (quoted)What it means in practice
1Componentization via services"a component is a unit of software that is independently replaceable and upgradeable"A service is an out-of-process component with an explicit, remote published interface
2Organized around business capabilities"splitting up into services organized around business capability"Cross-functional teams; see Conway's Law
3Products not projects"a team should own a product over its full lifetime""You build, you run it" (Amazon); on-call for your own service
4Smart endpoints and dumb pipes"they own their own domain logic and act more as filters in the classical Unix sense"No ESB with business rules; HTTP and a simple broker
5Decentralized governance"We prefer using the right tool for the job"Go for Catalog, Laravel for Billing; shared standards from working code
6Decentralized data management"Microservices prefer letting each service manage its own database"Database per service, Polyglot Persistence, eventual consistency
7Infrastructure automation"we run lots of automated tests. Promotion of working software 'up' the pipeline means we automate deployment"CI/CD per service, infrastructure as code
8Design for failure"Any service call could fail due to unavailability of the supplier"Timeouts, circuit breakers, bulkheads, monitoring, chaos testing
9Evolutionary design"If you find yourself repeatedly changing two services together, that's a sign that they should be merged."Boundaries move; services are replaceable
text
     Characteristic missing          Symptom you will see
1    componentization                "we deploy the shared jar to all services"
2    business capabilities           a feature needs the UI, API and DB teams
3    products                        "the project ended; ops owns it now"
4    smart endpoints                 business rules inside the broker/ESB config
5    decentralized governance        architecture board approves every library
6    decentralized data              two services UPDATE the same table
7    automation                      "release night" for 20 services
8    design for failure              one slow dependency hangs every thread
9    evolutionary design             services nobody dares to merge or delete

Real scenario: a team audits its "microservices": characteristics 1, 5 and 7 present; 6 missing (one shared PostgreSQL), 8 missing (no timeouts). The audit explains its outages (one slow query locks everyone) and its release trains (schema changes need all teams). The fix order follows: data ownership first, timeouts second.

How to use it: score each service against the nine on a 0-2 scale once a quarter; the lowest scores are your next architecture work items.

Independent deployability (the real test) Must-know ​

In plain words: can this team ship this service to production today, without asking another team and without anyone else shipping at the same time?

Common misunderstanding: "Separate repositories mean independent deployment." You can have twenty repositories and still need a coordinated release, because of a shared database, a shared library with domain types, or a breaking API change.

Definition: Lewis and Fowler: "One main reason for using services as components (rather than libraries) is that services are independently deployable." They also note the limit: "some changes will change service interfaces resulting in some coordination, but the aim of a good microservice architecture is to minimize these through cohesive service boundaries and evolution mechanisms in the service contracts." Richardson lists the matching force: "Team autonomy - a team needs to be able to develop, test and deploy their software independently of other teams."

text
     Billing adds a field "tax_cents" to its charge response
1    Billing deploys v2 (adds field; old fields unchanged)     consumers keep working (tolerant reader)
2    Orders deploys later, starts reading tax_cents            no lock-step
     --- versus a lock-step change ---
1    Billing renames amount_cents -> amount                    Orders breaks immediately
2    "release both on Tuesday at 22:00"                        distributed monolith behaviour

Real scenario: DORA's deployment frequency metric ("The number of deployments over a given period or the time between deployments") is the measurement; if Billing's deployment frequency is bounded by Orders' release calendar, the services are not independent. Other signals: a shared common-models library bumped in every service each sprint; integration environments that must hold the matching version of every service.

What provides it:

MechanismExample
Backward-compatible API changesAdd fields, never rename; Tolerant Reader
Consumer-driven contract tests in the provider's pipelinePact, Spring Cloud Contract, this page's Go contract test
Owned dataNo other service reads billing_db
One pipeline per serviceBuild, test, deploy only what changed
Feature flags, expand-and-contractShip code dark, switch on later
Deployment strategiesRolling update, blue/green, canary

How to use it: add a rule to your definition of done: "this change can be deployed alone". If it cannot, the pull request must say why and which expand-and-contract steps follow.

Granularity: disintegrators and integrators Must-know ​

In plain words: there are good reasons to split a service and good reasons to keep things together; the right size is where the two balance.

Common misunderstanding: "Smaller is always better." Ford, Richards and co-authors: "One common mistake many development teams make is focusing too much on granularity disintegrators while ignoring granularity integrators."

Definition: Software Architecture: The Hard Parts, chapter 7. Disintegrators answer "When should I consider breaking apart a service into smaller parts?"; integrators answer "When should I consider putting services back together?" The book's two summary tables:

Disintegrator (split)Question the book asksReason given in Table 7-2
Service scope and functionIs the service doing too many unrelated things?Single-purpose services with tight cohesion
Code volatilityAre changes isolated to only one part of the service?Agility (reduced testing scope and deployment risk)
Scalability and throughputDo parts of the service need to scale differently?Lower costs and faster responsiveness
Fault toleranceAre there errors that cause critical functions to fail within the service?Better overall uptime
SecurityDo some parts of the service need higher security levels than others?Better security access control to certain functions
ExtensibilityIs the service always expanding to add new contexts?Agility (ease of adding new functionality)
Integrator (keep together)Reason given in Table 7-3
Database transactionsData integrity and consistency
Workflow (and choreography)Fault tolerance, performance, and reliability
Shared codeMaintainability
Data relationshipsData integrity and correctness
text
     Notifications: SMS + email + postal letter in one service?
1    scope: one job ("notify the customer")                 -> keep (integrator wins)
2    volatility: postal letter rules change monthly          -> consider splitting letter out
3    scalability: email 1,000/min, letters 50/day            -> split email out?
4    workflow: one notification fans out to all three        -> splitting adds calls
     Decision: one Notifications service; revisit if letter volatility persists

Real scenario: the book's own example is a Notification Service doing SMS, email and postal letters; another is a payment service where splitting by payment method improves extensibility but slows orders paid with several methods. In our ordering platform, Catalog and Pricing were kept together (prices are read with products in every request, a workflow integrator), while Billing was split out (security disintegrator: PCI scope; volatility: payment providers change).

How to use it: write the trade-off as a sentence for the product owner, the book's suggested form: "We want to break apart our service to isolate frequent code changes, but in doing so we won't be able to maintain a database transaction. Which is more important...?" The detailed method for drawing boundaries lives in Service Boundaries and Bounded Context.

Team topology: Conway, two-pizza, stream-aligned Important ​

In plain words: your services will copy your org chart; so draw the org chart you want the services to have.

Common misunderstanding: "Architecture is a technical decision; teams are an HR decision." Conway's Law (quoted by Lewis and Fowler): "Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure." Splitting services without splitting ownership gives you services that everyone edits.

Definition:

IdeaSource (quoted)Use
Two-pizza teamAWS whitepaper quoting Bezos: "We try to create teams that are no larger than can be fed by two pizzas"Upper bound of a service-owning team (Lewis and Fowler: "no more than a dozen people")
Inverse Conway ManeuverFowler, Microservice Premium: organisations "deliberately split themselves into small, loosely coupled groups in order to push the software into a similar modular structure"Change the teams first, the code follows
Stream-aligned teamTeam Topologies: "aligned to a flow of work from (usually) a segment of the business domain"Owns one or a few services end to end
Platform teamTeam Topologies: provides "a compelling internal product to accelerate delivery by Stream-aligned teams"Owns the paved road: CI/CD, observability, mesh
Enabling, complicated-subsystem teamsTeam Topologies key conceptsCoaching; specialist components (e.g. pricing engine)
text
     Org                                   Services you will get
1    UI team, API team, DB team            three layers that every feature crosses
2    Checkout team, Catalog team,          Checkout, Catalog, Billing services
     Billing team + platform team          plus a shared platform (CI, tracing, mesh)

Real scenario: Uber's DOMA post describes teams building code inside each other's services and modifying each other's data models (paraphrased; we read the post through a fetch tool, see References); DOMA answered by grouping services into domains behind gateways. Amazon's two-pizza teams own services and run them ("you build, you run it", as Lewis and Fowler cite it).

How to use it: one service has exactly one owning team (written in CODEOWNERS and the service catalogue); one team may own several services. If a service has two owners, merge the teams or split the service. Detail: Service Boundaries.

The microservice premium and the prerequisites Must-know ​

In plain words: microservices cost extra effort every day; pay it only when the system is too complex for one deployable, and only after you can provision, monitor and deploy quickly.

Common misunderstanding: "We will add monitoring and CI later, once the services exist." Fowler: "if you don't have certain baseline competencies, you shouldn't consider using the microservice style."

Definition: Microservice Premium: "When you use microservices you have to work on automated deployment, monitoring, dealing with failure, eventual consistency, and other factors that a distributed system introduces." His guideline: "don't even consider microservices unless you have a system that's too complex to manage as a monolith." Monolith First: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up". The prerequisites (Fowler, 2014): rapid provisioning, basic monitoring, rapid application deployment, and a DevOps culture; beyond a handful of services, tracing business transactions across services and full continuous delivery.

PrerequisiteMinimum barTool examples
Rapid provisioning"fire up a new server in a matter of hours" (Fowler)Terraform, Kubernetes namespaces, a service template
Basic monitoringErrors, availability and business metrics ("a drop in orders")Prometheus, Grafana, alerting on SLOs
Rapid deploymentA pipeline "that can execute in no more than a couple of hours"GitHub Actions, GitLab CI, Argo CD
DevOps cultureDevelopers in incident response and root causeOn-call rota per service
Distributed tracing (beyond a handful)"trace business transactions through multiple services"OpenTelemetry, Jaeger, Tempo
A platformPaved road for new servicesService template, chassis, mesh
text
     Premium over time (illustrative)
1    month 1     monolith: 1 pipeline, 1 dashboard          productive at once
2    month 1     microservices: 4 pipelines, tracing, mesh  weeks of platform work first
3    year 2      monolith with 60 devs: merge queue, risky  premium now worth paying
4    year 2      microservices: teams ship daily            if the prerequisites exist

Real scenario: Fowler names the drivers that justify the premium: "dealing with large teams, multi-tenancy, supporting many user interaction models, allowing different business functions to evolve independently, and scaling", and above all "sheer size". The Prime Video monitoring tool shows the other side: for one team with one data-heavy pipeline, distribution added cost (S3 round-trips for every frame, many Step Functions state transitions) without benefit.

How to use it: before the first split, the platform must provide in one command: a new service with CI/CD, health endpoints, logs, metrics and traces wired. Decision method: Monolith vs Microservices vs Modular Monolith.

Cross-cutting concerns: chassis, sidecar, service mesh Important ​

In plain words: every service needs the same plumbing (auth, logs, traces, metrics, health, config, secrets); build it once and reuse it, either as a library inside the service or as a proxy next to it.

Common misunderstanding: "Each team should write its own plumbing; that is decentralized governance." Decentralized governance is about choosing tools; reimplementing token validation twenty times is how security holes appear. Lewis and Fowler call the shared tooling "Make it easy to do the right thing".

Definition: microservices.io lists the cross-cutting concerns a microservice chassis handles: "Security", "Externalized configuration", "Logging", "Health check", "Metrics" and "Distributed tracing". The out-of-process answer is the sidecar: "Implement cross-cutting concerns in a sidecar process or container that runs alongside the service instance." A service mesh applies sidecars (or node proxies) to all traffic: "Use a service mesh that mediates all communication in and out of each service." In Istio, the data plane is "a set of intelligent proxies (Envoy) deployed as sidecars" and the control plane "manages and configures the proxies to route traffic".

ConcernIn-process (chassis library)Out-of-process (sidecar / mesh)
Service-to-service authGo middleware validating JWT; Laravel Sanctum auth:sanctummTLS between sidecars, identity per workload
Logginglog/slog JSON with trace_id; Laravel ContextLog shipper DaemonSet (Fluent Bit)
TracingOpenTelemetry SDK, otelhttpProxy spans (Envoy); app must still propagate headers
MetricsOpenTelemetry metrics, Prometheus clientProxy request metrics (golden signals)
Retries, timeouts, breakerIn client code (this page's resilience package)Mesh retry/timeout/outlier-detection policy
ConfigEnv vars, 12-factorConfigMaps, feature-flag service
SecretsRead from file/env at startSecret store (Vault, Kubernetes Secrets, cloud KMS) mounted by the platform
Health/livez, /readyz; Laravel /upProbes run by the kubelet
text
     One call, with a mesh
1    orders process -> localhost:15001 (sidecar)       app speaks plain HTTP
2    sidecar -> mTLS -> catalog's sidecar               identity, encryption, retry policy, metrics
3    catalog sidecar -> catalog process                 app still receives traceparent
     Without a mesh, steps 1-3 are a direct HTTP call and the chassis does the work.

Real scenario: a company with Go, PHP and Java services adopts a mesh to get mTLS and uniform metrics without three libraries; a small team with four Go services keeps a chassis package (like internal/platform below) and no mesh.

How to use it: start with a chassis (cheap, debuggable); add a mesh when you have many languages, need mTLS everywhere, or a platform team to run it. Details in API Gateway, BFF & Service Mesh and Service Mesh & the Sidecar Pattern.

Data: database per service (summary) Must-know ​

In plain words: each service keeps its data private; others ask through the API or listen to events.

Common misunderstanding: "Database per service means a database server per service." microservices.io lists three options with the same privacy: "Private-tables-per-service", "Schema-per-service" and "Database-server-per-service", and notes the first two "have the lowest overhead".

Definition: "Keep each microservice’s persistent data private to that service and accessible only via its API." Consequences: no cross-service joins and no cross-service ACID transactions. Lewis and Fowler: "Distributed transactions are notoriously difficult to implement and as a consequence microservice architectures emphasize transactionless coordination between services, with explicit recognition that consistency may only be eventual consistency and problems are dealt with by compensating operations." The tools: a saga ("A saga is a reliably coordinated sequence of local transactions."), the transactional outbox, idempotent consumers, and CQRS read models for queries that span services. Each service may pick its own store: Polyglot Persistence. This page's example charges synchronously (Orders calls Billing and waits); the asynchronous alternative, where Billing reacts to OrderPlaced, is a saga:

text
     Checkout as a saga (orchestrated by Orders)
1    Orders: INSERT order (PENDING) + outbox OrderPlaced       local tx in orders_db
2    Billing: capture payment -> PaymentCaptured               local tx in billing_db
3    Orders: mark order CONFIRMED                              local tx
     Failure at 2: Billing emits PaymentFailed -> Orders marks CANCELLED (compensation)

How to use it: one owner per table, enforced by database credentials (each service's role can only see its schema; see the SQL in Mechanics). Brownfield options, shared-database migration and reporting: Data Ownership in Microservices and Data Patterns.

Communication: sync and async (summary) Important ​

In plain words: call synchronously only when you need the answer now; tell others asynchronously when they only need to know.

Common misunderstanding: "Turning method calls into HTTP calls is enough." Lewis and Fowler: "A naive conversion from in-memory method calls to RPC leads to chatty communications which don't perform well." And: "Any time you have a number of synchronous calls between services you will encounter the multiplicative effect of downtime."

Definition: two dominant styles, per the 2014 article: "HTTP request-response with resource API's and lightweight messaging". In our example, Orders calls Catalog synchronously (the price is needed to accept the order) and informs Notifications asynchronously (the customer can get the email a second later). The Guardian's rule, quoted in the article: "one synchronous call per user request".

NeedStyleExample in the ordering platform
Answer needed to continueSync request-response (HTTP/JSON, gRPC)Orders reads price from Catalog
Others must react, caller need not waitAsync event (RabbitMQ, Kafka)OrderPlaced.v1 to Notifications
Long multi-step business processSaga over messagesOrder, payment, shipment
Many reads of another service's dataReplicated read model via eventsOrders keeps a price snapshot

Contracts, idempotency keys, retries and the choice of protocol are taught in Service Communication; request-reply over a broker in Request-Reply.

Resilience: design for failure (summary) Must-know ​

In plain words: every remote call needs a deadline, a limited retry, a breaker that stops calling a dead dependency, and a plan for what the user sees.

Common misunderstanding: "Our services have 99.99% availability each, so the system does too." Netflix's Hystrix wiki does the arithmetic for an application with 30 dependencies at 99.99% each: 99.7% uptime, "2+ hours downtime/month even if all dependencies have excellent uptime."

Definition: the stability patterns Lewis and Fowler cite from Nygard's Release It!: Circuit Breaker, Bulkhead and Timeout. Fowler's CircuitBreaker: "You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all." Hystrix adds fallbacks and isolation "such as bulkhead, swimlane, and circuit breaker patterns".

text
     Catalog dies; Orders' client: 300 ms per try, 2 tries, breaker threshold 5, cooldown 10 s
1    req1: try1 refused, try2 refused                 failures=2   503 (6 ms)
2    req2: try1, try2 refused                         failures=4   503
3    req3: try1 refused -> failures=5 -> OPEN          503 (13 ms)
4    req4: breaker open, no network call               503 in 0.5 ms, Retry-After: 10
5    +10 s: half-open, one trial call                  success -> CLOSED; failure -> OPEN again

The numbers are from this page's lab. Each pattern has its own chapter: Timeouts, Retries & Jitter, Circuit Breaker, Bulkheads & Graceful Degradation, Cascading Failures, Chaos Engineering.

Observability: logs, metrics, traces, correlation IDs Must-know ​

In plain words: when one click touches five services, you need one ID that follows the click everywhere, and every service must log, count and time with that ID.

Common misunderstanding: "Centralised logs are enough." Logs from five services without a shared ID are five haystacks. Uber's DOMA post makes the same point: without the right tools you cannot see what is happening, so debugging becomes difficult (paraphrased).

Definition: three signals: logs (events, structured JSON), metrics (aggregated numbers: rate, errors, duration) and traces (the causal tree of spans of one request). Propagation uses the W3C Trace Context header: "traceparent describes the position of the incoming request in its trace graph in a portable, fixed-length format", for example traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01 (version, trace-id, parent-id, flags). OpenTelemetry is the vendor-neutral SDK and protocol (OTLP) to produce all three; in Go, otelhttp.NewHandler and otelhttp.NewTransport create and propagate spans. A correlation ID is a business-level request ID (here X-Correlation-ID) that you also log; Lewis and Fowler add semantic monitoring of business metrics ("how many orders per minute are received").

ordersorders clientcatalogorders (db)notificationsPOST /orders (server span, root of 9fff83...)HTTP GET (client)GET /productsorder+outboxPOST /events (async)traceparent: 00-9fff83...-<span>-01traceparent saved in the outbox rowt = 0 msrelay tick, t = 1 sEvery log line: "trace_id":"9fff83...", "correlation_id":"lab-1" (grep one ID, see all three services)

The picture is the real trace from the lab: one trace ID across Orders, Catalog and, one second later through the outbox, Notifications.

SignalGo in this pageLaravel in this pageBackend examples
Traceotelhttp handler + transport, W3C propagatortraceparent stored in Context and forwardedJaeger, Tempo, Zipkin, vendor APMs
Logslog JSON with trace_id, correlation_idContext::add(...) adds fields to every log lineLoki, Elasticsearch
MetricOpenTelemetry meter or Prometheus clientPulse, Prometheus exporterPrometheus, Mimir
Health/livez, /readyz/up + DiagnosingHealth listenerKubernetes probes

Async hops lose the trace unless you carry it: the Go relay stores traceparent in the outbox row and restores it when publishing. Depth: Observability, Messaging Observability.

Testing: unit, component, contract, end-to-end Must-know ​

In plain words: test each service alone, fast and thoroughly; test the agreements between services with contract tests; keep slow end-to-end tests few.

Common misunderstanding: "We need a full environment with all 40 services to test anything." microservices.io: "End to end testing (i.e. tests that launch multiple services) is difficult, slow, brittle, and expensive."

Definition: Clemson's deck (Fowler's site, 2014; we read its agenda) is organised as unit, integration, component, contract and end-to-end testing. In the usual reading, a component test exercises one service in isolation with its collaborators replaced by test doubles, and a contract test checks the shape of one integration. Pact: "Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a "contract"." In consumer-driven contracts, the consumer writes the expectations and the provider's pipeline runs them; Pact notes that "any provider behaviour not used by current consumers is free to change without breaking tests."

LayerScopeSpeedIn this page
UnitOne function or classmsbreaker_test.go
IntegrationOne adapter vs a real dependency (DB, broker)sTestcontainers (not shown)
ComponentOne service, dependencies fakedsLaravel feature test with PaymentProvider mocked
ContractOne consumer-provider pairms to scontract_test.go (Go), ChargeContractTest.php (Laravel)
End-to-endThe whole systemminutesA few smoke journeys only, plus the lab
text
     Consumer-driven contract flow (Orders -> Catalog)
1    Orders team writes testdata/orders-gets-product.json     expectation
2    Orders CI: consumer test decodes the contract response    Orders understands it
3    Catalog CI: provider test replays the request on the real handler
4    Catalog renames price_cents -> price                      provider test fails in Catalog's CI
5    Nothing reached production; no shared environment needed

How to use it: a test pyramid per service plus a contract per integration. Messaging contracts: Testing Messaging Systems.

Deployment: containers, Kubernetes, rolling, blue/green, canary Important ​

In plain words: package each service as an image, let an orchestrator run copies of it, and replace old copies with new ones gradually, with a quick way back.

Common misunderstanding: "Kubernetes gives us microservices." Newman's book page: seeing teams "flock to Kubernetes in the hope that it would solve all their issues with microservice architectures" gave him pause. Kubernetes runs containers; it does not fix boundaries or data ownership.

Definition:

StrategyDefinition (source)Kubernetes / tooling
Rolling updateReplace pods gradually; defaults "25% max unavailable, 25% max surge" (Kubernetes docs)Deployment strategy: RollingUpdate, maxUnavailable, maxSurge
Blue/green"two production environments, as identical as possible"; switch the router; "rapid way to rollback" (Fowler)Two Deployments, switch the Service selector
Canary"slowly rolling out the change to a small subset of users before rolling it out to the entire infrastructure" (Sato on Fowler's site)Two Deployments with weights; mesh or Argo Rollouts
Probes"Liveness probes determine when to restart a container"; readiness stops traffic to pods not ready (Kubernetes docs)livenessProbe, readinessProbe, startupProbe
text
     Rolling update of orders 1.4.1 -> 1.4.2, replicas 3, maxUnavailable 0, maxSurge 1
1    start pod 1.4.2 #1                     startupProbe until /livez answers
2    readinessProbe /readyz ok              Service sends traffic to it
3    stop one 1.4.1 pod: SIGTERM             our Serve(): /readyz -> 503, sleep 2 s, Shutdown drains
4    repeat until 3 x 1.4.2                  never fewer than 3 ready pods
yaml
# Orders on Kubernetes: rolling update with zero unavailable pods, and
# probes wired to the endpoints in internal/platform/health.go.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders
  labels: { app: orders }
spec:
  replicas: 3
  selector:
    matchLabels: { app: orders }
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxUnavailable: 0, maxSurge: 1 }
  template:
    metadata:
      labels: { app: orders, version: "1.4.2" }
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: orders
          image: registry.example.com/orders:1.4.2
          ports: [{ containerPort: 8080 }]
          env:
            - { name: CATALOG_URL, value: "http://catalog:8081" }
            - { name: NOTIFICATIONS_URL, value: "http://notifications:8082" }
            - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: "http://otel-collector:4318" }
          startupProbe:
            httpGet: { path: /livez, port: 8080 }
            failureThreshold: 30
            periodSeconds: 1
          livenessProbe:
            httpGet: { path: /livez, port: 8080 }
            periodSeconds: 10
          readinessProbe:
            httpGet: { path: /readyz, port: 8080 }
            periodSeconds: 2
          resources:
            requests: { cpu: 100m, memory: 64Mi }
            limits: { memory: 256Mi }

Depth: Containers & Kubernetes. For deployment frequency as a measure, DORA's five metrics are change lead time, deployment frequency, failed deployment recovery time, change fail rate and deployment rework rate; DORA says they "are best suited for measuring one application or service at a time".

Versioning and compatibility Must-know ​

In plain words: change APIs so that old callers keep working; add, do not rename; remove only after every caller has moved.

Common misunderstanding: "Put /v2/ in the URL whenever anything changes." Lewis and Fowler: "the preference in the microservice world is to only use versioning as a last resort. We can avoid a lot of versioning by designing services to be as tolerant as possible to changes in their suppliers."

Definition: Tolerant Reader (Fowler, 2011), built on Postel's Law: "be conservative in what you do, be liberal in what you accept from others." Consumers read only the fields they need and ignore the rest; providers make additive changes. When a breaking change is unavoidable: expand (add the new field or endpoint), migrate consumers (contract tests tell you who), contract (remove the old one). Google's HotOS paper names the cost when this fails: "C4: It freezes APIs. Once a microservice establishes an API, it becomes hard to change without breaking the other services that consume the API."

ChangeSafe?How
Add an optional response fieldYesConsumers that are tolerant readers ignore it (Go json.Decoder ignores unknown fields by default)
Add an optional request field with a defaultYesProvider treats missing as default
Rename or remove a fieldNoExpand-and-contract; dual-write both names for a while
Change a field's meaning or unitNoNew field (amount_minor), never reuse a name
Make an optional request field requiredNoNew endpoint or version
Event schema changeDependsMessage design & schema evolution

Depth: API Versioning & Evolution.

Anti-patterns: distributed monolith and friends Must-know ​

In plain words: most failed microservice projects have services, but not independence.

Common misunderstanding: "If it is split into services, it is microservices." The Google paper lists what goes wrong even in well-run organisations: "C1: It hurts performance", "C2: It hurts correctness", "C3: It is hard to manage", "C4: It freezes APIs", "C5: It slows down application development."

Definition:

Anti-patternDefinitionDetect it byFix
Distributed monolithServices that must be built, tested or released togetherRelease trains; "deploy order" documentsRestore independence (contracts, owned data) or merge
Shared databaseSeveral services read and write the same tablesTwo services in pg_stat_activity on the same tableOne owner; API or events; Data ownership
Chatty servicesFine-grained calls per requestTraces with dozens of spans for one pageCoarser APIs, API composition, read models
NanoservicesServices so small that overhead exceeds valueMore YAML than code; services always changed togetherMerge by cohesion (integrators)
Entity servicesOne service per noun doing CRUDEvery use case calls 5 entity servicesCut by capability (Service Boundaries)
Shared domain libraryA common jar/package with domain typesOne library bump redeploys everythingShare only technical code; duplicate small DTOs
Synchronous call chainsA calls B calls C calls DLatency = sum; availability = productAsync events, local copies, one sync call per request
Microservice envyStyle chosen for fashionNo team, scale or domain reasonMonolith first
text
     Distributed monolith in a trace
1    GET /checkout -> orders -> catalog -> pricing -> tax -> currency    5 sync hops
2    each hop 99.9% available                                            0.999^5 = 99.5%
3    each hop p99 120 ms                                                 p99 adds up, ~600 ms
4    pricing schema change                                               orders, tax, currency redeploy

Roles of the four services together ​

API gatewayOrders (Go)chi + OpenTelemetryCatalog (Go)products, pricesBilling (Laravel)Octane + SanctumNotificationsemail, SMSorders_db+ outboxcatalog_dbbilling_dbnotif_db + inboxMessage bus (RabbitMQ / Kafka): OrderPlaced.v1GET /products/:skusync, 300 ms, breakerPOST /chargestoken + idem. keyrelay publishesRule: a service reads onlyits own database; everythingelse goes through an APIor an event.consume

The picture is the worked example. Orders calls Catalog (sync, guarded) and Billing (sync, machine token, idempotency key), stores its order and an outbox row in its own database, and publishes OrderPlaced.v1; Notifications consumes it with an inbox (dedup). No arrow points into another service's database.

ServiceOwnsExposesCallsStack
Ordersorders, outboxPOST /ordersCatalog (sync), Billing (sync), bus (async)Go, chi, OpenTelemetry
Catalogproducts, pricesGET /products/{sku}nothingGo, chi
BillingchargesPOST /api/charges (Sanctum ability charges:create)payment providerLaravel 13, Octane, Sanctum
Notificationssent messages, inboxconsumes OrderPlaced.v1email/SMS providersGo in the lab

Mechanics ​

Anatomy of one service ​

PartGo (this page)Laravel (this page)
Routerchi (chi.NewRouter, chi.URLParam)routes/api.php
Server processnet/http Server, ReadHeaderTimeoutOctane on FrankenPHP (also RoadRunner, Swoole)
Health/livez, /readyz/up (200 when booted) + DiagnosingHealth event
Graceful shutdownsignal.NotifyContext, unready, ShutdownOctane worker stop; Kubernetes preStop
Inbound authmTLS or JWT middleware (not shown)auth:sanctum + abilities:charges:create
Outbound clienthttp.Client + otelhttp.NewTransport, timeout, retry, breakerHttp::timeout()->connectTimeout()->retry()
TelemetryOpenTelemetry SDK, OTLP exporterContext fields, traceparent forwarded
DataOwn schema and roleOwn database and migration

The database-level boundary ​

Ownership is enforced, not promised: each service connects with a role that can see only its schema. The outbox lives in the same database as the orders, so one local transaction writes both (PostgreSQL syntax):

sql
-- One PostgreSQL cluster, one schema and one login role per service.
CREATE SCHEMA orders;   CREATE ROLE orders_svc  LOGIN PASSWORD 'from-secret-store';
CREATE SCHEMA catalog;  CREATE ROLE catalog_svc LOGIN PASSWORD 'from-secret-store';
GRANT USAGE, CREATE ON SCHEMA orders  TO orders_svc;
GRANT USAGE, CREATE ON SCHEMA catalog TO catalog_svc;
REVOKE ALL ON SCHEMA catalog FROM orders_svc;   -- Orders reads prices via the API only

CREATE TABLE orders.orders (
  id           uuid PRIMARY KEY,
  customer_id  text   NOT NULL,
  sku          text   NOT NULL,
  qty          int    NOT NULL CHECK (qty > 0),
  price_cents  bigint NOT NULL,           -- snapshot copied from Catalog at order time
  total_cents  bigint NOT NULL,
  currency     char(3) NOT NULL,
  status       text   NOT NULL DEFAULT 'PENDING'
);
CREATE TABLE orders.outbox (
  id           uuid PRIMARY KEY,
  type         text NOT NULL,             -- 'OrderPlaced.v1'
  payload      jsonb NOT NULL,
  traceparent  text,                      -- keeps the trace across the async hop
  created_at   timestamptz NOT NULL DEFAULT now(),
  published_at timestamptz
);
BEGIN;
INSERT INTO orders.orders (id, customer_id, sku, qty, price_cents, total_cents, currency)
VALUES ('9727e043-8486-e0fe-e67f-d0c58d9f590e', 'c-42', 'sku-1', 2, 1299, 2598, 'EUR');
INSERT INTO orders.outbox (id, type, payload, traceparent)
VALUES ('72c17966-c8d9-baf5-8159-08985f2adf02', 'OrderPlaced.v1',
        '{"order_id":"9727e043","total_cents":2598}', '00-79fb3fa75555fc8ac1b7425491632b9c-0102030405060708-01');
COMMIT;

MySQL has no schemas separate from databases, so use one database per service and GRANT ... ON orders_db.*; MongoDB uses one database per service with role-based access. The relay that reads outbox is in Transactional Outbox.

The knobs ​

KnobWhereDefaultThis page usesWhy
http.Client.TimeoutGo net/http0 (no timeout)per-try context.WithTimeout 300 msNever wait forever on a dependency
http.Server.ReadHeaderTimeoutGo net/http05 sSlowloris protection
Retry attempts / baseresilience.Retryn/a2 tries, 50 ms full jitterRetry only idempotent reads
Breaker threshold / cooldownresilience.Breakern/a5 failures / 10 sFail fast while a dependency is down
Http::timeout()Laravel HTTP client30 s3 sDocs: "By default, the HTTP client will timeout after 30 seconds"
Http::connectTimeout()Laravel HTTP client10 s1 sDetect dead hosts fast
Http::retry()Laravel HTTP clientno retry[100, 300] ms, only on ConnectionExceptionNever retry a capture without an idempotency key
Sanctum expirationconfig/sanctum.phpnull (never)30 days per machine tokenRotate; sanctum:prune-expired cleans up
maxUnavailable / maxSurgeKubernetes Deployment25% / 25%0 / 1Never drop below capacity during rollout
readinessProbe.periodSecondsKubernetes10 s2 sDrain delay in Serve must exceed it
terminationGracePeriodSecondsKubernetes Pod30 s30 sLonger than drain + in-flight requests
--max-requestsOctane500500Recycle workers to contain memory leaks

Error codes and messages you will actually see ​

WhereMessage or codeMeaningRetry?
Go clientdial tcp [::1]:18081: connect: connection refusedNothing listening (service down)Yes, bounded; then breaker
Go clientcontext deadline exceededPer-try timeout hit (slow dependency)Yes if idempotent
This pagecircuit breaker is openFail fast, no network callNo (wait for cooldown)
HTTP503 + Retry-AfterDependency unavailable or breaker openYes, after the delay
HTTP504 Gateway TimeoutGateway or mesh gave up on upstreamMaybe; check idempotency
HTTP429 Too Many RequestsRate limitedYes, after Retry-After
HTTP409 ConflictIdempotency key reused with a different body, or state conflictNo
HTTP401 / 403Missing token / token lacks ability (Sanctum abilities middleware)No
LaravelIlluminate\Http\Client\ConnectionExceptionTimeout or connection failureYes (this page's when callback)
LaravelIlluminate\Http\Client\RequestExceptionAll retries failed with 4xx/5xxNo more
KubernetesReadiness probe failed: HTTP probe failed with statuscode: 503Pod removed from Service endpointsAutomatic
KubernetesCrashLoopBackOffLiveness or startup keeps failing; restarts back offFix the cause

Go ​

The worked example: an ordering platform split into Orders, Catalog, Billing and Notifications. The Go module at docs/snippets/architecture/microservices-architecture/go holds Orders, Catalog and Notifications; Billing is the Laravel service in the next section. gofmt -l ., go vet ./... and go test ./... pass. One Go module for three services is a lab convenience: in production each service has its own repository or module, its own go.mod, image and pipeline, so it can be released alone.

The chassis: tracing, correlation, health, shutdown ​

Every service imports the same small package. Tracing installs the W3C propagator and, when OTEL_EXPORTER_OTLP_ENDPOINT is set, an OTLP/HTTP exporter (Jaeger in the compose file):

go
// Package platform is the small "microservice chassis" every service in the
// lab shares: tracing, correlation IDs, structured logs, health and shutdown.
package platform

import (
	"context"
	"os"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

// SetupTracing installs a global TracerProvider and the W3C Trace Context
// propagator (traceparent/tracestate headers). Without a collector the
// provider still creates trace IDs, so logs can be correlated; with
// OTEL_EXPORTER_OTLP_ENDPOINT set (e.g. http://jaeger:4318) spans are
// exported over OTLP/HTTP.
func SetupTracing(ctx context.Context, service string) (func(context.Context) error, error) {
	res, err := resource.New(ctx, resource.WithAttributes(attribute.String("service.name", service)))
	if err != nil {
		return nil, err
	}
	opts := []sdktrace.TracerProviderOption{
		sdktrace.WithResource(res),
		sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
	}
	if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
		exp, err := otlptracehttp.New(ctx) // reads the standard OTEL_* env vars
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithBatcher(exp))
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{}, propagation.Baggage{},
	))
	return tp.Shutdown, nil
}

One JSON log line per request, with trace_id and correlation_id; an outbound transport that forwards the correlation ID:

go
package platform

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

	"go.opentelemetry.io/otel/trace"
)

// HeaderCorrelationID is the business-level request ID that travels with
// every call (the trace ID is the technical one; we log both).
const HeaderCorrelationID = "X-Correlation-ID"

type ctxKey struct{}

// CorrelationID returns the ID stored in ctx, or "".
func CorrelationID(ctx context.Context) string {
	id, _ := ctx.Value(ctxKey{}).(string)
	return id
}

// WithCorrelationID stores id in ctx.
func WithCorrelationID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

// NewID returns 16 random bytes, hex encoded.
func NewID() string {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	return hex.EncodeToString(b)
}

// TraceID returns the current trace ID or "".
func TraceID(ctx context.Context) string {
	sc := trace.SpanContextFromContext(ctx)
	if !sc.IsValid() {
		return ""
	}
	return sc.TraceID().String()
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}

// AccessLog accepts or creates the correlation ID, echoes it back, and
// writes one structured log line per request with trace_id and correlation_id.
// Mount it inside otelhttp.NewHandler so the server span is already in ctx.
func AccessLog(log *slog.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			id := r.Header.Get(HeaderCorrelationID)
			if id == "" {
				id = NewID()
			}
			ctx := WithCorrelationID(r.Context(), id)
			w.Header().Set(HeaderCorrelationID, id)
			rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
			start := time.Now()
			next.ServeHTTP(rec, r.WithContext(ctx))
			log.InfoContext(ctx, "http",
				"method", r.Method, "path", r.URL.Path, "status", rec.status,
				"duration_ms", time.Since(start).Milliseconds(),
				"trace_id", TraceID(ctx), "correlation_id", id)
		})
	}
}

// CorrelationTransport copies the correlation ID from the request context to
// the outgoing request. Wrap it with otelhttp.NewTransport for traceparent.
type CorrelationTransport struct{ Base http.RoundTripper }

// RoundTrip implements http.RoundTripper.
func (t CorrelationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	if id := CorrelationID(r.Context()); id != "" && r.Header.Get(HeaderCorrelationID) == "" {
		r = r.Clone(r.Context())
		r.Header.Set(HeaderCorrelationID, id)
	}
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	return base.RoundTrip(r)
}

Liveness and readiness are different questions; readiness checks only what the service owns:

go
package platform

import (
	"context"
	"encoding/json"
	"net/http"
	"sync/atomic"
	"time"
)

// Check verifies one dependency the service OWNS (its database, its broker
// connection). Never put another service here: a readiness probe that calls
// downstream services turns one outage into a fleet-wide one.
type Check func(ctx context.Context) error

// Health serves /livez (process alive) and /readyz (may receive traffic).
type Health struct {
	ready  atomic.Bool
	checks map[string]Check
}

// NewHealth returns a Health that is not ready until SetReady(true).
func NewHealth(checks map[string]Check) *Health {
	return &Health{checks: checks}
}

// SetReady flips readiness (false during startup and graceful shutdown).
func (h *Health) SetReady(v bool) { h.ready.Store(v) }

// Live answers 200 while the process can serve HTTP at all.
func (h *Health) Live(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("ok\n"))
}

// Ready answers 200 only when started, not draining, and own checks pass.
func (h *Health) Ready(w http.ResponseWriter, r *http.Request) {
	result := map[string]string{}
	status := http.StatusOK
	if !h.ready.Load() {
		status = http.StatusServiceUnavailable
		result["lifecycle"] = "not ready"
	}
	ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
	defer cancel()
	for name, check := range h.checks {
		if err := check(ctx); err != nil {
			status = http.StatusServiceUnavailable
			result[name] = err.Error()
			continue
		}
		result[name] = "ok"
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(result)
}

Graceful shutdown: unready first, wait for the probe period, then drain:

go
package platform

import (
	"context"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"time"
)

// Serve runs srv until ctx is cancelled (SIGTERM from Docker or Kubernetes),
// then marks the service unready, waits for load balancers to notice, and
// drains in-flight requests.
func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, h *Health, drainDelay time.Duration) error {
	ln, err := net.Listen("tcp", srv.Addr) // fail before claiming readiness
	if err != nil {
		return err
	}
	errc := make(chan error, 1)
	go func() { errc <- srv.Serve(ln) }()
	h.SetReady(true)
	log.Info("listening", "addr", srv.Addr)
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	h.SetReady(false)
	time.Sleep(drainDelay) // readiness probe period: stop new traffic first
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	log.Info("stopped")
	return nil
}

Resilience: breaker and retry ​

go
// Package resilience holds the two client-side stability patterns the lab
// needs: a circuit breaker and retries with jittered backoff.
package resilience

import (
	"errors"
	"sync"
	"time"
)

// ErrOpen is returned without calling the dependency while the breaker is open.
var ErrOpen = errors.New("circuit breaker is open")

// State of a Breaker.
type State int

// Breaker states.
const (
	Closed State = iota
	Open
	HalfOpen
)

func (s State) String() string {
	switch s {
	case Open:
		return "open"
	case HalfOpen:
		return "half-open"
	default:
		return "closed"
	}
}

// Breaker trips after Threshold consecutive failures, rejects calls for
// Cooldown, then lets exactly one trial call through (half-open).
type Breaker struct {
	Threshold int
	Cooldown  time.Duration
	Now       func() time.Time // injectable clock for tests

	mu       sync.Mutex
	state    State
	failures int
	openedAt time.Time
	trial    bool
}

// NewBreaker returns a closed breaker.
func NewBreaker(threshold int, cooldown time.Duration) *Breaker {
	return &Breaker{Threshold: threshold, Cooldown: cooldown, Now: time.Now}
}

// State reports the current state (for logs and metrics).
func (b *Breaker) State() State {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.state
}

// Do runs fn unless the breaker is open.
func (b *Breaker) Do(fn func() error) error {
	if err := b.before(); err != nil {
		return err
	}
	err := fn()
	b.after(err)
	return err
}

func (b *Breaker) before() error {
	b.mu.Lock()
	defer b.mu.Unlock()
	switch b.state {
	case Open:
		if b.Now().Sub(b.openedAt) < b.Cooldown {
			return ErrOpen
		}
		b.state = HalfOpen
		b.trial = true
		return nil
	case HalfOpen:
		if b.trial {
			return ErrOpen // one trial call at a time
		}
		b.trial = true
	}
	return nil
}

func (b *Breaker) after(err error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	if err == nil {
		b.state, b.failures, b.trial = Closed, 0, false
		return
	}
	b.failures++
	if b.state == HalfOpen || b.failures >= b.Threshold {
		b.state, b.openedAt, b.trial = Open, b.Now(), false
	}
}
go
package resilience

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

type permanent struct{ err error }

func (p permanent) Error() string { return p.err.Error() }
func (p permanent) Unwrap() error { return p.err }

// Permanent marks an error that must not be retried (4xx, open breaker).
func Permanent(err error) error { return permanent{err} }

// Retry calls fn up to attempts times with "full jitter" exponential backoff
// (sleep a random duration in [0, base*2^n)). It stops early on a Permanent
// error or when ctx is done. Only retry idempotent operations.
func Retry(ctx context.Context, attempts int, base time.Duration, fn func(context.Context) error) error {
	var err error
	for n := 0; n < attempts; n++ {
		if err = fn(ctx); err == nil {
			return nil
		}
		var p permanent
		if errors.As(err, &p) {
			return p.err
		}
		if n == attempts-1 {
			break
		}
		sleep := time.Duration(rand.Int64N(int64(base) << n))
		select {
		case <-ctx.Done():
			return errors.Join(err, ctx.Err())
		case <-time.After(sleep):
		}
	}
	return err
}
go
package resilience

import (
	"errors"
	"testing"
	"time"
)

func TestBreakerOpensAndRecovers(t *testing.T) {
	now := time.Unix(0, 0)
	b := NewBreaker(3, 5*time.Second)
	b.Now = func() time.Time { return now }
	boom := errors.New("timeout")
	for i := 0; i < 3; i++ {
		_ = b.Do(func() error { return boom })
	}
	if b.State() != Open {
		t.Fatalf("want open, got %v", b.State())
	}
	called := false
	if err := b.Do(func() error { called = true; return nil }); !errors.Is(err, ErrOpen) || called {
		t.Fatalf("open breaker must fail fast without calling, err=%v called=%v", err, called)
	}
	now = now.Add(6 * time.Second) // cooldown elapsed: one trial call
	if err := b.Do(func() error { return nil }); err != nil {
		t.Fatalf("trial call: %v", err)
	}
	if b.State() != Closed {
		t.Fatalf("want closed after successful trial, got %v", b.State())
	}
}

func TestHalfOpenFailureReopens(t *testing.T) {
	now := time.Unix(0, 0)
	b := NewBreaker(1, time.Second)
	b.Now = func() time.Time { return now }
	_ = b.Do(func() error { return errors.New("x") })
	now = now.Add(2 * time.Second)
	_ = b.Do(func() error { return errors.New("still down") })
	if b.State() != Open {
		t.Fatalf("failed trial must reopen, got %v", b.State())
	}
}

Catalog: the provider and its client ​

Catalog owns products and publishes a representation, not its table. The client used by Orders combines a per-try timeout, retry and breaker, and reads tolerantly:

go
// Package catalog is the Catalog service: it owns products and prices.
// Other services read them only through this API, never from its database.
package catalog

import (
	"encoding/json"
	"net/http"
	"sync"
	"time"

	"github.com/go-chi/chi/v5"
)

// Product is the published representation (the contract), not the table row.
type Product struct {
	SKU        string `json:"sku"`
	Name       string `json:"name"`
	PriceCents int64  `json:"price_cents"`
	Currency   string `json:"currency"`
}

// Store is an in-memory stand-in for Catalog's private database.
type Store struct {
	mu       sync.RWMutex
	products map[string]Product
}

// NewStore returns a store seeded with products.
func NewStore(seed ...Product) *Store {
	s := &Store{products: map[string]Product{}}
	for _, p := range seed {
		s.products[p.SKU] = p
	}
	return s
}

func (s *Store) get(sku string) (Product, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	p, ok := s.products[sku]
	return p, ok
}

// Routes mounts the provider side of the contract. delay simulates a slow
// dependency (used by the lab to trigger client timeouts).
func Routes(r chi.Router, s *Store, delay func() time.Duration) {
	r.Get("/products/{sku}", func(w http.ResponseWriter, req *http.Request) {
		if d := delay(); d > 0 {
			select {
			case <-time.After(d):
			case <-req.Context().Done():
				return
			}
		}
		w.Header().Set("Content-Type", "application/json")
		p, ok := s.get(chi.URLParam(req, "sku"))
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			_ = json.NewEncoder(w).Encode(map[string]string{"error": "product_not_found"})
			return
		}
		_ = json.NewEncoder(w).Encode(p)
	})
}
go
package catalog

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"academy/microservices-architecture/internal/platform"
	"academy/microservices-architecture/internal/resilience"

	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

// ErrNotFound is the consumer-side meaning of a 404 from Catalog.
var ErrNotFound = errors.New("catalog: product not found")

// Client is the consumer side used by Orders. Every remote call has a
// per-attempt timeout, bounded retries with jitter, and a circuit breaker.
type Client struct {
	BaseURL    string
	HTTP       *http.Client
	Breaker    *resilience.Breaker
	PerTry     time.Duration
	Attempts   int
	RetryDelay time.Duration
}

// NewClient wires the defaults used in the lab.
func NewClient(baseURL string) *Client {
	return &Client{
		BaseURL: baseURL,
		HTTP: &http.Client{
			// otelhttp injects traceparent; CorrelationTransport adds X-Correlation-ID.
			Transport: otelhttp.NewTransport(platform.CorrelationTransport{}),
		},
		Breaker:    resilience.NewBreaker(5, 10*time.Second),
		PerTry:     300 * time.Millisecond,
		Attempts:   2,
		RetryDelay: 50 * time.Millisecond,
	}
}

// GetProduct is a safe, idempotent read, so retrying it is allowed.
func (c *Client) GetProduct(ctx context.Context, sku string) (Product, error) {
	var p Product
	err := resilience.Retry(ctx, c.Attempts, c.RetryDelay, func(ctx context.Context) error {
		err := c.Breaker.Do(func() error {
			var err error
			p, err = c.once(ctx, sku)
			if errors.Is(err, ErrNotFound) {
				return nil // a 404 is an answer, not a failure of Catalog
			}
			return err
		})
		if errors.Is(err, resilience.ErrOpen) {
			return resilience.Permanent(err) // fail fast, do not hammer
		}
		return err
	})
	if err == nil && p.SKU == "" {
		return p, ErrNotFound
	}
	return p, err
}

func (c *Client) once(ctx context.Context, sku string) (Product, error) {
	ctx, cancel := context.WithTimeout(ctx, c.PerTry)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/products/"+url.PathEscape(sku), nil)
	if err != nil {
		return Product{}, err
	}
	req.Header.Set("Accept", "application/json")
	res, err := c.HTTP.Do(req)
	if err != nil {
		return Product{}, err // includes context.DeadlineExceeded
	}
	defer res.Body.Close()
	switch {
	case res.StatusCode == http.StatusNotFound:
		return Product{}, ErrNotFound
	case res.StatusCode >= 500:
		return Product{}, fmt.Errorf("catalog: status %d", res.StatusCode)
	case res.StatusCode != http.StatusOK:
		return Product{}, resilience.Permanent(fmt.Errorf("catalog: status %d", res.StatusCode))
	}
	var p Product
	// Tolerant reader: unknown fields are ignored, so Catalog may add fields.
	if err := json.NewDecoder(res.Body).Decode(&p); err != nil {
		return Product{}, err
	}
	return p, nil
}

The contract test ​

Orders wrote the contract file; both sides test against it, so Catalog's pipeline fails before a breaking change ships:

json
{
  "consumer": "orders",
  "provider": "catalog",
  "description": "orders reads a product's price before placing an order",
  "request": { "method": "GET", "path": "/products/sku-1" },
  "response": {
    "status": 200,
    "body": { "sku": "sku-1", "name": "Coffee beans 1kg", "price_cents": 1299, "currency": "EUR" }
  }
}
go
package catalog_test

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"

	"academy/microservices-architecture/internal/catalog"

	"github.com/go-chi/chi/v5"
)

// contract is the shared file both sides test against (consumer-driven:
// Orders wrote it; Catalog's pipeline must keep it green).
type contract struct {
	Request struct {
		Method string `json:"method"`
		Path   string `json:"path"`
	} `json:"request"`
	Response struct {
		Status int            `json:"status"`
		Body   map[string]any `json:"body"`
	} `json:"response"`
}

func load(t *testing.T) contract {
	t.Helper()
	raw, err := os.ReadFile("testdata/orders-gets-product.json")
	if err != nil {
		t.Fatal(err)
	}
	var c contract
	if err := json.Unmarshal(raw, &c); err != nil {
		t.Fatal(err)
	}
	return c
}

// Consumer side: the Orders client understands the response in the contract.
func TestConsumerOrdersUnderstandsContract(t *testing.T) {
	c := load(t)
	stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != c.Request.Method || r.URL.Path != c.Request.Path {
			t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
		}
		w.WriteHeader(c.Response.Status)
		_ = json.NewEncoder(w).Encode(c.Response.Body)
	}))
	defer stub.Close()
	p, err := catalog.NewClient(stub.URL).GetProduct(context.Background(), "sku-1")
	if err != nil {
		t.Fatal(err)
	}
	if p.PriceCents != 1299 || p.Currency != "EUR" {
		t.Fatalf("consumer misread contract: %+v", p)
	}
}

// Provider side: the real Catalog handler still returns every field Orders uses.
func TestProviderCatalogHonoursContract(t *testing.T) {
	c := load(t)
	r := chi.NewRouter()
	catalog.Routes(r, catalog.NewStore(catalog.Product{
		SKU: "sku-1", Name: "Coffee beans 1kg", PriceCents: 1299, Currency: "EUR",
	}), func() time.Duration { return 0 })
	rec := httptest.NewRecorder()
	r.ServeHTTP(rec, httptest.NewRequest(c.Request.Method, c.Request.Path, nil))
	if rec.Code != c.Response.Status {
		t.Fatalf("status %d, contract says %d", rec.Code, c.Response.Status)
	}
	var got map[string]any
	if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
		t.Fatal(err)
	}
	for k, want := range c.Response.Body {
		if got[k] != want {
			t.Errorf("field %q: got %v, contract says %v", k, got[k], want)
		}
	}
}

Orders: sync calls, owned data, outbox, relay ​

Orders calls Catalog (guarded read) and, when BILLING_URL is set, Billing (machine token, Idempotency-Key); the lab runs without Billing. The relay POSTs events straight to Notifications over HTTP, standing in for the message bus in the diagram; a real system relays to RabbitMQ or Kafka.

go
// Package orders is the Orders service: it owns orders and their outbox.
package orders

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"sync"
	"time"

	"academy/microservices-architecture/internal/catalog"
	"academy/microservices-architecture/internal/platform"
	"academy/microservices-architecture/internal/resilience"

	"github.com/go-chi/chi/v5"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"
)

// Order is owned by this service only.
type Order struct {
	ID         string `json:"id"`
	CustomerID string `json:"customer_id"`
	SKU        string `json:"sku"`
	Qty        int64  `json:"qty"`
	TotalCents int64  `json:"total_cents"`
	Currency   string `json:"currency"`
	// PriceCents is copied from Catalog at order time: Orders keeps its own
	// snapshot instead of joining Catalog's table later.
	PriceCents int64 `json:"price_cents"`
}

// Event is an integration event waiting in the outbox.
type Event struct {
	ID      string            `json:"id"`
	Type    string            `json:"type"`
	Payload json.RawMessage   `json:"payload"`
	Trace   map[string]string `json:"-"` // traceparent carried across the async hop
	Sent    bool              `json:"-"`
}

// Store stands in for the Orders database: the order row and the outbox row
// are written under one lock, the way one SQL transaction would write both.
type Store struct {
	mu     sync.Mutex
	orders map[string]Order
	outbox []*Event
}

// NewStore returns an empty store.
func NewStore() *Store { return &Store{orders: map[string]Order{}} }

func (s *Store) placeWithEvent(ctx context.Context, o Order) error {
	payload, err := json.Marshal(o)
	if err != nil {
		return err
	}
	carrier := propagation.MapCarrier{}
	otel.GetTextMapPropagator().Inject(ctx, carrier)
	s.mu.Lock()
	defer s.mu.Unlock()
	s.orders[o.ID] = o
	s.outbox = append(s.outbox, &Event{ID: platform.NewID(), Type: "OrderPlaced.v1", Payload: payload, Trace: carrier})
	return nil
}

// Catalog is the port Orders needs; *catalog.Client implements it.
type Catalog interface {
	GetProduct(ctx context.Context, sku string) (catalog.Product, error)
}

type placeRequest struct {
	CustomerID string `json:"customer_id"`
	SKU        string `json:"sku"`
	Qty        int64  `json:"qty"`
}

// Billing is the port for charging; nil means "not configured" (the lab
// runs without the Laravel service).
type Billing interface {
	Charge(ctx context.Context, o Order) error
}

// Routes mounts POST /orders.
func Routes(r chi.Router, log *slog.Logger, s *Store, cat Catalog, bill Billing) {
	r.Post("/orders", func(w http.ResponseWriter, req *http.Request) {
		var in placeRequest
		if err := json.NewDecoder(req.Body).Decode(&in); err != nil || in.SKU == "" || in.Qty <= 0 {
			writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "invalid_order"})
			return
		}
		p, err := cat.GetProduct(req.Context(), in.SKU)
		switch {
		case errors.Is(err, catalog.ErrNotFound):
			writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "unknown_sku"})
			return
		case errors.Is(err, resilience.ErrOpen):
			// Fail fast: the breaker already knows Catalog is down.
			w.Header().Set("Retry-After", "10")
			writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "catalog_unavailable", "breaker": "open"})
			return
		case err != nil:
			log.WarnContext(req.Context(), "catalog call failed", "err", err, "trace_id", platform.TraceID(req.Context()))
			writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "catalog_unavailable"})
			return
		}
		o := Order{
			ID: platform.NewID(), CustomerID: in.CustomerID, SKU: p.SKU, Qty: in.Qty,
			PriceCents: p.PriceCents, TotalCents: p.PriceCents * in.Qty, Currency: p.Currency,
		}
		if bill != nil {
			// Synchronous: the customer must know now whether payment worked.
			// The Idempotency-Key makes a retry of this call safe; making a
			// client's retry of POST /orders safe needs a client-supplied key
			// (see the API Idempotency chapter).
			if err := bill.Charge(req.Context(), o); err != nil {
				log.WarnContext(req.Context(), "billing call failed", "err", err, "trace_id", platform.TraceID(req.Context()))
				writeJSON(w, http.StatusBadGateway, map[string]string{"error": "payment_failed"})
				return
			}
		}
		if err := s.placeWithEvent(req.Context(), o); err != nil {
			writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "store_failed"})
			return
		}
		writeJSON(w, http.StatusCreated, o)
	})
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

// Relay publishes outbox events to Notifications at least once. If
// Notifications is down, orders still succeed; events wait and are retried.
// (A real system relays to a broker; see the outbox and messaging chapters.)
func Relay(ctx context.Context, log *slog.Logger, s *Store, client *http.Client, notificationsURL string, every time.Duration) {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
		s.mu.Lock()
		pending := make([]*Event, 0, len(s.outbox))
		for _, e := range s.outbox {
			if !e.Sent {
				pending = append(pending, e)
			}
		}
		s.mu.Unlock()
		for _, e := range pending {
			// Continue the trace of the request that created the event.
			ectx := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(e.Trace))
			if err := deliver(ectx, client, notificationsURL, e); err != nil {
				log.WarnContext(ectx, "relay: will retry", "event_id", e.ID, "err", err, "trace_id", platform.TraceID(ectx))
				break // keep order; try again on next tick
			}
			s.mu.Lock()
			e.Sent = true
			s.mu.Unlock()
		}
	}
}

func deliver(ctx context.Context, client *http.Client, base string, e *Event) error {
	ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
	defer cancel()
	body, err := json.Marshal(e)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/events", bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 300 {
		return errors.New("notifications: status " + res.Status)
	}
	return nil
}
go
package orders

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

// BillingClient calls the Laravel Billing service. The Sanctum token is a
// machine token with the "charges:create" ability, read from a secret at
// start-up. The Idempotency-Key is the order ID, so a retried call can never
// capture twice; Billing returns the first result for a repeated key.
type BillingClient struct {
	BaseURL string
	Token   string
	HTTP    *http.Client
	Timeout time.Duration
}

type chargeRequest struct {
	OrderID     string `json:"order_id"`
	AmountCents int64  `json:"amount_cents"`
	Currency    string `json:"currency"`
}

// Charge returns nil when Billing answered 200 (replay) or 201 (created).
func (b *BillingClient) Charge(ctx context.Context, o Order) error {
	ctx, cancel := context.WithTimeout(ctx, b.Timeout)
	defer cancel()
	body, err := json.Marshal(chargeRequest{OrderID: o.ID, AmountCents: o.TotalCents, Currency: o.Currency})
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.BaseURL+"/api/charges", bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Bearer "+b.Token)
	req.Header.Set("Idempotency-Key", "charge-"+o.ID)
	res, err := b.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
		return fmt.Errorf("billing: status %d", res.StatusCode)
	}
	return nil
}
go
// Command orders runs the Orders service: it calls Catalog synchronously
// (it needs the price now) and tells Notifications asynchronously (via outbox).
package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"academy/microservices-architecture/internal/catalog"
	"academy/microservices-architecture/internal/orders"
	"academy/microservices-architecture/internal/platform"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "orders")
	shutdown, err := platform.SetupTracing(ctx, "orders")
	if err != nil {
		log.Error("tracing", "err", err)
		os.Exit(1)
	}
	defer func() { _ = shutdown(context.Background()) }()

	cat := catalog.NewClient(env("CATALOG_URL", "http://localhost:8081"))
	store := orders.NewStore()
	outbound := &http.Client{Transport: otelhttp.NewTransport(platform.CorrelationTransport{})}
	// Billing (Laravel) is optional so the lab runs with three Go services.
	var bill orders.Billing
	if url := os.Getenv("BILLING_URL"); url != "" {
		bill = &orders.BillingClient{BaseURL: url, Token: os.Getenv("BILLING_TOKEN"), HTTP: outbound, Timeout: 2 * time.Second}
	}
	go orders.Relay(ctx, log, store, outbound, env("NOTIFICATIONS_URL", "http://localhost:8082"), time.Second)

	// Readiness checks only what Orders owns (here: nothing external).
	// Catalog being down must NOT make Orders unready, or the whole fleet drops.
	health := platform.NewHealth(nil)
	r := chi.NewRouter()
	r.Use(middleware.Recoverer)
	r.Get("/livez", health.Live)
	r.Get("/readyz", health.Ready)
	r.Group(func(r chi.Router) {
		r.Use(platform.AccessLog(log))
		orders.Routes(r, log, store, cat, bill)
	})
	srv := &http.Server{
		Addr:              ":" + env("PORT", "8080"),
		Handler:           otelhttp.NewHandler(r, "orders"),
		ReadHeaderTimeout: 5 * time.Second,
	}
	if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}

func env(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
go
// Command catalog runs the Catalog service (owns products and prices).
package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"academy/microservices-architecture/internal/catalog"
	"academy/microservices-architecture/internal/platform"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "catalog")
	shutdown, err := platform.SetupTracing(ctx, "catalog")
	if err != nil {
		log.Error("tracing", "err", err)
		os.Exit(1)
	}
	defer func() { _ = shutdown(context.Background()) }()

	// SLOW_MS lets the lab make Catalog slow without killing it.
	slow, _ := strconv.Atoi(os.Getenv("SLOW_MS"))
	store := catalog.NewStore(
		catalog.Product{SKU: "sku-1", Name: "Coffee beans 1kg", PriceCents: 1299, Currency: "EUR"},
		catalog.Product{SKU: "sku-2", Name: "Grinder", PriceCents: 8900, Currency: "EUR"},
	)
	health := platform.NewHealth(nil)
	r := chi.NewRouter()
	r.Use(middleware.Recoverer)
	r.Get("/livez", health.Live)
	r.Get("/readyz", health.Ready)
	r.Group(func(r chi.Router) {
		r.Use(platform.AccessLog(log))
		catalog.Routes(r, store, func() time.Duration { return time.Duration(slow) * time.Millisecond })
	})
	srv := &http.Server{
		Addr:              ":" + env("PORT", "8081"),
		Handler:           otelhttp.NewHandler(r, "catalog"),
		ReadHeaderTimeout: 5 * time.Second,
	}
	if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}

func env(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
go
// Command notifications consumes OrderPlaced events. It is idempotent:
// the relay delivers at least once, so duplicates are expected.
package main

import (
	"context"
	"encoding/json"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"academy/microservices-architecture/internal/platform"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

type event struct {
	ID      string          `json:"id"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "notifications")
	shutdown, err := platform.SetupTracing(ctx, "notifications")
	if err != nil {
		log.Error("tracing", "err", err)
		os.Exit(1)
	}
	defer func() { _ = shutdown(context.Background()) }()

	var mu sync.Mutex
	seen := map[string]bool{} // inbox: in production a table with a unique key
	health := platform.NewHealth(nil)
	r := chi.NewRouter()
	r.Use(middleware.Recoverer)
	r.Get("/livez", health.Live)
	r.Get("/readyz", health.Ready)
	r.Group(func(r chi.Router) {
		r.Use(platform.AccessLog(log))
		r.Post("/events", func(w http.ResponseWriter, req *http.Request) {
			var e event
			if err := json.NewDecoder(req.Body).Decode(&e); err != nil || e.ID == "" {
				w.WriteHeader(http.StatusBadRequest)
				return
			}
			mu.Lock()
			dup := seen[e.ID]
			seen[e.ID] = true
			mu.Unlock()
			if !dup && e.Type == "OrderPlaced.v1" {
				log.InfoContext(req.Context(), "email queued", "event_id", e.ID, "trace_id", platform.TraceID(req.Context()))
			}
			w.WriteHeader(http.StatusAccepted)
		})
	})
	srv := &http.Server{
		Addr:              ":" + env("PORT", "8082"),
		Handler:           otelhttp.NewHandler(r, "notifications"),
		ReadHeaderTimeout: 5 * time.Second,
	}
	if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}

func env(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

Packaging and the lab environment ​

# One image per service: docker build --build-arg SERVICE=orders -t orders .
FROM golang:1.26 AS build
ARG SERVICE
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/${SERVICE}

FROM alpine:3.20
RUN adduser -D -u 10001 app
COPY --from=build /out/app /app
USER app
ENTRYPOINT ["/app"]
yml
# Lab: three Go services plus Jaeger. `docker compose up --build`
# Jaeger UI: http://localhost:16686  (traces arrive over OTLP/HTTP on 4318)
x-otel: &otel
  OTEL_EXPORTER_OTLP_ENDPOINT: http://jaeger:4318
services:
  catalog:
    build: { context: ./go, args: { SERVICE: catalog } }
    environment: { <<: *otel, PORT: "8081", SLOW_MS: "${CATALOG_SLOW_MS:-0}" }
    ports: ["8081:8081"]
  notifications:
    build: { context: ./go, args: { SERVICE: notifications } }
    environment: { <<: *otel, PORT: "8082" }
    ports: ["8082:8082"]
  orders:
    build: { context: ./go, args: { SERVICE: orders } }
    environment:
      <<: *otel
      PORT: "8080"
      CATALOG_URL: http://catalog:8081
      NOTIFICATIONS_URL: http://notifications:8082
    ports: ["8080:8080"]
    depends_on: [catalog, notifications]
  jaeger:
    image: jaegertracing/all-in-one:1.62.0
    environment: { COLLECTOR_OTLP_ENABLED: "true" }
    ports: ["16686:16686", "4318:4318"]

The Go angle ​

Go feature or libraryRole in a microservice
net/http Server with ReadHeaderTimeout, ShutdownProduction HTTP server and graceful drain, no framework needed
chi (github.com/go-chi/chi/v5)Router "built on the new context package"; compatible with net/http handlers and middleware
contextDeadlines and cancellation flow from the inbound request into every outbound call
log/slogStructured JSON logs with trace_id, correlation_id
OpenTelemetry Go (otel, sdk/trace, otelhttp)Spans and W3C propagation for server and client
grpc-goTyped contracts in .proto, deadlines and interceptors for internal calls (gRPC)
encoding/jsonIgnores unknown fields by default: a tolerant reader for free
Static binaries, distroless imagesSmall images, fast starts, few CVEs

Laravel ​

Billing is a Laravel 13 application (PHP 8.4) served by Octane. The files live under docs/snippets/architecture/microservices-architecture/php; PHP is not installed on the authoring machine, so the code was reviewed against the Laravel 13 docs, not run. Octane, in its docs' words, "boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds", which is why per-request data must never be captured in a constructor or singleton.

Wiring: health route, ability middleware, correlation ​

bootstrap/app.php enables the /up health route and the Sanctum ability aliases the Sanctum docs define:

php
<?php

use App\Http\Middleware\CorrelationContext;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;

// Billing service (Laravel 13, served by Octane + FrankenPHP).
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up', // 200 when the app boots; DiagnosingHealth listeners add checks
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'abilities' => CheckAbilities::class,
            'ability' => CheckForAnyAbility::class,
        ]);
        $middleware->append(CorrelationContext::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
php
<?php

use App\Http\Controllers\ChargeController;
use Illuminate\Support\Facades\Route;

// Machine-to-machine: only a token carrying the "charges:create" ability
// (issued to the Orders service) may create charges.
Route::post('/charges', ChargeController::class)
    ->middleware(['auth:sanctum', 'abilities:charges:create']);

The correlation middleware writes to Laravel's Context, which adds the fields to every log line and carries them into queued jobs:

php
<?php

namespace App\Http\Middleware;

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

/**
 * Accepts the caller's correlation ID and W3C traceparent, puts them in
 * Laravel's Context (added to every log line and carried into queued jobs),
 * and echoes the correlation ID back.
 *
 * Octane keeps the app in memory between requests: never store these values
 * in a singleton or constructor; Context is per request.
 */
final class CorrelationContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $id = $request->header('X-Correlation-ID') ?: (string) Str::uuid();

        Context::add('service', 'billing');
        Context::add('correlation_id', $id);
        if ($traceparent = $request->header('traceparent')) {
            Context::add('traceparent', $traceparent);
        }

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

        return $response;
    }
}

Machine tokens with Sanctum ​

Each calling service gets its own identity and a scoped, expiring token (createToken($name, $abilities, $expiresAt)); the Orders service sends it as a bearer token:

php
<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

/**
 * php artisan billing:issue-token orders --ability=charges:create
 *
 * Each calling service gets its own identity (a dedicated user row) and a
 * short-lived Sanctum token limited to the abilities it needs. Store the
 * plain-text token in the caller's secret store, never in git.
 */
final class IssueServiceToken extends Command
{
    protected $signature = 'billing:issue-token {service} {--ability=*} {--days=30}';

    protected $description = 'Issue a scoped machine token for a calling service';

    public function handle(): int
    {
        $service = $this->argument('service');
        $account = User::firstOrCreate(
            ['email' => "svc-{$service}@services.internal"],
            ['name' => "service:{$service}", 'password' => Str::random(64)],
        );

        $token = $account->createToken(
            "{$service}-service",
            $this->option('ability') ?: ['charges:create'],
            now()->addDays((int) $this->option('days')),
        );

        $this->line($token->plainTextToken);

        return self::SUCCESS;
    }
}

The endpoint: owned data, idempotency, outbound call with retries ​

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Billing's own database: no other service has credentials for it.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('charges', function (Blueprint $table) {
            $table->id();
            $table->string('idempotency_key', 64)->unique();
            $table->string('order_id', 64)->index();
            $table->unsignedBigInteger('amount_cents');
            $table->char('currency', 3);
            $table->string('psp_reference', 128);
            $table->string('status', 16);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('charges');
    }
};
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

final class Charge extends Model
{
    protected $fillable = [
        'idempotency_key', 'order_id', 'amount_cents', 'currency', 'psp_reference', 'status',
    ];

    /** The published representation: the contract, not the table. */
    public function toContract(): array
    {
        return [
            'charge_id' => (string) $this->id,
            'order_id' => $this->order_id,
            'amount_cents' => (int) $this->amount_cents,
            'currency' => $this->currency,
            'status' => $this->status,
        ];
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Models\Charge;
use App\Services\PaymentProvider;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

final class ChargeController
{
    public function __invoke(Request $request, PaymentProvider $psp): JsonResponse
    {
        $data = $request->validate([
            'order_id' => ['required', 'string', 'max:64'],
            'amount_cents' => ['required', 'integer', 'min:1'],
            'currency' => ['required', 'string', 'size:3'],
        ]);
        $key = $request->header('Idempotency-Key');
        abort_if(! $key, 400, 'Idempotency-Key header is required');

        // A retry from Orders with the same key returns the first result.
        $existing = Charge::where('idempotency_key', $key)->first();
        if ($existing) {
            return response()->json($existing->toContract(), 200);
        }

        $pspReference = $psp->capture($key, $data['amount_cents'], $data['currency']);

        $charge = DB::transaction(fn () => Charge::create([
            'idempotency_key' => $key, // unique index: a concurrent duplicate fails here
            'order_id' => $data['order_id'],
            'amount_cents' => $data['amount_cents'],
            'currency' => $data['currency'],
            'psp_reference' => $pspReference,
            'status' => 'captured',
        ]));

        return response()->json($charge->toContract(), 201);
    }
}
php
<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * Outbound call to the payment provider: explicit timeouts, retries only on
 * connection failures, and the same Idempotency-Key on every attempt so a
 * retry can never capture twice.
 */
final class PaymentProvider
{
    public function capture(string $idempotencyKey, int $amountCents, string $currency): string
    {
        $response = Http::baseUrl(config('services.psp.url'))
            ->withToken(config('services.psp.secret'))
            ->acceptJson()
            ->connectTimeout(1)   // default is 10 seconds
            ->timeout(3)          // default is 30 seconds
            ->withHeaders([
                'Idempotency-Key' => $idempotencyKey,
                // Read per call, never cached: Octane reuses this process.
                'X-Correlation-ID' => (string) Context::get('correlation_id'),
            ])
            ->retry([100, 300], when: function (Throwable $e, PendingRequest $request): bool {
                return $e instanceof ConnectionException;
            })
            ->post('/v1/captures', [
                'amount' => $amountCents,
                'currency' => $currency,
            ]);

        // After the last failed attempt Laravel throws RequestException (4xx/5xx)
        // or ConnectionException; the controller lets it become a 5xx for Orders.
        return (string) $response->json('reference');
    }
}

Health and the provider contract test ​

php
<?php

namespace App\Listeners;

use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;

/**
 * Extends GET /up: Billing is healthy only if ITS OWN database answers.
 * It deliberately does not call Orders or the payment provider.
 */
final class CheckBillingDependencies
{
    public function handle(DiagnosingHealth $event): void
    {
        DB::select('select 1'); // throws -> /up returns 500
    }
}
php
<?php

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Sanctum\Sanctum;

// Provider side of the contract Orders depends on (consumer-driven).
// The JSON shape below is what Orders' Go client sends and expects; keep it green.
// Requires App\Models\User to use Laravel\Sanctum\HasApiTokens.

uses(RefreshDatabase::class);

beforeEach(function () {
    config(['services.psp.url' => 'https://psp.test', 'services.psp.secret' => 'test']);
    // The real PaymentProvider runs (timeouts, retry rules); only the network is faked.
    Http::fake([
        'psp.test/*' => Http::response(['reference' => 'psp_123'], 200),
    ]);
});

test('orders can create a charge and gets the contracted shape', function () {
    Sanctum::actingAs(User::factory()->create(), ['charges:create']);

    $this->postJson('/api/charges', [
        'order_id' => 'o-1', 'amount_cents' => 2598, 'currency' => 'EUR',
    ], ['Idempotency-Key' => 'charge-o-1'])
        ->assertCreated()
        ->assertJsonStructure(['charge_id', 'order_id', 'amount_cents', 'currency', 'status'])
        ->assertJson(['order_id' => 'o-1', 'amount_cents' => 2598, 'status' => 'captured']);
});

test('a retry with the same idempotency key does not charge twice', function () {
    Sanctum::actingAs(User::factory()->create(), ['charges:create']);
    $body = ['order_id' => 'o-2', 'amount_cents' => 100, 'currency' => 'EUR'];

    $this->postJson('/api/charges', $body, ['Idempotency-Key' => 'charge-o-2'])->assertCreated();
    $this->postJson('/api/charges', $body, ['Idempotency-Key' => 'charge-o-2'])->assertOk();

    Http::assertSentCount(1); // the payment provider was called once
});

test('a token without the ability is rejected', function () {
    Sanctum::actingAs(User::factory()->create(), ['catalog:read']);

    $this->postJson('/api/charges', [], ['Idempotency-Key' => 'x'])->assertForbidden();
});

The Laravel angle ​

Laravel featureRole in a microserviceNote from the Laravel 13 docs
Octane (FrankenPHP, RoadRunner, Swoole)Long-lived workers: low latency per requestService providers' register/boot run once per worker; avoid injecting the container or request into singletons
HTTP clientOutbound callstimeout default 30 s, connectTimeout default 10 s; retry($times, $sleep, $when, throw: ...); after the last failure a RequestException is thrown
Sanctum API tokensMachine-to-machine authTokens are SHA-256 hashed in the database; abilities checked by tokenCan or the abilities / ability middleware; install with php artisan install:api
Context facadeCorrelation fields in logs and jobsContext is "dehydrated" into queued job payloads
Health route /upProbes200 when booted, 500 on exception; DiagnosingHealth lets you add checks
Queues (Redis, SQS, database...)Async work inside the serviceCross-service events need a broker both sides speak; see Laravel Queue Internals

Solving the classic problems ​

"We cannot deploy one service alone" (distributed monolith) ​

SolutionHowAdvantageCost / limitation
Backward-compatible changesTolerant reader, additive changes, expand-and-contractNo coordinationDiscipline; temporary dual fields
Consumer-driven contractsContract file run in the provider's CIBreaks caught before deployContracts must be maintained
Remove shared domain libraryDuplicate small DTOs; share only technical codeLibrary bumps stop forcing releasesSome duplication
Merge servicesIf always changed together, they are one serviceSimplest fixAdmits the boundary was wrong

"Two services write the same tables" (shared database) ​

SolutionHowAdvantageCost / limitation
One owner per tableGrant write access to one role only (SQL above)Clear ownershipOthers need an API
API or events instead of readsOwner exposes a query API or publishes changesSchema can change freelyLatency, eventual consistency
Read model / replicated dataConsumer keeps its own copy (price snapshot)No runtime couplingStaleness to design for
Strangle the shared schemaMove tables one at a time (Data ownership)IncrementalLong migration

"One slow service takes everything down" (cascading failure) ​

SolutionHowAdvantageCost / limitation
Timeouts on every callcontext.WithTimeout, Http::timeout(3)Bounded waitingChoosing values needs latency data
Bounded retries with jitter2 tries, full jitter, idempotent onlyAbsorbs blipsRetry storms if unbounded
Circuit breakerFail fast after N failuresProtects caller and calleeNeeds fallback UX
BulkheadsSeparate pools per dependencyOne dependency cannot exhaust all workersMore tuning
Async instead of syncEvents for "inform" interactionsCaller does not depend on callee uptimeEventual consistency

"Where did my request go?" (no observability) ​

SolutionHowAdvantageCost / limitation
Trace propagationOpenTelemetry + W3C traceparent in every hop, including outbox rowsOne view of the requestInstrument every service
Correlation ID in logsMiddleware + slog / ContextGrep one ID across servicesMust be forwarded by clients
RED metrics per serviceRate, errors, duration per endpointAlerting on symptomsCardinality discipline
Semantic monitoringBusiness metrics: orders per minuteCatches silent failuresNeeds business input

"Too many tiny services" (nanoservices, entity services) ​

SolutionHowAdvantageCost / limitation
Apply integratorsTransactions, workflow, shared code, data relationshipsFewer remote callsLarger services
Cut by capabilityCheckout, Billing instead of Customer, Order CRUDUse cases stay inside one serviceRe-modelling
Merge by co-changeServices changed in the same PRs are mergedMatches the pattern of changeAdmits earlier mistake

"Every service does auth, logging and config differently" ​

SolutionHowAdvantageCost / limitation
Service template + chassisA generator that creates a service with plumbing wiredFast, consistentOne language at a time
Sidecar / meshEnvoy-based mesh (Istio, Linkerd) for mTLS, retries, metricsLanguage-independentOperational complexity, latency per hop
Platform teamOwns the paved road as a productStream-aligned teams go fasterA team to fund

Choosing ​

SituationRecommendationExtra techniqueReason
New product, one team, domain unclearModular monolithModule boundaries, fitness tests"Monolith First"; boundaries are not known yet
One team, one data-heavy pipelineOne processIn-memory hand-off between stagesPrime Video: distribution added S3 and orchestration cost
3-8 teams, stable domain, weekly release fightsFew coarse-grained servicesPlatform, contracts, CDFowler's "coarse-grained services" route; independent deploys
One part needs very different scale or securityExtract that one serviceStrangler fig at the edgeDisintegrator: scalability, security
Many teams, many languagesMicroservices with a platform and meshStream-aligned + platform teamsTeam autonomy is the main benefit
Hundreds of servicesGroup into domains with gatewaysDOMA-style domain gatewaysUber: ~2,200 services into 70 domains
No CI/CD, no monitoring, no on-callDo not split yetBuild the prerequisites firstFowler's prerequisites
Strong consistency across most operationsKeep togetherACID in one databaseIntegrator: database transactions

When NOT to use microservices: a small team (one or two pizzas total), an early product whose domain is still moving, no deployment automation or monitoring, a workload dominated by cross-entity transactions, latency budgets that cannot absorb network hops, or a motivation that is "everyone does it". Migration from a monolith is gradual, edge first, with a strangler fig ("Strangler Fig", Fowler, renamed from "Strangler Application", updated 22 August 2024).

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

The same ordering platform at each stage. The question at every step: what crosses the boundary, and what happens when the other side is slow or down?

Monolith: one process, one database ​

How it shows up: Orders, Catalog, Billing and Notifications are packages in one Go binary or folders in one Laravel app; checkout is one function call chain and one BEGIN ... COMMIT.

Simplest correct usage: layered or feature folders, one pipeline, one dashboard, horizontal scaling behind a load balancer.

Example (simple): a shop for one bakery: Laravel, one MySQL, emails queued with the database driver.

Example (production-shaped): a regional e-commerce site with 15 developers, one PostgreSQL primary and two replicas, deploying several times a day with blue/green (Fowler's Facebook and Etsy note: continuous delivery does not need microservices).

Modular monolith and multiple databases ​

How it shows up: each module owns its schema and exposes a facade; a fitness test forbids reaching into another module's tables. Events between modules are in-process. This is the stage where you learn the boundaries, cheaply (Modular Monolith).

Example: the same shop with orders, catalog, billing schemas and roles as in the SQL above, still in one deployable; the Billing module is the first candidate to extract because of PCI scope (security disintegrator).

Microservices: the boundary becomes a network ​

What survives: module APIs become HTTP or gRPC APIs; module events become broker messages; schema ownership becomes database ownership.

What breaks: the shared transaction (outbox, saga), latency (each call costs milliseconds), availability (calls fail), debugging (needs traces).

text
     Checkout across services
1    POST /orders                          orders-svc (Go)
2    GET /products/sku-1   300 ms, breaker  catalog-svc (Go)
3    POST /api/charges     Bearer token, Idempotency-Key: order-id   billing-svc (Laravel)
4    COMMIT order + outbox                  orders_db
5    relay -> OrderPlaced.v1 -> notifications-svc (dedup by event id)
     Failure: step 2 down -> 503 fast (breaker); step 3 down -> order PENDING, saga retries capture

Production example: Uber groups its services into domains, each with a gateway, so that other domains call one gateway instead of dozens of internal services.

Distributed data: replicas, caches, regions ​

WhereWhat breaksDesign response
Catalog read replicasPrice updated, replica still oldOrders snapshots the price it used; reconciliation job
Cache of products in OrdersStale price after changeShort TTL, version in key, invalidate on PriceChanged event
Outbox relayDuplicates on retryIdempotent consumer with an inbox table
Multi-regionCross-region sync calls are slowEach region runs a full set; replicate catalog read-only
Reporting across servicesNo cross-service joinCQRS read model or a data warehouse fed by events/CDC

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

ScaleStructureWhat changes
1× (one team)Modular monolithModules, schemas, ADRs, one pipeline
10× (5-8 teams)4-10 coarse services + platformPipelines per service, contracts, tracing, breaker defaults in the chassis
100× (dozens of teams)Hundreds of services grouped into domainsDomain gateways, mesh with mTLS, service catalogue, SLOs and error budgets per service

Lab: three services, one failure, one trace ​

You will run Orders, Catalog and Notifications, place an order, kill Catalog, watch the breaker, make Catalog slow, bring it back, take Notifications down and watch the outbox catch up, then follow one trace ID across all three. Everything below was run on the authoring machine; outputs are real (IDs will differ).

Setup (no Docker needed):

bash
cd docs/snippets/architecture/microservices-architecture/go
go test ./...            # breaker unit tests + contract tests
go build -o /tmp/msa/ ./cmd/...
cd /tmp/msa
PORT=18081 ./catalog > catalog.log 2>&1 &
PORT=18082 ./notifications > notif.log 2>&1 &
PORT=18080 CATALOG_URL=http://localhost:18081 NOTIFICATIONS_URL=http://localhost:18082 ./orders > orders.log 2>&1 &

With Docker instead: docker compose up --build in the snippet folder (ports 8080-8082, Jaeger UI on http://localhost:16686). The steps below were run with the binaries; the compose path was built but not walked through step by step.

Step 1: the happy path.

bash
curl -s -X POST localhost:18080/orders -H 'X-Correlation-ID: lab-1' \
  -d '{"customer_id":"c-42","sku":"sku-1","qty":2}'
# {"id":"b8495dc2...","customer_id":"c-42","sku":"sku-1","qty":2,"total_cents":2598,"currency":"EUR","price_cents":1299}

Step 2: kill Catalog and watch the breaker open.

bash
kill %1    # catalog
for i in 1 2 3 4; do curl -s -o /dev/null -w "req$i status=%{http_code} time=%{time_total}s\n" \
  -X POST localhost:18080/orders -d '{"customer_id":"c-42","sku":"sku-1","qty":1}'; done
# req1 status=503 time=0.006297s
# req2 status=503 time=0.051295s     (second try waited for jitter)
# req3 status=503 time=0.013541s     (5th failed attempt: breaker opens)
# req4 status=503 time=0.000488s     (no network call at all)
curl -s -i -X POST localhost:18080/orders -d '{"customer_id":"c-42","sku":"sku-1","qty":1}' | grep -E "HTTP/|Retry-After|error"
# HTTP/1.1 503 Service Unavailable
# Retry-After: 10
# {"breaker":"open","error":"catalog_unavailable"}

Expected: Orders stays up and answers within milliseconds; /readyz of Orders stays 200 (it does not check Catalog). Orders' log: "msg":"catalog call failed",...,"err":"... connect: connection refused".

Step 3: a slow dependency. Restart Catalog with SLOW_MS=1000, wait 10 s for the cooldown, then order again:

text
slow status=503 time=0.315355s

Expected: one trial call (half-open) hits the 300 ms per-try timeout (context deadline exceeded), the breaker reopens, the retry is refused by the open breaker, and the user waits 0.3 s instead of 1 s or forever.

Step 4: recovery. Restart Catalog without SLOW_MS, wait 10 s, order again: recovered status=201 time=0.001940s. The trial call succeeded and closed the breaker.

Step 5: Notifications down, orders still succeed. Stop Notifications, place an order (status=201), watch Orders log "msg":"relay: will retry","event_id":"902d0a14..." every second, start Notifications again: the event is delivered ("msg":"email queued"). The order never depended on Notifications.

Step 6: one trace across three services.

bash
T=$(grep '"correlation_id":"lab-1"' orders.log | sed 's/.*"trace_id":"\([0-9a-f]*\)".*/\1/')
grep -l "$T" *.log
# catalog.log
# notif.log
# orders.log

The same trace_id (9fff831ec7a41f395523bcd8893c6424 in our run) appears in Orders' request log, Catalog's request log and, one second later, Notifications' email queued line, because the relay restored the traceparent saved with the outbox event. With docker compose, open Jaeger and search for service orders to see the spans as in the trace diagram.

MeasureObservedWhy
Time to fail with Catalog down, breaker closed6-51 msConnection refused is fast; jitter on retry
Time to fail with breaker open0.5 msNo network call
Time to fail with Catalog slow315 ms300 ms per-try timeout, then the open breaker refuses the retry
Orders availability while Notifications down100% (201)Async via outbox
Services sharing one trace3 of 3traceparent over HTTP and through the outbox

Step 7 (Laravel, optional). In a Laravel 13 app with Octane and Sanctum (php artisan install:api, and HasApiTokens on the User model), copy the PHP files, run the migration, issue a token with php artisan billing:issue-token orders --ability=charges:create, and run ./vendor/bin/pest tests/Feature/ChargeContractTest.php. Expected: three passing tests (created, idempotent replay returns 200, missing ability returns 403).

Common misconceptions ​

BeliefReality
Microservices means small servicesSize varies widely; the test is independent deployability and single ownership
Containers or Kubernetes make it microservicesPackaging and scheduling; boundaries and data ownership are separate decisions
Microservices are fasterEach hop adds latency and failure; they scale teams and uneven load
You need microservices for continuous deliveryFowler cites Facebook and Etsy doing it with monoliths
Database per service means a server per servicePrivate tables or a private schema also qualify (microservices.io)
Distributed transactions (2PC) solve cross-service writes"notoriously difficult"; use sagas, outbox, compensation
Shared domain libraries save timeThey couple releases: a distributed monolith
End-to-end tests are the main safety netSlow and brittle; use component and contract tests, few E2E
More services means more autonomyPast the integrators' balance you get chatty nanoservices
Readiness should check all dependenciesChecking downstream services spreads one outage to all callers
Retries make calls reliableUnbounded retries amplify outages; bound them, jitter them, retry idempotent calls only
Prime Video proved microservices are wrongIt showed one workload was better as one process; the lesson is to justify distribution
Microservices and SOA are unrelatedLewis and Fowler: some call microservices "service orientation done right"; the ESB is the main difference

Cheat sheet ​

TopicRemember
DefinitionSuite of small services, own process, lightweight communication, business capabilities, independently deployable (Lewis and Fowler 2014)
Nine characteristicsServices as components, business capabilities, products, smart endpoints, decentralized governance and data, automation, design for failure, evolutionary design
Real testCan this service ship today, alone?
Granularity6 disintegrators (scope, volatility, scalability, fault tolerance, security, extensibility) vs 4 integrators (transactions, workflow, shared code, data relationships)
TeamsOne owner per service; two-pizza size; stream-aligned teams plus a platform team
PremiumDeployment, monitoring, failure handling, eventual consistency: pay only above a complexity threshold
PrerequisitesRapid provisioning, monitoring, rapid deployment, DevOps culture; then tracing and full CD
Cross-cuttingChassis library or sidecar/mesh: auth, logs, traces, metrics, health, config, secrets
DataPrivate per service; sagas, outbox, inbox, CQRS read models
CallsSync only when the answer is needed now; one sync call per request is a good target
ResilienceTimeout every call, bounded jittered retries for idempotent calls, breaker, bulkhead, fallback
ObservabilityOpenTelemetry, W3C traceparent, correlation ID in every log, RED and business metrics
TestingUnit, component, consumer-driven contract per integration, very few E2E
DeploymentImage per service, rolling/blue-green/canary, liveness vs readiness
VersioningTolerant reader, additive changes, expand-and-contract; versions as last resort
Anti-patternsDistributed monolith, shared DB, chatty, nanoservices, entity services, envy

Self-check: questions & answers ​

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

1 — Give Lewis and Fowler's definition in one sentence and name the property it rests on. Must-know ​

Answer

Answer: "A suite of small services, each running in its own process and communicating with lightweight mechanisms", built around business capabilities and "independently deployable by fully automated deployment machinery". The property is independent deployability (a component is "independently replaceable and upgradeable"). See Definition.

2 — Ten services share one PostgreSQL schema and are released every second Tuesday together. Are they microservices? Must-know ​

Answer

Answer: No: they are a distributed monolith. Decentralized data management and independent deployability are missing. See Anti-patterns.

3 — Name three granularity disintegrators and three integrators. Good to know ​

Answer

Answer: Disintegrators: service scope and function, code volatility, scalability and throughput, fault tolerance, security, extensibility. Integrators: database transactions, workflow and choreography, shared code, data relationships. See Granularity.

4 — What are Fowler's microservice prerequisites? Important ​

Answer

Answer: Rapid provisioning, basic monitoring, rapid application deployment, and a DevOps culture; beyond a handful of services, tracing business transactions and full continuous delivery. See Premium.

5 — Why should Orders' readiness probe not check Catalog? Must-know ​

Answer

Answer: If Catalog goes down, every Orders pod would become unready and Orders would disappear entirely, although it could still answer (fail fast, serve other endpoints). Readiness checks only dependencies the service owns. See Lab step 2.

6 — In the lab, why did the fourth request fail in 0.5 ms? Important ​

Answer

Answer: The breaker was open after five failed attempts; it returned ErrOpen without a network call, and the client treats that as permanent (no retry). See Resilience.

7 — How does the trace survive the asynchronous hop to Notifications? Important ​

Answer

Answer: The order handler injects the current context into a map (W3C traceparent) stored with the outbox event; the relay extracts it before sending, and otelhttp puts it on the outgoing request. See Observability.

8 — What is a consumer-driven contract, and where does it run? Must-know ​

Answer

Answer: The consumer writes the expectations (request and the fields it reads); the provider's pipeline replays them against the real handler, so a breaking change fails in the provider's CI. See Testing and contract_test.go.

9 — Billing renames amount_cents to amount. How do you ship it without a lock-step release? Must-know ​

Answer

Answer: Expand: return both fields; migrate consumers (contract tests show who reads amount_cents); contract: remove the old field when no contract uses it. See Versioning.

10 — What do the Prime Video post and Google's HotOS paper have in common? Good to know ​

Answer

Answer: Both argue that physical distribution is a cost that must be justified: Prime Video moved one workload into a single process (90% cheaper per InfoQ); Google argues that microservices "conflate logical boundaries ... with physical boundaries". Neither rejects service boundaries as such. See History.

11 — Why does PaymentProvider::capture only retry on ConnectionException and always send the same Idempotency-Key? Must-know ​

Answer

Answer: A capture is not naturally idempotent: retrying after a 5xx could charge twice unless the provider deduplicates by key. Connection failures before a response are the safe case to retry, and the constant key makes even those safe. See Laravel.

Glossary ​

TermMeaning
Microservice architectureOne application as a suite of small, independently deployable services built around business capabilities
Independent deployabilityA service can be released alone, without coordinated releases of others
Componentization via servicesComponents are out-of-process services, not in-process libraries
Business capabilitySomething the business does (billing, catalogue), used as the unit of decomposition
Products not projectsA team owns a service for its whole life ("you build, you run it")
Smart endpoints and dumb pipesLogic in services; transport (HTTP, simple broker) only moves messages
ESBEnterprise Service Bus: SOA-era middleware with routing, transformation and business rules
SOAService-oriented architecture; microservices are often called a fine-grained form of it
Decentralized governanceTeams choose tools per service; standards come from working code
Decentralized data managementEach service owns its data; no shared schema
Polyglot PersistenceDifferent services using different database technologies
Infrastructure automationPipelines for build, test, provisioning and deployment
Design for failureTreat every remote call as able to fail; timeouts, breakers, monitoring
Evolutionary designExpect to split, merge and replace services as understanding grows
Granularity disintegratorA force for splitting a service (Richards and Ford)
Granularity integratorA force for keeping or putting services together
Conway's LawSystem structure copies the organisation's communication structure
Inverse Conway ManeuverReshape teams to get the desired architecture
Two-pizza teamA team small enough to be fed by two pizzas (Amazon)
Stream-aligned teamA team aligned to a flow of work from a business domain segment (Team Topologies)
Platform teamProvides an internal product (paved road) for stream-aligned teams
Microservice premiumThe extra cost and risk of running a distributed system
Monolith FirstFowler's advice to start with a monolith and split later
Microservice chassisA library or framework handling cross-cutting concerns in every service
SidecarA helper process or container next to each service instance
Service meshInfrastructure layer (data plane proxies + control plane) mediating all service traffic
API gatewaySingle entry point that routes, authenticates and composes for clients
Service discoveryFinding network locations of service instances
Database per servicePrivate persistent data per service, accessible only via its API
SagaA reliably coordinated sequence of local transactions with compensations
Transactional outboxWriting events in the same local transaction as the data, relayed later
Inbox / idempotent consumerDedup table so a redelivered message is processed once
CQRSSeparate read models from the write model; used for cross-service queries
Eventual consistencyReplicas or services converge over time rather than instantly
Circuit breakerStops calling a failing dependency for a cooldown, then probes
BulkheadIsolated resource pools so one dependency cannot exhaust all
JitterRandomised backoff to avoid synchronized retries
Idempotency keyClient-chosen key that lets a server deduplicate retried requests
OpenTelemetryVendor-neutral APIs, SDKs and protocol (OTLP) for traces, metrics and logs
traceparentW3C Trace Context header carrying trace ID, parent span ID and flags
Correlation IDBusiness-level request ID logged by every service on the path
Semantic monitoringMonitoring business outcomes, not only technical metrics
Liveness / readiness / startup probeKubernetes checks: restart, route traffic, wait for start
Rolling updateReplace instances gradually (maxUnavailable, maxSurge)
Blue/green deploymentTwo identical environments; switch traffic; switch back to roll back
Canary releaseRoute a small share of users to the new version first
Contract testVerifies an integration against a shared contract, each side in isolation
Consumer-driven contractContract written by the consumer, verified in the provider's pipeline (Pact)
Component testOne service tested in isolation with collaborators faked
Test pyramidMany unit tests, fewer integration/component/contract, very few end-to-end
Tolerant ReaderConsumers read only what they need and ignore unknown data
Expand and contractAdd new form, migrate users, remove old form
Distributed monolithServices that cannot be deployed independently
NanoserviceA service so small its overhead exceeds its value
Entity serviceA CRUD service per data noun, an anti-pattern for decomposition
Strangler figGradual replacement of a legacy system around its edges
DOMAUber's Domain-Oriented Microservice Architecture: services grouped into domains behind gateways
Logical monolithGoogle HotOS 2023: write one logical application, let a runtime decide physical distribution
DORA metricsChange lead time, deployment frequency, failed deployment recovery time, change fail rate, deployment rework rate
OctaneLaravel package serving the app from long-lived workers (FrankenPHP, RoadRunner, Swoole)
SanctumLaravel's lightweight API-token authentication with abilities
chiLightweight, net/http-compatible Go router
gRPCRPC framework over HTTP/2 with Protocol Buffers contracts (grpc-go in Go)
HystrixNetflix's latency and fault-tolerance library (maintenance mode)

References ​

Built by Morteza Negahi