The previous lesson ended with two questions. The first: db-tracking lives in the cloud and shipments change status in the monolith, in the data center; how does Tracking find out without the monolith having to wait for it or depend on it? The second goes much further back, to the lesson on design principles: RouteManager sends the SMS to the recipient inside the delivery confirmation itself, so that when the SMS provider is slow, the courier waits at the doorway with the package in hand. Both have the same answer. In this lesson we will study asynchronous communication: which types of message brokers exist, which guarantees they offer and which they do not, how to publish events without losing them, and how to consume them without duplicating effects. By the end, the monolith will publish status change events that will feed Tracking and Notifications.

Contents

  1. Synchronous and asynchronous communication: temporal coupling
  2. Queues, publish-subscribe, and event streams
  3. Commands and events
  4. Delivery guarantees and ordering
  5. Retries with exponential backoff and dead letter queues
  6. The transactional outbox pattern
  7. Load leveling: the queue as a buffer
  8. Event design: ShipmentStatusChanged
  9. An idempotent consumer
  10. Design for Rutaverde

  1. Synchronous and asynchronous communication: temporal coupling

In synchronous communication, the caller waits for the response before continuing. In asynchronous communication, the sender leaves a message with an intermediary and gets on with its work; the receiver will process it when it can.

The underlying difference is temporal coupling: in synchronous communication, both parties have to be available and fast at the same instant. This is how a delivery confirmation works today:

sequenceDiagram
    participant R as Courier app
    participant G as RouteManager
    participant S as SMS provider
    R->>G: Confirm delivery
    G->>G: Save the status change
    G->>S: Send SMS to the recipient
    Note over G,S: Between 1 and 3 seconds, or an error
    S-->>G: Accepted
    G-->>R: Delivery confirmed

The consequences of that coupling:

Problem Effect on RouteManager
Latency adds up The confirmation takes as long as the SMS provider takes
Availability multiplies If the provider fails, the confirmation fails, even though the delivery was made
Peaks are passed on A delivery peak is an identical peak against the provider
The sender knows all the receivers Adding a new interested party means modifying the delivery code
Aspect Synchronous Asynchronous
The sender waits Yes No
Both parties available at the same time Essential Not needed
Result Immediate Deferred
Error handling Simple: the error comes back right away More elaborate: retries, failed messages
Consistency Immediate Eventual
Ease of diagnosis High Lower: the flow is spread out over time

Asynchronous communication is not better in general. It is appropriate when the sender does not need the result in order to continue. Creating a shipment and returning its tracking code must be synchronous. Letting the recipient know that their package is out for delivery need not be.

  1. Queues, publish-subscribe, and event streams

The intermediary that receives, stores, and delivers the messages is called a message broker. There are three main models.

Point-to-point queue. Each message is received by a single consumer. If several consumers are listening to the same queue, they share the messages: this is the competing consumers pattern, which makes it possible to process faster by adding consumers.

Publish-subscribe. The sender publishes to a topic, and each subscriber receives its own copy of every message. The sender does not know how many subscribers there are or who they are.

Event stream. Messages are appended to an ordered, persistent log that is not deleted on read. Each consumer keeps track of how far it has read and can go back and reread.

flowchart TB
    subgraph QUEUE["Point-to-point queue"]
        P1["Sender"] --> Q1["Queue"]
        Q1 --> C1["Consumer A"]
        Q1 --> C2["Consumer B"]
    end
    subgraph PUBSUB["Publish-subscribe"]
        P2["Sender"] --> T["Topic"]
        T --> QA["Queue of subscriber 1"]
        T --> QB["Queue of subscriber 2"]
    end
    subgraph LOG["Event stream"]
        P3["Sender"] --> L["Ordered, persistent log"]
        L --> G1["Consumer with its read position"]
    end
Aspect Point-to-point queue Publish-subscribe Event stream
Who receives each message One consumer Each subscriber, one copy Each consumer group
After it is processed It is deleted It is deleted from that subscriber's queue It stays for the configured time
Rereading old messages No No Yes
Volume it is designed for Medium Medium Very high
Operational complexity Low Low or medium High
Example products RabbitMQ, managed cloud queues RabbitMQ, managed cloud topics Apache Kafka and compatible systems
Typical use Distributing work Notifying several interested parties Data analysis, state reconstruction, large volumes

The models are combined. The most common setup, and the one Rutaverde will use, is a topic with one queue per subscriber: each interested service receives its copy and, within each service, several instances compete for the messages in its queue.

  1. Commands and events

A message can express two different intentions, and confusing them creates coupling.

Aspect Command Event
What it expresses A request: "do this" A fact: "this has happened"
Verb form Imperative: SendNotification Past tense: ShipmentStatusChanged
Recipient One, known Zero, one, or many, unknown
Can be rejected Yes No: it has already happened
Who decides what to do The sender Each receiver
Natural model Queue Publish-subscribe

With a command, the delivery module would tell Notifications "send an SMS to this recipient": it would have to know that Notifications exists and what it must do. With an event, it merely announces that the shipment has changed status. Notifications decides to send an SMS; Tracking, to update its record; tomorrow, a third service could notify the merchant's system. The sender does not change when new interested parties appear. It is the low coupling principle, applied to communication.

  1. Delivery guarantees and ordering

No broker can guarantee everything. There are three levels of delivery guarantee:

Guarantee Meaning Risk How it is obtained
At most once The message arrives once or not at all Loss It is acknowledged before processing
At least once The message is sure to arrive, perhaps repeated Duplicates It is acknowledged after processing; if there is no acknowledgment, it is resent
Exactly once It arrives and is processed only once None, in theory It cannot be guaranteed end to end across different systems

The key lies in the moment of the acknowledgment. If the consumer processes the message and crashes just before acknowledging it, the broker cannot know whether it was processed, and does the only safe thing: deliver it again.

Since exactly-once delivery does not exist in practice, its equivalent is built:

at-least-once delivery + idempotent consumer = exactly-once effect

Messages may arrive repeated, but processing a repeated one changes nothing. It is the same idempotency we studied in the pattern catalog, now applied to the receiving side.

Ordering

Ordering is not guaranteed either. With several competing consumers, the "out for delivery" message and the "delivered" message for the same shipment may be processed by two different instances, and the one that received the second may finish first. A retry also alters the order.

There are two ways of dealing with it:

  • Ordering by key. Some brokers guarantee the order among messages that share a key, for example the shipment identifier, at the cost of limiting parallelism.
  • Sequence number. Each message carries a counter that grows with every change to the same shipment. For the purposes of the current status, the consumer ignores changes with a number lower than or equal to the last one it applied.

The second does not depend on any feature of the broker, and it is the one we will use.

  1. Retries with exponential backoff and dead letter queues

A consumer can fail to process a message for two kinds of reasons:

Type of error Example Handling
Transient The SMS provider does not respond; the database is failing over Retry later
Permanent The message has an invalid format; the phone number does not exist Do not retry: set it aside

Transient errors are retried, but not immediately and not at a fixed rate. If a service is saturated and all its clients retry every second, it will never recover. Exponential backoff doubles the wait on each attempt:

Retry Wait before the retry
1 1 s
2 2 s
3 4 s
4 8 s
5 16 s

A small amount of jitter is added to each wait so that many failed messages do not all retry at the same instant. We will come back to this detail in the next lesson.

If after five retries the message still fails, or if the error is permanent, it cannot stay there blocking the queue, nor can it be silently discarded. It is moved to a dead letter queue or DLQ: a separate queue where it waits for someone to examine it.

flowchart LR
    Q["Main queue"] --> C["Consumer"]
    C -->|"processed"| OK["Acknowledge and delete"]
    C -->|"transient error"| R["Retry with increasing wait"]
    R --> Q
    C -->|"permanent error or 5 retries exhausted"| D["Dead letter queue"]
    D --> H["Alert and review by a person"]

A message that always makes the consumer fail is called a poison message. Without a DLQ, it is retried forever and blocks everything behind it. A DLQ must be monitored: a message in it is an unattended business case, for example a recipient who has not been notified.

  1. The transactional outbox pattern

The subtlest problem of all remains, and it is on the publishing side. When a shipment changes status, the monolith has to do two things: save the change in its database and publish the event to the broker. These are two different systems, and no transaction spans both. This is the dual write problem:

Order chosen If the second step fails Result
Save and then publish The change is saved, the event is not published Tracking never finds out: lost event
Publish and then save The event is published, the change is not saved Tracking announces something that did not happen: phantom event

The transactional outbox pattern solves it by turning the two writes into one. The event is not sent to the broker: it is saved in a table in the same database, the outbox, within the same transaction as the business change. A separate process reads that table and publishes.

sequenceDiagram
    participant A as Delivery module
    participant B as db-01
    participant P as Outbox publisher
    participant I as Message broker
    A->>B: A single transaction with the status change and the outbox row
    B-->>A: Committed
    loop Every second
        P->>B: Read pending rows
        P->>I: Publish event
        I-->>P: Accepted
        P->>B: Mark as published
    end
CREATE TABLE shipments.outbox (
    id            uuid         PRIMARY KEY,
    type          text         NOT NULL,
    ordering_key  text         NOT NULL,
    payload       jsonb        NOT NULL,
    created       timestamptz  NOT NULL DEFAULT now(),
    published     timestamptz
);
  • id is the unique identifier of the event. It will travel with it and will allow consumers to detect duplicates.
  • type indicates which event it is, for example ShipmentStatusChanged.
  • ordering_key is the shipment identifier.
  • payload is the complete event in JSON, ready to publish.
  • created is filled in automatically with the insertion time.
  • published is empty until the publisher confirms the send. Rows with this field empty are the pending ones.

Why it works: the database guarantees that the change and the outbox row are saved both or neither. There can be no lost events and no phantom ones. If the publisher crashes after publishing and before marking the row, on restart it will publish it again: you get at-least-once delivery, and the duplicates are absorbed by the consumer's idempotency.

The pattern also provides a valuable property for a hybrid architecture: if the broker or the link between the data center and the cloud is unavailable, the monolith keeps working. The rows pile up in the outbox and are published when communication returns.

  1. Load leveling: the queue as a buffer

A queue between a sender and a receiver also decouples their rates. The sender produces at the speed of demand, peaks included; the receiver consumes at a constant speed, the one it can sustain. The queue grows during the peak and empties afterwards. This is load leveling.

Let's see it with Notifications. The contract with the SMS and email provider allows 80 messages per second. In peak season, the estimated peak is 100 notifications per second. Suppose it lasts 15 minutes and that arrivals then drop to 40 per second:

  • During the peak, every second 100 arrive and 80 leave: the queue grows by 20 per second.
  • In 15 minutes, 900 seconds, 20 × 900 = 18,000 messages build up.
  • The maximum wait for a message is 18,000 / 80 = 225 seconds, less than 4 minutes.
  • Afterwards 40 arrive and 80 leave: the queue shrinks by 40 per second and empties in 18,000 / 40 = 450 seconds, 7 and a half minutes.

Without a queue, 20 out of every 100 notifications would have been rejected by the provider. With a queue, all of them are delivered with a maximum delay of 4 minutes, within what the business accepted for this function: it tolerates a delay of minutes, but not loss.

Leveling has a limit: a queue only buffers if, on average, the consumer is faster than the producer. If arrivals exceed the output capacity in a sustained way, the queue grows without end. That is why the queue length is a metric to be monitored and, as we saw, the one that governs the autoscaling of the consumers.

  1. Event design: ShipmentStatusChanged

The format of an event is a contract between teams (P2) and, as we saw when discussing decisions, one of those that affect several teams. This is the platform's main event:

{
  "id": "0b6f3c1e-8a4d-4e57-9c1b-2f7d5a9e4c10",
  "type": "ShipmentStatusChanged",
  "version": 1,
  "occurred_at": "2026-11-27T10:15:42Z",
  "source": "monolith.delivery",
  "ordering_key": "48213377",
  "data": {
    "shipment_id": 48213377,
    "tracking_code": "RV-0048213",
    "sequence": 4,
    "previous_status": "OUT_FOR_DELIVERY",
    "new_status": "DELIVERED",
    "city": "zaragoza",
    "estimated_delivery": "2026-11-27T12:00:00Z"
  }
}

The event has two parts. The envelope, common to all the platform's events:

  • id: unique identifier of the event. It is the basis of idempotency.
  • type: the name of the event, in the past tense.
  • version: the schema version. It allows the format to evolve.
  • occurred_at: when the fact happened, in UTC. It is neither the publication time nor the reception time.
  • source: which module emitted it.
  • ordering_key: events with the same key refer to the same shipment.

And the data, specific to this type of event:

  • sequence: the change number within the shipment. The 4 indicates that this is its fourth status change.
  • previous_status and new_status: with the canonical values REGISTERED, AT_WAREHOUSE, OUT_FOR_DELIVERY, DELIVERED, and INCIDENT. In the first event of a shipment, previous_status is null.
  • The rest is what consumers need so that they do not have to go back and ask the monolith.

Three design rules:

  • Compatible evolution. Optional fields can be added without changing the version, and consumers must ignore the fields they do not know. Removing a field or changing its meaning requires a new version, which is published alongside the previous one during a transition period.
  • Neither too thin nor too fat. An event with only the identifier forces every consumer to call back to the sender, which recreates the coupling. One with the whole shipment spreads data that nobody needs.
  • No personal data. The event does not include the recipient's name, address, or phone number. Notifications obtains the contact details at the time of sending, through the internal interface of the Shipments module. That way personal data is not left copied in queues or in logs. It is a decision with data protection implications, which must be validated by the head of security and which we will review in Module 3.

  1. An idempotent consumer

This is the Tracking service's consumer, in simple Python:

def process(event):
    data = event["data"]
    code = data["tracking_code"]

    with transaction() as tx:
        if tx.processed_events.exists(event["id"]):
            return                                   # duplicate: already applied

        record = tx.tracking.get_or_create(code)
        record.history.add(data["sequence"], data["new_status"], event["occurred_at"])

        if data["sequence"] > record.last_sequence:
            record.current_status = data["new_status"]
            record.last_sequence = data["sequence"]
            record.updated = event["occurred_at"]

        tx.tracking.save(record)
        tx.processed_events.register(event["id"])

    cache.delete(f"trk:v1:{code}")

Step by step:

  • with transaction() as tx opens a transaction in db-tracking. Everything inside is saved in full or not saved at all.
  • First check: duplicates. If the event identifier already appears in the processed_events table, the function ends without doing anything. This is what happens when the broker delivers the same message twice.
  • get_or_create retrieves the shipment's record or creates it if this is its first event.
  • The history is always completed. Even if the event arrives late, it is part of the shipment's history.
  • Second check: ordering. The current status is only updated if the event's sequence is greater than the last one applied. If "out for delivery," with sequence 3, arrives after "delivered," with sequence 4, it does not overwrite the status.
  • register records the identifier in the same transaction as the change. That is the key: the change cannot end up applied with the event unrecorded, or the other way around.
  • cache.delete invalidates the key in cache-tracking, outside the transaction. It is the explicit invalidation we left pending in the caching lesson. If it failed, the 30-second TTL acts as a safety net.

The consumer acknowledges the message to the broker after this function finishes without error. If it crashes halfway through, the message is redelivered and the first check prevents the duplicate effect.

  1. Design for Rutaverde

flowchart LR
    subgraph DC["Zaragoza data center"]
        MONO["Modular monolith"] -->|"same transaction"| DB["db-01: data and outbox table"]
        PUB["Outbox publisher"] --> DB
    end
    subgraph CLOUD["Public cloud"]
        T["Topic shipments.events"]
        T --> Q1["Queue tracking.shipment-status"]
        T --> Q2["Queue notifications.shipment-status"]
        Q1 --> TRK["Tracking service"]
        Q2 --> NOT["Notifications service"]
        Q1 -.-> D1["tracking.shipment-status.dlq"]
        Q2 -.-> D2["notifications.shipment-status.dlq"]
        TRK --> BS["db-tracking and cache-tracking"]
    end
    PUB -->|"private link"| T
    NOT --> EXT["SMS and email provider"]
Element Decision
Broker event-bus: managed message broker in the cloud, with the standard AMQP protocol, persistent messages, and replication across two zones
Topic shipments.events
Queues tracking.shipment-status and notifications.shipment-status, each with its own DLQ
Publishing Transactional outbox in db-01; the publisher runs on every instance of the monolith, reads batches of 100 rows every second, locking the ones it takes so that two instances do not publish the same one, and deletes published rows after 7 days
Guarantee At least once, with idempotent consumers
Ordering Sequence number per shipment
Retries 5, with waits of 1, 2, 4, 8, and 16 seconds plus jitter; after that, to the DLQ
DLQ 14-day retention and an alert on the first message
Propagation target p95 under 5 seconds between the status change and its appearance in tracking

Why a message broker and not a Kafka-style event stream: the peak volume, about 200 events per second, is modest; there is no need to reread the history, because the source of truth is db-01; and the team has no experience with distributed systems. An event stream would add operational complexity that nothing justifies (P3). Since the protocol is standard, the decision is reversible.

Let's see what a delivery confirmation looks like now:

sequenceDiagram
    participant R as Courier app
    participant M as Modular monolith
    participant B as event-bus
    participant S as Tracking
    participant N as Notifications
    R->>M: Confirm delivery with idempotency key
    M->>M: Transaction with the DELIVERED status and the outbox row
    M-->>R: Delivery confirmed
    M->>B: Publish ShipmentStatusChanged
    B->>S: Copy of the event
    B->>N: Copy of the event
    S->>S: Update record and invalidate cache
    N->>N: Send SMS with retries

The courier receives the confirmation as soon as the local transaction finishes, in milliseconds. Whatever happens afterwards, including an outage at the SMS provider, no longer affects them. Notifications subscribes to all the changes and decides which ones to communicate: going out for delivery, delivery, and incidents.

# ADR-007: Integrate the monolith with Tracking and Notifications through asynchronous events

Status: Accepted
Date: 2026-05-21
Participants: Marta (architecture), Íñigo (operations), Clara (security)

## Context
ADR-001 extracts Tracking and Notifications, fed by events. Today the
SMS is sent synchronously inside the delivery confirmation. The monolith
is in the data center and the new services are in the cloud (ADR-002),
joined by a link that can fail.

## Options considered
A. Synchronous calls from the monolith to each service.
B. Events through a message broker with topics and queues.
C. Events through a Kafka-style event stream.

## Decision
We will adopt option B. The monolith will publish the
ShipmentStatusChanged event to the shipments.events topic using the
transactional outbox pattern. Tracking and Notifications will each have
their own queue and DLQ. Delivery will be at least once, with idempotent
consumers and a sequence number per shipment. Events will not carry
personal data about the recipient.

## Consequences
Positive: the delivery confirmation no longer depends on the SMS
provider; the monolith keeps operating if the cloud or the link is
unavailable; consumers can be added without touching the monolith.
Negative: tracking and notifications are eventually consistent;
diagnosing a flow requires following it through several components; the
event format becomes a contract that has to be versioned.
Risks: unmonitored DLQ; growth of the outbox if the link is down for a
long time.

Common Mistakes and Tips

  • Making everything asynchronous. If the user needs the result in order to continue, the communication must be synchronous. Asynchrony adds complexity and is only justified where it pays off.
  • Publishing the event outside the transaction. That is the dual write: sooner or later an event is lost or a false one is published. Use an outbox.
  • Assuming there will be no duplicates. There will be. Every consumer must be idempotent from day one.
  • Assuming the order. Always include a sequence number or a version.
  • Retrying immediately and without limit. It finishes off the service that was trying to recover.
  • A DLQ nobody looks at. It is a dumping ground for unresolved business cases.
  • Events with a command name. SendDeliverySms published to a topic is a command in disguise: the sender is still deciding what the receiver must do.
  • Changing the format of an event without versioning it. It breaks consumers you may not even know about.
  • Queues whose length is not monitored. A growing queue is the first warning that a consumer cannot keep up.
  • Tip: to decide whether something can be asynchronous, ask "what does the user see if this takes one more minute?" If the answer is "nothing," it is a good candidate.

Exercises

Exercise 1

State whether each interaction should be synchronous or asynchronous and, if it is asynchronous, whether it is a command or an event:

  1. When a shipment is created, the portal validates that the postal code belongs to a city in which Rutaverde operates.
  2. When an incident is recorded on a delivery, the merchant has to be notified, tracking has to be updated, and it has to be logged for the statistics.
  3. The Billing module asks a document generator to create the PDF of a specific invoice, which will be sent by email when it is ready.
  4. The courier app requests the list of deliveries on its route at the start of the working day.

Exercise 2

In the middle of the seasonal peak, with 100 notifications per second, the SMS provider stops working for 10 minutes. When it recovers, it again accepts 80 messages per second and arrivals have dropped to 40 per second.

  1. How many messages build up during the outage?
  2. How long does the queue take to empty after the recovery?
  3. Is any notification lost? What role do the retries and the DLQ play?
  4. What would have happened with RouteManager's old design?

Exercise 3

The Tracking consumer receives, for the same shipment whose record has last_sequence = 2, these three messages in this order:

  1. Event e-104, sequence 4, status DELIVERED.
  2. Event e-103, sequence 3, status OUT_FOR_DELIVERY.
  3. Event e-104 again.

Describe what the consumer does with each one and what the final state of the record is.

Solutions

Solution 1

  1. Synchronous. The user needs the answer in order to continue, and it is a fast, local check.
  2. Asynchronous, event. It is a fact with several independent interested parties. The ShipmentStatusChanged event with the new status INCIDENT serves all three without the sender knowing them.
  3. Asynchronous, command. There is a single recipient that is asked to do a specific job, and the result is not needed immediately. It fits a point-to-point queue.
  4. Synchronous. The courier cannot start without the list. It is a different matter that the app stores it in order to keep working offline, as NFR-02 requires.

Solution 2

  1. For 10 minutes, 600 seconds, 100 arrive per second and none leave: 60,000 messages.
  2. 40 come in and 80 go out: the queue shrinks by 40 per second. 60,000 / 40 = 1,500 seconds, 25 minutes.
  3. None is lost. The messages stay in the queue, which is persistent. The ones being processed when the provider went down fail and are retried with increasing waits. The five retries add up to 31 seconds, far less than the 10 minutes of the outage, so some of them would end up in the DLQ; since it is monitored, the alert fires and, after the recovery, they are reinjected into the main queue. A reasonable improvement is to stop consuming while the provider is down, instead of exhausting the retries of every message: that is the circuit breaker pattern from the next lesson.
  4. Every delivery confirmation would have waited for the provider until it failed. For 10 minutes, in the middle of peak season, the couriers would not have been able to confirm deliveries. A failure in an important function would have stopped a critical function.

Solution 3

  1. e-104, sequence 4. It is not in processed_events. It is added to the history. Since 4 is greater than 2, the status becomes DELIVERED and last_sequence becomes 4. e-104 is registered and the cache is invalidated.
  2. e-103, sequence 3. It has not been processed. It is added to the history, which is now complete. Since 3 is not greater than 4, the current status is not touched. e-103 is registered.
  3. e-104 repeated. It is already in processed_events: the function ends without doing anything.

Final state: DELIVERED, last_sequence = 4, and a history with changes 3 and 4 that will be displayed ordered by sequence. Neither the out-of-order arrival nor the duplicate has produced an incorrect result.

Conclusion

Asynchronous communication eliminates temporal coupling: sender and receiver no longer need to be available or fast at the same instant. We have distinguished queues, publish-subscribe, and event streams; commands and events; and the delivery guarantees, with the practical conclusion that you work with at-least-once delivery and idempotent consumers. We have seen retries with exponential backoff, dead letter queues, the outbox pattern for publishing without losing or inventing events, and the queue as a buffer for peaks.

With ADR-007, the monolith publishes ShipmentStatusChanged to event-bus, and Tracking and Notifications each consume it from their own queue. The synchronous SMS that held the couriers back disappears, tracking is fed within seconds without touching db-01, and the monolith keeps working even if the cloud is unreachable.

Let's review what we have built in this module: several instances behind load balancers, a cache, a data layer divided by function, and event-based communication. The platform now has capacity. But it also has many more components than RouteManager, and every component can fail. db-01 is still the only one for writes; so is the link between the data center and the cloud. What availability results from chaining all of this together, and how do you design so that the failure of one component is not the failure of the whole? That is the question that closes the module: high availability and resilience.

© Copyright 2026. All rights reserved