Chapter 04 of 27 · Part 3: Communication style

Interprocess communication and synchronous APIs

Once FTGO's services run as separate processes, every call between them crosses the network, where it is slower, can fail, and can break when the other side changes. This chapter shows how to make those calls work.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 03 we organized the logic inside each FTGO service into aggregates that refer to each other by id and publish domain events. That left one problem open: aggregates in different services can no longer call each other in memory. Order Service must now ask Consumer, Kitchen and Accounting over the network.

This chapter

How should FTGO's services talk to each other? By the end you can pick an interaction style, evolve an API without breaking clients, choose REST or gRPC, let services find each other, and contain a failed callee.

A method call becomes a network call

Problem

In the monolith, createOrder() validated the consumer and looked up each line item's price with plain method calls. The team moves Consumer and Restaurant into services and keeps the code shape. An order with ten items now makes eleven network calls: checkout becomes slow, and sometimes fails with a time-out the old code never handled.

A network call is not a method call with a longer wire.

Method call versus network call Four things change when a call leaves the process: speed, data passing, changing the interface, and errors. In-process Inter-process Speed Inlined, nearly free Packets: milliseconds Data Pass a pointer Serialize, send, parse Changes Refactor both sides at once Separate deploys, so a contract Errors Mostly deterministic Timeouts, outages, partial So design coarser APIs: 1,000 method calls were fine, 1,000 network calls are not.
Services run as separate processes, so they need interprocess communication (IPC).

Errors are the biggest change. A call between processes can fail in five ways, and since many failures are short-lived, the error must tell the caller whether a retry can help.

Failure modes and error codes Five kinds of failure between processes, and how HTTP error code ranges tell a client whether to retry. Five failure modes between processes Crash server went down Omission no reply at all Timing too slow or early Response reply looks wrong Arbitrary no agreement Rich error codes let a client choose its reaction 4xx: the request is wrong 404: retrying will not help 5xx: the server has a problem 503 may pass, so retry. 501: do not. Many failures are short-lived, so retries help, but only if the error says so.
Solution · Explicit, coarse-grained IPC

Do not hide the network from developers: code that crosses a process boundary should look like it, so nobody is surprised by latency or failure. Design coarser operations (validate the whole order in one call, not item by item), and return error codes that tell the caller whether a retry can help.

Cost

Every interaction between services is now a design decision. The first one is whether the caller should wait for an answer at all.

Wait for an answer or announce a fact: interaction styles

Problem

To place an order, Order Service needs Accounting's card authorization before it can answer; Kitchen and Notification only need to hear about the order eventually. One FTGO team wants REST for everything, another wants Kafka for everything, including the authorization.

Styles vary along two dimensions: one-to-one or one-to-many, and synchronous (the caller waits) or not.

Interaction styles Two dimensions: one-to-one or one-to-many, synchronous or asynchronous. One-to-one One-to-many Synchronous Asynchronous Request / response wait for the answer (none) Async request / response One-way notification Publish / subscribe Publish / async responses

In practice, first ask: request-response or event-driven?

Choosing a communication style Decide first between request-response and event-driven. Request-response can be blocking or not. Event-driven is always asynchronous. Common data is a third, indirect option. Which style fits the job? Request-response I ask, you act, tell me the result Event-driven I announce a fact, others react Sync, blocking Async, nonblocking Async, nonblocking only Common data: drop a file or table, others poll for it. Asynchronous, big volumes.
Most systems mix styles. One service can offer a request-response API and also publish events.
Blocking versus nonblocking Synchronous blocking is simple but couples caller and callee in time. Asynchronous nonblocking decouples them but is harder to reason about. Synchronous blocking Asynchronous nonblocking Simple and familiar Callee must be up right now A slow callee slows the caller Callee can be down for a while Fits jobs that take hours or days More choices, more complexity Careful: using async/await on a result still blocks your code. It is asynchronous only underneath.

A third, indirect option is common data: one service drops a file or table (in a data lake or a warehouse) and others poll for it. It suits big volumes and older systems, but latency is high, and a shared database that several services write is a trap (chapter 8).

Style also decides what a message means: a command (better called a request) names one receiver that may refuse it; an event is a fact, published for many readers.

Command versus event A command goes to one named service, which may refuse. An event is a published fact that many services can read. A correlation id links the command to the event that follows. UI Order svc Event topic Kitchen svc Notification svc command event event carries the correlation id Command or request Names one receiver. It may say no. Send/receive, point to point Event A fact that already happened. Publish/subscribe, many readers Prefer the word request: a command sounds like an order, but a service may reject it.

How much an event should carry, and where its metadata goes, is the subject of chapter 7. For now: put in an event only what you would also share in an API.

Solution · Style first, technology second

Decide per interaction. FTGO's card authorization is synchronous request-response: Order Service needs the answer. Telling Kitchen and Notification that an order was created is an event. Kafka for request-response, or a single-page-app framework for a plain website, are examples of a shiny tool in the wrong place.

Cost

Mixing styles means more to learn and run. And whichever style you pick, the two sides now depend on the exact shape of what they exchange, while being built and deployed separately.

Services are not compiled together: APIs are contracts

Problem

The Consumer Service team renames consumerId to customerId in a response. Their tests pass and they deploy. Order Service, deployed separately, reads an empty field and rejects every new order. No compiler warned anyone; customers found out first.

Solution · API-first, explicit schema

Treat each API as a contract. Write its definition first (for example in OpenAPI or a protobuf file), agree it with the clients, and then implement it. Version it semantically: MAJOR.MINOR.PATCH, bumping MAJOR only for breaking changes.

Evolving an API Backward-compatible (easy) Add optional request fields Add response fields Add new operations Breaking (be careful) Support old and new versions together Version in the URL: /v1/ and /v2/ Or put the version in the message Semantic version: MAJOR.MINOR.PATCH. Bump MAJOR only for breaking changes.

Pick the message format with care. Text (JSON, XML) is readable and self-describing but verbose; binary (Protocol Buffers, Avro) is compact and its typed schema forces API-first. Always use a cross-language format, never Java serialization.

A schema also lets the build spot breaking changes, but only structural ones.

Structural and semantic breaking changes A schema comparison can catch structural breaks, such as a removed field. A semantic break keeps the shape but changes behavior, so only tests catch it. Structural break Semantic break calculate(a, b) becomes calculate(a) Same shape, but add becomes multiply Schema comparison fails the CI build Tests: consumer-driven contracts Tools: Protolock (protobuf), openapi-diff, JSON Schema diff, Confluent Schema Registry. Pact is a tool for consumer-driven contract tests.

The renamed consumerId was structural, so a schema diff would have failed the build. Contract tests come in chapter 15.

Cost

Schemas and checks catch accidents, but some changes are on purpose. Sooner or later a service must change its API while clients still depend on the old one.

Changing an API without breaking its callers

Problem

For security, Accounting must replace raw card numbers in its authorize request with a payment token. Order Service and a refund tool, owned by other teams, call this API. If Accounting simply switches, every order fails until both have shipped.

Five ways to avoid breaking changes Prefer expansion changes, read tolerantly, pick technology that evolves easily, keep the interface explicit and catch accidents early. Expansion changes add things, do not remove Tolerant reader take only what you need Right technology e.g. protobuf field numbers Explicit interface a schema shows what is public Catch breaks early fail the build, not production
Solution · Expansion changes and tolerant reader

Prefer adding to removing: Accounting can add an optional paymentToken field next to the card number. On the client side, read only the fields you need, find them by name or path rather than position, and ignore the rest.

Tolerant reader A consumer that reads only the fields it needs keeps working when other fields are removed or when the payload is restructured. Consumer response Notification service reads firstname lastname email telephone firstname lastname email telephone is not read, so it is free to remove Be liberal in what you accept. Find fields by name or path, never by position.

The format helps too: some formats let old and new clients coexist without extra work.

How formats help evolution JSON names fields in every payload. Protocol buffers number fields. Avro can send the schema with the data. JSON / XML Field names travel in every payload. Add fields freely; schema is optional. Protocol buffers Each field has a number. Old clients ignore new ones. Used by gRPC. Avro Schema can ride along with the payload. Common for message payloads. For events, AsyncAPI and CloudEvents try to describe the interface in the same explicit way.

In the end Accounting must stop accepting card numbers, which is a real break. Lockstep deployment gives up independent releases, and running two service versions is costly. The usual answer is a third way.

Solution · Expand and contract

One service offers the old and new endpoints side by side (expand), clients move over at their own pace, and the old endpoint is removed once nobody calls it (contract).

Handling a breaking change Lockstep deployment breaks independent deploys. Running two service versions is costly. Emulating the old endpoint, then removing it later, is the expand and contract approach. Lockstep Change service and every consumer together. Run two versions Two codebases and routing. Short canaries only. Expand and contract One service, old and new endpoints side by side. Expand and contract in three steps 1 Expand: /v1 + /v2 2 Consumers move 3 Contract: drop /v1 Track who still calls the old endpoint before you remove it. Version in the URL (/v1/) or a header. Avoid keeping more than two versions.
Track your callers. One company gave consumers a year to leave an old interface but never checked who still used it. Without that record you cannot safely remove the old endpoint, or even know whom you will break.
Cost

Accounting maintains two endpoints for a while and must track who calls which. All of this assumes the coupling is visible in an API. It is not always.

Shared libraries: a contract in disguise

Problem

FTGO puts its Order, Consumer and Money classes in an ftgo-common library used by every service. Delivery Service adds a field to Order; services on old and new versions now serialize orders differently, and every team must upgrade this week.

Sharing code between services Code that stays inside one service is fine to share. Code that crosses the boundary couples services, because they cannot all upgrade at once. Usually fine Risky Logging helpers, invisible outside Copy a service template, no sharing SDKs written by a different team Shared domain objects everywhere Server logic leaking into client libs Forcing every client to upgrade You cannot update a library everywhere at once. Accept several versions in the wild, or put the shared behavior in a service. Clients should choose when to upgrade.
Solution · Share internals, not the domain

Share code that stays invisible outside a service, such as logging helpers. Do not share domain objects across services; each bounded context keeps its own model (chapter 3). Client libraries are fine when they do not leak server logic and clients choose when to upgrade. Otherwise put the shared behavior in a service.

DRY means not duplicating knowledge, but across services a little duplication is often cheaper than coupling. Netflix's client libraries carried discovery and failure handling as well as the API.

Cost

Some code and some model classes now exist in several places. With contracts settled, the remaining question is which protocol carries the synchronous calls.

REST, gRPC or GraphQL for synchronous calls

A client that sends a request and waits for the reply uses remote procedure invocation.

Problem

Order Service calls Kitchen Service many times a second and JSON parsing shows up in the profiler. Meanwhile restaurants' point-of-sale systems and the mobile app call FTGO from outside, with technology FTGO does not control. One protocol does not fit both.

REST applies a few HTTP verbs to resources such as an order, and returns a representation while the storage stays hidden. HTTP brings caching proxies, load balancers and security tools, passes firewalls, and is easy to test with curl.

REST resources and verbs Clients use a few HTTP verbs on a resource and get back a representation. HTTP also brings caching proxies, load balancers and security tools. GET: read it POST: create one PUT: change it Order resource /orders/42 JSON view Other view Same few verbs on every resource: no createOrder or editOrder methods. How it is stored inside stays hidden. The client sees only a representation.

REST can go further with hypermedia controls: a response carries links, such as an order's link to cancel, that the client follows instead of hard-coding URLs, so the server can move things behind them. It is a sound idea that rarely repays the extra work, so treat it as optional.

RPC frameworks such as gRPC make a remote call look local and generate client code from the schema. gRPC adds HTTP/2, compact Protocol Buffers and streaming. The same traits are its risks.

RPC: attractive but risky RPC makes a remote call look local and generates client code from a schema. The same trait hides the network and can force clients and servers to deploy together. Why people like it Watch out Remote call looks like a local call Client code generated from schema gRPC: HTTP/2, fast, many languages Hides the network: chatty designs Binary stubs: removing a field breaks Can force lockstep releases Put gRPC first when you control both client and server. With many unknown clients, REST over HTTP is usually the better fit.
Solution · Match the protocol to the caller

Use gRPC for internal calls where FTGO controls both ends, such as Order Service to Kitchen Service. Use REST over HTTP at the perimeter and wherever many different clients call. GraphQL fits the edge, where mobile and web screens aggregate data (chapter 12).

TechnologyStyleBest forWatch out
gRPC / RPCSync, request-responseInternal calls you control at both endsSchema coupling, hidden network cost, needs HTTP/2
REST over HTTPSync, request-responseMany different clients, the perimeterFew schemas by default, chatty, request-response only
GraphQLSync queriesEdge: mobile and GUI aggregationCaching, query load, mostly reads
SOAPSync RPC over HTTPLegacy integrationHeavyweight, ignores HTTP verbs and codes
Message brokerAsyncEvents and long jobsAnother system to run
Cost

Every synchronous protocol shares two weaknesses: the client must know where the server is, and the server must be up when the client calls.

Finding a service whose address keeps changing

Problem

Kitchen Service scales out at lunchtime, and each restarted container gets a new IP address. Order Service's config file lists the three addresses from the morning. By 12:15 two of them are gone: two thirds of ticket requests fail while new Kitchen instances sit idle.

Solution · Service discovery

Keep a registry of the live instances of each service, and have callers look up the current addresses. Prefer the discovery that the deployment platform already provides.

Service discovery Instances get dynamic addresses, so clients look them up in a registry. Either the app does it or the platform does. Application-level (client-side) Client Registry 1 query 2 list of instances Instance 1 Instance 2 Instances register themselves (self registration). The client load-balances (client-side discovery). Platform-provided (recommended) Client Router / DNS Instance 1 Instance 2 The platform registers instances (3rd party registration). The client calls one DNS name (server-side discovery).

Three common implementations:

Service discovery options DNS is simple but cached entries go stale. Registries such as Consul track live instances. Kubernetes finds pods by labels. DNS Works with every stack. Entries cache for the TTL, so changes are slow. Point it at a load balancer. Registry (Consul) Services register themselves. HTTP API and DNS SRV records. Health checks built in. Handy beyond Kubernetes. Kubernetes A service picks pods by label. Requests go to a healthy pod. Often all you need. etcd stores the state.
Also publish the catalog in a form people can browse, not only machines.

On Kubernetes, Order Service just calls kitchen-service and reaches a healthy pod (chapter 19).

Cost

The registry is now critical infrastructure: if it is wrong or down, nobody finds anybody. DNS-based lookups can be stale for the length of the cache time. And discovery only finds an instance; it cannot make that instance answer quickly.

When the service you call is slow or down

That leaves the second weakness: a synchronous call needs the server to be up and responsive right now.

Problem

Order Service stalls on a locked table: not down, just silent. The API gateway calls it with no time-out, so every POST /orders holds a gateway thread. Within minutes the gateway runs out of threads and the whole FTGO API goes down, even restaurant search.

Partial failure can cascade Mobile app POST /orders API gateway waits forever Order service unresponsive Without timeouts the gateway runs out of threads and the whole API goes down.

This is partial failure: one part fails while the rest runs, and unprepared callers fail with it.

Solution · Time-outs, request limits and a circuit breaker

Give every call a time-out, cap the number of outstanding requests to each service, and wrap calls in a circuit breaker. After too many failures the breaker opens and calls fail at once; after a pause it lets one request through to test whether the service has recovered.

Circuit breaker states Closed allows calls. Too many failures open it so calls fail fast. After a timeout it tries once in half-open. Closed calls flow Open calls fail fast Half-open try one request failures timeout success: close again failure: open again
Also: use timeouts and cap the number of outstanding requests.

On failure the caller returns an error or falls back to a cached or default value (chapter 18 goes deeper).

These defenses stop the spread, but they cannot make a down service answer. With synchronous calls, availability multiplies: if placing an order calls Consumer, Kitchen and Accounting in turn and each is up 99.5% of the time, the whole request succeeds only about 0.995 × 0.995 × 0.995 ≈ 98.5% of the time.

Cost

Time-outs and breakers need tuning and a fallback for every call. Above all, they turn a hang into an error, not into a success: while Accounting is down, no order can be placed, however well Order Service itself is running.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Explicit, coarse-grained IPCChatty, hidden network calls that are slow and fail in surprising waysEvery interaction becomes a design decision
Style first, technology secondOne tool forced onto every interactionSeveral styles to learn and run
Command / event distinctionUnclear whether a message is a refusable request or a factCorrelation ids to link the two
API-first, explicit schemaBreaking changes surface as runtime failures in productionSchemas to write, review and version
Expansion changes and tolerant readerSmall changes break clients that read too muchDiscipline on both sides; old fields linger
Expand and contractAn unavoidable breaking change would force lockstep releasesTwo endpoints to run; callers to track
Share internals, not the domainShared domain libraries force every service to upgrade togetherSome duplicated code and models
REST at the perimeter, gRPC insideOne protocol cannot suit both external and high-volume internal callsTwo stacks; gRPC adds schema coupling
Service discoveryHard-coded addresses go stale as instances scale and restartA registry that must stay correct and available
Time-outs, request limits, circuit breakerA slow callee exhausts the caller's threads and the failure cascadesTuning and fallbacks; calls still fail while the callee is down

Recap

Quick check

To place an order, FTGO's Order Service synchronously calls Consumer, Kitchen and Accounting, each available 99.5% of the time. What availability can customers expect for placing an order, and why?
Show answer

About 98.5%. A synchronous request needs all three services to be up at once, so the probabilities multiply: 0.995 × 0.995 × 0.995 ≈ 0.985. Time-outs and circuit breakers stop the failure from spreading, but they cannot raise this number; only less synchronous coupling can.

What is the difference between a structural and a semantic breaking change?
Show answer

A structural break changes the shape of the interface (a field removed, a new required field), and a schema comparison in the build can catch it. A semantic break keeps the shape but changes behavior, so only tests such as consumer-driven contracts catch it.

Kitchen Service autoscales at lunch, and Order Service reads Kitchen's addresses from a config file. At 12:15 many ticket requests fail. What breaks, and which pattern fixes it?
Show answer

Instances were replaced and got new addresses, so the config points at containers that no longer exist, while new instances get no traffic. Service discovery fixes it: on Kubernetes, Order Service calls the stable name of Kitchen's service and the platform routes each request to a healthy pod.

Still open

Synchronous calls tie every service's availability to its callees: while Accounting is down, nobody can order, and the more services a request touches, the worse it gets. We need a way for services to work together without all being up at the same moment.

Next: 05 Asynchronous messaging and brokers →