Chapter 05 of 27 · Part 3: Communication style

Asynchronous messaging and brokers

When FTGO's services call each other synchronously, a request works only if every service in the chain is up at the same moment. This chapter shows how messages and a broker let services work at different times, and which mistakes to avoid when you use them.

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

Where we are

In chapter 4 we turned FTGO's in-memory method calls into network calls: REST and gRPC APIs with contracts, time-outs for partial failure, and service discovery to find each other. That left one problem open: with synchronous calls, a service can answer only while every service it calls is also up.

This chapter

How can FTGO's services talk without all being available at the same time? By the end you can explain channels and brokers, choose between a queue, a topic and a durable log, pick the right kind of message, avoid the usual messaging mistakes, and keep messages in order when you scale out.

Every synchronous hop lowers availability

Problem

A customer taps "Place order" in the FTGO app. The API Gateway calls Order Service, which calls Consumer Service to check the customer and Restaurant Service to check the menu, all with REST, all before it answers. Each service is up 99.5% of the time. When Restaurant Service restarts for a deploy, nobody can place an order, even though Order Service itself is fine.

A synchronous request succeeds only if every service on its path is up at that moment, so the availabilities multiply. Three services that each manage 99.5% give the whole request only about 98.5%. Every extra hop makes it worse.

Synchronous calls reduce availability Sync call chain (all must be up) Availability Order svc 99.5% alone: 99.5% + Consumer svc 99.5% two in a row: 99.0% + Restaurant svc 99.5% three in a row: 98.5% Availability multiplies: 0.995 x 0.995 x 0.995 = 98.5%.
Solution · Asynchronous messaging

Cut the synchronous hops out of the request. Services send each other messages that can wait to be read, so the sender does not need the receiver to be up right now.

There are three ways to remove a synchronous call, and FTGO uses all of them:

Three ways to cut sync calls Avoid sync calls Use async interaction styles Replicate data via events Reply first, finish later
Reply first, finish later Client Order svc Consumer svc Restaurant svc createOrder save order: PENDING return order id ValidateConsumer ValidateOrder ConsumerValidated OrderValidated state: VALIDATED Order service answers right away. Validation finishes through messages.

Now a Restaurant Service deploy only delays validation by a few seconds. The customer still gets an order id.

Cost

The customer sees "pending" instead of a final answer, and the code must handle an order that is not validated yet. And "send a message" hides real questions: where does the message go, who reads it, and how does Order Service match a reply to the order it belongs to?

Messages and channels: who receives, and how a reply comes back

Messages need somewhere to go. That place is a channel.

Problem

Order Service sends ValidateOrder to Restaurant Service; exactly one instance of Restaurant Service should handle it. When the order is created, Kitchen, Accounting and Notification all need to hear about it. And when OrderValidated comes back, Order Service has hundreds of pending orders and must know which one it belongs to.

A message has a header and a body. The header carries metadata such as a message id, a correlation id, a version or a timestamp. The body carries the data. Keep flags that drive business logic out of the header, where consumers would not expect them.

Solution · Message channels

Send messages over named channels. A point-to-point channel delivers each message to exactly one consumer. A publish-subscribe channel delivers a copy to every subscriber.

Message channels A point-to-point channel delivers to one consumer. A publish-subscribe channel delivers to all. Point-to-point: one consumer gets it Sender Channel A B C Publish-subscribe: all consumers Sender Channel A B C
Commands usually use point-to-point. Events usually use publish-subscribe.

A reply is just another message. Order Service gives each request a message id and names a reply channel. Restaurant Service copies that id into the reply as the correlation id, so Order Service can match OrderValidated to the right order.

Async request and reply Client Request channel Service Reply channel msgId + reply channel deliver correlationId = msgId match reply to request The correlation id ties the reply back to the request.
Cost

Channels say where a message goes, not who keeps it. If Order Service writes straight to Restaurant Service while Restaurant Service is restarting, the message has nowhere to wait, and we are back to needing both sides up at once.

Keep messages while a service is down: the broker

To decouple services in time, something must hold a message until the receiver is ready.

Problem

Kitchen Service is redeployed during the lunch rush and is gone for 40 seconds. Every OrderCreated message sent in that window must still become a ticket. Order Service should not know or care that Kitchen was away, or how many Kitchen instances run, or on which hosts.

Solution · Message broker

Put a broker between the services. Senders hand messages to the broker; the broker stores them and delivers them when a consumer is ready. The broker also hides where consumers live and how many there are.

Broker-based messaging Broker: gains Loose coupling Buffers messages All interaction styles IPC is explicit Broker: costs Can be a bottleneck Single point of failure One more thing to run

"IPC is explicit" means a remote call no longer looks like a local method call, so nobody forgets that it can fail. A broker usually offers two kinds of channel. A queue shares the work among the instances of one consumer group: three Kitchen instances, each message to one of them. A topic gives every consumer group its own copy: Kitchen and Notification both see every OrderCreated.

Queues and topics A queue shares work among instances of one consumer group. A topic gives each consumer group its own copy of every message. Queue: one group Topic: many groups Sender Queue Inst 1 Inst 2 Inst 3 each message goes to one instance Sender Topic Kitchen one instance Notification one instance each group gets a copy

A side example from the FlixTube app you build in chapter 26 shows the difference in practice. Its video-streaming service tells a history service that a video was viewed. It can do this directly, with an HTTP POST to a named service, or indirectly, through a RabbitMQ queue or a fanout exchange that copies the message to every bound queue. "Direct" and "indirect" are clearer words here than "synchronous" and "asynchronous".

Direct and indirect messaging Direct: an HTTP POST with an immediate reply. Indirect: a message to a queue the receiver reads later. Broadcast: an exchange copies each message to every bound queue. Direct: HTTP POST to a named service Video-streaming History POST http://history/viewed direct response Indirect: queue, one receiver Video-streaming Queue History publish pull no reply goes back to the sender Indirect: exchange, broadcast Video-streaming Exchange fanout Queue A Queue B History Another svc
A video-streaming service sends a "viewed" message to a history service.
Direct (HTTP)Indirect (RabbitMQ)
ReplyImmediate success or failureNone to the sender
CouplingSender names the receiverSender does not know who listens
ReceiverCannot ignore itHandles it when ready
Best forCommands needing an answerNotifications and broadcasts
CostTight couplingFlow is harder to trace

With indirect messages no single service is in charge; the behavior emerges from services reacting to messages. If a consumer crashes before it acknowledges a message, the message is not lost: the broker hands it to another instance. For direct calls, plain DNS names are often enough to find the receiver. Docker Compose uses the container name as the host name, so http://history/viewed works with no extra setup.

Back at FTGO, how hard the broker tries to deliver is a choice with a trade-off, called the delivery guarantee.

Delivery guarantees At-most-once may lose messages. At-least-once may repeat them. Exactly-once is very hard, so write handlers that tolerate duplicates. At most once May lose messages. Never duplicates. At least once Never lost, may repeat. Make handlers idempotent. Exactly once Very hard in a cluster. Ask how the broker does it. Order: usually guaranteed only within one partition (Kafka). Kafka also keeps messages for a set time, so consumers can replay them. Telemetry may accept losses. Business events usually cannot.

A lost OrderCreated means a customer pays for food nobody cooks, so FTGO's business messages use at-least-once. It is the most flexible choice: failures are rare, so the extra work is small, and a duplicate costs little when the handler is idempotent (handling the same message twice has the same effect as handling it once). Chapter 6 shows how to build such handlers.

Cost

The broker can become a bottleneck and a single point of failure, so it must be run as a highly available cluster: one more critical system to operate. At-least-once delivery means duplicates. And a classic queue forgets a message once it is acknowledged, which matters as soon as a new service needs messages that were sent last week.

Keep messages after they are read: durable logs and the right to be forgotten

Buffering a message until it is read solves a short outage. Some needs reach further back in time.

Problem

FTGO adds a Delivery service that needs to know about every open order, including the ones created before it was deployed. With classic RabbitMQ queues, those OrderCreated messages were removed the moment Kitchen acknowledged them. There is nothing left to read.

Brokers come in two kinds. An ephemeral broker, such as classic RabbitMQ queues, deletes a message once it is consumed. A durable broker, such as Kafka, appends messages to a log and keeps them. Each consumer remembers its own position in the log, called its offset.

Solution · Durable event log

Publish to a log that keeps messages for a set time or forever. A new consumer such as Delivery starts at offset 0 and reads the whole history; a consumer with a bug can go back and read again.

Ephemeral queue versus durable log An ephemeral broker removes messages after acknowledgement. A durable broker keeps them and consumers read by offset. Ephemeral Producer Queue removed after ack Consumer one pass Durable Producer Event log kept, read by offset Kitchen (offset 120) New Delivery (offset 0)
EphemeralDurable
Message after handlingRemoved by the brokerStays in the log
Best atPoint-to-point routing, fast short-lived messagesStreaming, replay, sharing data with many consumers
WeaknessStruggles when messages pile up, which can hurt the whole clusterReplication cost; erasure and security are harder
Right to be forgottenNaturally satisfiedNeeds a strategy such as crypto shredding

The last row is the catch. Data protection laws give a customer the right to have their personal data erased. If that customer's orders sit in a log that is kept forever, deleting them means rewriting history that many consumers depend on. Publishing a "deleted" event (a tombstone) marks the entity as gone, but the old events with the address are still there.

Solution · Crypto shredding

Encrypt each customer's data in the events with a key that belongs to that customer, kept in a key store. To forget the customer, destroy the key. The events stay in the log, but nobody can read them.

Crypto shredding Events are encrypted with a per-user key from a key store. Destroying the key makes the user events unreadable. Order service encrypts per user Broker stores ciphertext Delivery decrypts Key store one key per user Destroy a user key and that user data is unusable, even though the events stay in the log.

Only the services that handle personal data need this. It can also live in the infrastructure, in a sidecar that encrypts before publishing, so each service does not implement it on its own.

Cost

A durable log costs storage and replication, and every consumer that handles personal data must deal with keys. With messages now flowing and kept, the next risk is in their content: a message whose meaning is unclear makes every consumer guess what the sender wanted.

Say what you mean: commands, events, documents and queries

The broker does not care what a message means. The services do.

Problem

A customer changes the delivery address of an order. Order Service publishes a message called Order with the full order in it. Accounting must update the invoice address, but cannot tell from the message what changed: the address, the items, or nothing at all. It has to compare every field with its own copy.

Solution · Explicit message types

Decide what each message is and name it accordingly. A command asks one receiver to do something. An event states a fact that already happened. A document carries an entity's full state. A query asks for data and is usually not a message at all.

Command, event, document and query Four kinds of message with their naming, meaning and receivers. Command imperative verb may be rejected one receiver Event past tense a fact many receivers Document full entity state no change meaning many receivers Query read only usually sync HTTP not a message CreateOrderCommand OrderCreatedEvent OrderDocument GET /orders/4521

The types map onto the channels from earlier. A command is sent to one receiver (send/receive). An event is published to any number of subscribers (publish/subscribe). Request/response over messaging is a command plus the event that answers it, matched by correlation id. Here the app sends CreateOrder; Order Service validates and saves, then publishes OrderCreated to Kitchen and Notification, and the app recognizes the same event as its answer.

Send/receive, publish/subscribe and request/response The UI sends a command, the order service publishes an event to subscribers, and the UI matches the event by correlation id. UI Order svc Kitchen Notify CreateOrder command validate and save OrderCreated event OrderCreated event event + correlation id Send/receive: one target. Pub/sub: any number. The response is the event with the same correlation id.

Events and documents both announce that an entity changed, so the address change could go either way. Choose by what the consumer needs.

One change as an event and as a document OrderAddressChanged holds the change only. OrderDocument holds the whole order. OrderAddressChanged OrderId, Address, UserId keeps the meaning of the change good for Accounting's billing OrderDocument OrderId, Address, OrderLines OrderedAt, UserId meaning must be inferred good when most fields are needed or With Kafka log compaction, documents keyed by OrderId act like a table of current orders.
Consumer situationPrefer
Reacts only to one kind of change (Accounting updates the invoice address)Event
Needs most of the entity (Notification sends the customer all order details)Document
Needs the meaning or the customer's intent for its logicEvent
Two fields changed together, and you want one messageDocument
New consumers must load the current state of everythingDocument on a compacted topic

Log compaction keeps only the latest message for each key, so a topic of documents keyed by order id behaves like a table of current orders. Default to events that capture the user's intent, then adapt to what consumers need. Chapter 7 returns to how much an event should carry.

Cost

Clear types are a design decision for every message, and teams must agree on them. Even well-named messages can be wired into a system in awkward ways, and a few of those ways are common enough to have names.

Service shapes and three common mistakes

Not every FTGO service needs to be fully event-driven. Four shapes show up often.

Four service topologies CRUD service, CRUD service that publishes, command-driven service, and process manager. 1 CRUD service Client Service DB 2 CRUD that also publishes DB Service Events 3 Commands in, events out Commands Service Events 4 Process manager Events Manager Commands
ShapeFitsWatch out
1 CRUD serviceSimple, low-scale domains; gives immediate feedbackEvery caller depends on it synchronously
2 CRUD that also publishesA cheap way to bring an existing service, such as Consumer Service, into an event-driven systemSaving and publishing are two separate steps
3 Commands in, events outFully asynchronous work, such as Kitchen creating ticketsValidation errors are hard to return to the caller
4 Process managerReacting to events in one domain by sending commands to each affected aggregateA new component that owns a flow

A process manager example: when a customer changes their default address, a process manager hears the event and sends an update command for each open order of that customer.

Problem

FTGO's web team wants the checkout page to keep its old behavior, so the API sends CreateOrder, then blocks and polls until the order shows up as validated. Elsewhere, Order Service publishes its CreateOrder command to Kitchen and Accounting at once, and Restaurant Service publishes a StockLow event that is really a hidden request for someone to reorder supplies.

Three common anti-patterns Faking synchronous answers, publishing a command to many services, and passive-aggressive events. Faking sync API returns 202 then blocks and polls Command to many CreateOrder command two services obey it Passive-aggressive StockLow event hidden "reorder!"
PitfallWhy it hurtsInstead
Faking synchronous responsesBlocking until the change shows up breaks under load and times out.Return 202 with the order id and expose its status, as in "reply first, finish later"; accept eventual consistency.
Publishing one command to many servicesA command targets one aggregate, and other receivers may even reject it.One service owns the command; the others react to the event it publishes.
Passive-aggressive eventsAn event that secretly asks another service to act is a hidden command.Send a real command, or use a saga or process manager so the flow is visible.
Solution · One owner per command, events for facts

Accept that the answer arrives later and show status instead of blocking. Send each command to the one service that owns it, and let everyone else react to the event it publishes. If you need someone to act, say so with a command.

Cost

Honest asynchronous flows push "pending" states into the UI and the code. And as the load grows, FTGO runs several instances of each consumer, which raises a question the single-instance picture hid: in which order are the messages handled?

Scaling consumers without breaking order

A queue spreads messages across instances. That is good for throughput and bad for order.

Problem

At peak time Kitchen Service runs three instances on one queue. A customer places an order and cancels it a second later. Instance 1 picks up OrderCreated, instance 2 picks up OrderCancelled, and instance 2 is faster. Kitchen tries to cancel a ticket that does not exist yet, then instance 1 creates it. The restaurant cooks a cancelled order.

Solution · Sharded (partitioned) channel

Split the channel into shards and give each message a shard key, such as the order id. All messages with the same key go to the same shard, and each shard is read by one consumer instance, so one order's messages are handled in order. Different orders still run in parallel.

Sharded channel keeps order Messages with the same shard key go to the same shard and the same consumer instance. Sender key = orderId Channel with shards Shard 0 Shard 1 Shard 2 Consumer instance 1 Consumer instance 2
All events for one order go to one shard, so they are processed in order.

Kafka calls shards partitions, and it guarantees order only within one partition, as the delivery-guarantee figure noted. One instance may read several shards, as instance 2 does here, but a shard is never split between two instances of the same consumer group.

Cost

Ordering now depends on picking a good key, and the number of shards limits how far the consumer can scale. Two problems are still open. At-least-once delivery means Kitchen will sometimes get the same message twice. And Order Service must save the order in its database and publish OrderCreated to the broker: two writes that can fail separately.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Asynchronous messagingSynchronous chains multiply downtime: the request fails if any service is downEventual consistency; "pending" states in UI and code
Reply first, finish laterThe customer waits for every downstream checkThe caller sees a pending result, not a final one
Point-to-point and publish-subscribe channelsA message must reach one handler, or every interested serviceChannel names and routing to design and manage
Correlation idMatching an asynchronous reply to its requestEvery request and reply must carry and copy the id
Message broker (queues and topics)Messages lost while a receiver is down; senders that must know receivers' locationsA critical cluster to run; possible bottleneck; duplicates under at-least-once
Durable event logNew or repaired consumers need messages that were already readStorage, replication, and harder erasure
Crypto shreddingErasing a person's data from a log that is never rewrittenPer-user keys, a key store, and decryption in every consumer
Command, event, document, queryConsumers guessing what a message meansA deliberate choice per message, agreed across teams
Process managerAn event in one domain must trigger commands to many aggregatesA new component that owns the flow
Sharded channelSeveral consumer instances handle one entity's messages out of orderKey choice matters; shard count limits scale

Recap

Quick check

Accounting must update the invoice address whenever an order's delivery address changes. Should Order Service publish an event or a document?
Show answer

An event, OrderAddressChanged. Accounting only cares about that one change, and the event keeps its meaning. A document would force Accounting to compare the whole order with its own copy to find out what changed.

Kitchen Service runs three instances on one plain queue. A customer creates an order and cancels it a second later, and the restaurant cooks it anyway. What broke, and which pattern fixes it?
Show answer

The two messages went to different instances, and the cancel was handled before the create. Use a sharded channel keyed by order id, so all messages for one order go to one shard and one instance, in order.

A customer asks FTGO to erase their data, but their order events sit in a Kafka topic that is kept forever. What can you do?
Show answer

If the events were encrypted with a per-customer key from a key store, destroy that key. The data in the log becomes unreadable without rewriting the log.

Still open

FTGO's services now talk through a broker, but two gaps remain. Saving an order and publishing OrderCreated are two separate writes that can fail independently, and at-least-once delivery means consumers will see duplicates and, across keys, reordering.

Next: 06 Transactional messaging and idempotent consumers →