Service Communication: Sync vs Async, Contracts, Retries, Idempotency
"In general, our view is that APIs with side effects aren't safe to retry unless they provide idempotency." — Marc Brooker, Timeouts, retries, and backoff with jitter, Amazon Builders' Library
Summary: Once a function call becomes a network call, every interaction needs four decisions: the style (wait for an answer or not), the contract (what both sides promise), the failure policy (how long to wait and when to try again) and the duplicate policy (what happens when the same request arrives twice). Focus: The styles matrix (sync request/response, async request/response, event notification, event-carried state transfer, streams), coupling dimensions, orchestration vs choreography, contracts (OpenAPI, Protobuf, AsyncAPI, Pact), compatibility and versioning, timeouts and deadline propagation, retries with backoff, jitter and budgets, idempotency keys, hedging, API composition and BFF, trace propagation and error semantics, with Go and Laravel code and a retry-storm lab. Learning goal: For any arrow between two services, choose the style and say why, write its contract, give it a deadline and a retry policy that cannot cause a storm, make it safe to repeat, and prove it with a contract test and a fault-injection run.
This chapter sits in the Microservices in Practice group, after Service Boundaries (where to cut) and before API Gateway, BFF & Service Mesh (what sits on the edge). It works at the level of architecture decisions. Depth lives elsewhere: REST, gRPC and GraphQL design in REST API Design, gRPC & Protobuf and GraphQL; brokers, delivery guarantees, the outbox, DLQs and the inbox in the messaging path, especially Delivery Guarantees, Transactional Outbox, Idempotent Consumers & the Inbox and Saga; the resilience mechanics in Timeouts, Retries & Jitter, Circuit Breaker, Bulkheads and API Idempotency. This page tells you which of those tools an interaction needs and how they fit together.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a network call is not a function call | Why it exists |
| Postel, consumer-driven contracts, jitter, Problem Details | Where it comes from |
| The five styles, one block each | Sync, Async commands, Event notification, Event-carried state transfer, Streams |
| Temporal, availability, latency and consistency coupling | Coupling |
| Orchestration vs choreography | Orchestration and choreography |
| OpenAPI, Protobuf, AsyncAPI, Pact, versioning | Contracts, Consumer-driven contracts, Compatibility |
| Timeouts, deadlines, retries, jitter, budgets | Deadlines, Retries |
| Idempotency-Key design | Idempotency keys |
| Circuit breakers, bulkheads, hedging | Breakers and bulkheads, Hedging |
| Reads across services | API composition and BFF |
| mTLS, tokens, traceparent, error formats | Auth, Tracing, Errors |
| Numbers, knobs, status codes | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Contract tests, consumer tests, chaos | Testing |
| Which style, which policy | Choosing |
| Monolith to distributed system | In architecture |
| Retry storm with real numbers | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The styles. Newman's Building Microservices (2nd ed.) organises chapter 4 around exactly this split: "asynchronous vs synchronous calls, request-response and event-driven collaboration styles".
| Style | In plain words | Tiny example | Who waits | Main risk |
|---|---|---|---|---|
| Sync request/response | Call and wait for the answer | GET /customers/42 over REST or a gRPC unary call | The caller, for the whole chain | One slow or dead dependency stalls the caller |
| Async request/response (command) | Ask someone to do something; hear back later | ChargeOrder on a queue, PaymentSucceeded comes back | Nobody blocks; the workflow waits | Lost or duplicated messages, harder debugging |
| Event notification | Tell the world something happened, with an ID | OrderPlaced {order_id} | Nobody | Hidden flow; consumers call back for details |
| Event-carried state transfer | Tell the world what changed, with the data | CustomerChanged {id, name, tier, version} | Nobody | Copies of data everywhere, staleness |
| Event stream | Append facts to a durable, replayable log | Kafka topic orders with retention | Nobody; each consumer keeps its offset | Schema evolution, ordering per key |
The coupling each style creates.
| Coupling | Question it answers | Sync | Async command | Events |
|---|---|---|---|---|
| Temporal | Must both be up at the same moment? | Yes | No (broker buffers) | No |
| Availability | Does the caller fail when the callee fails? | Yes, unless degraded | No, it queues | No |
| Latency | Does the callee's latency add to the user's? | Yes, per hop | No | No |
| Consistency | Is the result visible immediately? | Yes (read-your-write) | Eventually | Eventually |
| Knowledge | Does the sender know the receiver? | Yes | Yes (one named receiver) | No |
The reliability toolkit, in the order you apply it.
| Tool | Promise | Must-have companion | Owner page |
|---|---|---|---|
| Deadline | Nobody waits past the point the user stopped caring | Propagation to every hop | Deadlines |
| Retry with backoff + jitter | Transient failures become invisible | Idempotency, a budget | Retries |
| Idempotency key | Doing it twice equals doing it once | Storage with TTL, fingerprint | Idempotency keys |
| Circuit breaker | Stop calling a dependency that is failing | Fallback | Circuit Breaker |
| Bulkhead | One slow dependency cannot use all threads | Per-dependency pools | Bulkheads |
| Hedging | Cut tail latency on idempotent reads | Cancellation, throttling | Hedging |
| Contract test | A provider change cannot silently break a consumer | CI gate | Consumer-driven contracts |
| Trace context | One request can be followed across all hops | traceparent on every call and message | Tracing |
The picture is the styles matrix. Request/response can be synchronous or asynchronous; event-driven collaboration is asynchronous by nature. Moving right removes temporal coupling and costs visibility of the overall flow.
Why it exists
Inside one process a call costs nanoseconds, cannot be half-done and either returns or throws. Across a network the same line of code can be slow, fail before sending, fail after the other side did the work, or arrive twice. The microservices.io pattern for synchronous calls (Remote Procedure Invocation) names the price directly: "Reduced availability since the client and the service must be available for the duration of the interaction". Its messaging pattern names the other side: "Additional complexity of message broker, which must be highly available". Every service-communication decision is a choice between those two costs, plus the work you must add to survive either.
| Synchronous request/response | Asynchronous messaging |
|---|---|
| Simple to write, read and debug | More moving parts: broker, consumers, DLQ |
| Answer available now; strong read-after-write | Answer arrives later; the UI must show "pending" |
| Availability multiplies: 3 services at 99.9% give about 99.7% | Broker buffers; producer stays up when consumers are down |
| Latency adds per hop | Latency of the request path stays short |
| Failure is visible immediately (timeout, 503) | Failure is delayed (DLQ, stuck saga) |
| Retries happen in the caller, under a deadline | Retries happen in the consumer, with redelivery |
| Good for queries and for decisions the user waits on | Good for side effects, fan-out, slow or spiky work |
The analogy we reuse on this page: the phone call, the letter and the noticeboard. A phone call is synchronous: both must be available, and if the line drops mid-sentence you do not know what the other person heard. A letter is an asynchronous command: you name the receiver, it waits in their mailbox, the reply comes later, and the post may occasionally deliver the same letter twice. A noticeboard is an event: you pin "the office moves on Monday" and do not know or care who reads it. A deadline is "if you cannot answer before my train leaves, do not bother". An idempotency key is the reference number on the letter that lets the receiver say "I already did this one".
Three common misunderstandings, up front
- "Async is always better because it decouples." It removes temporal coupling and adds other costs: the user waits for an eventual result, duplicates and reordering appear, and the flow is no longer visible in any one program. Fowler warns that with event notification "it's very easy to make nicely decoupled systems with event notification, without realizing that you're losing sight of that larger-scale flow".
- "Retries make a system more reliable." Retries make transient failures invisible and make overload worse. AWS's article puts it in one word: retries are "selfish".
- "A timeout means the call did not happen." A timeout means you stopped waiting. gRPC's status-code table says
DEADLINE_EXCEEDED"may be returned even if the operation has completed successfully". Every retry design starts from that fact.
Where it comes from
The problem is as old as distributed computing; the vocabulary we use for it today was written down mostly after 2005.
Postel's robustness principle. Fowler's Tolerant Reader (9 May 2011) quotes it as the governing law of decoupled collaboration: "be conservative in what you do, be liberal in what you accept from others" (Jon Postel). In service terms: read only the fields you need, ignore the rest, and never send more than the contract allows.
Consumer-driven contracts, 2006. Ian Robinson's Consumer-Driven Contracts: A Service Evolution (martinfowler.com, 12 June 2006) separated the provider contract ("Closed and complete", "Singular and authoritative") from consumer contracts ("Open and incomplete", "Multiple and non-authoritative"). A provider that knows every consumer's expectations can evolve without breaking them. Pact turned this into a tool: "Contract testing is a technique for testing an integration point by checking each application in isolation", against a shared, documented contract.
Tail latency and hedging, 2013. Dean and Barroso's The Tail at Scale (CACM, February 2013) named "hedged requests" and showed that sending the second request only after the first has been outstanding longer than the 95th-percentile expected latency "limits the additional load to approximately 5% while substantially shortening the latency tail".
Microservices, 2014. Lewis and Fowler's article (25 March 2014) popularised "smart endpoints and dumb pipes": put logic in the services, keep the transport simple.
Exponential backoff and jitter, 2015. Marc Brooker's AWS Architecture Blog post (4 March 2015) compared "Full Jitter", "Equal Jitter" and "Decorrelated Jitter" and concluded that "Equal Jitter" is "the loser"; with 100 contending clients, jitter "reduced our call count by more than half".
Google SRE, 2016. The SRE book's chapters on handling overload and cascading failures gave the retry budget (per request "up to three attempts", per client a retry ratio "below 10%"), the multiplication rule ("64 attempts (4^3) on the database") and deadline propagation.
Events, 2017. Fowler's What do you mean by "Event-Driven"? (7 February 2017) split the word into event notification, event-carried state transfer, event sourcing and CQRS, and named the "passive-aggressive command".
Idempotency keys, 2017. Brandur Leach's Stripe post (22 February 2017) described the Idempotency-Key header on mutating endpoints, combined with exponential backoff and jitter in the client libraries.
Standards, 2020 to now. W3C Trace Context became a Recommendation (6 February 2020; current edition 23 November 2021). RFC 9457 Problem Details for HTTP APIs (July 2023) obsoleted RFC 7807. OpenAPI 3.1.0 and AsyncAPI 3.0.0 are the current description formats. The IETF Idempotency-Key HTTP Header Field is still a draft (-09, 21 November 2026), not an RFC.
Year Idea What changed in practice
1 - Postel's principle (quoted by Fowler) Tolerant readers, additive changes
2 2006 Consumer-driven contracts (Robinson) Providers test against consumer expectations
3 2011 Tolerant Reader (Fowler) Ignore unknown fields by design
4 2013 Tail at Scale: hedged requests Tail latency treated as a design input
5 2014 Microservices: smart endpoints, dumb pipes Every module boundary becomes a network hop
6 2015 Backoff + jitter (Brooker) Randomised retries become the default
7 2016 SRE: retry budgets, deadline propagation Retries are rationed, deadlines shared
8 2017 Event-driven taxonomy; Stripe keys Events named precisely; safe POST retries
9 2020 W3C Trace Context One traceparent header across vendors
10 2023 RFC 9457 Problem Details One error shape for HTTP APIs
11 2026 Idempotency-Key draft -09 Header standardisation still in progressThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a request flow, real scenarios, how products provide it, and the fix.
Synchronous request/response Must-know
In plain words: the caller sends a request and does nothing else on that path until the answer, an error or its own deadline arrives.
Common misunderstanding: "gRPC or HTTP/2 makes it asynchronous." The client library may be non-blocking (futures, goroutines, Guzzle promises), but the interaction is still synchronous: the caller's business step cannot finish without the callee being up right now. Non-blocking I/O changes thread usage, not coupling.
Definition: an interaction in which the caller needs the response to continue and the callee must be available for the duration of the call (microservices.io, Remote Procedure Invocation: "The client uses a request/reply-based protocol to make requests to a service.").
Checkout (budget 800 ms) Pricing Inventory
1 POST /checkout arrives
2 -> GET /quote (deadline 780) computes 40 ms
3 <- 200 {total: 4999}
4 -> POST /reservations (deadline 720, Idempotency-Key k1)
5 reserves, 60 ms
6 <- 201 {reservation_id}
7 responds 201 to the user at ~130 ms; any hop failing fails the whole requestReal scenario: price and stock checks during checkout (the user waits for the answer); permission checks ("may user 7 see invoice 9?"); a mobile app reading a profile; a payment authorisation that must succeed or fail before the order page renders.
What provides it:
| Product | Synchronous primitive | Default timeout | Notes |
|---|---|---|---|
Go net/http | http.Client.Do | None (Timeout zero means no timeout) | Always set Timeout or a context deadline |
| Laravel HTTP client (Guzzle) | Http::get/post | 30 s response, 10 s connect | timeout(), connectTimeout() |
| gRPC (all languages) | Unary RPC | No deadline by default | "always explicitly set a realistic deadline" |
| GraphQL | Query over HTTP | Whatever the HTTP client sets | One request, many resolvers behind it |
| Envoy / Istio / Linkerd | Route timeout, retries | Per-route config | See Service Mesh |
Fix / how to use it: keep sync for reads and for decisions the user is actively waiting on; give every call a deadline derived from the user's budget (Deadlines); keep sync chains short (two hops is a smell to review, four is a design problem); retry only idempotent calls (Retries).
Asynchronous request/response and commands Must-know
In plain words: you hand a named receiver a job ("charge this order") through a queue and carry on; the result comes back as another message, a callback or a status you poll.
Common misunderstanding: "If it goes through a queue, it is an event." A message that tells one specific receiver to do something is a command, even on Kafka. Fowler calls a command dressed as an event a "passive-aggressive command": the source "expects the recipient to carry out an action, and ought to use a command message to show that intention, but styles the message as an event instead."
Definition: microservices.io lists the asynchronous variants: "Request/response - a service sends a request message to a recipient and expects to receive a reply message promptly", "Request/asynchronous response - a service sends a request message to a recipient and expects to receive a reply message eventually", and "Notifications - a sender sends a message a recipient but does not expect a reply."
Orders Broker (queue) Payments
1 INSERT order (PENDING) + outbox row in one transaction
2 relay publishes ChargeOrder{msg_id, order_id} -> payments.commands
3 responds 202 Accepted + Location: /orders/1001
4 consumes ChargeOrder
5 charges (Idempotency-Key order-1001-charge)
6 <- PaymentSucceeded{order_id} on payments.events
7 consumes; UPDATE order SET status = PAID
8 user polls GET /orders/1001 or gets a push: "paid"Real scenario: charging a card after checkout; generating an invoice PDF; sending email; provisioning an account in a third-party system; any long-running or rate-limited job.
What provides it:
| Product | Command transport | Reply mechanism | Deep page |
|---|---|---|---|
| RabbitMQ | Queue per receiver | reply_to + correlation id, direct reply-to | Request-Reply |
| Kafka | Topic per command type | Reply topic keyed by correlation id | Kafka |
| Amazon SQS | Queue | Second queue, or callback URL | Other Brokers |
| Laravel queues | dispatch(new ChargeOrder(...)) | Event or job dispatched on completion | Laravel Queue Internals |
| HTTP | 202 Accepted + status URL | Poll or webhook | REST API Design |
Fix / how to use it: publish through a transactional outbox so the command is not lost when the database commits and the broker call fails; give each command a stable message ID; make the handler idempotent (Idempotency keys, Inbox); show "pending" in the UI instead of pretending it is done.
Event notification Important
In plain words: "something happened, here is its ID"; anyone interested reacts, and if they need details they ask.
Common misunderstanding: "Events remove coupling." They remove the sender's knowledge of receivers, but receivers that call back for details are synchronously coupled to the sender again, and the end-to-end flow is no longer written anywhere. Fowler: "Often the only way to figure out this flow is from monitoring a live system."
Definition: Fowler: "This happens when a system sends event messages to notify other systems of a change in its domain. A key element of event notification is that the source system doesn't really care much about the response."
Orders Broker Shipping Loyalty
1 publish OrderPlaced{order_id: 1001}
2 fan-out to subscribers
3 GET /orders/1001 (sync callback)
4 adds points from event only
5 a change to OrderPlaced's meaning now affects two teams nobody listedReal scenario: cache invalidation ("product 42 changed"); audit and analytics feeds; triggering a search re-index; webhooks to customers.
What provides it: RabbitMQ fanout/topic exchanges, Kafka topics with consumer groups, Redis Pub/Sub (no persistence) and Redis Streams, SNS and Google Pub/Sub; in-process, Laravel events and Go channels. The routing details are in Routing Topologies.
Fix / how to use it: keep event names in the past tense and the payload a fact, not an instruction; if consumers keep calling back, switch to event-carried state transfer; document the flow (an AsyncAPI file plus a sequence diagram) because the code will not show it; trace it (Tracing).
Event-carried state transfer Must-know
In plain words: the event carries the changed data, so receivers keep their own copy and never need to ask the source.
Common misunderstanding: "A local copy means the data is wrong." The copy is stale for a bounded time and correct after that, which is exactly what most reads need (a shipping label needs the address as of the order, not as of this millisecond). What breaks it is unordered or duplicated delivery without a version check.
Definition: Fowler: "This pattern shows up when you want to update clients of a system in such a way that they don't need to contact the source system in order to do further work." The gain: "greater resilience, since the recipient systems can function if the customer system is becomes unavailable" and "We reduce latency, as there's no remote call required". The cost: "lots of data schlepped around and lots of copies", and complexity on the receiver.
Customers Broker Orders (local customer_snapshots)
1 UPDATE customer 42 tier=gold, version 7
2 publish CustomerChanged{id 42, tier gold, version 7}
3 UPDATE customer 42 email=..., version 8
4 publish CustomerChanged{..., version 8}
5 v8 delivered first upsert v8 (8 > 0)
6 v7 delivered late ignored (7 < 8): WHERE version < EXCLUDED.version
7 customers is down for an hour - orders still prices with tier goldReal scenario: orders keeps customer tier and address; search keeps product name and price; a billing service keeps the plan of each tenant; a mobile BFF keeps a denormalised view.
What provides it:
| Product | Fit for ECST | Notes |
|---|---|---|
| Kafka with log compaction | Very good | Latest value per key retained; new consumers rebuild from the topic |
| RabbitMQ | Good for live updates | No replay of history; bootstrap a new consumer from an API or snapshot |
| Redis Streams | Good, bounded by MAXLEN | Trimmed history; plan the bootstrap |
| CDC (Debezium) | Very good | Events derived from the database log (CDC) |
Fix / how to use it: include a monotonically increasing version (or the source's commit position) and upsert only when it is newer; read with a tolerant reader; define who owns the data (the source) and never write back to the copy (Data Ownership); plan how a new consumer gets the initial state.
Event streams Good to know
In plain words: a durable, ordered log of facts that any number of consumers read at their own pace and can re-read from the start.
Common misunderstanding: "A stream is just a queue that keeps messages." The consumer, not the broker, owns its position (offset), so replay, new projections and late consumers are normal; ordering is per partition (per key), not global.
Definition: an append-only log with retention, partitioned by key; consumers in a group share partitions and commit offsets. Kafka, Redis Streams, Pulsar, Kinesis and NATS JetStream implement it.
Producer Kafka topic orders (partition by order_id) Analytics Search (new)
1 append e1..e100 p0: e1 e4 ... | p1: e2 e5 ... | p2: ...
2 offset 100 -
3 starts at offset 0, replays all
4 append e101 ordering holds per order_id onlyReal scenario: feeding analytics, search and recommendation from the same facts; rebuilding a read model after a bug; audit trails. Details: Kafka, Event Sourcing & CQRS, Stream Processing.
Fix / how to use it: pick the partition key from the ordering you need (Ordering & Partitioning); version the schema (Message Design & Schema Evolution); size retention for the longest replay you will need.
Coupling dimensions: temporal, availability, latency, consistency Must-know
In plain words: "coupled" is not one thing. Ask four separate questions about every arrow: must both be up at once, does my failure follow yours, does your slowness become mine, and must I see your result immediately?
Common misunderstanding: "Loose coupling means using a broker." A broker removes temporal and availability coupling. It does not remove semantic coupling: if the OrderPlaced schema changes, every consumer still breaks. Contracts handle that (Contracts).
Definition:
| Dimension | Coupled when | Example | Decoupled by |
|---|---|---|---|
| Temporal | Both must run at the same moment | Checkout calls Pricing synchronously | Queue, events, local copy |
| Availability | Callee down means caller down | Profile page fails when Recommendations fails | Fallback, cache, async |
| Latency | Callee latency adds to caller's | Five sequential calls of 50 ms each | Parallel calls, local data, async |
| Consistency | Caller needs callee's latest state | "Is the seat still free?" | Cannot be removed; keep sync or redesign ownership |
| Semantic (contract) | Both depend on field meaning | amount in cents vs euros | Versioned contracts, contract tests |
| Deployment | Both must deploy together | Shared library with the DTOs | Backward-compatible changes |
Arrow Temporal Availability Latency Consistency need
1 checkout -> pricing (sync) yes yes yes high (price shown = price charged)
2 checkout -> email (queue) no no no low (email may arrive later)
3 orders <- customers (ECST) no no no medium (tier may lag seconds)Real scenario: the classic distributed monolith: every request crosses six services synchronously, so availability is the product of six SLOs (SLOs & Error Budgets).
Fix / how to use it: write the four answers next to every arrow on your architecture diagram; any arrow with high consistency need stays synchronous or moves the data into the same service; everything else is a candidate for async or a local copy.
Orchestration vs choreography Must-know
In plain words: in orchestration one component tells the others what to do, step by step; in choreography each service reacts to events from the others and nobody holds the whole plan.
Common misunderstanding: "Choreography is more decoupled, so it is better." It removes the central coordinator and moves the workflow into the gaps between services. With more than three or four steps, nobody can answer "where is order 1001 stuck?" without a trace. Orchestration is not "a monolith": the orchestrator owns the process, not the participants' data.
Definition: microservices.io (Saga): "Choreography - each local transaction publishes domain events that trigger local transactions in other services"; "Orchestration - an orchestrator (object) tells the participants what local transactions to execute". The same two styles apply to any multi-step interaction, not only sagas. Richards and Ford (Software Architecture: The Hard Parts) treat coordination as one of three independent dimensions of a distributed workflow, next to communication (sync or async) and consistency (atomic or eventual).
Choreography Orchestration
1 Orders: OrderCreated -> Orchestrator: create order PENDING
2 Payments: hears it, charges, PaymentDone -> Orchestrator -> Payments: ChargeOrder (command)
3 Inventory: hears PaymentDone, reserves Payments -> Orchestrator: Charged (reply)
4 Shipping: hears StockReserved, books Orchestrator -> Inventory: Reserve (command)
5 failure: who compensates? each listener must failure: orchestrator runs compensations in orderReal scenario: order fulfilment (orchestration usually wins: many steps, compensations, a status page); "user signed up" fan-out to email, analytics and CRM (choreography wins: independent reactions, no compensation).
What provides it: Temporal, AWS Step Functions, Camunda and Laravel Bus::chain for orchestration (Durable Workflows); any broker for choreography. Compensation and saga state are taught in Saga Pattern.
Fix / how to use it: use the decision table in Choosing; whichever you pick, give the workflow an ID, propagate it, and make every step idempotent.
Contracts: OpenAPI, Protobuf, AsyncAPI, contract-first Must-know
In plain words: the contract is the written promise between two services: which operations, which fields, which errors, which guarantees. If it only exists in code, it changes by accident.
Common misunderstanding: "The schema is the contract." Robinson lists more: document schemas, interfaces, conversations (message exchange patterns), policy (security, transactions) and "Quality of service characteristics" such as "availability, latency and throughput". A schema-compatible change that makes an endpoint ten times slower breaks the contract too.
Definition: a machine-readable description that both sides build or test against:
| Format | Describes | Spec quote | Generates |
|---|---|---|---|
| OpenAPI 3.1.0 | HTTP APIs | "a standard, programming language-agnostic interface description for HTTP APIs" | Clients, servers, docs, mock servers |
| Protocol Buffers (proto3) + gRPC | RPC services and messages | Field numbers are the wire identity | Go/PHP/Java stubs |
| AsyncAPI 3.0.0 | Message-driven APIs | "protocol-agnostic, so you can use it for APIs that work over any protocol (e.g., AMQP, MQTT, WebSockets, Kafka, STOMP, HTTP, Mercure, etc)" | Docs, code, validators |
| JSON Schema / Avro | Message payloads | Used by schema registries | Validators |
| GraphQL SDL | Graph APIs | Typed schema | Clients, resolvers |
Contract-first vs code-first: in contract-first the team writes openapi.yaml or billing.proto first, reviews it with consumers, and generates code; in code-first the contract is generated from annotations. Contract-first is better when several teams consume the API or when you need a mock before the provider exists; code-first is fine inside one team.
Contract-first workflow
1 billing team drafts billing.proto (ChargeRequest, ChargeReply, errors)
2 orders team reviews: needs idempotency_key, currency
3 buf lint + breaking check in CI against main
4 generate Go server stub and PHP client
5 orders writes consumer contract test (Pact) against the mock
6 billing implements; provider verification runs in billing's CIFix / how to use it: keep the contract in the provider's repository, versioned with the code; run a breaking-change check in CI (for Protobuf, the rules in Compatibility); publish AsyncAPI for every event topic, because events have no URL anyone can browse.
Consumer-driven contract tests and Pact Important
In plain words: each consumer writes down the exact requests it sends and the parts of the responses it reads; the provider runs those expectations in its own CI, without the consumer running.
Common misunderstanding: "Contract tests replace integration tests." They check the shape of each interaction in isolation. They do not check that the whole flow works end to end, or performance. Pact docs: "Without contract testing, the only way to ensure that applications will work correctly together is by using expensive and brittle integration tests." Contract tests make most of those unnecessary; a few smoke tests stay.
Definition: a consumer test runs the real client against a mock provider built from the expected interaction; Pact then writes a pact file. In provider verification, "each request is sent to the provider, and the actual response it generates is compared with the minimal expected response described in the consumer test", and it passes if the response "contains at least the data described". Provider states describe preconditions ("customer 42 has enough credit").
Orders CI (consumer) Billing CI (provider)
1 test: BillingClient.Charge vs Pact mock
2 pact file orders-billing.json written
3 published to a Pact Broker (or shared file)
4 fetch pacts for billing
5 set provider state "customer 42 has enough credit"
6 replay POST /charges against real handler
7 response has charge_id (string) and status "captured": pass
8 billing renames status -> state: verification fails BEFORE deployWhat provides it: Pact (HTTP and message pacts, many languages, Pact Broker/PactFlow), Spring Cloud Contract (JVM), schema-registry compatibility checks for events. This page's code is "Pact-style": the same JSON file is verified by Go and by Laravel without the Pact runtime, so it runs anywhere.
Fix / how to use it: consumers only assert fields they actually read (that keeps the provider free to add fields); use type matchers for generated values; block the provider's deploy when any consumer's pact fails. Testing messaging contracts: Testing Messaging.
Compatibility and versioning Must-know
In plain words: backward compatible means new providers still work with old consumers; forward compatible means old consumers still work with messages from new producers. Independent deployment needs both.
Common misunderstanding: "Add /v2 and you are safe." A new version is a new contract that must be run, monitored and retired. The cheaper default is to make every change additive and keep one version; version only when you must break.
Definition and rules:
| Change | JSON over HTTP | Protobuf (binary) | Safe? |
|---|---|---|---|
| Add an optional field | Old readers ignore it (tolerant reader) | "Adding new fields is safe" | Yes |
| Remove a field | Breaks readers that use it | "Removing fields is safe" only if the number is never reused; reserved 2, 3; | Only after no consumer reads it |
| Rename a field | Breaks readers | Wire-safe (number unchanged), breaks ProtoJSON and code | No (add new, deprecate old) |
| Change a field's type or number | Breaks | "Changing field numbers for any existing field is not safe" | No |
| Add a required field | Breaks old senders | "Don’t Add a Required Field" | No |
| Add an enum value | Breaks exhaustive switches | "Adding additional values to an enum is safe" on the wire | Wire yes, code maybe |
| Tighten validation | Breaks old senders | Same | No |
| Change meaning (cents to euros) | Silent corruption | Same | Never; new field |
Expand-and-contract (parallel change) for renaming amount -> amount_cents
1 v1: provider sends amount and amount_cents (expand)
2 consumers move to amount_cents, one deploy at a time; pacts show who still reads amount
3 pact verification: no consumer reads amount any more
4 provider stops sending amount; Protobuf: reserved its number (contract)Versioning strategies: URI (/v2/charges), header or media type (Accept: application/vnd.example.v2+json), date-based versions (Stripe-style API versions pinned per account), package versions in Protobuf (billing.v2), and new topic or event type names for messages. Details: API Versioning & Evolution and Message Design & Schema Evolution.
Fix / how to use it: tolerant reader on every consumer; additive changes by default; expand-and-contract for renames; a deprecation header or changelog with a removal date; contract tests that tell you when the last consumer moved.
Timeouts, budgets per hop and deadline propagation Must-know
In plain words: decide once, at the edge, how long the user will wait; every hop below gets "what is left minus a little", and work stops everywhere when the time is up.
Common misunderstanding: "Give every client a generous timeout, like 30 seconds, to be safe." Long fixed timeouts are the cause of thread exhaustion. The SRE book's bimodal-latency example: a deadline "three orders of magnitude larger than the normal mean latency" led to thread exhaustion when 5% of requests never completed. And a timeout per hop that ignores the caller wastes work: the callee keeps going after the user is gone.
Definition: gRPC: "A deadline is used to specify a point in time past which a client is unwilling to wait for a response from a server." Deadline propagation (Google SRE): "a deadline is set high in the stack (e.g., in the frontend). The tree of RPCs emanating from an initial request will all have the same absolute deadline." gRPC sends it as a remaining timeout to avoid clock skew: "gRPC converts the deadline to a timeout from which the already elapsed time is already deducted."
Hop Receives budget Spends Sends on (minus 10 ms margin)
1 client 1000 ms - 1000
2 edge 1000 50 940
3 orders 940 200 730
4 billing 730 100 620
5 payment 620 - refuses work it knows takes longer than 620 msHow to choose the numbers: AWS: start from the callee's latency; "we choose an acceptable rate of false timeouts (such as 0.1%). Then, we look at the corresponding latency percentile on the downstream service (p99.9 in this example)." The top-level budget comes from the product (the page must render in 1 s) or the SLO (SLOs, Latency Budgets). The SRE book adds: reduce the outgoing deadline by "a few hundred milliseconds" for transit, and consider an upper bound per dependency.
Real scenario: a search page with a 300 ms budget fanning out to five backends; a payment API whose partner promises 2 s; a batch job that calls an API with a 30 s budget (budgets differ by caller, so they must travel with the request).
What provides it:
| Product | Deadline primitive | Propagates automatically? | Error when exceeded |
|---|---|---|---|
| gRPC Go | context.WithTimeout; grpc-timeout on the wire | Yes, when you pass the incoming ctx to the outgoing call (docs: enabled by default in Java and Go) | codes.DeadlineExceeded; server side sees CANCELLED |
| gRPC C++ | ClientContext::set_deadline | Must be enabled explicitly | DEADLINE_EXCEEDED |
Go net/http | http.NewRequestWithContext(ctx, ...) | No header; you add one (this page: Request-Timeout-Ms, a convention) | context deadline exceeded |
| Laravel HTTP client | Http::timeout($seconds) (accepts int|float) | No; compute from a scoped budget | ConnectionException |
| Envoy | x-envoy-expected-rq-timeout-ms header, route timeout | Within the mesh | 504, upstream request timeout |
Fix / how to use it: Go: callbudget middleware plus Outgoing; Laravel: PropagateCallBudget middleware plus CallBudget::outgoingHeaders(); servers check the remaining time before each expensive stage and stop when the context is done.
Retries: backoff, jitter, storms and budgets Must-know
In plain words: try again only when the failure is probably temporary, only if doing it twice is harmless, after a random wait, a limited number of times, at one layer, and only while most calls are succeeding.
Common misunderstanding: "Three retries is a safe default everywhere." Three retries at each of several layers multiplies. Google SRE: if "the backend, frontend, and JavaScript layers all issue 3 retries (4 attempts), then a single user action may create 64 attempts (4^3) on the database." AWS gives the five-layer version: "the load on the database will increase 243x".
Definition: a retry policy has six parts:
| Part | Rule | Source |
|---|---|---|
| What to retry | Transient errors only: connection failure, 503, 429, UNAVAILABLE | gRPC: UNAVAILABLE "most likely a transient condition" |
| Precondition | Idempotent operation, or an idempotency key | AWS: "APIs with side effects aren't safe to retry unless they provide idempotency" |
| How many | Per request at most 3 attempts | SRE: "per-request retry budget of up to three attempts" |
| When | Exponential backoff with jitter | SRE: "Always use randomized exponential backoff when scheduling retries" |
| Where | One layer, the one right above the failing one | SRE: "retried at the layer immediately above the layer that is rejecting them"; AWS: "retry at a single point in the stack" |
| How much overall | A budget: retries below about 10% of requests, or a token bucket | SRE per-client ratio "below 10%"; gRPC retryThrottling |
t (ms) Naive clients (no jitter) Full-jitter clients
1 0 1000 clients fail together 1000 clients fail together
2 100 1000 retry at exactly 100 ms retries spread over 0..100 ms
3 300 1000 retry at exactly 300 ms spread over 0..200 ms; server drains between
4 700 same spike again; recovery delayed most succeeded; few remainReal scenario: a deploy restarts half of the billing pods for 20 s; a database failover takes 30 s; a partner API rate-limits with 429 and Retry-After: 2; a network blip drops connections for 200 ms. All four are worth retrying; a 400, a 422, a PERMISSION_DENIED or a timeout on a non-idempotent call are not.
What provides it:
| Product | Retry mechanism | Jitter | Budget |
|---|---|---|---|
| gRPC (Java, C++, Go) | Service config retryPolicy per method | ±20% applied automatically | retryThrottling {maxTokens, tokenRatio} |
| AWS SDKs | Built-in retry modes | Yes | Token bucket, "added this behavior to the AWS SDK in 2016" |
| Laravel HTTP client | Http::retry($times, $sleepMs|closure, $when, throw:) | Only if your closure adds it | None; add RateLimiter |
| Laravel queues | #[Tries], #[Backoff([1, 5, 15])], release() | No (fixed list) | Per job; see Retry & Backoff |
| Envoy / Istio | Route retry_policy, retryOn | Yes | retry_budget on the cluster |
| Go stdlib | None | - | - (this page's retry package) |
Fix / how to use it: full jitter sleep = random(0, min(cap, base * 2^attempt)); honour Retry-After and gRPC server pushback (grpc-retry-pushback-ms); stop when the deadline cannot fit another attempt; count retries in metrics; mechanics in Timeouts, Retries & Jitter.
Idempotency keys: storage, TTL, replay, concurrent duplicates Must-know
In plain words: the client invents one ID for "this operation" and sends it on every attempt; the server remembers what it answered for that ID and gives the same answer again instead of doing the work twice.
Common misunderstanding: "Our POST checks if the order exists, so it is idempotent." A check-then-insert is a race: two retries arriving 5 ms apart both see "not exists". Idempotency needs an atomic claim (a unique key), a stored outcome, and a rule for the duplicate that arrives while the first is still running.
Definition: Stripe: "A client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request." Stripe's rules (API v1): keys "up to 255 characters long", "we suggest using V4 UUIDs", keys may be removed "after they’re at least 24 hours old", and "The idempotency layer compares incoming parameters to those of the original request and errors if they’re not the same". The IETF draft (-09) adds the status codes: 400 when a required key is missing, 422 when a key is reused with a different payload, and 409 when "the request is retried, while the original request is still being processed".
Client A (retrying) Billing (idempotency_keys has PK (scope, key))
1 POST /charges Idempotency-Key: k1 INSERT (cust-7, k1, fp, in progress) -> 1 row
2 ...network times out at 2 s still charging the card
3 POST /charges Idempotency-Key: k1 (retry) INSERT -> 0 rows; row in progress -> 409 Conflict
4 backs off 400 ms charge done; UPDATE row SET status 201, body
5 POST /charges Idempotency-Key: k1 (retry) INSERT -> 0 rows; fingerprint equal -> replay 201 (Idempotent-Replayed: true)
6 POST /charges Idempotency-Key: k1, amount changed fingerprint differs -> 422Design decisions:
| Decision | Options | Recommendation |
|---|---|---|
| Who makes the key | Client (UUID v4) or derived from business identity (order-1001-charge) | Derived when one business action maps to one call; UUID otherwise |
| Scope | Global, per client, per endpoint | Per authenticated client and endpoint, so tenants cannot collide |
| Storage | Same database as the side effect, Redis, a dedicated table | Same database and transaction as the effect when possible; Redis only with persistence and an accepted gap |
| Claim | Unique constraint / INSERT ... ON CONFLICT DO NOTHING, Redis SET NX | Unique constraint; it is atomic and survives restarts |
| What is stored | Status, headers you need, body, fingerprint | Enough to replay byte-for-byte |
| Failure (5xx) | Store it (Stripe v1 replays "including 500 errors") or delete the claim | Choose and document; this page deletes so a clean retry can run |
| Crashed holder | Lock forever, or take over after a lease | Lease (locked_at older than N minutes) |
| TTL | Hours to days | At least the client's longest retry window; Stripe: at least 24 h |
| Fingerprint | Hash of method, path and body | Required to detect key reuse (422) |
Real scenario: charges and refunds, order creation from a flaky mobile network, transfers between accounts, sending an SMS that costs money, creating a cloud resource (AWS's EC2 RunInstances has "explicit token-based mechanisms to provide idempotency").
Fix / how to use it: the SQL is in Solving the classic problems; Go idempotency middleware and Laravel RequireIdempotencyKey below; the key travels on the client's retries, and the same key must be passed downstream when this service calls a payment provider. Consumers of messages use the same idea with the message ID (Inbox). Deep dive: API Idempotency.
Circuit breakers and bulkheads Important
In plain words: a circuit breaker stops calling a dependency that keeps failing and fails fast for a while; a bulkhead gives each dependency its own limited pool so one slow dependency cannot take all your threads or connections.
Common misunderstanding: "A circuit breaker is the fix for retry storms." It helps, but AWS notes that breakers "introduce modal behavior into systems that can be difficult to test, and can introduce significant addition time to recovery"; AWS prefers "limiting retries locally using a token bucket". Use both deliberately, not by default.
Definition: microservices.io: "When the number of consecutive failures crosses a threshold, the circuit breaker trips, and for the duration of a timeout period all attempts to invoke the remote service will fail immediately. After the timeout expires the circuit breaker allows a limited number of test requests to pass through."
t Calls to recommendations Breaker state
1 0 s 5 consecutive timeouts closed -> open
2 0-30 s calls fail in 0 ms; page shows "popular items" fallback
3 30 s one trial call half-open
4 30 s trial succeeds closedWhat provides it: Resilience4j (JVM), Polly (.NET), sony/gobreaker (Go), Envoy outlier detection and Istio DestinationRule, Laravel via packages or a Cache-based counter. Mechanics: Circuit Breaker, Bulkheads & Graceful Degradation, Load Shedding, Cascading Failures.
Fix / how to use it: a breaker per dependency (not per instance of the caller), always with a fallback the product team agreed on; a bulkhead as a bounded worker pool or connection pool per dependency.
Request hedging Good to know
In plain words: if the first copy of a read is slower than usual, send a second copy to another replica and take whichever answers first.
Common misunderstanding: "Hedging is a retry." A retry follows a failure; a hedge runs alongside a slow request. It doubles work for that request, so it is only for idempotent reads and must be throttled.
Definition: gRPC: "With hedging, a gRPC client sends multiple copies of the same request to different backends and uses the first response it receives. Subsequently, the client cancels any outstanding requests". Dean and Barroso: wait until the 95th-percentile latency before the second copy, which "limits the additional load to approximately 5%".
t (ms) Replica A Replica B Client
1 0 request 1 starts waits
2 40 (p95 = 40 ms passed) request 2 starts hedge sent
3 55 answers uses B's answer, cancels A
4 300 (A was in a GC pause) tail cut from 300 to 55 msWhat provides it: gRPC hedgingPolicy (maxAttempts capped at 5, hedgingDelay, nonFatalStatusCodes) in Java; the gRPC docs list Go as "Not yet supported" and C++ as "Not yet available", so this page's Go hedge package does it by hand; Envoy supports hedging on per-try timeouts.
Fix / how to use it: reads only, delay at about p95, cancel the losers, cap total copies, and watch backend load.
API composition and Backend-for-Frontend for reads Important
In plain words: when a screen needs data owned by five services, one component calls them (in parallel) and joins the answers; a BFF is such a component made for one kind of client.
Common misunderstanding: "Composition is free because the calls are parallel." Latency is the slowest call, availability is the product of all of them, and microservices.io warns "Some queries would result in inefficient, in-memory joins of large datasets." For lists and searches, a read model fed by events (ECST, CQRS) is usually the right answer.
Definition: microservices.io: "Implement a query by defining an API Composer, which invoking the services that own the data and performs an in-memory join of the results." Backends for Frontends "defines a separate API gateway for each kind of client".
Mobile BFF (budget 400 ms) Orders Customers Shipping
1 GET /app/orders/1001 arrives
2 parallel: GET order, GET customer, GET shipment (each deadline 380 ms)
3 60 ms 30 ms timeout at 380 ms
4 responds with order + customer, shipment: null, "tracking unavailable"Real scenario: an order detail page; a mobile home screen; an admin dashboard. Placement and gateway features: API Gateway, BFF & Service Mesh.
Fix / how to use it: parallel calls (Go errgroup, Laravel Http::pool), a deadline for the whole composition, partial results for non-critical parts, and a read model when the join is large or hot.
Service-to-service authentication Good to know
In plain words: every service must know which service is calling (authentication) and whether it may (authorisation); being inside the network is not proof of either.
Common misunderstanding: "Internal traffic is trusted." Zero-trust networking assumes the network is hostile; one compromised pod should not be able to call the payment API.
Definition: two complementary mechanisms: mutual TLS (each side presents a certificate; identity is the workload, for example a SPIFFE ID issued by a mesh) and tokens (a JWT or OAuth 2.0 client-credentials token carrying the calling service and, when needed, the end user).
orders pod billing pod
1 TLS handshake: presents cert spiffe://prod/ns/orders/sa/orders
2 verifies cert; presents its own (mutual)
3 POST /charges Authorization: Bearer <token aud=billing, sub=orders>
4 policy: orders may POST /charges; reporting may notWhat provides it: Istio and Linkerd (automatic mTLS), SPIFFE/SPIRE, cloud IAM, OAuth 2.0 client credentials, Laravel Passport client credentials, Go crypto/tls with ClientAuth: tls.RequireAndVerifyClientCert. Depth: mTLS & Service Security, OAuth 2.0 & OIDC, Messaging Security.
Fix / how to use it: mTLS for every hop (often from the mesh), a token with audience and caller for authorisation, and messages signed or authenticated at the broker.
Correlation and trace propagation (W3C traceparent) Must-know
In plain words: every request and message carries one trace ID from the edge to the last consumer, so a single slow or failed user action can be found across all services.
Common misunderstanding: "Each service logs its own request ID, so we have correlation." Different IDs per hop cannot be joined. The trace ID must be propagated, including through queues where the HTTP header disappears.
Definition: W3C Trace Context defines traceparent ("describes the position of the incoming request in its trace graph in a portable, fixed-length format") and tracestate (vendor data). Format: version-traceid-parentid-flags, for example traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01. A component that does not participate must at minimum "propagate the traceparent and tracestate headers".
edge orders queue message payments
1 traceparent 00-T-A-01 (new trace T)
2 reads T; logs trace_id=T; outbound parent-id B
3 publishes ChargeOrder with header traceparent 00-T-C-01
4 stored with message
5 consumes; continues trace TWhat provides it: OpenTelemetry SDKs (Go otelhttp, otelgrpc; PHP), Envoy and meshes forward headers; messaging propagation in Messaging Observability; Laravel Context::add('trace_id', ...), which the docs say is "automatically appended as metadata to any log entries" and shared with queued jobs. Stack: Observability.
Fix / how to use it: accept or start a trace at the edge, put the trace ID in every log line, copy traceparent into message headers, and propagate the deadline and criticality the same way.
Error semantics across services: Problem Details and gRPC status codes Important
In plain words: errors are part of the contract; the caller must be able to tell "try again later" from "your request is wrong" from "it may have happened" without parsing English text.
Common misunderstanding: "Return 500 with a message, the caller will figure it out." A 500 for a validation failure makes every client retry a request that can never succeed; a 200 with {"error": ...} hides failures from every proxy, metric and retry policy.
Definition: HTTP: RFC 9457 defines a "problem detail" "to carry machine-readable details of errors in HTTP response content", with members type, status, title, detail, instance and the media type application/problem+json. gRPC: a status code plus message; libraries generate some codes themselves (DEADLINE_EXCEEDED, UNAVAILABLE, CANCELLED...), and codes such as INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, DATA_LOSS "are never generated by the library", so seeing them means the application chose them.
Billing returns Orders (caller) does
1 422 problem+json "Invalid amount" no retry; surface to user
2 409 "outstanding for this key" back off, retry same key
3 503 Retry-After: 2 retry after 2 s if budget allows
4 504 / DEADLINE_EXCEEDED unknown outcome: retry only with the same idempotency key
5 UNAVAILABLE retry with backoff (idempotent only)What provides it: Laravel exception rendering in bootstrap/app.php ($exceptions->render(...)), Go encoding/json with application/problem+json, google.golang.org/grpc/status and codes, and the richer google.rpc.Status details. The full retry table is in Mechanics.
Fix / how to use it: map every domain error to one status and one problem type URL, document them in OpenAPI, never leak stack traces, and propagate the trace ID in the problem body so support can find it.
Mechanics
Budget arithmetic
| Quantity | Formula | Example |
|---|---|---|
| Remaining budget at hop k | B - sum(time spent before k) - k * margin | 1000 - 350 - 3 x 10 = 620 ms |
| Per-call timeout (from AWS) | latency percentile matching an accepted false-timeout rate | 0.1% false timeouts -> p99.9 |
| Availability of a sync chain | product of each hop's availability | 0.999^4 = 0.996 (about 35 h/year down) |
| Latency of a sequential chain | sum of hops | 4 x 50 ms = 200 ms |
| Latency of a parallel fan-out | max of the calls; tail grows with fan-out | p99 of 100 calls is near the p99.99 of one |
Retry amplification
| Setup | Attempts on the bottom layer per user action | Source |
|---|---|---|
| No retries | 1 | - |
| 3 retries (4 attempts) at one layer | 4 | - |
| 4 attempts at 3 layers | 4^3 = 64 | Google SRE, cascading failures |
| 3 tries at 5 layers | 3^5 = 243 | AWS Builders' Library |
| Per-request budget of 3 attempts, single layer | at most 3; "just below 3X" in the worst case | Google SRE, handling overload |
| Plus per-client ratio below 10% | about 1.1 when most calls fail | Google SRE |
gRPC retryThrottling {10, 0.1} | retries stop once tokens fall to 5 | gRPC retry guide |
Backoff and jitter formulas
| Strategy | Wait before attempt n | Verdict (Brooker 2015) |
|---|---|---|
| Fixed | base | Synchronises clients; avoid |
| Exponential | min(cap, base * 2^n) | Spreads retries in time but clients still cluster |
| Full jitter | random(0, min(cap, base * 2^n)) | Least work; this page's default |
| Equal jitter | t/2 + random(0, t/2) where t = min(cap, base * 2^n) | "the loser" |
| Decorrelated jitter | min(cap, random(base, previous * 3)) | Slightly faster, more calls |
| gRPC built-in | exponential with "Jitter of plus or minus 20%" | Automatic in service-config retries |
gRPC knobs
| Knob | Where | Meaning |
|---|---|---|
retryPolicy.maxAttempts | service config, per method | Including the first call; values above 5 are treated as 5 (gRFC A6) |
initialBackoff, maxBackoff, backoffMultiplier | service config | Exponential backoff, plus 20% jitter |
retryableStatusCodes | service config | Usually ["UNAVAILABLE"]; only add others if the method is idempotent |
retryThrottling.maxTokens, tokenRatio | service config | Failed RPC -1 token, success +tokenRatio; retries pause below half |
hedgingPolicy.maxAttempts, hedgingDelay, nonFatalStatusCodes | service config | Parallel copies; Go not supported |
timeout | service config methodConfig | Default deadline per method |
grpc-timeout | request metadata | Remaining deadline on the wire |
grpc-retry-pushback-ms | response metadata | Server tells the client how long to wait, or not to retry |
grpc-previous-rpc-attempts | request metadata | How many attempts preceded this one |
| Transparent retry | always on | Only when the RPC "never leaves the client" or never reached the application |
gRPC also says: "Once the response header is received, the RPC is committed. No further retries will be attempted".
Status codes and what the caller does
| Signal | Meaning | Retry? | Caller action |
|---|---|---|---|
HTTP 400, gRPC INVALID_ARGUMENT | Request is wrong | No | Fix the request; surface the error |
401 / UNAUTHENTICATED | Missing or bad credentials | Once, after refreshing the token | Laravel docs show this with withToken in the retry callback |
403 / PERMISSION_DENIED | Not allowed | No | Surface |
404 / NOT_FOUND | Missing | No (unless replica lag is expected) | Surface or wait |
409 (idempotency) | Same key still running | Yes, same key, after backoff | Do not create a new key |
409 / ALREADY_EXISTS, ABORTED | Conflict or concurrency abort | Depends; ABORTED usually at a higher level | Re-read and retry the whole step |
422 (idempotency) | Key reused with another payload | No | Bug in the client |
429 / RESOURCE_EXHAUSTED | Rate limited or out of quota | Yes, honour Retry-After | Slow down |
500 / INTERNAL, UNKNOWN | Bug or invariant broken | Only with an idempotency key, rarely | Alert |
502, 503 / UNAVAILABLE | Transient | Yes, with backoff | gRPC: "not always safe to retry non-idempotent operations" |
504 / DEADLINE_EXCEEDED | Gave up waiting; outcome unknown | Only idempotent or keyed | Check status or retry with the same key |
| Connection refused before sending | Nothing reached the server | Yes | Safe even for POST |
| Connection reset after sending | Unknown outcome | Only idempotent or keyed | Same as 504 |
Error messages you will actually see
| Where | Message | Meaning |
|---|---|---|
Go net/http | context deadline exceeded (Client.Timeout exceeded while awaiting headers) | http.Client.Timeout fired |
| Go | context deadline exceeded | Your context's deadline fired |
| Go gRPC | rpc error: code = DeadlineExceeded desc = context deadline exceeded | gRPC deadline |
| Go gRPC | rpc error: code = Unavailable desc = connection error | Transport failure; retryable |
| Laravel | Illuminate\Http\Client\ConnectionException (cURL error 28: Operation timed out) | timeout() exceeded |
| Laravel | Illuminate\Http\Client\RequestException | All retries failed with an error response |
| Envoy | upstream request timeout (504) | Route timeout in the proxy |
| Problem Details | {"type": ..., "title": "A request is outstanding for this Idempotency-Key", "status": 409} | Concurrent duplicate |
Go
The Go module (academy/service-communication) has one package per idea. All of it is standard library except the gRPC client.
Before
A typical first version: a shared client with no timeout, a retry loop with a fixed pause around a POST, no key, no deadline from the caller.
// Command before is the version NOT to copy: a client without a timeout,
// a fixed-pause retry loop around a POST, no idempotency key and no
// deadline from the caller.
package main
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
)
const billingURL = "http://billing.internal"
var client = &http.Client{} // no Timeout: waits forever
func charge(orderID string, cents int64) error {
body := fmt.Sprintf(`{"order_id":%q,"amount_cents":%d}`, orderID, cents)
for i := 0; i < 3; i++ { // every layer above does the same: 3 x 3 x 3
resp, err := client.Post(billingURL+"/charges", "application/json", strings.NewReader(body))
if err == nil && resp.StatusCode < 500 {
resp.Body.Close()
return nil
}
time.Sleep(100 * time.Millisecond) // all clients wake up together
} // a timeout after billing charged the card -> a second charge
return errors.New("billing failed")
}
func main() {
if err := charge("1001", 4999); err != nil {
fmt.Println(err)
}
}After
Deadline and trace propagation. The middleware turns Request-Timeout-Ms into a context deadline and keeps or starts the W3C trace; Outgoing stamps "what is left minus a margin" on every outbound call and refuses to send a doomed one.
// Package callbudget propagates a request deadline and W3C trace context
// across HTTP hops. HTTP has no standard deadline header (gRPC has
// grpc-timeout); Request-Timeout-Ms is this codebase's convention.
package callbudget
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net/http"
"strconv"
"strings"
"time"
)
const (
HeaderTimeout = "Request-Timeout-Ms" // convention, not a standard
HeaderTraceparent = "traceparent" // W3C Trace Context
)
type ctxKey struct{}
// ErrBudgetSpent means there is no time left to make a useful call.
var ErrBudgetSpent = errors.New("callbudget: remaining budget below safety margin")
// Middleware turns the caller's remaining budget into a context deadline.
// A missing header gets defaultBudget; anything above maxBudget is capped.
func Middleware(defaultBudget, maxBudget time.Duration, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
budget := defaultBudget
if v := r.Header.Get(HeaderTimeout); v != "" {
if ms, err := strconv.Atoi(v); err == nil && ms > 0 {
budget = time.Duration(ms) * time.Millisecond
}
}
if budget > maxBudget {
budget = maxBudget
}
ctx, cancel := context.WithTimeout(r.Context(), budget)
defer cancel()
tp := r.Header.Get(HeaderTraceparent)
if !valid(tp) {
tp = "00-" + randHex(16) + "-" + randHex(8) + "-01"
}
ctx = context.WithValue(ctx, ctxKey{}, tp)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Outgoing stamps the remaining budget (minus a margin for the network and
// for our own post-processing) and a child traceparent on an outbound request.
// It fails fast when the budget is already spent: a doomed call is not sent.
func Outgoing(req *http.Request, margin time.Duration) error {
ctx := req.Context()
if dl, ok := ctx.Deadline(); ok {
left := time.Until(dl) - margin
if left < time.Millisecond {
return ErrBudgetSpent
}
req.Header.Set(HeaderTimeout, strconv.FormatInt(left.Milliseconds(), 10))
}
if tp, ok := ctx.Value(ctxKey{}).(string); ok {
// Same trace-id, new parent-id: this hop becomes the parent span.
parts := strings.Split(tp, "-")
req.Header.Set(HeaderTraceparent, parts[0]+"-"+parts[1]+"-"+randHex(8)+"-"+parts[3])
}
return nil
}
// TraceID returns the trace-id for logs, or "" when none is known.
func TraceID(ctx context.Context) string {
if tp, ok := ctx.Value(ctxKey{}).(string); ok {
return strings.Split(tp, "-")[1]
}
return ""
}
// valid checks the version-00 shape: 2-32-16-2 lowercase hex fields.
func valid(tp string) bool {
p := strings.Split(tp, "-")
if len(p) != 4 || len(p[0]) != 2 || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
return false
}
for _, s := range p {
if _, err := hex.DecodeString(s); err != nil || strings.ToLower(s) != s {
return false
}
}
return p[1] != strings.Repeat("0", 32) && p[2] != strings.Repeat("0", 16)
}
func randHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}Retry with full jitter, an idempotency check and a retry budget. Do only retries idempotent methods or requests with an Idempotency-Key, honours Retry-After, stops when the deadline cannot fit another attempt, and stops when the shared budget is spent.
// Package retry is an HTTP retry loop that is safe by construction: it only
// retries idempotent requests, waits with full jitter, respects the caller's
// deadline and Retry-After, and stops when a client-wide retry budget is spent.
package retry
import (
"context"
"errors"
"io"
"math/rand/v2"
"net/http"
"strconv"
"sync"
"time"
)
// Budget is a client-side retry budget modelled on gRPC retry throttling:
// failures cost 1 token, successes earn tokenRatio, and retries pause while
// tokens are at or below half of maxTokens.
type Budget struct {
mu sync.Mutex
tokens, max float64
ratio float64
Denied, Spent int
}
func NewBudget(maxTokens int, tokenRatio float64) *Budget {
return &Budget{tokens: float64(maxTokens), max: float64(maxTokens), ratio: tokenRatio}
}
func (b *Budget) record(ok bool) {
b.mu.Lock()
defer b.mu.Unlock()
if ok {
b.tokens = min(b.max, b.tokens+b.ratio)
} else {
b.tokens = max(0, b.tokens-1)
}
}
func (b *Budget) allow() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.tokens > b.max/2 {
b.Spent++
return true
}
b.Denied++
return false
}
// Policy configures Do. Zero Rand means math/rand/v2.
type Policy struct {
MaxAttempts int // total attempts, including the first
Base, Cap time.Duration // exponential backoff base and ceiling
Budget *Budget // optional, shared by all calls to one dependency
Rand func(n int64) int64
}
// FullJitter returns a random wait in [0, min(cap, base*2^attempt)].
func FullJitter(base, cap time.Duration, attempt int, rnd func(int64) int64) time.Duration {
d := cap
if attempt < 30 && base<<attempt < cap {
d = base << attempt
}
return time.Duration(rnd(int64(d) + 1))
}
// ErrNotIdempotent is returned when a retry would be unsafe.
var ErrNotIdempotent = errors.New("retry: request is not idempotent and has no Idempotency-Key")
// Do sends the request built by newReq, retrying transient failures.
// newReq is called once per attempt so the body can be rebuilt.
func Do(ctx context.Context, c *http.Client, p Policy, newReq func(context.Context) (*http.Request, error)) (*http.Response, error) {
rnd := p.Rand
if rnd == nil {
rnd = rand.Int64N
}
for attempt := 0; ; attempt++ {
req, err := newReq(ctx)
if err != nil {
return nil, err
}
maxAttempts := p.MaxAttempts
if !idempotent(req) {
maxAttempts = 1 // one attempt only: a retry could double the side effect
}
resp, err := c.Do(req)
retryable, after := classify(ctx, resp, err)
if p.Budget != nil {
p.Budget.record(!retryable)
}
if !retryable || attempt+1 >= maxAttempts {
if retryable && maxAttempts == 1 && p.MaxAttempts > 1 && err != nil {
return resp, errors.Join(err, ErrNotIdempotent)
}
return resp, err
}
if p.Budget != nil && !p.Budget.allow() {
return resp, err // budget spent: fail fast instead of adding load
}
wait := max(after, FullJitter(p.Base, p.Cap, attempt, rnd))
if dl, ok := ctx.Deadline(); ok && time.Until(dl) <= wait {
return resp, err // the next attempt could not finish in time
}
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
t := time.NewTimer(wait)
select {
case <-ctx.Done():
t.Stop()
return nil, ctx.Err()
case <-t.C:
}
}
}
// idempotent: RFC 9110 idempotent methods, or any request carrying a key.
func idempotent(r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
return true
}
return r.Header.Get("Idempotency-Key") != ""
}
// classify decides whether a result is worth another attempt.
func classify(ctx context.Context, resp *http.Response, err error) (bool, time.Duration) {
if err != nil {
return ctx.Err() == nil, 0 // our own deadline or cancel: never retry
}
switch resp.StatusCode {
case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
if s, e := strconv.Atoi(resp.Header.Get("Retry-After")); e == nil && s >= 0 {
return true, time.Duration(s) * time.Second
}
return true, 0
}
return false, 0
}Server-side idempotency keys, with a test for the four outcomes (first run, 409 while running, replay, 422 on reuse):
// Package idempotency is server-side Idempotency-Key handling: first request
// runs, a completed duplicate gets the stored response replayed, a concurrent
// duplicate gets 409, and a key reused with a different payload gets 422.
// The in-memory map stands in for a table with a unique key (see the SQL on
// the page); the state machine is the same.
package idempotency
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"sync"
"time"
)
type record struct {
fingerprint string
done bool
status int
header http.Header
body []byte
expires time.Time
}
// Store keeps keys for ttl (Stripe prunes v1 keys after at least 24 hours).
type Store struct {
mu sync.Mutex
m map[string]*record
ttl time.Duration
now func() time.Time
}
func NewStore(ttl time.Duration) *Store {
return &Store{m: map[string]*record{}, ttl: ttl, now: time.Now}
}
// Middleware enforces keys on POST and PATCH.
func (s *Store) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost && r.Method != http.MethodPatch {
next.ServeHTTP(w, r)
return
}
key := r.Header.Get("Idempotency-Key")
if key == "" || len(key) > 255 {
Problem(w, http.StatusBadRequest, "Idempotency-Key is missing", "This operation requires an Idempotency-Key header of at most 255 characters.")
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
Problem(w, http.StatusBadRequest, "Unreadable body", err.Error())
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
sum := sha256.Sum256(append([]byte(r.Method+" "+r.URL.Path+"\n"), body...))
fp := hex.EncodeToString(sum[:])
// Scope keys per caller so two clients cannot collide.
scoped := r.Header.Get("X-Client-Id") + "|" + r.URL.Path + "|" + key
s.mu.Lock()
rec, seen := s.m[scoped]
if seen && s.now().After(rec.expires) {
delete(s.m, scoped)
seen = false
}
switch {
case seen && rec.fingerprint != fp:
s.mu.Unlock()
Problem(w, http.StatusUnprocessableEntity, "Idempotency-Key is already used", "The key was used with a different payload.")
return
case seen && !rec.done:
s.mu.Unlock()
Problem(w, http.StatusConflict, "A request is outstanding for this Idempotency-Key", "Retry after the first request finishes.")
return
case seen:
s.mu.Unlock()
for k, v := range rec.header {
w.Header()[k] = v
}
w.Header().Set("Idempotent-Replayed", "true")
w.WriteHeader(rec.status)
_, _ = w.Write(rec.body)
return
}
s.m[scoped] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}
s.mu.Unlock()
cw := &capture{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(cw, r)
s.mu.Lock()
defer s.mu.Unlock()
if cw.status >= 500 {
delete(s.m, scoped) // our choice: let the client retry a server failure
return
}
rec = s.m[scoped]
rec.done, rec.status, rec.header, rec.body = true, cw.status, w.Header().Clone(), cw.buf.Bytes()
})
}
type capture struct {
http.ResponseWriter
status int
buf bytes.Buffer
}
func (c *capture) WriteHeader(code int) { c.status = code; c.ResponseWriter.WriteHeader(code) }
func (c *capture) Write(b []byte) (int, error) {
c.buf.Write(b)
return c.ResponseWriter.Write(b)
}
// Problem writes an RFC 9457 problem details response.
func Problem(w http.ResponseWriter, status int, title, detail string) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{
"type": "https://errors.example.com/idempotency",
"title": title,
"status": status,
"detail": detail,
})
}package idempotency
import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestKeyStates(t *testing.T) {
var runs atomic.Int32
release := make(chan struct{})
h := NewStore(24 * time.Hour).Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if runs.Add(1) == 1 {
<-release // keep the first request in flight
}
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"charge_id":"ch_1"}`))
}))
send := func(key, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/charges", strings.NewReader(body))
req.Header.Set("Idempotency-Key", key)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
first := make(chan *httptest.ResponseRecorder)
go func() { first <- send("k1", `{"amount":10}`) }()
for runs.Load() == 0 {
time.Sleep(time.Millisecond)
}
if c := send("k1", `{"amount":10}`).Code; c != http.StatusConflict {
t.Fatalf("concurrent duplicate: want 409 got %d", c)
}
close(release)
if c := (<-first).Code; c != http.StatusCreated {
t.Fatalf("first: want 201 got %d", c)
}
replay := send("k1", `{"amount":10}`)
if replay.Code != http.StatusCreated || replay.Header().Get("Idempotent-Replayed") != "true" {
t.Fatalf("replay: got %d %v", replay.Code, replay.Header())
}
if c := send("k1", `{"amount":99}`).Code; c != http.StatusUnprocessableEntity {
t.Fatalf("payload mismatch: want 422 got %d", c)
}
if c := send("", `{"amount":10}`).Code; c != http.StatusBadRequest {
t.Fatalf("missing key: want 400 got %d", c)
}
if runs.Load() != 1 {
t.Fatalf("handler ran %d times, want 1", runs.Load())
}
}gRPC client with a retry policy, throttling and a deadline (uses the standard health service, so no code generation is needed):
// Command grpcclient shows a gRPC client with a per-method retry policy,
// retry throttling (a client-side retry budget) and a deadline taken from
// the caller's context. It uses the standard health service so that no
// generated code is needed.
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
)
// serviceConfig is normally delivered by the name resolver; a default is set
// here so the client still behaves well without it.
const serviceConfig = `{
"methodConfig": [{
"name": [{"service": "grpc.health.v1.Health", "method": "Check"}],
"timeout": "0.8s",
"retryPolicy": {
"maxAttempts": 3,
"initialBackoff": "0.05s",
"maxBackoff": "0.5s",
"backoffMultiplier": 2,
"retryableStatusCodes": ["UNAVAILABLE"]
}
}],
"retryThrottling": {"maxTokens": 10, "tokenRatio": 0.1}
}`
func main() {
addr := os.Getenv("BILLING_ADDR")
if addr == "" {
log.Println("BILLING_ADDR not set; nothing to call")
return
}
conn, err := grpc.NewClient(addr,
grpc.WithTransportCredentials(insecure.NewCredentials()), // use mTLS credentials in production
grpc.WithDefaultServiceConfig(serviceConfig),
)
if err != nil {
log.Fatalf("new client: %v", err)
}
defer conn.Close()
// The deadline comes from the caller. In a server handler you would pass
// the incoming ctx unchanged so grpc-go propagates the remaining budget.
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: "billing"})
switch status.Code(err) {
case codes.OK:
log.Printf("billing status: %s", resp.GetStatus())
case codes.DeadlineExceeded:
log.Printf("budget spent; the call may still have run on the server: %v", err)
case codes.Unavailable:
log.Printf("still unavailable after retries: %v", err)
default:
log.Printf("non-retryable error: %v", err)
}
}Hedged reads by hand (grpc-go has no hedgingPolicy):
// Package hedge sends a backup request when the first one is slower than
// delay (pick roughly the p95 latency) and returns the first success.
// grpc-go does not support hedgingPolicy, so this is done by hand.
// Use it only for idempotent reads.
package hedge
import (
"context"
"time"
)
type result[T any] struct {
v T
err error
}
// First runs call up to maxCalls times, starting a new one every delay
// (or immediately after a failure), and cancels the losers.
func First[T any](ctx context.Context, delay time.Duration, maxCalls int, call func(context.Context) (T, error)) (T, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel() // cancels every outstanding copy when we return
results := make(chan result[T], maxCalls)
launch := func() {
go func() {
v, err := call(ctx)
results <- result[T]{v, err}
}()
}
launch()
launched, failed := 1, 0
timer := time.NewTimer(delay)
defer timer.Stop()
var zero T
var lastErr error
for {
select {
case r := <-results:
if r.err == nil {
return r.v, nil
}
failed, lastErr = failed+1, r.err
if failed == launched && launched == maxCalls {
return zero, lastErr
}
if launched < maxCalls {
launch()
launched++
}
case <-timer.C:
if launched < maxCalls {
launch()
launched++
timer.Reset(delay)
}
case <-ctx.Done():
return zero, ctx.Err()
}
}
}An asynchronous command with an idempotent handler. The first delivery charges and then loses its acknowledgement; the redelivery is skipped. Output: nack msg-1001 attempt=1, skip msg-1001 (duplicate), charge msg-1002, ledger: map[1001:4999 1002:1500].
// Command asynccmd sends a ChargeOrder command through a queue with
// at-least-once delivery and shows that an idempotent handler charges once
// even when the broker redelivers. The channel stands in for the broker and
// the map for a processed_messages table (see the SQL on the page).
package main
import (
"context"
"errors"
"fmt"
"sync"
)
// ChargeOrder is a command: one named receiver, imperative name, an ID the
// producer chooses so every redelivery carries the same identity.
type ChargeOrder struct {
MessageID string
OrderID string
AmountCents int64
Traceparent string
}
// Inbox records processed message IDs. In SQL this is an INSERT ... ON
// CONFLICT DO NOTHING in the same transaction as the side effect.
type Inbox struct {
mu sync.Mutex
seen map[string]bool
}
func (i *Inbox) FirstTime(id string) bool {
i.mu.Lock()
defer i.mu.Unlock()
if i.seen[id] {
return false
}
i.seen[id] = true
return true
}
type Ledger struct {
mu sync.Mutex
charges map[string]int64
}
func (l *Ledger) Charge(orderID string, cents int64) {
l.mu.Lock()
defer l.mu.Unlock()
l.charges[orderID] += cents
}
var errTransient = errors.New("payment gateway timeout")
func handle(ctx context.Context, in *Inbox, l *Ledger, m ChargeOrder, failOnce *bool) error {
if err := ctx.Err(); err != nil {
return err
}
if !in.FirstTime(m.MessageID) {
fmt.Printf("skip %s (duplicate)\n", m.MessageID)
return nil // ack: already done
}
// In production the inbox row and the charge commit in ONE transaction,
// so a failed charge also rolls back the mark.
l.Charge(m.OrderID, m.AmountCents)
if *failOnce {
*failOnce = false
return errTransient // charged, but the ack is lost: broker redelivers
}
fmt.Printf("charge %s order=%s amount=%d\n", m.MessageID, m.OrderID, m.AmountCents)
return nil
}
func main() {
queue := make(chan ChargeOrder, 8)
in := &Inbox{seen: map[string]bool{}}
ledger := &Ledger{charges: map[string]int64{}}
failOnce := true
queue <- ChargeOrder{MessageID: "msg-1001", OrderID: "1001", AmountCents: 4999}
queue <- ChargeOrder{MessageID: "msg-1002", OrderID: "1002", AmountCents: 1500}
close(queue)
ctx := context.Background()
for m := range queue {
for attempt := 1; ; attempt++ { // the broker redelivers until acked
if err := handle(ctx, in, ledger, m, &failOnce); err != nil {
fmt.Printf("nack %s attempt=%d err=%v\n", m.MessageID, attempt, err)
continue
}
break
}
}
fmt.Println("ledger:", ledger.charges)
}Pact-style contract test. One JSON file is the contract; the consumer test runs the real client against a mock built from it, the provider test replays it against the real handler.
{
"consumer": { "name": "orders" },
"provider": { "name": "billing" },
"interactions": [
{
"description": "a charge for a pending order",
"providerState": "customer 42 has enough credit",
"request": {
"method": "POST",
"path": "/charges",
"headers": { "Content-Type": "application/json", "Idempotency-Key": "order-1001-charge" },
"body": { "order_id": "1001", "customer_id": "42", "amount_cents": 4999, "currency": "EUR" }
},
"response": {
"status": 201,
"headers": { "Content-Type": "application/json" },
"body": { "charge_id": "ch_example", "status": "captured" },
"matchingRules": { "$.body.charge_id": { "match": "type" } }
}
}
],
"metadata": { "pactSpecification": { "version": "2.0.0" } }
}// Package contract is a Pact-style consumer-driven contract between the
// orders service (consumer) and billing (provider), using only the standard
// library. The JSON file is the contract both sides test against; with the
// real Pact tools it would be generated by the consumer test and published
// to a Pact Broker.
package contract
import (
_ "embed"
"encoding/json"
)
//go:embed pacts/orders-billing.json
var pactJSON []byte
type Pact struct {
Consumer struct{ Name string } `json:"consumer"`
Provider struct{ Name string } `json:"provider"`
Interactions []Interaction `json:"interactions"`
}
type Interaction struct {
Description string `json:"description"`
ProviderState string `json:"providerState"`
Request struct {
Method string `json:"method"`
Path string `json:"path"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
} `json:"request"`
Response struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
MatchingRules map[string]map[string]string `json:"matchingRules"`
} `json:"response"`
}
func Load() (Pact, error) {
var p Pact
err := json.Unmarshal(pactJSON, &p)
return p, err
}
// Matches checks that actual contains at least the expected fields
// ("provider verification passes if each request generates a response that
// contains at least the data described"); type rules relax exact values.
func Matches(expected, actual map[string]any, rules map[string]map[string]string) []string {
var problems []string
for k, want := range expected {
got, ok := actual[k]
if !ok {
problems = append(problems, "missing field "+k)
continue
}
if rules["$.body."+k]["match"] == "type" {
if _, same := got.(string); same != isString(want) {
problems = append(problems, "wrong type for "+k)
}
continue
}
wj, _ := json.Marshal(want)
gj, _ := json.Marshal(got)
if string(wj) != string(gj) {
problems = append(problems, "field "+k+": want "+string(wj)+" got "+string(gj))
}
}
return problems
}
func isString(v any) bool { _, ok := v.(string); return ok }package contract
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
// ChargeRequest is what orders sends to billing.
type ChargeRequest struct {
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
AmountCents int64 `json:"amount_cents"`
Currency string `json:"currency"`
}
// ChargeResult holds only the fields orders reads (Tolerant Reader:
// unknown fields from billing are ignored, so billing may add fields freely).
type ChargeResult struct {
ChargeID string `json:"charge_id"`
Status string `json:"status"`
}
type BillingClient struct {
BaseURL string
HTTP *http.Client
}
func (c BillingClient) Charge(ctx context.Context, in ChargeRequest, idempotencyKey string) (ChargeResult, error) {
body, err := json.Marshal(in)
if err != nil {
return ChargeResult{}, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/charges", bytes.NewReader(body))
if err != nil {
return ChargeResult{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", idempotencyKey)
resp, err := c.HTTP.Do(req)
if err != nil {
return ChargeResult{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
return ChargeResult{}, fmt.Errorf("billing: unexpected status %d", resp.StatusCode)
}
var out ChargeResult
err = json.NewDecoder(resp.Body).Decode(&out)
return out, err
}package contract
import (
"encoding/json"
"net/http"
"strconv"
"sync/atomic"
"time"
)
// NewBillingHandler is the provider. It returns more fields than orders
// reads (created_at, amount_cents); that is a compatible extension.
func NewBillingHandler() http.Handler {
var seq atomic.Int64
mux := http.NewServeMux()
mux.HandleFunc("POST /charges", func(w http.ResponseWriter, r *http.Request) {
var in ChargeRequest
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.AmountCents <= 0 {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusUnprocessableEntity)
_ = json.NewEncoder(w).Encode(map[string]any{"type": "about:blank", "title": "Invalid charge", "status": 422})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{
"charge_id": "ch_" + strconv.FormatInt(seq.Add(1), 10),
"status": "captured",
"amount_cents": in.AmountCents,
"created_at": time.Now().UTC().Format(time.RFC3339),
})
})
return mux
}package contract
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
// TestConsumerAgainstContract plays the Pact mock provider: it checks that
// the real BillingClient sends exactly the request in the contract and can
// read the contracted response.
func TestConsumerAgainstContract(t *testing.T) {
p, err := Load()
if err != nil {
t.Fatal(err)
}
for _, it := range p.Interactions {
t.Run(it.Description, func(t *testing.T) {
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != it.Request.Method || r.URL.Path != it.Request.Path {
t.Errorf("request line: got %s %s", r.Method, r.URL.Path)
}
for k, v := range it.Request.Headers {
if r.Header.Get(k) != v {
t.Errorf("header %s: want %q got %q", k, v, r.Header.Get(k))
}
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if !reflect.DeepEqual(body, it.Request.Body) {
t.Errorf("body: want %v got %v", it.Request.Body, body)
}
for k, v := range it.Response.Headers {
w.Header().Set(k, v)
}
w.WriteHeader(it.Response.Status)
_ = json.NewEncoder(w).Encode(it.Response.Body)
}))
defer mock.Close()
c := BillingClient{BaseURL: mock.URL, HTTP: mock.Client()}
res, err := c.Charge(context.Background(), ChargeRequest{
OrderID: "1001", CustomerID: "42", AmountCents: 4999, Currency: "EUR",
}, "order-1001-charge")
if err != nil {
t.Fatal(err)
}
if res.Status != "captured" || res.ChargeID == "" {
t.Fatalf("unexpected result %+v", res)
}
})
}
}package contract
import (
"bytes"
"encoding/json"
"net/http/httptest"
"testing"
)
// TestProviderHonoursContract replays every contracted request against the
// real billing handler (no orders service running) and checks the response.
func TestProviderHonoursContract(t *testing.T) {
p, err := Load()
if err != nil {
t.Fatal(err)
}
h := NewBillingHandler()
for _, it := range p.Interactions {
t.Run(it.Description, func(t *testing.T) {
// Provider state "customer 42 has enough credit" would be set up here.
body, _ := json.Marshal(it.Request.Body)
req := httptest.NewRequest(it.Request.Method, it.Request.Path, bytes.NewReader(body))
for k, v := range it.Request.Headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != it.Response.Status {
t.Fatalf("status: want %d got %d", it.Response.Status, rec.Code)
}
var got map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
for _, problem := range Matches(it.Response.Body, got, it.Response.MatchingRules) {
t.Error(problem)
}
if ct := rec.Header().Get("Content-Type"); ct != it.Response.Headers["Content-Type"] {
t.Errorf("content type %q", ct)
}
})
}
}The Go angle
| Go feature | Use in service communication | Note |
|---|---|---|
context.Context | Deadline, cancellation and request values across every call | The Go blog's context article: pass it as the first argument |
http.Client.Timeout | Whole-exchange limit: connection time, redirects and reading the response body (per the field's doc comment) | Zero means no timeout; http.DefaultClient has none |
http.NewRequestWithContext | Ties a request to the caller's deadline | Cancelling the context aborts the request |
net/http/httptest | Mock providers and recorders for contract tests | No network needed |
math/rand/v2 | Jitter | rand.Int64N |
golang.org/x/sync/errgroup | Parallel composition with one deadline | First error cancels the rest |
google.golang.org/grpc | grpc.NewClient, WithDefaultServiceConfig, status.Code(err) | Deadline propagates when you pass the incoming ctx |
go.opentelemetry.io/contrib/.../otelhttp | Automatic traceparent handling | Replaces the hand-written trace code here |
Laravel
Before
<?php
namespace App\Actions;
use App\Models\Order;
use Illuminate\Support\Facades\Http;
/**
* Before: do not copy. Retries 4xx as well as 5xx with a fixed 100 ms pause
* (and every layer above may do the same), keeps the default 30 s timeout,
* and sends no Idempotency-Key, so a timeout after billing charged the card
* leads to a second charge.
*/
final class ChargeOrderBefore
{
public function __invoke(Order $order): void
{
Http::retry(3, 100)
->post(config('services.billing.url').'/charges', [
'order_id' => $order->id,
'amount_cents' => $order->total_cents,
]);
}
}After
A per-request budget registered with $this->app->scoped(CallBudget::class) (the container docs: resolved "one time within a given Laravel request / job lifecycle"), and middleware that fills it from Request-Timeout-Ms and traceparent:
<?php
namespace App\Support;
use RuntimeException;
/**
* The time left for the current request, and its W3C trace context.
* Registered with $this->app->scoped(CallBudget::class) so each request
* (or queued job) gets a fresh instance.
*/
final class CallBudget
{
public const HEADER_TIMEOUT = 'Request-Timeout-Ms'; // our convention, not a standard
private ?float $deadline = null; // monotonic seconds, from hrtime()
private ?string $traceparent = null;
public function start(float $seconds, ?string $traceparent): void
{
$this->deadline = hrtime(true) / 1e9 + $seconds;
$this->traceparent = $traceparent;
}
public function remainingSeconds(): ?float
{
return $this->deadline === null ? null : $this->deadline - hrtime(true) / 1e9;
}
public function traceparent(): ?string
{
return $this->traceparent;
}
/**
* Headers for an outbound call: remaining budget minus a safety margin,
* and a child traceparent (same trace-id, new parent-id).
*
* @return array<string, string>
*/
public function outgoingHeaders(float $marginSeconds = 0.005): array
{
$headers = [];
$left = $this->remainingSeconds();
if ($left !== null) {
$left -= $marginSeconds;
if ($left < 0.001) {
throw new RuntimeException('Call budget spent; not sending a doomed request.');
}
$headers[self::HEADER_TIMEOUT] = (string) (int) floor($left * 1000);
}
if ($this->traceparent !== null) {
[$version, $traceId, , $flags] = explode('-', $this->traceparent);
$headers['traceparent'] = "{$version}-{$traceId}-".bin2hex(random_bytes(8))."-{$flags}";
}
return $headers;
}
}<?php
namespace App\Http\Middleware;
use App\Support\CallBudget;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;
/**
* Turns the caller's Request-Timeout-Ms into this request's budget and
* keeps (or starts) the W3C trace so every log line and outbound call
* carries the same trace-id.
*/
final class PropagateCallBudget
{
private const DEFAULT_SECONDS = 2.0;
private const MAX_SECONDS = 10.0;
public function __construct(private CallBudget $budget) {}
public function handle(Request $request, Closure $next): Response
{
$ms = (int) $request->header(CallBudget::HEADER_TIMEOUT, '0');
$seconds = $ms > 0 ? min($ms / 1000, self::MAX_SECONDS) : self::DEFAULT_SECONDS;
$traceparent = (string) $request->header('traceparent', '');
if (preg_match('/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/', $traceparent) !== 1) {
$traceparent = '00-'.bin2hex(random_bytes(16)).'-'.bin2hex(random_bytes(8)).'-01';
}
$this->budget->start($seconds, $traceparent);
Context::add('trace_id', explode('-', $traceparent)[1]); // appears in every log entry
return $next($request);
}
}The HTTP client: timeout() from the budget, retry() with a full-jitter closure and a when callback that only retries transient failures while time and the RateLimiter budget allow, and the same Idempotency-Key on every attempt:
<?php
namespace App\Clients;
use App\Support\CallBudget;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Throwable;
/**
* Synchronous call from orders to billing: deadline from the incoming
* request, retries only for transient failures, full jitter, an
* Idempotency-Key so a retried POST cannot charge twice, and a
* cluster-wide retry budget (at most 60 retries per minute, via the cache).
*/
final class BillingClient
{
public function __construct(private CallBudget $budget) {}
/** @return array{charge_id: string, status: string} */
public function charge(string $orderId, string $customerId, int $amountCents, string $currency): array
{
$headers = $this->budget->outgoingHeaders(); // throws when the budget is already spent
$remaining = $this->budget->remainingSeconds() ?? 2.0;
$response = Http::baseUrl(config('services.billing.url'))
->acceptJson()
->connectTimeout(min(0.5, $remaining))
->timeout($remaining)
->withHeaders($headers + [
'Idempotency-Key' => "order-{$orderId}-charge", // same key on every attempt
])
->retry(
3,
fn (int $attempt, Exception $e): int => random_int(0, min(1000, 100 * 2 ** ($attempt - 1))),
function (Throwable $e, PendingRequest $request): bool {
$transient = $e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [429, 502, 503, 504], true));
$left = $this->budget->remainingSeconds() ?? 2.0;
// increment() is atomic on redis, memcached and database stores.
if (! $transient || $left < 0.05 || RateLimiter::increment('retry-budget:billing') > 60) {
return false; // not transient, no time left, or budget spent
}
$request->timeout($left)->withHeaders($this->budget->outgoingHeaders());
return true;
},
)
->post('/charges', [
'order_id' => $orderId,
'customer_id' => $customerId,
'amount_cents' => $amountCents,
'currency' => $currency,
]);
// Tolerant Reader: read only the two fields we need, ignore the rest.
return [
'charge_id' => (string) $response->json('charge_id'),
'status' => (string) $response->json('status'),
];
}
}Server side idempotency with a table whose primary key is the lock:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Provider side: one row per (caller, key); the primary key is the lock.
Schema::create('idempotency_keys', function (Blueprint $table) {
$table->string('scope', 100);
$table->string('key', 255);
$table->char('fingerprint', 64);
$table->unsignedSmallInteger('response_status')->nullable();
$table->longText('response_body')->nullable();
$table->string('response_content_type', 100)->nullable();
$table->timestamp('locked_at')->nullable();
$table->timestamp('expires_at')->index();
$table->timestamp('created_at');
$table->primary(['scope', 'key']);
});
// Consumer side: one row per handled message (inbox / dedup table).
Schema::create('processed_messages', function (Blueprint $table) {
$table->string('message_id', 100);
$table->string('handler', 100);
$table->timestamp('processed_at');
$table->primary(['message_id', 'handler']);
});
// Local copy of another service's data (event-carried state transfer).
Schema::create('customer_snapshots', function (Blueprint $table) {
$table->string('customer_id', 64)->primary();
$table->string('name');
$table->string('email');
$table->string('tier', 20);
$table->unsignedBigInteger('version');
$table->timestamp('updated_at');
});
}
public function down(): void
{
Schema::dropIfExists('customer_snapshots');
Schema::dropIfExists('processed_messages');
Schema::dropIfExists('idempotency_keys');
}
};<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
/**
* Server side of Idempotency-Key: the (scope, key) primary key is the lock.
* First request runs; a finished duplicate is replayed; a concurrent one
* gets 409; a key reused with another payload gets 422 (IETF draft -09).
*/
final class RequireIdempotencyKey
{
public function handle(Request $request, Closure $next): Response
{
if (! in_array($request->method(), ['POST', 'PATCH'], true)) {
return $next($request);
}
$key = (string) $request->header('Idempotency-Key', '');
if ($key === '' || strlen($key) > 255) {
return $this->problem(400, 'Idempotency-Key is missing', 'Send an Idempotency-Key header of at most 255 characters.');
}
$scope = (string) ($request->user()?->getAuthIdentifier() ?? $request->header('X-Client-Id', 'anonymous'));
$fingerprint = hash('sha256', $request->method().' '.$request->path()."\n".$request->getContent());
$row = ['scope' => $scope, 'key' => $key];
$inserted = DB::table('idempotency_keys')->insertOrIgnore($row + [
'fingerprint' => $fingerprint,
'locked_at' => now(),
'expires_at' => now()->addDay(),
'created_at' => now(),
]);
if ($inserted === 0) {
$existing = DB::table('idempotency_keys')->where($row)->first();
if (! hash_equals($existing->fingerprint, $fingerprint)) {
return $this->problem(422, 'Idempotency-Key is already used', 'The key was used with a different payload.');
}
if ($existing->response_status === null) {
// Take over only if the first attempt crashed long ago.
$takenOver = DB::table('idempotency_keys')->where($row)
->whereNull('response_status')
->where('locked_at', '<', now()->subMinutes(5))
->update(['locked_at' => now()]);
if ($takenOver === 0) {
return $this->problem(409, 'A request is outstanding for this Idempotency-Key', 'Retry after the first request finishes.');
}
} else {
return response($existing->response_body, (int) $existing->response_status, [
'Content-Type' => $existing->response_content_type,
'Idempotent-Replayed' => 'true',
]);
}
}
$response = $next($request);
if ($response->getStatusCode() >= 500) {
DB::table('idempotency_keys')->where($row)->delete(); // our choice: allow a clean retry
return $response;
}
DB::table('idempotency_keys')->where($row)->update([
'response_status' => $response->getStatusCode(),
'response_body' => $response->getContent(),
'response_content_type' => $response->headers->get('Content-Type'),
'locked_at' => null,
]);
return $response;
}
private function problem(int $status, string $title, string $detail): Response
{
return response()->json([
'type' => 'https://errors.example.com/idempotency',
'title' => $title,
'status' => $status,
'detail' => $detail,
], $status, ['Content-Type' => 'application/problem+json']);
}
}Errors as Problem Details and middleware registration:
<?php
use App\Http\Middleware\PropagateCallBudget;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->api(prepend: [PropagateCallBudget::class]);
$middleware->alias(['idempotent' => RequireIdempotencyKey::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
// Errors leave this service as RFC 9457 Problem Details, so every
// caller can tell "retry later" from "your request is wrong".
$exceptions->render(function (Throwable $e, Request $request) {
if (! $request->is('api/*')) {
return null; // default rendering
}
[$status, $title, $headers] = match (true) {
$e instanceof ConnectionException => [503, 'A dependency is unavailable', ['Retry-After' => '1']],
$e instanceof HttpExceptionInterface => [$e->getStatusCode(), 'Request failed', $e->getHeaders()],
default => null,
} ?? [null, null, []];
if ($status === null) {
return null; // validation, auth etc. keep Laravel's handling
}
return response()->json([
'type' => 'about:blank',
'title' => $title,
'status' => $status,
'detail' => $e->getMessage(),
'instance' => $request->path(),
'trace_id' => Context::get('trace_id'),
], $status, $headers + ['Content-Type' => 'application/problem+json']);
});
})
->create();An asynchronous command with ShouldBeUnique and an idempotent handler. The queue docs describe ShouldBeUnique as a dispatch-time lock: "If the lock is already held, the job is not dispatched. This lock is released when the job completes processing or fails all of its retry attempts." That stops duplicate queueing, not duplicate execution after a crash, so the handler still records the message ID in the same transaction:
<?php
namespace App\Contracts;
interface PaymentGateway
{
/** Returns the gateway's charge id; the same key always yields the same charge. */
public function charge(string $orderId, int $amountCents, string $idempotencyKey): string;
}<?php
namespace App\Jobs;
use App\Contracts\PaymentGateway;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Support\Facades\DB;
/**
* An asynchronous command. ShouldBeUnique stops a second ChargeOrder for the
* same order from being QUEUED while one is pending (a dispatch-time lock).
* It does not make the handler idempotent: a worker can still crash after
* charging and the job runs again. The processed_messages row does that.
*/
#[Tries(5)]
#[Backoff([1, 5, 15, 60])]
#[UniqueFor(3600)]
final class ChargeOrder implements ShouldBeUnique, ShouldQueue
{
use Queueable;
public function __construct(
public string $messageId,
public string $orderId,
public int $amountCents,
) {}
public function uniqueId(): string
{
return $this->orderId;
}
public function handle(PaymentGateway $gateway): void
{
DB::transaction(function () use ($gateway) {
$first = DB::table('processed_messages')->insertOrIgnore([
'message_id' => $this->messageId,
'handler' => self::class,
'processed_at' => now(),
]);
if ($first === 0) {
return; // already handled: finish so the job is acknowledged
}
// If this transaction rolls back, the retry calls the gateway
// again with the SAME key and gets the same charge back.
$chargeId = $gateway->charge($this->orderId, $this->amountCents, "order-{$this->orderId}-charge");
DB::table('orders')->where('id', $this->orderId)
->update(['status' => 'paid', 'charge_id' => $chargeId]);
});
}
}An event-carried state transfer consumer. The broker consumer (see Laravel Queue Internals and the RabbitMQ/Kafka packages in the messaging path) decodes the JSON with a tolerant reader and dispatches CustomerChanged; the queued listener upserts only newer versions:
<?php
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Integration event published by the customers service and decoded here by
* the broker consumer. It carries the state (event-carried state transfer),
* so orders never has to call customers to read a name or a tier.
*/
final class CustomerChanged
{
use Dispatchable;
public function __construct(
public string $customerId,
public string $name,
public string $email,
public string $tier,
public int $version,
) {}
/** Tolerant Reader: take what we need, ignore unknown fields, default new optional ones. */
public static function fromMessage(array $payload): self
{
return new self(
customerId: (string) $payload['customer_id'],
name: (string) ($payload['name'] ?? ''),
email: (string) ($payload['email'] ?? ''),
tier: (string) ($payload['tier'] ?? 'standard'),
version: (int) $payload['version'],
);
}
}<?php
namespace App\Listeners;
use App\Events\CustomerChanged;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
/**
* Keeps orders' local copy of customer data. Idempotent and order-tolerant:
* a duplicate or an older event (lower version) changes nothing.
*/
final class StoreCustomerSnapshot implements ShouldQueue
{
public function handle(CustomerChanged $event): void
{
DB::statement(<<<'SQL'
INSERT INTO customer_snapshots (customer_id, name, email, tier, version, updated_at)
VALUES (?, ?, ?, ?, ?, now())
ON CONFLICT (customer_id) DO UPDATE
SET name = EXCLUDED.name, email = EXCLUDED.email, tier = EXCLUDED.tier,
version = EXCLUDED.version, updated_at = now()
WHERE customer_snapshots.version < EXCLUDED.version
SQL, [$event->customerId, $event->name, $event->email, $event->tier, $event->version]);
}
}Contract tests against the same JSON file as the Go tests (copy go/contract/pacts/orders-billing.json to contracts/ in both apps, or fetch it from a Pact Broker):
<?php
namespace Tests\Contract;
use App\Clients\BillingClient;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/**
* Runs in the ORDERS app. Plays the provider from the shared contract file
* (the same JSON the Go tests use) and checks that BillingClient sends
* exactly the contracted request and can read the contracted response.
*/
final class BillingConsumerContractTest extends TestCase
{
public function test_orders_sends_the_contracted_charge_request(): void
{
$pact = json_decode(file_get_contents(base_path('contracts/orders-billing.json')), true, flags: JSON_THROW_ON_ERROR);
$it = $pact['interactions'][0];
config(['services.billing.url' => 'https://billing.test']);
Http::preventStrayRequests();
Http::fake([
'billing.test/*' => Http::response($it['response']['body'], $it['response']['status'], $it['response']['headers']),
]);
$result = app(BillingClient::class)->charge('1001', '42', 4999, 'EUR');
$this->assertSame('captured', $result['status']);
$this->assertNotSame('', $result['charge_id']);
Http::assertSent(fn (Request $request): bool => $request->method() === $it['request']['method']
&& $request->url() === 'https://billing.test'.$it['request']['path']
&& $request->hasHeader('Idempotency-Key', $it['request']['headers']['Idempotency-Key'])
&& $request->data() == $it['request']['body']);
}
}<?php
namespace Tests\Contract;
use Illuminate\Support\Facades\DB;
use Illuminate\Testing\Fluent\AssertableJson;
use Tests\TestCase;
/**
* Runs in the BILLING app. Replays every contracted request against the real
* routes and checks the response contains at least the contracted fields
* (extra fields are allowed: that is what keeps additions compatible).
*/
final class BillingProviderContractTest extends TestCase
{
public function test_billing_honours_the_orders_contract(): void
{
$pact = json_decode(file_get_contents(base_path('contracts/orders-billing.json')), true, flags: JSON_THROW_ON_ERROR);
foreach ($pact['interactions'] as $it) {
$this->givenProviderState($it['providerState']);
$response = $this->json($it['request']['method'], $it['request']['path'], $it['request']['body'], $it['request']['headers']);
$response->assertStatus($it['response']['status']);
$response->assertJson(function (AssertableJson $json) use ($it) {
$rules = $it['response']['matchingRules'] ?? [];
foreach ($it['response']['body'] as $field => $value) {
($rules["$.body.{$field}"]['match'] ?? null) === 'type'
? $json->whereType($field, gettype($value))
: $json->where($field, $value);
}
$json->etc();
});
}
}
private function givenProviderState(string $state): void
{
match ($state) {
'customer 42 has enough credit' => DB::table('credit_limits')
->updateOrInsert(['customer_id' => '42'], ['available_cents' => 100_000]),
default => $this->fail("Unknown provider state: {$state}"),
};
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
Http::timeout() / connectTimeout() | Per-call limits | Defaults 30 s and 10 s; signature accepts int|float |
Http::retry($times, $sleep, $when, throw:) | Retries | The $when callback can change the request (new token, new timeout) |
Http::pool() | Parallel composition | One request per backend, concurrently |
Http::globalRequestMiddleware() | Add traceparent to every outgoing call | Register in AppServiceProvider::boot |
Http::fake(), Http::preventStrayRequests(), Http::assertSent() | Consumer contract tests | No network |
Context::add() | Trace ID in every log line and in queued jobs | Shared "across the HTTP request / queued job boundary" |
ShouldBeUnique, #[UniqueFor], uniqueId() | One pending job per key | Needs a lock-capable cache (redis, memcached, dynamodb, database, file, array) |
ShouldBeUniqueUntilProcessing | Unlock when processing starts | Allows a new dispatch while the first runs |
WithoutOverlapping job middleware | One job per key executing | Lock with expireAfter() |
#[Tries], #[Backoff], #[RetryFor], #[MaxExceptions] | Consumer-side retry policy | Retry & Backoff |
ShouldQueueAfterCommit | Dispatch only after the transaction commits | Not a full outbox; see Outbox |
RateLimiter::increment() | A cluster-wide retry budget (60 retries per minute here) | Atomic on redis, memcached and database stores |
Solving the classic problems
Retry storm during an outage
t Event Load on billing
1 0 s billing slows down (GC, failover) 100%
2 1 s frontends, orders and gateway each retry 3x up to 64x on the slowest path
3 5 s billing recovers capacity, but the queue of retries still above 100%: no recovery
4 fix retry at one layer, jittered, budgeted about 1.1x; recovers in seconds| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Retry at one layer | Only the layer right above the failing one retries; others pass errors up | Kills multiplication | Teams must agree; libraries default to retrying |
| Retry budget | Per-client ratio below 10% (SRE) or token bucket (retryThrottling, AWS SDK) | Caps load during outages | Fewer successes when failures are random and heavy (see the lab) |
| Full jitter | random(0, min(cap, base * 2^n)) | No synchronised waves | Slightly longer mean wait |
| "overloaded; don't retry" signal | Server returns a distinct error or grpc-retry-pushback-ms | Stops retries at the source | Needs a protocol convention |
| Circuit breaker | Fail fast for a cool-down | Gives the dependency room | Modal behaviour, harder to test |
Double charge after a timeout
Client Billing
1 POST /charges (no key) charges card
2 timeout at 2 s (response was slow)
3 retry POST /charges (no key) charges card again: customer charged twice| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Idempotency key with stored response | Unique (scope, key), fingerprint, replay | Safe retries for any POST | Storage, TTL, a 409 path |
| Natural idempotency | PUT /charges/{order_id} or upsert on a business key | No extra table | Needs a business key that is unique per action |
| Deduplicate on the consumer | Message ID in an inbox table | Works for queues | Per consumer, see Inbox |
| Do not retry POST | One attempt, then reconcile | Simple | Worse availability; manual follow-up |
The provider-side table and the atomic claim in PostgreSQL (the Laravel migration above creates the same shape):
CREATE TABLE idempotency_keys (
scope varchar(100) NOT NULL, -- caller identity (tenant, client id)
key varchar(255) NOT NULL, -- Stripe allows up to 255 characters
fingerprint char(64) NOT NULL, -- sha256(method, path, body)
response_status smallint, -- NULL while in progress
response_body text,
response_content_type varchar(100),
locked_at timestamptz, -- lease for crashed holders
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
CREATE INDEX idempotency_keys_expires_at ON idempotency_keys (expires_at);
-- 1. Claim: exactly one concurrent request gets a row back.
INSERT INTO idempotency_keys (scope, key, fingerprint, locked_at, expires_at)
VALUES ($1, $2, $3, now(), now() + interval '24 hours')
ON CONFLICT (scope, key) DO NOTHING
RETURNING key;
-- 2. No row returned: read the existing claim and decide 422 / 409 / replay.
SELECT fingerprint, response_status, response_body, response_content_type, locked_at
FROM idempotency_keys WHERE scope = $1 AND key = $2;
-- 3. Success: store the outcome in the SAME transaction as the business change.
UPDATE idempotency_keys
SET response_status = $3, response_body = $4, response_content_type = $5, locked_at = NULL
WHERE scope = $1 AND key = $2;
-- 4. Housekeeping (scheduled): drop expired keys.
DELETE FROM idempotency_keys WHERE expires_at < now();
-- Consumer side: the inbox claim for a message, inside the handler's transaction.
INSERT INTO processed_messages (message_id, handler, processed_at)
VALUES ($1, $2, now())
ON CONFLICT (message_id, handler) DO NOTHING;Wasted work after the caller gave up
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Deadline propagation | grpc-timeout, or Request-Timeout-Ms + context | Every hop stops together | HTTP needs a convention |
| Check before each stage | if ctx.Err() != nil or remaining budget before expensive work | Stops doomed work early | Code discipline |
| Cancellation propagation | Cancel outbound calls when the inbound one is cancelled | Frees resources fast | Not all clients support it (PHP-FPM is blocking) |
| Short, realistic timeouts | p99.9 of the callee, not "30 s" | No thread exhaustion | Needs latency data |
A provider change breaks a consumer in production
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Consumer-driven contract tests | Pact files verified in the provider's CI | Break found before deploy | Consumers must write and publish pacts |
| Tolerant reader | Ignore unknown fields, default missing optional ones | Additive changes are free | Can hide meaning changes |
| Breaking-change check on schemas | Protobuf breaking rules, schema-registry compatibility, OpenAPI diff | Mechanical, cheap | Shape only, not semantics |
| Expand-and-contract | Add new, migrate consumers, remove old | No flag day | Two fields for a while |
Slow page built from many services
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Parallel composition with one deadline | errgroup / Http::pool, partial results | Latency = slowest, bounded | Availability still the product |
| Read model (ECST or CQRS) | Keep a denormalised copy fed by events | One local query | Staleness, more storage |
| Hedging for tail | Second copy after p95 | Cuts p99 | Extra load; idempotent reads only |
| BFF per client | Shape data for one screen | Fewer round trips from mobile | One more service to run |
Nobody can follow a request
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
W3C traceparent everywhere | Middleware, HTTP clients, message headers | Vendor-neutral traces | Every hop must forward it |
| Trace ID in logs | Laravel Context, Go slog with trace attributes | Logs join traces | Discipline at log call sites |
| Workflow ID for async flows | Saga or order ID in every message | Find stuck flows | One more field in contracts |
Errors that cannot be told apart
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Problem Details (RFC 9457) | application/problem+json with a stable type URL | Machine-readable, documented | Must map every exception |
| Precise gRPC codes | INVALID_ARGUMENT vs FAILED_PRECONDITION vs UNAVAILABLE | Retry policies can rely on codes | Teams must agree on the mapping |
Never 200 with an error body | Use the status line | Proxies, metrics and retries see failures | Legacy clients may need a shim |
Testing service communication
| Test | What it proves | Tools | Runs where |
|---|---|---|---|
| Consumer contract test | My client sends what the contract says and reads what it needs | Pact, Http::fake, httptest | Consumer CI |
| Provider verification | My API still satisfies every consumer's contract | Pact verifier, Laravel feature tests, httptest.NewRecorder | Provider CI, blocks deploy |
| Schema compatibility | The new schema is backward/forward compatible | Protobuf breaking checks, schema registry | CI |
| Component test with fakes | Retry, timeout and fallback logic work | httptest.Server that returns 503 or sleeps | Unit-level CI |
| Fault injection | The system degrades as designed | Toxiproxy ("a framework for simulating network conditions"), Istio fault injection (fixedDelay: 7s, HTTP abort) | Staging, game days |
| Chaos experiment | Hypothesis about steady state holds under real failure | Chaos engineering practice | Production, small blast radius (Chaos Engineering) |
| End-to-end smoke test | The happy path works with real services | A few scripted calls | After deploy |
Fault-injection run for orders -> billing (staging)
1 hypothesis: with billing at 30% 503s, checkout success stays above 99% and billing load stays below 1.2x
2 inject: Istio abort 30% on billing, or Toxiproxy latency 500 ms
3 observe: checkout success, retries per request, billing RPS, p99, breaker state
4 example outcome to look for: success above 99%, load near 1.1x; at 80% failures the budget stops retriesChoosing
Which style
| Situation | Style | Extra technique | Reason |
|---|---|---|---|
| User waits for an answer that only another service has (price, permission, stock check) | Sync request/response | Deadline, retry for idempotent reads, fallback | The answer is needed now |
| Side effect the user does not need to wait for (email, invoice, analytics) | Async command or event | Outbox, idempotent consumer | No temporal coupling |
| Long or rate-limited work (charge, export, provisioning) | Async command + status | 202 Accepted, poll or push | Do not hold connections |
| Many services need to react to one fact | Event notification | AsyncAPI, tracing | Producer does not know consumers |
| A service often reads another's data | Event-carried state transfer | Versioned upsert, tolerant reader | Remove the runtime dependency |
| Replay, audit, new consumers later | Event stream | Retention, partition key, schema registry | History is the product |
| Strong consistency across two services | Usually a boundary problem | Merge ownership, or a saga with compensations | No cheap cross-service ACID |
| Screen needs data from many services | API composition / BFF | Parallel calls, partial results | One round trip for the client |
| Tail latency on hot reads | Sync + hedging | Delay at p95, cancel losers | Cuts p99 |
Orchestration or choreography
| Factor | Prefer orchestration | Prefer choreography |
|---|---|---|
| Number of steps | More than 3-4, or branching | 1-3 independent reactions |
| Compensation needed | Yes, in a defined order | No, or each reaction is self-contained |
| "Where is my order?" visibility | Required (support, SLA) | Not needed |
| Team ownership | One team owns the process | Each reaction is owned by a different team |
| Change frequency of the flow | Often (one place to change) | Rarely |
| Coupling you accept | Orchestrator knows participants' commands | Participants know event names |
| Typical tools | Temporal, Step Functions, Camunda, Bus::chain | Broker topics, Laravel events |
Which failure policy
1 Does the operation change state?
2 no -> retry transient errors (UNAVAILABLE, 503, 429, connect errors), jitter, budget
3 yes -> is it naturally idempotent (PUT by id, upsert, "set status = paid where status = pending")?
4 yes -> same as reads
5 no -> add an Idempotency-Key (stored response, 409 while running, 422 on reuse); then retry
6 Which layer retries? the one directly above the failing dependency; the others pass the error up
7 How long? the propagated deadline; never a fixed 30 s
8 What if it keeps failing? budget stops retries; breaker or fallback; async + DLQ for commandsIn architecture: from a single process to a distributed system
The same interaction, "after checkout, charge the customer and tell shipping", changes shape as the system grows. The four decisions (style, contract, failure policy, duplicate policy) stay the same; what changes is how much of each the infrastructure gives you for free.
Monolith: one process, one database
How it shows up: a method call. CheckoutService calls PaymentService::charge() inside one DB::transaction (ACID); the only network call is to the external payment provider.
Simplest correct usage: even here, the payment provider call needs a timeout, an idempotency key (order-1001-charge) and a retry only for transient errors. In-process events (Laravel events, Go function callbacks) are synchronous unless queued.
Example (simple): a shop with one Laravel app: PlaceOrder action, Http::timeout(5)->retry(...)->withHeaders(['Idempotency-Key' => ...]) to Stripe, a queued SendOrderEmail job.
Example (production-shaped): the same app with Horizon workers: the email and invoice jobs are asynchronous commands; the payment is synchronous because the user waits; a nightly reconciliation job compares orders with the provider's charges.
Modular monolith: boundaries without the network
How it shows up: modules talk through a facade or in-process events, so the contract exists (interfaces, DTOs) but failures are still local. This is where to practise the contracts: if Billing\Api\ChargeRequest is the only way in, extracting billing later is a transport change, not a redesign (Modular Monolith).
Example: orders publishes OrderPlaced on an in-process bus; billing and shipping listen. Moving billing out later means: the listener becomes a broker consumer, the facade becomes an HTTP/gRPC client, and the outbox replaces "dispatch after commit".
| Concern | In-process now | When extracted |
|---|---|---|
| Contract | PHP interface / Go interface + DTO | OpenAPI / Protobuf / AsyncAPI |
| Failure | Exception | Timeout, 503, unknown outcome |
| Duplicates | Impossible | Need keys and inbox |
| Transaction | One BEGIN ... COMMIT | Saga, outbox |
Microservices: every arrow is a decision
How it shows up: each arrow on the diagram needs a style, a contract, a deadline, a retry policy and a duplicate policy. A concrete flow:
Client -> Gateway -> Orders (sync, budget 1 s)
1 Orders: INSERT order PENDING + outbox ChargeOrder (one transaction); reply 202 + /orders/1001
2 Relay -> payments.commands: ChargeOrder{msg_id, order_id, traceparent}
3 Payments: inbox claim msg_id; POST provider /charges (Idempotency-Key order-1001-charge, deadline 5 s)
4 Payments -> payments.events: PaymentSucceeded{order_id, version}
5 Orders: consumes, marks PAID; Shipping: consumes, books courier (choreography for the reactions)
6 Customers -> customers.events: CustomerChanged (ECST) -> Orders keeps customer_snapshots
7 Contract tests: orders<->payments (commands/events, AsyncAPI), gateway<->orders (OpenAPI)What survives across the boundary: the trace ID, the deadline (for sync hops), the idempotency key and the message ID. What does not: transactions (use sagas), exceptions (use Problem Details and status codes), and shared types (use published contracts). The edge concerns (authentication, rate limits, BFF) belong to API Gateway, BFF & Service Mesh; finding instances belongs to Service Discovery.
Distributed data: replicas, caches, regions
How it shows up: a synchronous read may hit a replica that is behind, so "I just paid and the order page says pending" is a communication problem, not only a database one (Replication). Caches in front of a service turn ECST-like staleness into the default. Across regions, a 1 s budget leaves room for one cross-region hop (about 70-150 ms round trip) and little else, so cross-region calls move to async replication.
| Effect | Where it hurts | Mitigation |
|---|---|---|
| Replica lag | Read-your-writes after a command | Read from primary for N seconds, or return the new state in the command's response |
| Stale cache | ECST copies, BFF caches | Version in events, short TTL, invalidate on event |
| Cross-region latency | Sync chains spanning regions | Keep sync calls in-region; replicate data async |
| Clock skew | Absolute deadlines | Send remaining time, not a timestamp (as gRPC does) |
| Idempotency store replicated | Two regions accept the same key | Scope keys to a home region, or use a strongly consistent store |
Scaling path: 1x, 10x, 100x
| Load | What changes | Example |
|---|---|---|
| 1x | Sync calls with timeouts and keyed retries; one queue for side effects | One Laravel app + workers, one Go service |
| 10x | Deadlines propagated, retry budgets, breakers per dependency, ECST copies replace hot sync reads, contract tests in CI | 5-15 services; Kafka or RabbitMQ; Pact Broker |
| 100x | Service mesh (mTLS, retries, outlier detection), hedging on hot reads, criticality propagated with the request (Google SRE), load shedding at the edge, streams as the integration backbone | Hundreds of services; per-method gRPC service config from the resolver |
Lab: retry storm vs budgeted retry, with numbers
You will run two strategies against the same injected failures and latency and compare the load that reaches the bottom service. Everything runs offline on loopback.
Setup.
cd docs/snippets/architecture/service-communication/go
go vet ./... && go test ./...
go run ./asynccmd # duplicate delivery, single chargeThe lab program lab/stormlab starts three HTTP services on loopback, edge -> api -> db, and injects failures (-fail, a seeded fraction of 503s at db) and latency (-latency, time db spends per attempt). Naive mode: edge and api each make up to 4 attempts with a fixed 1 ms pause and their own fixed timeouts; db ignores deadlines. Budgeted mode: only edge retries (3 attempts, full jitter, gRPC-style budget {10, 0.1}), one deadline is propagated with Request-Timeout-Ms, and db stops work when the deadline passes.
// Command stormlab runs three HTTP services on loopback, edge -> api -> db,
// injects failures and latency at db, and compares two client strategies:
//
// naive: every hop retries 4 times with a fixed pause and its own
// fixed timeout; db does not watch the deadline.
// budgeted: only the edge retries (3 attempts, full jitter, retry budget),
// one deadline is propagated with Request-Timeout-Ms, db stops
// work when the caller's deadline passes.
//
// Failures are drawn from a seeded generator and requests are sequential,
// so the counts are reproducible.
package main
import (
"context"
"flag"
"fmt"
"io"
"math/rand/v2"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"time"
"academy/service-communication/callbudget"
"academy/service-communication/retry"
)
var (
mode = flag.String("mode", "naive", "naive or budgeted")
failRate = flag.Float64("fail", 0.0, "fraction of db attempts rejected with 503")
dbLatency = flag.Duration("latency", 2*time.Millisecond, "db work per attempt")
n = flag.Int("n", 100, "user requests")
edgeTotal = flag.Duration("budget", 300*time.Millisecond, "edge deadline (budgeted) / per-attempt timeout x4 (naive)")
)
var (
dbAttempts, dbOrphans, dbCancelled atomic.Int64
rngMu sync.Mutex
rng = rand.New(rand.NewPCG(1, 2))
inflight sync.WaitGroup
)
func shouldFail() bool {
rngMu.Lock()
defer rngMu.Unlock()
return rng.Float64() < *failRate
}
func db(budgeted bool) http.Handler {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
inflight.Add(1)
defer inflight.Done()
dbAttempts.Add(1)
if shouldFail() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
if budgeted {
select {
case <-time.After(*dbLatency):
case <-r.Context().Done():
dbCancelled.Add(1) // stopped doomed work early
w.WriteHeader(http.StatusGatewayTimeout)
return
}
} else {
time.Sleep(*dbLatency) // deadline-unaware work
}
_, _ = io.WriteString(w, "ok")
})
if budgeted {
return callbudget.Middleware(time.Second, 5*time.Second, h)
}
return h
}
func api(dbURL string, budgeted bool) http.Handler {
if budgeted {
client := &http.Client{}
return callbudget.Middleware(time.Second, 5*time.Second, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, dbURL, nil)
if err := callbudget.Outgoing(req, 2*time.Millisecond); err != nil {
w.WriteHeader(http.StatusGatewayTimeout)
return
}
resp, err := client.Do(req) // no retry here: retry at one layer only
if err != nil {
w.WriteHeader(http.StatusGatewayTimeout)
return
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
}))
}
client := &http.Client{Timeout: time.Second} // fixed per-hop timeout
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
inflight.Add(1)
defer inflight.Done()
for attempt := 0; attempt < 4; attempt++ {
resp, err := client.Get(dbURL) // context not propagated
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
if r.Context().Err() != nil {
dbOrphans.Add(1) // the edge gave up: this work was for nobody
}
return
}
}
time.Sleep(time.Millisecond)
}
w.WriteHeader(http.StatusServiceUnavailable)
})
}
func main() {
flag.Parse()
budgeted := *mode == "budgeted"
dbSrv := httptest.NewServer(db(budgeted))
defer dbSrv.Close()
apiSrv := httptest.NewServer(api(dbSrv.URL, budgeted))
defer apiSrv.Close()
budget := retry.NewBudget(10, 0.1)
ok := 0
start := time.Now()
for i := 0; i < *n; i++ {
if budgeted {
ctx, cancel := context.WithTimeout(context.Background(), *edgeTotal)
resp, err := retry.Do(ctx, http.DefaultClient, retry.Policy{
MaxAttempts: 3, Base: 5 * time.Millisecond, Cap: 50 * time.Millisecond, Budget: budget,
}, func(ctx context.Context) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiSrv.URL, nil)
if err == nil {
err = callbudget.Outgoing(req, 2*time.Millisecond)
}
return req, err
})
if err == nil {
if resp.StatusCode == http.StatusOK {
ok++
}
resp.Body.Close()
}
cancel()
continue
}
c := &http.Client{Timeout: *edgeTotal / 4} // a timeout per attempt, not per request
for attempt := 0; attempt < 4; attempt++ {
resp, err := c.Get(apiSrv.URL)
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
ok++
break
}
}
time.Sleep(time.Millisecond)
}
}
elapsed := time.Since(start)
inflight.Wait()
fmt.Printf("mode=%-8s fail=%.2f latency=%-6v requests=%d ok=%d db_attempts=%d amplification=%.2fx orphaned=%d cancelled=%d budget_denied=%d elapsed=%v\n",
*mode, *failRate, *dbLatency, *n, ok, dbAttempts.Load(),
float64(dbAttempts.Load())/float64(*n), dbOrphans.Load(), dbCancelled.Load(), budget.Denied, elapsed.Round(10*time.Millisecond))
}Step 1: failures, no latency. Run both modes at four failure rates:
for m in naive budgeted; do for f in 0 0.1 0.5 1; do go run ./lab/stormlab -mode $m -fail $f; done; doneOutput on the author's machine (counts are deterministic; elapsed times vary):
mode=naive fail=0.00 latency=2ms requests=100 ok=100 db_attempts=100 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=250ms
mode=naive fail=0.10 latency=2ms requests=100 ok=100 db_attempts=112 amplification=1.12x orphaned=0 cancelled=0 budget_denied=0 elapsed=260ms
mode=naive fail=0.50 latency=2ms requests=100 ok=100 db_attempts=174 amplification=1.74x orphaned=0 cancelled=0 budget_denied=0 elapsed=350ms
mode=naive fail=1.00 latency=2ms requests=100 ok=0 db_attempts=1600 amplification=16.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=2.53s
mode=budgeted fail=0.00 latency=2ms requests=100 ok=100 db_attempts=100 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=250ms
mode=budgeted fail=0.10 latency=2ms requests=100 ok=100 db_attempts=112 amplification=1.12x orphaned=0 cancelled=0 budget_denied=0 elapsed=290ms
mode=budgeted fail=0.50 latency=2ms requests=100 ok=65 db_attempts=105 amplification=1.05x orphaned=0 cancelled=0 budget_denied=35 elapsed=180ms
mode=budgeted fail=1.00 latency=2ms requests=100 ok=0 db_attempts=103 amplification=1.03x orphaned=0 cancelled=0 budget_denied=99 elapsed=30ms| Failure rate | Naive db attempts | Budgeted db attempts | Naive ok | Budgeted ok | Reading |
|---|---|---|---|---|---|
| 0% | 100 (1.00x) | 100 (1.00x) | 100 | 100 | No difference when healthy |
| 10% | 112 | 112 | 100 | 100 | Light transient errors: both retry, both succeed |
| 50% | 174 | 105 | 100 | 65 | The budget trades successes for load: correct for overload, too strict for random loss |
| 100% (outage) | 1600 (16.00x = 4 x 4) | 103 (1.03x) | 0 | 0 | The storm: naive multiplies load by the product of attempts per layer |
Step 2: latency, no failures. db takes 150 ms; the edge has 400 ms in total (naive splits it into 4 attempts of 100 ms each):
go run ./lab/stormlab -mode naive -n 20 -latency 150ms -budget 400ms
go run ./lab/stormlab -mode budgeted -n 20 -latency 150ms -budget 400ms
go run ./lab/stormlab -mode budgeted -n 20 -latency 150ms -budget 100msmode=naive fail=0.00 latency=150ms requests=20 ok=0 db_attempts=80 amplification=4.00x orphaned=80 cancelled=0 budget_denied=0 elapsed=8.16s
mode=budgeted fail=0.00 latency=150ms requests=20 ok=20 db_attempts=20 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=3.03s
mode=budgeted fail=0.00 latency=150ms requests=20 ok=0 db_attempts=20 amplification=1.00x orphaned=0 cancelled=20 budget_denied=17 elapsed=1.91sExpected reading: a per-attempt timeout below the callee's normal latency fails every request and still does all the work four times (80 orphaned completions: db finished, nobody was listening). One propagated deadline that fits the latency succeeds 20/20 with 20 attempts. When the budget is genuinely too small, db cancels the doomed work (cancelled=20) instead of finishing it, and the budget stops retries (budget_denied may differ by one or two between runs because it depends on timing).
Step 3: make the budget fit the failure mode. Change retry.NewBudget(10, 0.1) to retry.NewBudget(10, 1.0) in main.go and rerun -mode budgeted -fail 0.5 and -fail 1. Observed: at 50% failures ok=79 db_attempts=136 (1.36x, up from 65 and 1.05x); at 100% still db_attempts=103 (1.03x), because the budget only refills on successes. Write down which setting you would choose for a dependency that fails because of overload and for one that fails because of a lossy network.
Step 4: probe the order of the checks. Add a test that sends, while the first request with key k1 is still in flight, (a) the same key with body {"amount":99} and (b) the same key and the same body. Observed: (a) gets 422 and (b) gets 409: the middleware compares the fingerprint before it looks at the in-progress state, so a client bug (reused key) is reported as such even during a race. Swap the two case lines in idempotency.go and (a) becomes 409; decide which behaviour your API documents.
Step 5: break the contract. In contract/provider.go, rename the JSON field status to state and run go test ./contract. Expected: TestProviderHonoursContract fails with missing field status, while the consumer test still passes. That is the point: the provider learns about the break in its own CI.
Step 6 (Laravel, optional). Copy the PHP files into a Laravel 13 app with PostgreSQL, run the migration, register CallBudget as scoped, route POST /api/charges through the idempotent middleware, and send the same request twice with curl -H 'Idempotency-Key: k1'. Expected: the second response carries Idempotent-Replayed: true and the handler ran once.
Common misconceptions
| Belief | Reality |
|---|---|
| Async is always more decoupled | It removes temporal coupling; semantic coupling and hidden flows remain (Fowler on event notification) |
| A timeout means the call failed | It means you stopped waiting; gRPC DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully" |
| Retries improve reliability | Only for transient faults; under overload they are "selfish" and multiply load (64x, 243x) |
| Three retries is a safe default | At three layers it is 64 attempts; retry at one layer with a budget |
| Exponential backoff is enough | Without jitter, clients stay synchronised; full jitter cut calls "by more than half" |
| A circuit breaker solves storms | It helps, but adds modal behaviour; a retry budget is simpler and always on |
ShouldBeUnique makes a Laravel job idempotent | It prevents duplicate dispatch while one is pending; a crashed worker still re-runs the job |
| Checking "exists?" before insert makes POST idempotent | Check-then-insert races; use a unique key claim |
| Events must never carry data | Event-carried state transfer carries data on purpose, to remove runtime dependencies |
/v2 is how you evolve an API | Additive changes, tolerant readers and expand-and-contract avoid most new versions |
| Contract tests replace integration tests entirely | They replace most; keep a few end-to-end smoke tests |
| Internal calls do not need auth | Zero trust: mTLS plus a token with caller and audience |
| The request ID per service is enough for tracing | Only a propagated trace ID can be joined across hops and queues |
| gRPC retries everything for you | No default retry policy; only transparent retries of RPCs that never reached the application |
Cheat sheet
| Topic | Remember |
|---|---|
| Styles | Sync req/resp, async req/resp (command), event notification, event-carried state transfer, stream |
| Coupling questions | Temporal, availability, latency, consistency, semantic, deployment |
| When sync | The user waits for an answer only another service has |
| When async | Side effects, slow or spiky work, fan-out to many reactions |
| Orchestration | Many steps, compensations, visibility needed |
| Choreography | Few independent reactions owned by different teams |
| Contracts | OpenAPI (HTTP), Protobuf (gRPC), AsyncAPI (messages); contract-first across teams |
| Compatibility | Additive changes, tolerant reader, never reuse Protobuf field numbers, expand-and-contract |
| Pact | Consumer writes expectations; provider verifies in its CI; provider states for data |
| Deadline | Set once at the edge; pass remaining time minus a margin; stop work when it passes |
| Timeout value | Callee's latency percentile at an accepted false-timeout rate (AWS: 0.1% -> p99.9) |
| Retry rule | Transient only, idempotent only, max 3 attempts, one layer, full jitter, budget |
| Full jitter | random(0, min(cap, base * 2^n)) |
| Idempotency key | Client-chosen, scoped, unique claim, fingerprint, stored response, 409 while running, 422 on reuse, TTL >= 24 h |
| Hedging | Idempotent reads, after p95, cancel losers; gRPC-Go: do it by hand |
| Errors | RFC 9457 Problem Details; precise gRPC codes; never 200 with an error |
| Tracing | W3C traceparent on every request and message; trace ID in every log line |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the five communication styles and give one example of each. Must-know
Answer
Answer: Sync request/response (GET /customers/42), async request/response or command (ChargeOrder on a queue, PaymentSucceeded back), event notification (OrderPlaced {id}), event-carried state transfer (CustomerChanged with the data and a version), event stream (a Kafka topic consumers replay). See the catalogue.
2 — A service calls three dependencies sequentially, each 99.9% available. What is the best-case availability of that request, and what are two ways to improve it? Must-know
Answer
Answer: About 0.999^3 = 99.7%. Make non-essential calls asynchronous or optional with a fallback, or replace a runtime read with a local copy fed by events (ECST). See Coupling.
3 — Your POST to billing timed out after 2 s. Can you retry it? What must be true first? Must-know
Answer
Answer: Only if it is idempotent: send the same Idempotency-Key on the retry and the server must claim keys atomically and replay the stored response. A timeout does not mean the charge did not happen. See Idempotency keys.
4 — Frontend, backend and data service each retry 3 times on error. The database is overloaded. How many attempts can one user action produce, and what do you change? Must-know
Answer
Answer: 4 x 4 x 4 = 64 (Google SRE's example). Retry only at the layer directly above the failing one, add full jitter and a retry budget (per-client ratio below 10% or token bucket). See Retries.
5 — The edge has a 1000 ms budget, spends 50 ms, and each hop uses a 10 ms margin. Orders spends 200 ms before calling billing. What timeout does billing receive? Important
Answer
Answer: 1000 - 50 - 10 = 940 to orders; 940 - 200 - 10 = 730 to billing. See Deadlines.
6 — What does an idempotency layer return for (a) a duplicate while the first is still running, (b) a duplicate after completion, (c) the same key with a different body? Important
Answer
Answer: (a) 409 Conflict, (b) the stored response replayed, (c) 422 Unprocessable Content (IETF draft -09; Stripe also rejects mismatched parameters).
7 — Does Laravel's ShouldBeUnique make the job handler idempotent? Explain. Must-know
Answer
Answer: No. It holds a lock from dispatch until the job completes or fails all retries, so a second dispatch with the same uniqueId is not queued. A worker that crashes after the side effect will run the job again; the handler needs an inbox row or a natural idempotent write.
8 — When would you pick orchestration over choreography? Important
Answer
Answer: When the flow has more than a few steps, needs ordered compensations, or someone must answer "where is this order stuck?". Choreography fits a few independent reactions owned by different teams. See Choosing.
9 — Billing wants to rename status to state in its JSON response. How do you do it without breaking orders? Important
Answer
Answer: Expand and contract: send both fields, let consumers move (pact verification shows who still reads status), then stop sending status. Never change meaning in place. See Compatibility.
10 — Why does gRPC send a remaining timeout rather than an absolute deadline on the wire? Good to know
Answer
Answer: Because server clocks may differ; "gRPC converts the deadline to a timeout from which the already elapsed time is already deducted. This shields your system from any clock skew issues."
11 — In the lab at 50% random failures, the budgeted client succeeded 65 times and the naive one 100 times. Is the budget wrong? Good to know
Answer
Answer: It is tuned for overload, where extra attempts make things worse. For independent, random loss a looser budget (higher tokenRatio) recovers more requests. Choose per dependency and measure; the budget's job is to cap the worst case. See Lab.
12 — Which header carries the trace across services, and what must a component that does not trace still do with it? Must-know
Answer
Answer: traceparent (with optional tracestate), W3C Trace Context. Even a non-participating component "MUST propagate the traceparent and tracestate headers".
Glossary
| Term | Meaning |
|---|---|
| Synchronous request/response | Caller waits for the answer; callee must be up for the duration |
| Asynchronous request/response | Request as a message; reply arrives later as another message or callback |
| Command | Message asking one named receiver to do something |
| Event | Message stating a fact that happened; any number of receivers |
| Event notification | Event with an ID only; receivers may call back for details (Fowler) |
| Event-carried state transfer (ECST) | Event carries the changed data so receivers keep a local copy (Fowler) |
| Passive-aggressive command | A command disguised as an event (Fowler) |
| Event stream | Durable, partitioned, replayable log; consumers own offsets |
| Temporal coupling | Both parties must be available at the same time |
| Orchestration | One coordinator tells participants what to do |
| Choreography | Participants react to each other's events; no coordinator |
| Saga | Sequence of local transactions with compensations (Saga) |
| Contract-first | Write and review the API description before the code |
| OpenAPI | Description format for HTTP APIs (3.1.0) |
| Protocol Buffers | Binary schema and IDL used by gRPC; fields identified by numbers |
| AsyncAPI | Description format for message-driven APIs (3.0.0) |
| Consumer-driven contract | Consumer's expectations, verified by the provider |
| Pact | Contract-testing tool; pact files, provider states, Pact Broker |
| Provider state | Precondition a provider sets up before verifying an interaction |
| Tolerant Reader | Read only what you need; ignore unknown fields (Fowler, Postel) |
| Backward compatible | New provider works with old consumers |
| Forward compatible | Old consumer works with data from a new producer |
| Expand-and-contract | Add the new form, migrate, then remove the old |
| Deadline | Absolute point in time after which the caller stops waiting |
| Deadline propagation | Passing the remaining budget to every downstream call |
Request-Timeout-Ms | This page's HTTP header convention for the remaining budget (not a standard) |
grpc-timeout | gRPC's wire representation of the remaining deadline |
DEADLINE_EXCEEDED | gRPC status 4: deadline passed; the operation may still have completed |
UNAVAILABLE | gRPC status 14: transient; retry with backoff if safe |
| Exponential backoff | Wait grows as base x 2^attempt up to a cap |
| Jitter | Randomness in the wait to desynchronise clients |
| Full jitter | Wait uniformly random between 0 and the exponential value |
| Retry storm | Retries at many layers or clients multiplying load on a failing dependency |
| Retry budget | Limit on retries per request or as a share of traffic (SRE: below 10%) |
| Retry throttling | gRPC token bucket that pauses retries when failures dominate |
| Transparent retry | gRPC retry of RPCs that never reached the server application |
| Idempotency | Doing an operation twice has the same effect as once |
| Idempotency key | Client-chosen ID for one operation, sent on every attempt (Idempotency-Key) |
| Fingerprint | Hash of the request used to detect a key reused with another payload |
| Inbox / processed messages | Consumer-side table of handled message IDs |
| Circuit breaker | Fails fast after repeated failures, then probes (half-open) |
| Bulkhead | Separate, bounded resource pool per dependency |
| Hedged request | Second copy of a slow idempotent request; first answer wins |
| API composition | A component calls the owning services and joins results in memory |
| BFF | Backend for Frontend: one gateway per kind of client |
| mTLS | Mutual TLS: both sides present certificates |
traceparent | W3C header: version, trace-id, parent-id, flags |
| Problem Details | RFC 9457 JSON error format, application/problem+json |
| Fault injection | Deliberately adding latency or errors (Toxiproxy, Istio) to test resilience |
References
- Sam Newman, Building Microservices, 2nd ed., O'Reilly, chapter 4 "Microservice Communication Styles" (chapter summary on the author's book page; book text not quoted)
- Mark Richards and Neal Ford, Fundamentals of Software Architecture and Ford, Richards, Sadalage, Dehghani, Software Architecture: The Hard Parts (O'Reilly); communication, consistency and coordination dimensions of distributed workflows (book, not quoted)
- Chris Richardson, microservices.io: Remote Procedure Invocation, Messaging, Saga, API Composition, API Gateway / BFF, Circuit Breaker
- Martin Fowler, "What do you mean by 'Event-Driven'?", 7 February 2017; "Tolerant Reader", 9 May 2011; James Lewis and Martin Fowler, "Microservices", 25 March 2014
- Ian Robinson, "Consumer-Driven Contracts: A Service Evolution", 12 June 2006
- Pact: Introduction, How Pact works
- OpenAPI Specification v3.1.0; AsyncAPI Specification 3.0.0; Protocol Buffers proto3 language guide and Dos and Don'ts
- gRPC: Deadlines, Retry, Request Hedging, Status codes, gRFC A6 client retries, grpc-go retry example
- Marc Brooker, "Timeouts, retries, and backoff with jitter", Amazon Builders' Library; "Exponential Backoff And Jitter", AWS Architecture Blog, 4 March 2015
- Google SRE Book: "Addressing Cascading Failures", "Handling Overload"
- Jeffrey Dean and Luiz André Barroso, "The Tail at Scale", CACM, February 2013
- Stripe: Idempotent requests; Brandur Leach, "Designing robust and predictable APIs with idempotency", 22 February 2017
- IETF, The Idempotency-Key HTTP Header Field, draft-ietf-httpapi-idempotency-key-header-09 (Internet-Draft, work in progress)
- RFC 9457: Problem Details for HTTP APIs, July 2023; W3C Trace Context, Recommendation 23 November 2021
- Laravel 13: HTTP Client, Queues, Events, Context, Service Container;
PendingRequestsource (13.x) - Go:
net/httpclient source (Client.Timeout),contextsource, Go Concurrency Patterns: Context - Fault injection: Toxiproxy README, Istio fault injection task