Sub topic 3
Event brokers and what they do for you
This chapter assumes you know what an event is and how producers and consumers relate. It also assumes you are comfortable with HTTP APIs and database transactions. It covers what a broker is, which jobs it takes over, how brokers store messages, and the errors teams commonly make when adopting one.
What a broker is
An event broker is a server that sits between producers and consumers. Producers send events to it. Consumers read events from it. Neither side connects to the other.
Without a broker, a producer must know every consumer's address, wait for each to respond, and handle each one's failures. The in-process bus from the earlier chapter showed the idea in one process. A broker provides the same shape across machines, with durability and network failure handling added.
What the broker does for you
A broker takes over several jobs that you would otherwise write into each service.
- Decoupling in space. The producer addresses a topic or queue name, not a consumer. You can add a fourth consumer without changing or redeploying the producer.
- Decoupling in time. The broker stores events. If a consumer is down for an hour, events wait and the consumer catches up when it returns.
- Buffering. If the producer emits 5,000 events per second for a minute and the consumer handles 1,000 per second, the broker absorbs the difference. The consumer works through the backlog at its own pace.
- Routing and fan-out. The broker copies one event to every interested subscriber, or hands it to exactly one worker, depending on how you configure it. The next chapter covers these two modes.
- Delivery tracking. The broker records which events a consumer has acknowledged, so it knows what to redeliver after a failure.
- Retention and replay. Some brokers keep events for days or indefinitely, so a new consumer can read history.
The broker does not make your consumers correct. It gives you tools. Duplicates, ordering and failures still reach your code, and later chapters show how to handle them.
Two storage models
Brokers fall into two broad families. The difference in how they store messages shapes what you can do with them.
Queue-style brokers
A queue-style broker holds a message until a consumer acknowledges it, then deletes it. The broker tracks the state of each message. RabbitMQ and Amazon SQS work this way.
- Messages are removed after successful processing.
- The broker decides which message goes to which consumer.
- Replaying old events is usually not possible, because they are gone.
Log-style brokers
A log-style broker appends events to an ordered, durable log and keeps them for a retention period. Consumers track their own position, called an offset, which is the index of the next event they will read. Apache Kafka, Redpanda and Amazon Kinesis work this way.
- Reading does not delete events. Many consumers can read the same log independently.
- A consumer can rewind its offset to reprocess history.
- A new consumer can start from the beginning and build its own state.
The following sketch shows the log idea in a few lines. It is not a real broker, but it makes the offset concept concrete.
class Log:
def __init__(self):
self._events = []
def append(self, event):
self._events.append(event)
return len(self._events) - 1 # offset of the new event
def read_from(self, offset):
return self._events[offset:]
log = Log()
log.append({"type": "order.placed", "orderId": "o-1"})
log.append({"type": "order.placed", "orderId": "o-2"})
log.append({"type": "order.cancelled", "orderId": "o-1"})
# Two consumers keep separate offsets over the same events.
receipts_offset = 0
analytics_offset = 0
for event in log.read_from(receipts_offset):
print("receipts saw", event["type"], event["orderId"])
receipts_offset = 3
# Analytics starts later and still sees everything.
for event in log.read_from(analytics_offset):
print("analytics saw", event["type"], event["orderId"])
analytics_offset = 3The table compares the two families.
| Property | Queue-style | Log-style |
|---|---|---|
| Message after processing | Deleted | Retained until retention expires |
| Who tracks progress | Broker | Consumer (offset) |
| Replay of history | Generally no | Yes |
| Typical strength | Task distribution, per-message routing | High-throughput streams, multiple readers, replay |
| Examples | RabbitMQ, SQS | Kafka, Redpanda, Kinesis |
Many products blur this line. Some queue brokers offer stream features, and some log brokers can emulate consumer groups that behave like work queues. Check the documentation of the product you use instead of relying on the category name.
Durability and acknowledgement
A broker is only useful if it does not lose events. Two settings control this.
Producer acknowledgement. When a producer publishes, the broker can confirm receipt at different points: after it accepts the message into memory, after it writes to disk, or after it replicates to other broker nodes. Faster confirmation means a higher risk of loss if the broker node crashes right then. A producer that ignores confirmations can believe an event was sent when it was not.
Consumer acknowledgement. The consumer tells the broker when it has finished with a message. If the consumer crashes before acknowledging, the broker redelivers. This is the source of duplicates, which the delivery guarantees chapter explains.
Common errors
- Treating the broker as a database. Log-style brokers retain events, but they are not built for ad hoc queries or updates. Keep your current state in a database and use the broker to move changes.
- Assuming exactly-once delivery. Most brokers redeliver after a failure. Plan for duplicates on the consumer side.
- Ignoring producer confirmations. Fire-and-forget publishing loses events during broker failover.
- Making the broker a single point of failure without noticing. All services now depend on it. Run it as a replicated cluster or use a managed service, and test what your services do when it is unreachable.
- Putting large payloads in events. Brokers enforce message size limits and perform best with small messages. Store large files elsewhere and put a reference in the event.
- Forgetting that the broker adds latency. A hop through a broker usually adds milliseconds, and under load or backlog it can add much more. Do not use it where a caller needs an immediate answer.
Choosing a broker
Start from your requirements, not from the product.
- Do you need to replay history or let new consumers build state from past events? Prefer a log-style broker.
- Do you mainly distribute tasks to a pool of workers with per-message retry? A queue-style broker fits well.
- Do you need strict ordering for related events? Check how the broker orders messages and what it requires of you, covered in the ordering chapter.
- Who will operate it? A managed service from your cloud provider costs more per message but removes the work of running a cluster.
Exercise
A new analytics service must be added to a system that already has a stock service and a receipt service consuming order events. Analytics also needs every order event from the past 30 days. Name two benefits a broker gives you here, and say which storage model makes the 30-day requirement easy.
Show answer
The broker lets you add analytics as a new consumer without changing the order producer (decoupling in space), and the broker buffers events so analytics can run at its own pace (buffering). The 30-day history requirement is easy with a log-style broker, because it retains events for a configured period and a new consumer can start reading from an earlier offset. A queue-style broker normally deletes messages after acknowledgement, so the old events would be gone.
Exercise
A service saves an order to its database and then publishes an event without checking the broker's confirmation. Describe two separate ways an event can be lost.
Show answer
First, the service can crash after the database commit but before the publish call, so the event is never sent. Second, the broker can fail to store the event (for example, a node crashes before writing it to disk or replicating it), and because the producer ignored confirmations, it never learns the publish failed.