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
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.
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
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.
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:
- Async interaction styles. Send a message and get on with the work, instead of blocking on an answer.
- Replicate data. Order Service can keep its own copy of the restaurant menus, updated by events from Restaurant Service, so it never needs to ask during an order.
- Reply first, finish later. Order Service saves the order as
PENDING, answers the customer at once, and finishes validation through messages.
Now a Restaurant Service deploy only delays validation by a few seconds. The customer still gets an order id.
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.
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.
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.
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.
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.
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.
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.
"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.
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 (HTTP) | Indirect (RabbitMQ) | |
|---|---|---|
| Reply | Immediate success or failure | None to the sender |
| Coupling | Sender names the receiver | Sender does not know who listens |
| Receiver | Cannot ignore it | Handles it when ready |
| Best for | Commands needing an answer | Notifications and broadcasts |
| Cost | Tight coupling | Flow 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.
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.
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.
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.
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 | Durable | |
|---|---|---|
| Message after handling | Removed by the broker | Stays in the log |
| Best at | Point-to-point routing, fast short-lived messages | Streaming, replay, sharing data with many consumers |
| Weakness | Struggles when messages pile up, which can hurt the whole cluster | Replication cost; erasure and security are harder |
| Right to be forgotten | Naturally satisfied | Needs 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.
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.
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.
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.
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.
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.
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.
Events and documents both announce that an entity changed, so the address change could go either way. Choose by what the consumer needs.
| Consumer situation | Prefer |
|---|---|
| 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 logic | Event |
| Two fields changed together, and you want one message | Document |
| New consumers must load the current state of everything | Document 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.
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.
| Shape | Fits | Watch out |
|---|---|---|
| 1 CRUD service | Simple, low-scale domains; gives immediate feedback | Every caller depends on it synchronously |
| 2 CRUD that also publishes | A cheap way to bring an existing service, such as Consumer Service, into an event-driven system | Saving and publishing are two separate steps |
| 3 Commands in, events out | Fully asynchronous work, such as Kitchen creating tickets | Validation errors are hard to return to the caller |
| 4 Process manager | Reacting to events in one domain by sending commands to each affected aggregate | A 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.
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.
| Pitfall | Why it hurts | Instead |
|---|---|---|
| Faking synchronous responses | Blocking 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 services | A 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 events | An 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. |
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.
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.
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.
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.
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.
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Asynchronous messaging | Synchronous chains multiply downtime: the request fails if any service is down | Eventual consistency; "pending" states in UI and code |
| Reply first, finish later | The customer waits for every downstream check | The caller sees a pending result, not a final one |
| Point-to-point and publish-subscribe channels | A message must reach one handler, or every interested service | Channel names and routing to design and manage |
| Correlation id | Matching an asynchronous reply to its request | Every 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' locations | A critical cluster to run; possible bottleneck; duplicates under at-least-once |
| Durable event log | New or repaired consumers need messages that were already read | Storage, replication, and harder erasure |
| Crypto shredding | Erasing a person's data from a log that is never rewritten | Per-user keys, a key store, and decryption in every consumer |
| Command, event, document, query | Consumers guessing what a message means | A deliberate choice per message, agreed across teams |
| Process manager | An event in one domain must trigger commands to many aggregates | A new component that owns the flow |
| Sharded channel | Several consumer instances handle one entity's messages out of order | Key choice matters; shard count limits scale |
Recap
- Synchronous call chains multiply downtime, so FTGO cuts them with asynchronous messages, replicated data, and replying first while finishing the work later.
- Point-to-point channels deliver a message to one consumer and publish-subscribe channels to all, and a correlation id ties an asynchronous reply to its request.
- A broker buffers messages while consumers are down and offers queues and topics; FTGO uses at-least-once delivery, so handlers must tolerate duplicates.
- Durable logs such as Kafka keep messages for replay and new consumers, and crypto shredding lets you forget a person without rewriting the log.
- Name each message as a command, an event, a document or a query, and avoid faking synchronous replies, sending one command to many services, and passive-aggressive events.
- A sharded channel keyed by entity id keeps one entity's messages in order while different entities run in parallel.
Quick check
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.
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.
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.
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.