AlgoViz

Microservice communication

medium 35 min

Microservices 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

0:00 / 3:32

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

  1. 1987

    Hector Garcia-Molina and Kenneth Salem publish Sagas: a long transaction as a row of smaller ones, each with a compensating step.

  2. May 2011

    Architects at a workshop near Venice use the word microservice for a style many of them had been exploring.

  3. 25 March 2014

    James Lewis and Martin Fowler publish the article Microservices, with the advice smart endpoints and dumb pipes.

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

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

Step 1 of 3

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.

Organising a fair
SamNoorAre the tents free?Yes, all fourOne call

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

Shoppers reach an API gateway over HTTPS. The gateway calls a user service and an order service. The order service calls a payment service and sends an event to an event bus, which passes it to a stock service and an email service.
Solid arrows are calls that wait. Dashed arrows are events. Each service owns its data, which is not drawn here.

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

PatternHowGoodCosts
HTTP and RESTGET /api/users/123 returns 200 and the userSimple, immediate answer, easy to readCoupling in time, failures can spread
gRPCCall a method defined in Protocol Buffers, over HTTP/2Compact, typed contract, streamingMore tooling, harder to read by eye
GraphQLOne query names the fields, a server collects themFewer round trips for rich screensA layer to run and protect
Behind an API gatewayThe gateway calls services and may join their answersOne entry point for identity and limitsCan be a single point of failure, so run several copies
The waiting itself is covered in synchronous communication, and the styles in REST, GraphQL and gRPC.

A chain of calls

A client waits 260 milliseconds for an order service that takes 10, which waits 250 for a stock service that takes 20, which waits 230 for a payment service that takes 200, which waits 30 for a shipping service that takes 30.
Each service's own work adds to the wait of everyone before it. Network time is left out.

A chain adds delay and multiplies risk

10+20+200+30=260 ms0.9994≈0.99610 + 20 + 200 + 30 = 260\text{ ms} \qquad 0.999^4 \approx 0.996
Four services that are each up 99.9% of the time, failing independently, give 99.6% together. In a 30-day month that is about 173 minutes of failures instead of 43.

Every synchronous call needs

  1. 1

    A timeout

    Do not wait forever. See timeouts.

  2. 2

    Retries with backoff, if a repeat is safe

    Growing random pauses and a limit. See retries.

  3. 3

    A circuit breaker

    Stop calling a service that keeps failing. See circuit breaker.

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

PatternWho receivesUse it forExamples
Message queueOne consumer handles each messageBackground work, commandsRabbitMQ, Amazon SQS, ActiveMQ
Publish and subscribeEvery subscriber gets its own copyFacts that several teams care aboutKafka, Google Pub/Sub, Amazon SNS
Event-driven designServices react to events and emit new onesOrder placed, then stock, payment, emailAny of the above
Delivery, ordering and dead letters belong to asynchronous communication and queues.

One event, several reactions

The order service does not know who listens. Adding a listener does not change it.

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

Order and event are saved together or not at all. If the relay crashes before the last step it publishes again, so consumers must accept repeats.

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

An orchestrator with the list of steps calls a stock service to reserve stock, a payment service to charge the card and a shipping service to create a shipment. It writes the steps done so far to its saga state database.
The orchestrator saves its progress before and after each step, so after a crash it knows where to continue.

Two ways to coordinate

ChoreographyOrchestration
Who knows the processNobody: each service reacts to eventsOne orchestrator
CouplingTo event typesThe orchestrator knows every service
Seeing the state of one orderHard, spread over servicesEasy, one place
Adding a stepEasy at first, then cycles appearChange the orchestrator
RiskNobody sees the whole flowThe orchestrator grows too clever, and it must be reliable
Fits2 to 4 simple stepsLonger processes with branches

Choreography

Each service listens for the event of the one before it and publishes its own.

When a step fails

Undo runs in the opposite order. The failed step changed nothing, so it is not undone.

Rules that make sagas work

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

    Every step is safe to repeat

    The orchestrator may crash after a step worked and before it noted so.

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

The client can have many requests open. The id tells it which answer is which.

CQRS with a read copy

A user may not see their own write at once. Show the new value from the command's answer, or read that one item from the write side.

Backend for frontend

A web app reaches a web backend and a phone app reaches a phone backend. The web backend calls the user, order and product services. The phone backend calls the user and order services.
Two backends, one per client, share the same services behind them.

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

In the order pod the order service makes a plain call to its proxy. That proxy calls the proxy in the stock pod with mutual TLS, retries and a timeout, and the second proxy passes a plain call to the stock service.
The services only talk to the proxy next to them.

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

The second question removes many calls: a service that keeps a copy of the few fields it needs does not have to ask.
ScenarioPatternWhy
User login, live queriesSynchronous callThe user waits for this answer
Order follow-up, notificationsEventsIt can happen a second later
Heavy reading with complex writingCQRSEach side gets a fitting model
One action over several servicesSagaNo shared transaction
Different clients, same servicesBackend for frontendAnswers shaped for each

Practice

Good habits

  1. 1

    Design for failure

    Timeouts on all calls, circuit breakers, retries with exponential backoff, and fallback answers where they are correct.

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

Put the id into event headers as well, otherwise the trail ends at the queue.

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

50 calls×5 ms=250 ms, one after the other1 batch call≈10 ms50 \text{ calls} \times 5\text{ ms} = 250\text{ ms, one after the other} \qquad 1 \text{ batch call} \approx 10\text{ ms}
Times are assumptions inside one data centre. Parallel calls help the delay, but then the slowest of 50 decides, and the load stays.

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.

Sources