Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a network call is not a function callWhy it exists
Postel, consumer-driven contracts, jitter, Problem DetailsWhere it comes from
The five styles, one block eachSync, Async commands, Event notification, Event-carried state transfer, Streams
Temporal, availability, latency and consistency couplingCoupling
Orchestration vs choreographyOrchestration and choreography
OpenAPI, Protobuf, AsyncAPI, Pact, versioningContracts, Consumer-driven contracts, Compatibility
Timeouts, deadlines, retries, jitter, budgetsDeadlines, Retries
Idempotency-Key designIdempotency keys
Circuit breakers, bulkheads, hedgingBreakers and bulkheads, Hedging
Reads across servicesAPI composition and BFF
mTLS, tokens, traceparent, error formatsAuth, Tracing, Errors
Numbers, knobs, status codesMechanics
CodeGo, Laravel
Classic failures and their fixesSolving the classic problems
Contract tests, consumer tests, chaosTesting
Which style, which policyChoosing
Monolith to distributed systemIn architecture
Retry storm with real numbersLab
Wrong beliefs, summary, quiz, termsMisconceptions, 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".

StyleIn plain wordsTiny exampleWho waitsMain risk
Sync request/responseCall and wait for the answerGET /customers/42 over REST or a gRPC unary callThe caller, for the whole chainOne slow or dead dependency stalls the caller
Async request/response (command)Ask someone to do something; hear back laterChargeOrder on a queue, PaymentSucceeded comes backNobody blocks; the workflow waitsLost or duplicated messages, harder debugging
Event notificationTell the world something happened, with an IDOrderPlaced {order_id}NobodyHidden flow; consumers call back for details
Event-carried state transferTell the world what changed, with the dataCustomerChanged {id, name, tier, version}NobodyCopies of data everywhere, staleness
Event streamAppend facts to a durable, replayable logKafka topic orders with retentionNobody; each consumer keeps its offsetSchema evolution, ordering per key

The coupling each style creates.

CouplingQuestion it answersSyncAsync commandEvents
TemporalMust both be up at the same moment?YesNo (broker buffers)No
AvailabilityDoes the caller fail when the callee fails?Yes, unless degradedNo, it queuesNo
LatencyDoes the callee's latency add to the user's?Yes, per hopNoNo
ConsistencyIs the result visible immediately?Yes (read-your-write)EventuallyEventually
KnowledgeDoes the sender know the receiver?YesYes (one named receiver)No

The reliability toolkit, in the order you apply it.

ToolPromiseMust-have companionOwner page
DeadlineNobody waits past the point the user stopped caringPropagation to every hopDeadlines
Retry with backoff + jitterTransient failures become invisibleIdempotency, a budgetRetries
Idempotency keyDoing it twice equals doing it onceStorage with TTL, fingerprintIdempotency keys
Circuit breakerStop calling a dependency that is failingFallbackCircuit Breaker
BulkheadOne slow dependency cannot use all threadsPer-dependency poolsBulkheads
HedgingCut tail latency on idempotent readsCancellation, throttlingHedging
Contract testA provider change cannot silently break a consumerCI gateConsumer-driven contracts
Trace contextOne request can be followed across all hopstraceparent on every call and messageTracing
Synchronous (blocking)Asynchronous (non-blocking)Request-responseEvent-drivenSync request/responseCaller waits for the answerREST, gRPC unary, GraphQL query"Is this card valid?" during checkoutCoupling: temporal + availabilityLatency adds up per hopUse: reads, needs answer nowAsync request/responseCommand on a queue, reply laterChargeOrder -> queue -> PaymentDoneReply queue, callback, 202 + pollCoupling: no temporal coupling;still knows the receiverUse: slow or retried workNot a real combinationEvents are not awaited: if thesender blocks on a handler result,it is request/response in disguise(in-process listeners that run inlineare synchronous, but stay insideone process)Event-driven (three variants)1 Event notificationOrderPlaced {id}; consumer may call back2 Event-carried state transferCustomerChanged {all fields, version}3 Event stream (log, replayable)Kafka topic, Redis Stream; consumerskeep their own offsetMore temporal coupling, simpler to followLess coupling, flow harder to see

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/responseAsynchronous messaging
Simple to write, read and debugMore moving parts: broker, consumers, DLQ
Answer available now; strong read-after-writeAnswer 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 hopLatency 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 deadlineRetries happen in the consumer, with redelivery
Good for queries and for decisions the user waits onGood 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 ​

  1. "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".
  2. "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".
  3. "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.

text
     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 progress

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

text
     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 request

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

ProductSynchronous primitiveDefault timeoutNotes
Go net/httphttp.Client.DoNone (Timeout zero means no timeout)Always set Timeout or a context deadline
Laravel HTTP client (Guzzle)Http::get/post30 s response, 10 s connecttimeout(), connectTimeout()
gRPC (all languages)Unary RPCNo deadline by default"always explicitly set a realistic deadline"
GraphQLQuery over HTTPWhatever the HTTP client setsOne request, many resolvers behind it
Envoy / Istio / LinkerdRoute timeout, retriesPer-route configSee 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."

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

ProductCommand transportReply mechanismDeep page
RabbitMQQueue per receiverreply_to + correlation id, direct reply-toRequest-Reply
KafkaTopic per command typeReply topic keyed by correlation idKafka
Amazon SQSQueueSecond queue, or callback URLOther Brokers
Laravel queuesdispatch(new ChargeOrder(...))Event or job dispatched on completionLaravel Queue Internals
HTTP202 Accepted + status URLPoll or webhookREST 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."

text
     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 listed

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

text
     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 gold

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

ProductFit for ECSTNotes
Kafka with log compactionVery goodLatest value per key retained; new consumers rebuild from the topic
RabbitMQGood for live updatesNo replay of history; bootstrap a new consumer from an API or snapshot
Redis StreamsGood, bounded by MAXLENTrimmed history; plan the bootstrap
CDC (Debezium)Very goodEvents 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.

text
     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 only

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

DimensionCoupled whenExampleDecoupled by
TemporalBoth must run at the same momentCheckout calls Pricing synchronouslyQueue, events, local copy
AvailabilityCallee down means caller downProfile page fails when Recommendations failsFallback, cache, async
LatencyCallee latency adds to caller'sFive sequential calls of 50 ms eachParallel calls, local data, async
ConsistencyCaller needs callee's latest state"Is the seat still free?"Cannot be removed; keep sync or redesign ownership
Semantic (contract)Both depend on field meaningamount in cents vs eurosVersioned contracts, contract tests
DeploymentBoth must deploy togetherShared library with the DTOsBackward-compatible changes
text
     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).

text
     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 order

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

FormatDescribesSpec quoteGenerates
OpenAPI 3.1.0HTTP APIs"a standard, programming language-agnostic interface description for HTTP APIs"Clients, servers, docs, mock servers
Protocol Buffers (proto3) + gRPCRPC services and messagesField numbers are the wire identityGo/PHP/Java stubs
AsyncAPI 3.0.0Message-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 / AvroMessage payloadsUsed by schema registriesValidators
GraphQL SDLGraph APIsTyped schemaClients, 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.

text
     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 CI

Fix / 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").

text
     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 deploy

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

ChangeJSON over HTTPProtobuf (binary)Safe?
Add an optional fieldOld readers ignore it (tolerant reader)"Adding new fields is safe"Yes
Remove a fieldBreaks 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 fieldBreaks readersWire-safe (number unchanged), breaks ProtoJSON and codeNo (add new, deprecate old)
Change a field's type or numberBreaks"Changing field numbers for any existing field is not safe"No
Add a required fieldBreaks old senders"Don’t Add a Required Field"No
Add an enum valueBreaks exhaustive switches"Adding additional values to an enum is safe" on the wireWire yes, code maybe
Tighten validationBreaks old sendersSameNo
Change meaning (cents to euros)Silent corruptionSameNever; new field
text
     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."

With deadline propagation: one budget, shrinking at every hopClientbudget 1000 msEdgespends 50 msOrdersspends 200 msBilling -> Paymentspends 100 ms, sends 620timeout 1000Timeout-Ms: 940Timeout-Ms: 7300 ms: client startsabout 380 ms: Payment starts with 620 ms left and can refuse work it cannot finish1000 ms: everyone stops togetherWithout propagation: every hop invents its own timeoutClient: gives up at 1000 ms and maybe retries (a second copy starts)Orders: own 1000 ms timeout, still waiting after the client leftPayment:own 1000 ms timeout, runs until about 1370 msRed = work after the client stopped listening: it costs capacity, its result is thrown away,and if the client retried, two copies of the side effect may now be running.gRPC does this per call (grpc-timeout, DEADLINE_EXCEEDED); for HTTP, Request-Timeout-Ms is our convention.
text
     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 ms

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

ProductDeadline primitivePropagates automatically?Error when exceeded
gRPC Gocontext.WithTimeout; grpc-timeout on the wireYes, 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_deadlineMust be enabled explicitlyDEADLINE_EXCEEDED
Go net/httphttp.NewRequestWithContext(ctx, ...)No header; you add one (this page: Request-Timeout-Ms, a convention)context deadline exceeded
Laravel HTTP clientHttp::timeout($seconds) (accepts int|float)No; compute from a scoped budgetConnectionException
Envoyx-envoy-expected-rq-timeout-ms header, route timeoutWithin the mesh504, 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:

PartRuleSource
What to retryTransient errors only: connection failure, 503, 429, UNAVAILABLEgRPC: UNAVAILABLE "most likely a transient condition"
PreconditionIdempotent operation, or an idempotency keyAWS: "APIs with side effects aren't safe to retry unless they provide idempotency"
How manyPer request at most 3 attemptsSRE: "per-request retry budget of up to three attempts"
WhenExponential backoff with jitterSRE: "Always use randomized exponential backoff when scheduling retries"
WhereOne layer, the one right above the failing oneSRE: "retried at the layer immediately above the layer that is rejecting them"; AWS: "retry at a single point in the stack"
How much overallA budget: retries below about 10% of requests, or a token bucketSRE per-client ratio "below 10%"; gRPC retryThrottling
Naive: every layer retries 3 timesBudgeted: retry at one layer, with a budgetBrowser / appFrontendBackendDatabase (overloaded)Browser / appFrontendBackendDatabase (overloaded)4 attemptsx 4 attempts = 16x 4 attempts = 6464 attempts per click1 attempt (no retry)up to 3 attempts, jitteredonly while tokens > max/21 attempt (no retry)≈ 1 attempt per clickwhen the budget is spentGoogle SRE: 3 retries (4 attempts) at three layers -> "64 attempts (4^3) on the database".This page's lab, two retrying layers, db down: naive 1600 db attempts for 100 requests (16.00x);budgeted 103 attempts (1.03x); all 100 fail either way, budgeted in 30 ms instead of 2.5 s.
text
     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 remain

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

ProductRetry mechanismJitterBudget
gRPC (Java, C++, Go)Service config retryPolicy per method±20% applied automaticallyretryThrottling {maxTokens, tokenRatio}
AWS SDKsBuilt-in retry modesYesToken bucket, "added this behavior to the AWS SDK in 2016"
Laravel HTTP clientHttp::retry($times, $sleepMs|closure, $when, throw:)Only if your closure adds itNone; add RateLimiter
Laravel queues#[Tries], #[Backoff([1, 5, 15])], release()No (fixed list)Per job; see Retry & Backoff
Envoy / IstioRoute retry_policy, retryOnYesretry_budget on the cluster
Go stdlibNone-- (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".

Key not seenPOST + Idempotency-KeyIn progressrow inserted, handler runsCompletedstatus + body storedDeletedhandler returned 5xxExpiredafter TTL (e.g. 24 h)INSERT ok2xx / 4xx5xx (retry allowed)same payload while running -> 409same fingerprint -> replay stored responseother payload, any state-> 422The unique (scope, key) row is the lock; the fingerprint catches key reuse.Missing key on aPOST that needs one-> 400 (IETF draft -09)
text
     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 -> 422

Design decisions:

DecisionOptionsRecommendation
Who makes the keyClient (UUID v4) or derived from business identity (order-1001-charge)Derived when one business action maps to one call; UUID otherwise
ScopeGlobal, per client, per endpointPer authenticated client and endpoint, so tenants cannot collide
StorageSame database as the side effect, Redis, a dedicated tableSame database and transaction as the effect when possible; Redis only with persistence and an accepted gap
ClaimUnique constraint / INSERT ... ON CONFLICT DO NOTHING, Redis SET NXUnique constraint; it is atomic and survives restarts
What is storedStatus, headers you need, body, fingerprintEnough to replay byte-for-byte
Failure (5xx)Store it (Stripe v1 replays "including 500 errors") or delete the claimChoose and document; this page deletes so a clean retry can run
Crashed holderLock forever, or take over after a leaseLease (locked_at older than N minutes)
TTLHours to daysAt least the client's longest retry window; Stripe: at least 24 h
FingerprintHash of method, path and bodyRequired 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."

text
     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                 closed

What 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%".

text
     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 ms

What 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".

text
     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).

text
     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 not

What 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".

text
     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 T

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

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

QuantityFormulaExample
Remaining budget at hop kB - sum(time spent before k) - k * margin1000 - 350 - 3 x 10 = 620 ms
Per-call timeout (from AWS)latency percentile matching an accepted false-timeout rate0.1% false timeouts -> p99.9
Availability of a sync chainproduct of each hop's availability0.999^4 = 0.996 (about 35 h/year down)
Latency of a sequential chainsum of hops4 x 50 ms = 200 ms
Latency of a parallel fan-outmax of the calls; tail grows with fan-outp99 of 100 calls is near the p99.99 of one

Retry amplification ​

SetupAttempts on the bottom layer per user actionSource
No retries1-
3 retries (4 attempts) at one layer4-
4 attempts at 3 layers4^3 = 64Google SRE, cascading failures
3 tries at 5 layers3^5 = 243AWS Builders' Library
Per-request budget of 3 attempts, single layerat most 3; "just below 3X" in the worst caseGoogle SRE, handling overload
Plus per-client ratio below 10%about 1.1 when most calls failGoogle SRE
gRPC retryThrottling {10, 0.1}retries stop once tokens fall to 5gRPC retry guide

Backoff and jitter formulas ​

StrategyWait before attempt nVerdict (Brooker 2015)
FixedbaseSynchronises clients; avoid
Exponentialmin(cap, base * 2^n)Spreads retries in time but clients still cluster
Full jitterrandom(0, min(cap, base * 2^n))Least work; this page's default
Equal jittert/2 + random(0, t/2) where t = min(cap, base * 2^n)"the loser"
Decorrelated jittermin(cap, random(base, previous * 3))Slightly faster, more calls
gRPC built-inexponential with "Jitter of plus or minus 20%"Automatic in service-config retries

gRPC knobs ​

KnobWhereMeaning
retryPolicy.maxAttemptsservice config, per methodIncluding the first call; values above 5 are treated as 5 (gRFC A6)
initialBackoff, maxBackoff, backoffMultiplierservice configExponential backoff, plus 20% jitter
retryableStatusCodesservice configUsually ["UNAVAILABLE"]; only add others if the method is idempotent
retryThrottling.maxTokens, tokenRatioservice configFailed RPC -1 token, success +tokenRatio; retries pause below half
hedgingPolicy.maxAttempts, hedgingDelay, nonFatalStatusCodesservice configParallel copies; Go not supported
timeoutservice config methodConfigDefault deadline per method
grpc-timeoutrequest metadataRemaining deadline on the wire
grpc-retry-pushback-msresponse metadataServer tells the client how long to wait, or not to retry
grpc-previous-rpc-attemptsrequest metadataHow many attempts preceded this one
Transparent retryalways onOnly 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 ​

SignalMeaningRetry?Caller action
HTTP 400, gRPC INVALID_ARGUMENTRequest is wrongNoFix the request; surface the error
401 / UNAUTHENTICATEDMissing or bad credentialsOnce, after refreshing the tokenLaravel docs show this with withToken in the retry callback
403 / PERMISSION_DENIEDNot allowedNoSurface
404 / NOT_FOUNDMissingNo (unless replica lag is expected)Surface or wait
409 (idempotency)Same key still runningYes, same key, after backoffDo not create a new key
409 / ALREADY_EXISTS, ABORTEDConflict or concurrency abortDepends; ABORTED usually at a higher levelRe-read and retry the whole step
422 (idempotency)Key reused with another payloadNoBug in the client
429 / RESOURCE_EXHAUSTEDRate limited or out of quotaYes, honour Retry-AfterSlow down
500 / INTERNAL, UNKNOWNBug or invariant brokenOnly with an idempotency key, rarelyAlert
502, 503 / UNAVAILABLETransientYes, with backoffgRPC: "not always safe to retry non-idempotent operations"
504 / DEADLINE_EXCEEDEDGave up waiting; outcome unknownOnly idempotent or keyedCheck status or retry with the same key
Connection refused before sendingNothing reached the serverYesSafe even for POST
Connection reset after sendingUnknown outcomeOnly idempotent or keyedSame as 504

Error messages you will actually see ​

WhereMessageMeaning
Go net/httpcontext deadline exceeded (Client.Timeout exceeded while awaiting headers)http.Client.Timeout fired
Gocontext deadline exceededYour context's deadline fired
Go gRPCrpc error: code = DeadlineExceeded desc = context deadline exceededgRPC deadline
Go gRPCrpc error: code = Unavailable desc = connection errorTransport failure; retryable
LaravelIlluminate\Http\Client\ConnectionException (cURL error 28: Operation timed out)timeout() exceeded
LaravelIlluminate\Http\Client\RequestExceptionAll retries failed with an error response
Envoyupstream 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.

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

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

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

go
// 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,
	})
}
go
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):

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

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

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

json
{
  "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" } }
}
go
// 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 }
go
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
}
go
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
}
go
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)
			}
		})
	}
}
go
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 featureUse in service communicationNote
context.ContextDeadline, cancellation and request values across every callThe Go blog's context article: pass it as the first argument
http.Client.TimeoutWhole-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.NewRequestWithContextTies a request to the caller's deadlineCancelling the context aborts the request
net/http/httptestMock providers and recorders for contract testsNo network needed
math/rand/v2Jitterrand.Int64N
golang.org/x/sync/errgroupParallel composition with one deadlineFirst error cancels the rest
google.golang.org/grpcgrpc.NewClient, WithDefaultServiceConfig, status.Code(err)Deadline propagates when you pass the incoming ctx
go.opentelemetry.io/contrib/.../otelhttpAutomatic traceparent handlingReplaces the hand-written trace code here

Laravel ​

Before ​

php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureUseNote
Http::timeout() / connectTimeout()Per-call limitsDefaults 30 s and 10 s; signature accepts int|float
Http::retry($times, $sleep, $when, throw:)RetriesThe $when callback can change the request (new token, new timeout)
Http::pool()Parallel compositionOne request per backend, concurrently
Http::globalRequestMiddleware()Add traceparent to every outgoing callRegister in AppServiceProvider::boot
Http::fake(), Http::preventStrayRequests(), Http::assertSent()Consumer contract testsNo network
Context::add()Trace ID in every log line and in queued jobsShared "across the HTTP request / queued job boundary"
ShouldBeUnique, #[UniqueFor], uniqueId()One pending job per keyNeeds a lock-capable cache (redis, memcached, dynamodb, database, file, array)
ShouldBeUniqueUntilProcessingUnlock when processing startsAllows a new dispatch while the first runs
WithoutOverlapping job middlewareOne job per key executingLock with expireAfter()
#[Tries], #[Backoff], #[RetryFor], #[MaxExceptions]Consumer-side retry policyRetry & Backoff
ShouldQueueAfterCommitDispatch only after the transaction commitsNot 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 ​

text
     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
SolutionHowAdvantageCost / limitation
Retry at one layerOnly the layer right above the failing one retries; others pass errors upKills multiplicationTeams must agree; libraries default to retrying
Retry budgetPer-client ratio below 10% (SRE) or token bucket (retryThrottling, AWS SDK)Caps load during outagesFewer successes when failures are random and heavy (see the lab)
Full jitterrandom(0, min(cap, base * 2^n))No synchronised wavesSlightly longer mean wait
"overloaded; don't retry" signalServer returns a distinct error or grpc-retry-pushback-msStops retries at the sourceNeeds a protocol convention
Circuit breakerFail fast for a cool-downGives the dependency roomModal behaviour, harder to test

Double charge after a timeout ​

text
     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
SolutionHowAdvantageCost / limitation
Idempotency key with stored responseUnique (scope, key), fingerprint, replaySafe retries for any POSTStorage, TTL, a 409 path
Natural idempotencyPUT /charges/{order_id} or upsert on a business keyNo extra tableNeeds a business key that is unique per action
Deduplicate on the consumerMessage ID in an inbox tableWorks for queuesPer consumer, see Inbox
Do not retry POSTOne attempt, then reconcileSimpleWorse availability; manual follow-up

The provider-side table and the atomic claim in PostgreSQL (the Laravel migration above creates the same shape):

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

SolutionHowAdvantageCost / limitation
Deadline propagationgrpc-timeout, or Request-Timeout-Ms + contextEvery hop stops togetherHTTP needs a convention
Check before each stageif ctx.Err() != nil or remaining budget before expensive workStops doomed work earlyCode discipline
Cancellation propagationCancel outbound calls when the inbound one is cancelledFrees resources fastNot all clients support it (PHP-FPM is blocking)
Short, realistic timeoutsp99.9 of the callee, not "30 s"No thread exhaustionNeeds latency data

A provider change breaks a consumer in production ​

SolutionHowAdvantageCost / limitation
Consumer-driven contract testsPact files verified in the provider's CIBreak found before deployConsumers must write and publish pacts
Tolerant readerIgnore unknown fields, default missing optional onesAdditive changes are freeCan hide meaning changes
Breaking-change check on schemasProtobuf breaking rules, schema-registry compatibility, OpenAPI diffMechanical, cheapShape only, not semantics
Expand-and-contractAdd new, migrate consumers, remove oldNo flag dayTwo fields for a while

Slow page built from many services ​

SolutionHowAdvantageCost / limitation
Parallel composition with one deadlineerrgroup / Http::pool, partial resultsLatency = slowest, boundedAvailability still the product
Read model (ECST or CQRS)Keep a denormalised copy fed by eventsOne local queryStaleness, more storage
Hedging for tailSecond copy after p95Cuts p99Extra load; idempotent reads only
BFF per clientShape data for one screenFewer round trips from mobileOne more service to run

Nobody can follow a request ​

SolutionHowAdvantageCost / limitation
W3C traceparent everywhereMiddleware, HTTP clients, message headersVendor-neutral tracesEvery hop must forward it
Trace ID in logsLaravel Context, Go slog with trace attributesLogs join tracesDiscipline at log call sites
Workflow ID for async flowsSaga or order ID in every messageFind stuck flowsOne more field in contracts

Errors that cannot be told apart ​

SolutionHowAdvantageCost / limitation
Problem Details (RFC 9457)application/problem+json with a stable type URLMachine-readable, documentedMust map every exception
Precise gRPC codesINVALID_ARGUMENT vs FAILED_PRECONDITION vs UNAVAILABLERetry policies can rely on codesTeams must agree on the mapping
Never 200 with an error bodyUse the status lineProxies, metrics and retries see failuresLegacy clients may need a shim

Testing service communication ​

TestWhat it provesToolsRuns where
Consumer contract testMy client sends what the contract says and reads what it needsPact, Http::fake, httptestConsumer CI
Provider verificationMy API still satisfies every consumer's contractPact verifier, Laravel feature tests, httptest.NewRecorderProvider CI, blocks deploy
Schema compatibilityThe new schema is backward/forward compatibleProtobuf breaking checks, schema registryCI
Component test with fakesRetry, timeout and fallback logic workhttptest.Server that returns 503 or sleepsUnit-level CI
Fault injectionThe system degrades as designedToxiproxy ("a framework for simulating network conditions"), Istio fault injection (fixedDelay: 7s, HTTP abort)Staging, game days
Chaos experimentHypothesis about steady state holds under real failureChaos engineering practiceProduction, small blast radius (Chaos Engineering)
End-to-end smoke testThe happy path works with real servicesA few scripted callsAfter deploy
text
     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 retries

Choosing ​

Which style ​

SituationStyleExtra techniqueReason
User waits for an answer that only another service has (price, permission, stock check)Sync request/responseDeadline, retry for idempotent reads, fallbackThe answer is needed now
Side effect the user does not need to wait for (email, invoice, analytics)Async command or eventOutbox, idempotent consumerNo temporal coupling
Long or rate-limited work (charge, export, provisioning)Async command + status202 Accepted, poll or pushDo not hold connections
Many services need to react to one factEvent notificationAsyncAPI, tracingProducer does not know consumers
A service often reads another's dataEvent-carried state transferVersioned upsert, tolerant readerRemove the runtime dependency
Replay, audit, new consumers laterEvent streamRetention, partition key, schema registryHistory is the product
Strong consistency across two servicesUsually a boundary problemMerge ownership, or a saga with compensationsNo cheap cross-service ACID
Screen needs data from many servicesAPI composition / BFFParallel calls, partial resultsOne round trip for the client
Tail latency on hot readsSync + hedgingDelay at p95, cancel losersCuts p99

Orchestration or choreography ​

FactorPrefer orchestrationPrefer choreography
Number of stepsMore than 3-4, or branching1-3 independent reactions
Compensation neededYes, in a defined orderNo, or each reaction is self-contained
"Where is my order?" visibilityRequired (support, SLA)Not needed
Team ownershipOne team owns the processEach reaction is owned by a different team
Change frequency of the flowOften (one place to change)Rarely
Coupling you acceptOrchestrator knows participants' commandsParticipants know event names
Typical toolsTemporal, Step Functions, Camunda, Bus::chainBroker topics, Laravel events

Which failure policy ​

text
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 commands

In 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".

ConcernIn-process nowWhen extracted
ContractPHP interface / Go interface + DTOOpenAPI / Protobuf / AsyncAPI
FailureExceptionTimeout, 503, unknown outcome
DuplicatesImpossibleNeed keys and inbox
TransactionOne BEGIN ... COMMITSaga, 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:

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

EffectWhere it hurtsMitigation
Replica lagRead-your-writes after a commandRead from primary for N seconds, or return the new state in the command's response
Stale cacheECST copies, BFF cachesVersion in events, short TTL, invalidate on event
Cross-region latencySync chains spanning regionsKeep sync calls in-region; replicate data async
Clock skewAbsolute deadlinesSend remaining time, not a timestamp (as gRPC does)
Idempotency store replicatedTwo regions accept the same keyScope keys to a home region, or use a strongly consistent store

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

LoadWhat changesExample
1xSync calls with timeouts and keyed retries; one queue for side effectsOne Laravel app + workers, one Go service
10xDeadlines propagated, retry budgets, breakers per dependency, ECST copies replace hot sync reads, contract tests in CI5-15 services; Kafka or RabbitMQ; Pact Broker
100xService 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 backboneHundreds 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.

bash
cd docs/snippets/architecture/service-communication/go
go vet ./... && go test ./...
go run ./asynccmd     # duplicate delivery, single charge

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

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

bash
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; done

Output on the author's machine (counts are deterministic; elapsed times vary):

text
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 rateNaive db attemptsBudgeted db attemptsNaive okBudgeted okReading
0%100 (1.00x)100 (1.00x)100100No difference when healthy
10%112112100100Light transient errors: both retry, both succeed
50%17410510065The budget trades successes for load: correct for overload, too strict for random loss
100% (outage)1600 (16.00x = 4 x 4)103 (1.03x)00The 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):

bash
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 100ms
text
mode=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.91s

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

BeliefReality
Async is always more decoupledIt removes temporal coupling; semantic coupling and hidden flows remain (Fowler on event notification)
A timeout means the call failedIt means you stopped waiting; gRPC DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully"
Retries improve reliabilityOnly for transient faults; under overload they are "selfish" and multiply load (64x, 243x)
Three retries is a safe defaultAt three layers it is 64 attempts; retry at one layer with a budget
Exponential backoff is enoughWithout jitter, clients stay synchronised; full jitter cut calls "by more than half"
A circuit breaker solves stormsIt helps, but adds modal behaviour; a retry budget is simpler and always on
ShouldBeUnique makes a Laravel job idempotentIt prevents duplicate dispatch while one is pending; a crashed worker still re-runs the job
Checking "exists?" before insert makes POST idempotentCheck-then-insert races; use a unique key claim
Events must never carry dataEvent-carried state transfer carries data on purpose, to remove runtime dependencies
/v2 is how you evolve an APIAdditive changes, tolerant readers and expand-and-contract avoid most new versions
Contract tests replace integration tests entirelyThey replace most; keep a few end-to-end smoke tests
Internal calls do not need authZero trust: mTLS plus a token with caller and audience
The request ID per service is enough for tracingOnly a propagated trace ID can be joined across hops and queues
gRPC retries everything for youNo default retry policy; only transparent retries of RPCs that never reached the application

Cheat sheet ​

TopicRemember
StylesSync req/resp, async req/resp (command), event notification, event-carried state transfer, stream
Coupling questionsTemporal, availability, latency, consistency, semantic, deployment
When syncThe user waits for an answer only another service has
When asyncSide effects, slow or spiky work, fan-out to many reactions
OrchestrationMany steps, compensations, visibility needed
ChoreographyFew independent reactions owned by different teams
ContractsOpenAPI (HTTP), Protobuf (gRPC), AsyncAPI (messages); contract-first across teams
CompatibilityAdditive changes, tolerant reader, never reuse Protobuf field numbers, expand-and-contract
PactConsumer writes expectations; provider verifies in its CI; provider states for data
DeadlineSet once at the edge; pass remaining time minus a margin; stop work when it passes
Timeout valueCallee's latency percentile at an accepted false-timeout rate (AWS: 0.1% -> p99.9)
Retry ruleTransient only, idempotent only, max 3 attempts, one layer, full jitter, budget
Full jitterrandom(0, min(cap, base * 2^n))
Idempotency keyClient-chosen, scoped, unique claim, fingerprint, stored response, 409 while running, 422 on reuse, TTL >= 24 h
HedgingIdempotent reads, after p95, cancel losers; gRPC-Go: do it by hand
ErrorsRFC 9457 Problem Details; precise gRPC codes; never 200 with an error
TracingW3C traceparent on every request and message; trace ID in every log line

Self-check: questions & answers ​

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

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

TermMeaning
Synchronous request/responseCaller waits for the answer; callee must be up for the duration
Asynchronous request/responseRequest as a message; reply arrives later as another message or callback
CommandMessage asking one named receiver to do something
EventMessage stating a fact that happened; any number of receivers
Event notificationEvent 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 commandA command disguised as an event (Fowler)
Event streamDurable, partitioned, replayable log; consumers own offsets
Temporal couplingBoth parties must be available at the same time
OrchestrationOne coordinator tells participants what to do
ChoreographyParticipants react to each other's events; no coordinator
SagaSequence of local transactions with compensations (Saga)
Contract-firstWrite and review the API description before the code
OpenAPIDescription format for HTTP APIs (3.1.0)
Protocol BuffersBinary schema and IDL used by gRPC; fields identified by numbers
AsyncAPIDescription format for message-driven APIs (3.0.0)
Consumer-driven contractConsumer's expectations, verified by the provider
PactContract-testing tool; pact files, provider states, Pact Broker
Provider statePrecondition a provider sets up before verifying an interaction
Tolerant ReaderRead only what you need; ignore unknown fields (Fowler, Postel)
Backward compatibleNew provider works with old consumers
Forward compatibleOld consumer works with data from a new producer
Expand-and-contractAdd the new form, migrate, then remove the old
DeadlineAbsolute point in time after which the caller stops waiting
Deadline propagationPassing the remaining budget to every downstream call
Request-Timeout-MsThis page's HTTP header convention for the remaining budget (not a standard)
grpc-timeoutgRPC's wire representation of the remaining deadline
DEADLINE_EXCEEDEDgRPC status 4: deadline passed; the operation may still have completed
UNAVAILABLEgRPC status 14: transient; retry with backoff if safe
Exponential backoffWait grows as base x 2^attempt up to a cap
JitterRandomness in the wait to desynchronise clients
Full jitterWait uniformly random between 0 and the exponential value
Retry stormRetries at many layers or clients multiplying load on a failing dependency
Retry budgetLimit on retries per request or as a share of traffic (SRE: below 10%)
Retry throttlinggRPC token bucket that pauses retries when failures dominate
Transparent retrygRPC retry of RPCs that never reached the server application
IdempotencyDoing an operation twice has the same effect as once
Idempotency keyClient-chosen ID for one operation, sent on every attempt (Idempotency-Key)
FingerprintHash of the request used to detect a key reused with another payload
Inbox / processed messagesConsumer-side table of handled message IDs
Circuit breakerFails fast after repeated failures, then probes (half-open)
BulkheadSeparate, bounded resource pool per dependency
Hedged requestSecond copy of a slow idempotent request; first answer wins
API compositionA component calls the owning services and joins results in memory
BFFBackend for Frontend: one gateway per kind of client
mTLSMutual TLS: both sides present certificates
traceparentW3C header: version, trace-id, parent-id, flags
Problem DetailsRFC 9457 JSON error format, application/problem+json
Fault injectionDeliberately adding latency or errors (Toxiproxy, Istio) to test resilience

References ​

Built by Morteza Negahi