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
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.
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
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.
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.
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.
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
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.
In practice, first ask: request-response or event-driven?
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.
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.
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.
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
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.
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.
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.
The renamed consumerId was structural, so a schema diff would have failed the build. Contract tests come in chapter 15.
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
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.
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.
The format helps too: some formats let old and new clients coexist without extra work.
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.
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).
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
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.
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.
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.
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 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.
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).
| Technology | Style | Best for | Watch out |
|---|---|---|---|
| gRPC / RPC | Sync, request-response | Internal calls you control at both ends | Schema coupling, hidden network cost, needs HTTP/2 |
| REST over HTTP | Sync, request-response | Many different clients, the perimeter | Few schemas by default, chatty, request-response only |
| GraphQL | Sync queries | Edge: mobile and GUI aggregation | Caching, query load, mostly reads |
| SOAP | Sync RPC over HTTP | Legacy integration | Heavyweight, ignores HTTP verbs and codes |
| Message broker | Async | Events and long jobs | Another system to run |
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
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.
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.
Three common implementations:
On Kubernetes, Order Service just calls kitchen-service and reaches a healthy pod (chapter 19).
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.
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.
This is partial failure: one part fails while the rest runs, and unprepared callers fail with it.
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.
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.
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Explicit, coarse-grained IPC | Chatty, hidden network calls that are slow and fail in surprising ways | Every interaction becomes a design decision |
| Style first, technology second | One tool forced onto every interaction | Several styles to learn and run |
| Command / event distinction | Unclear whether a message is a refusable request or a fact | Correlation ids to link the two |
| API-first, explicit schema | Breaking changes surface as runtime failures in production | Schemas to write, review and version |
| Expansion changes and tolerant reader | Small changes break clients that read too much | Discipline on both sides; old fields linger |
| Expand and contract | An unavoidable breaking change would force lockstep releases | Two endpoints to run; callers to track |
| Share internals, not the domain | Shared domain libraries force every service to upgrade together | Some duplicated code and models |
| REST at the perimeter, gRPC inside | One protocol cannot suit both external and high-volume internal calls | Two stacks; gRPC adds schema coupling |
| Service discovery | Hard-coded addresses go stale as instances scale and restart | A registry that must stay correct and available |
| Time-outs, request limits, circuit breaker | A slow callee exhausts the caller's threads and the failure cascades | Tuning and fallbacks; calls still fail while the callee is down |
Recap
- A network call is slower than a method call, passes serialized data, fails in five distinct ways and changes across separate deploys, so APIs between services should be coarse and visibly remote.
- Choose the interaction style before the technology: request-response when the caller needs an answer, events when it announces a fact; a command names one receiver that may refuse, an event is published for many.
- APIs are contracts: define them first with a schema, version them semantically, and let the build catch structural breaks while contract tests catch semantic ones.
- Avoid breaking changes with expansion changes and tolerant readers; when a break is unavoidable, use expand and contract and track who still calls the old version.
- Use gRPC for internal calls you control at both ends and REST at the perimeter, prefer the platform's service discovery, and do not share domain objects between services.
- Protect every synchronous call with time-outs, request limits and a circuit breaker, but remember that a chain of synchronous calls multiplies the callees' downtime.
Quick check
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.
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.
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.
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.