Microservice communication
medium 35 minMicroservices work together over the network, so every link between two of them is a design decision: a call that waits for an answer, or a message that does not.
Video lesson · Chapter 1 of 5
Buy a bicycle across three counters
Call or event? In 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A microservice is a small program that owns one part of the business, with its own data, and can be changed and deployed on its own. One user action, such as placing an order, usually needs several of them. Microservice communication is how they work together.
There are two basic kinds of link. In a synchronous call the caller waits for the answer. In an asynchronous one the sender hands over a message or an event and goes on. Everything else on this page, from gateways to sagas, is built from these two.
Why it exists
Inside one program, a function call is fast and either works or fails. Between programs it is slower, it can time out without telling you whether the work was done, and the other side may be down. The links decide how far a failure spreads.
They also decide how independent the teams really are. If services have to be deployed together, or if one slow service stops all of them, you have the cost of many services and the freedom of one. Choosing the links well is what makes the split worth it.
A short history
1987
Hector Garcia-Molina and Kenneth Salem publish Sagas: a long transaction as a row of smaller ones, each with a compensating step.
May 2011
Architects at a workshop near Venice use the word microservice for a style many of them had been exploring.
25 March 2014
James Lewis and Martin Fowler publish the article Microservices, with the advice smart endpoints and dumb pipes.
8 September 2015
The gRPC motivation and design principles appear. They grew out of Stubby, the remote call system Google had used between its services for over a decade.
24 May 2017
Google, IBM and Lyft announce Istio 0.1, which moves retries, security and monitoring between services into proxies: a service mesh.
Words to know
- Coupling
- How much one service must know about another, or need it to be up.
- Event
- A record that something happened, such as order placed. The sender does not say who must react.
- Command
- A message that asks one receiver to do something, such as charge this card.
- Saga
- A business action made of local transactions in several services, with a way to undo each one.
- Compensation
- A step that undoes an earlier step in business terms, such as a refund.
- Choreography and orchestration
- Services react to each other's events, or one service tells the others what to do.
- Service mesh
- Proxies beside the services that handle calls between them: security, retries, balancing and measuring.
How it works
Step through the idea, or press Play.
Look at one link. Does the caller need the answer to go on?
Understand it
Start here
The village fair
Four people organise a fair, and each one looks after one thing. Their story has every pattern of this page in it.
People choose between phoning and pinning up a notice every day. Services make the same choice on every link.
The picture
A typical system
Calls and events in one system
Parts around the services
API gateway
One entry point that routes, checks identity and limits traffic. See API gateway.
Service discovery
How one service finds another while addresses change: Consul, Eureka or Kubernetes DNS. See service discovery.
Load balancing
Spreads calls over the instances of a service. See load balancing.
Service mesh
A layer of proxies for calls between services, such as Istio or Linkerd. Explained below.
Wait
Synchronous patterns
| Pattern | How | Good | Costs |
|---|---|---|---|
| HTTP and REST | GET /api/users/123 returns 200 and the user | Simple, immediate answer, easy to read | Coupling in time, failures can spread |
| gRPC | Call a method defined in Protocol Buffers, over HTTP/2 | Compact, typed contract, streaming | More tooling, harder to read by eye |
| GraphQL | One query names the fields, a server collects them | Fewer round trips for rich screens | A layer to run and protect |
| Behind an API gateway | The gateway calls services and may join their answers | One entry point for identity and limits | Can be a single point of failure, so run several copies |
A chain of calls
A chain adds delay and multiplies risk
Every synchronous call needs
- 1
A timeout
Do not wait forever. See timeouts.
- 2
Retries with backoff, if a repeat is safe
Growing random pauses and a limit. See retries.
- 3
A circuit breaker
Stop calling a service that keeps failing. See circuit breaker.
- 4
A fallback, where a correct one exists
Old product details may be fine. Old stock must not become a promise. See fallbacks.
Do not wait
Asynchronous patterns
| Pattern | Who receives | Use it for | Examples |
|---|---|---|---|
| Message queue | One consumer handles each message | Background work, commands | RabbitMQ, Amazon SQS, ActiveMQ |
| Publish and subscribe | Every subscriber gets its own copy | Facts that several teams care about | Kafka, Google Pub/Sub, Amazon SNS |
| Event-driven design | Services react to events and emit new ones | Order placed, then stock, payment, email | Any of the above |
One event, several reactions
Trap
Save and publish: the gap between two systems
The order service writes to its database and then publishes an event. If it crashes between the two, the order exists and nobody hears about it. If it publishes first, others may hear about an order that was never saved.
The outbox closes the gap
Several services
The saga
A database transaction cannot easily span services that own separate databases. A saga replaces it with a sequence of local transactions. When one step fails, the completed steps are undone by compensations, last one first.
An orchestrated order saga
Two ways to coordinate
| Choreography | Orchestration | |
|---|---|---|
| Who knows the process | Nobody: each service reacts to events | One orchestrator |
| Coupling | To event types | The orchestrator knows every service |
| Seeing the state of one order | Hard, spread over services | Easy, one place |
| Adding a step | Easy at first, then cycles appear | Change the orchestrator |
| Risk | Nobody sees the whole flow | The orchestrator grows too clever, and it must be reliable |
| Fits | 2 to 4 simple steps | Longer processes with branches |
Choreography
When a step fails
Rules that make sagas work
- 1
Put the step that cannot be undone last
Everything before it can be compensated, everything after it must be repeated until it works. This point of no return is called the pivot.
- 2
Compensations must not give up
Retry them until they succeed, and raise an alarm for a person. Logging and moving on leaves money or stock wrong.
- 3
Every step is safe to repeat
The orchestrator may crash after a step worked and before it noted so.
- 4
Expect others to look in between
A saga has no isolation. Use states such as pending, so that nobody ships an order that may still be cancelled.
Mixed
Hybrid patterns
CQRS
Command Query Responsibility Segregation: one model for writing, another for reading. Reads are fast and shaped for the screen. The read side is often filled by events, so it can be a little old. It does not require queues or two databases.
Request and reply over messages
The client puts a request in one queue and reads the answer from another. A correlation id links the two. Buffers load, but needs a time limit, as any wait does.
Backend for frontend
One backend for each kind of client. The phone gets small answers, the web app gets wide ones. Each calls the same services.
Request and reply over queues
CQRS with a read copy
Backend for frontend
Platform
The service mesh
Timeouts, retries, encryption and measuring are needed on every call. Instead of a library in every language, a service mesh puts a proxy beside each service, or on each node, and the proxies make the calls. A control plane configures them.
Proxies make the calls
A mesh gives you
- Mutual TLS between services without code changes.
- The same timeouts, retries and balancing in every language.
- Traffic numbers for every link.
- Gradual releases by splitting traffic.
It does not give you
- Safe retries: it cannot know which calls may be repeated.
- Sagas or any business logic.
- Free speed: extra proxy work on each call.
- Less to learn: it is one more system to run.
Decide
Call or event?
Ask for each link
| Scenario | Pattern | Why |
|---|---|---|
| User login, live queries | Synchronous call | The user waits for this answer |
| Order follow-up, notifications | Events | It can happen a second later |
| Heavy reading with complex writing | CQRS | Each side gets a fitting model |
| One action over several services | Saga | No shared transaction |
| Different clients, same services | Backend for frontend | Answers shaped for each |
Practice
Good habits
- 1
Design for failure
Timeouts on all calls, circuit breakers, retries with exponential backoff, and fallback answers where they are correct.
- 2
Prefer asynchronous when possible
Call only when an answer is needed now. Queue background work, decouple with events, accept eventual consistency where the business allows it.
- 3
Manage contracts
Make backward compatible changes, use schemas such as Protobuf or Avro with a registry, and test against what consumers really use. See API versioning.
- 4
Observe everything
Distributed tracing with tools such as Jaeger or Zipkin, a trace id on every call and event, logs in one place, metrics and alerts.
- 5
Make work safe to repeat
Idempotency keys for commands, and consumers that recognise an event they have seen. Without this a retry is not safe.
- 6
Secure each link
Every service proves who it is, for example with mutual TLS. Pass signed user tokens for the user's rights, and let network rules allow only the links you need.
One trace id through everything
Traps
Anti-patterns
Chatty communication
Fifty small calls for one page. Batch them, or let one service return the whole answer.
Distributed monolith
Services so coupled that they must be deployed together. All the cost, none of the freedom.
Shared database
Two services write the same tables, so neither can change them alone.
No timeouts
Calls that wait forever use up threads and connections until the caller falls over too.
What chatty costs
Summary
The whole topic in one minute.
Decide per link. If the caller cannot go on without the answer, use a synchronous call with a timeout and a plan for failure. If it can go on, record the fact and send an event.
Work that spans several services is a saga: local transactions with a compensation for each. Give every service its own data, keep contracts compatible, carry a trace id everywhere, and make handlers safe to run twice.
- Choose call or event for every link, by asking whether the caller can go on.
- A chain of calls adds delays and multiplies the chance of failure.
- Save the change and the event together, with an outbox.
- A saga is local transactions with compensations, undone in reverse order.
- A mesh secures and measures calls. It does not make them safe to repeat.