The previous lesson ended with two unsolved problems: Verdalia's customer waits while an email is sent whose result they do not need, and when the notification service fails, the email is lost. Both have the same solution: an intermediate place where the work can wait its turn. In this lesson you will study asynchronous messaging, the guarantees it offers, the available technologies, and the architectural style built on top of it, event-driven architecture. Verdalia will apply it to order confirmation, measure the result, and record the decision in ADR-004.

Asynchronous Messaging: The Basic Concepts

In message-based communication, components do not call each other. One leaves a message with an intermediary and carries on with its work. Another picks it up when it can.

Concept What it is
Message A packet of data with a meaning: an order or a notice
Producer The component that creates the message and sends it
Consumer The component that receives it and processes it
Queue The structure where messages wait, in order of arrival
Broker The intermediary program that manages the queues: it receives, stores, and delivers

The queue decouples the two parties in three ways:

  • In time. The producer does not wait. The consumer may be stopped: the messages wait for it.
  • In pace. If a hundred messages arrive at once, the consumer processes them at its own speed. The queue absorbs the peak.
  • In knowledge. The producer does not know who consumes, nor how many consumers there are.

Queues, Topics, Commands, and Events

Two Distribution Models

Model Who receives each message Typical use
Point-to-point queue A single consumer. If there are several, the messages are shared out among them Work that must be done once
Publish-subscribe Every subscriber of the topic receives a copy Facts that interest several areas

Two Kinds of Message

Aspect Command Event
What it expresses An order: “do this” A fact: “this has happened”
Name In the imperative: send_confirmation_email In the past tense: order_confirmed
Recipient One, known Anyone, unknown to the sender
Usual model Point-to-point queue Publish-subscribe
Who decides what is done The sender Each receiver

The EventPublisher from Module 2 was already publish-subscribe, but in-process and synchronous. Now we will take it outside.

Delivery Guarantees and Their Consequences

The Three Guarantees

Guarantee What it means Risk Use
At most once The message is delivered once or not at all Messages can be lost Expendable data, such as a temperature reading
At least once The message is delivered, and may be repeated Duplicates The usual option
Exactly once The message is delivered a single time It is misleading See below

Why is the third one misleading? For the same reason we saw in the previous lesson. The consumer processes the message and sends its acknowledgment to the broker. If that acknowledgment is lost, the broker cannot know whether the work was done, and it has only two options: not deliver again, at the risk of losing the message, or deliver again, at the risk of repeating it. No network can avoid that dilemma.

What can be achieved is that the effect happens a single time, by combining two pieces:

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

Idempotent Consumers

An idempotent consumer is one that can receive the same message twice without repeating the effect. The technique is that of idempotency keys: each message carries a unique identifier, and the consumer records the ones it has processed.

Order

A queue delivers messages in order of arrival, but that guarantee is lost as soon as there are several consumers or retries. The prudent thing is to design messages that do not depend on order. If that is not possible, each message includes a version number or a date, so that the consumer discards stale ones.

Dead-Letter Queue

A message that always fails, for example because it has an invalid email address, would go back to the queue again and again and block the others. To avoid this, after one or several failed attempts it is set aside in a dead-letter queue. There it waits for a person to review it. That queue has to be watched: if it grows, something is wrong.

Backpressure

If producers publish faster than consumers process, the queue grows without limit. Backpressure is the set of mechanisms to prevent this:

  • Limit how many messages each consumer receives at a time.
  • Limit the size of the queue, and reject or slow down the producer when it fills up.
  • Add consumers. We will see it in Module 4.

The measure to watch is the queue length. A queue that grows steadily indicates a lack of consumption capacity.

Technology Landscape

Technology What it is Strength Fits when...
RabbitMQ Classic message broker Queues, topics, acknowledgments, and dead letters, with little complexity Work has to be distributed between components
Apache Kafka Distributed event log Huge volumes; events are retained and can be reread There are continuous data streams and many consumers
Managed cloud queues Services from the cloud provider Nothing to install or maintain The system is already in the cloud
Redis In-memory store, with lists and streams Simplicity, if it is already in use Light tasks where losing a message is tolerable

Event-Driven Architecture

In Module 1 we introduced this style: components announce facts and others react. When applying it, two decisions have to be made.

What the Event Contains

Aspect Event notification State transfer
Content The minimum: “order 1042 has been confirmed” The data the consumer needs
The consumer Asks the sender for the rest of the data Works with what it receives
Advantage Small messages, always current data The consumer does not depend on the sender being available
Drawback Calls back to the sender Larger messages; the data may become stale

Who Directs the Process

Aspect Orchestration Choreography
Idea A central component orders the steps Each component reacts to the others' events
The flow is seen... In a single place Spread among the consumers
Coupling The orchestrator knows everyone Nobody knows anybody
Adding a step The orchestrator has to be modified Subscribing a consumer is enough
Fits Processes with mandatory steps and strict order Consequences independent of one another

They can be combined. At Verdalia, OrderService.confirm orchestrates the essential steps, and the consequences are handled with choreography.

Eventual Consistency

With messages, changes do not all happen at once. For a few seconds, the order is confirmed and the warehouse does not know yet. The system is eventually consistent: if no new changes arrive, all its parts end up agreeing. The question to ask the business is how much delay is acceptable for each piece of data. For an email, a few seconds do not matter. For the charge, they do.

There are more advanced event-based techniques, such as event sourcing and CQRS, which are outside the scope of this course.

What Goes to the Queue at Verdalia

In Module 2 we left a table with what went through the publisher and warned that it was debatable. This is the revision:

Step Until now From now on Reason
Charge Synchronous call Same, with an idempotency key The result is needed
Save the order In-process call Same The result is needed
Deduct stock In-process subscriber Same Stock must be correct instantly
Confirmation email Synchronous call to the service Command in a queue The result is not needed
Warehouse alert In-process subscriber Event published on the broker Consequence that can wait
flowchart LR
    subgraph store["Store - monolith"]
        service["OrderService"]
        publisher["EventPublisher"]
        inventory["Inventory"]
        service --> publisher
        publisher -->|"in-process"| inventory
    end
    subgraph broker["RabbitMQ"]
        emails["Queue emails.confirmation"]
        events["Topic verdalia.events"]
        warehouse["Queue warehouse.alerts"]
        failed["Queue emails.failed"]
        events --> warehouse
        emails -.-> failed
    end
    service -->|"QueueNotifier"| emails
    publisher -->|"EventQueueBridge"| events
    emails --> worker["notification-service worker"]
    warehouse --> worker
    worker --> provider["Email provider"]

As for content, both options coexist. The email command carries all the data needed to write it, because the service has no access to the store's database: it is a state transfer. The order_confirmed event carries only the order number, which is what the warehouse needs: it is a notification.

The Mechanism, With an In-Memory Queue

Before installing anything, it is worth understanding the mechanism. Python includes queue.Queue, an in-memory queue, and threading, to run a worker in the background. The sleeps simulate the real durations.

import queue
import threading
import time

work_queue = queue.Queue()


def charge(order_id):
    time.sleep(0.85)                      # PagoRaiz takes 850 ms


def send_email(order_id):
    time.sleep(1.3)                       # The email takes 1.3 s
    print(f"    [email] Email for order {order_id} sent")


def confirm_sync(order_id):
    charge(order_id)
    send_email(order_id)                  # the customer waits for the email


def confirm_with_queue(order_id):
    charge(order_id)
    work_queue.put({"type": "send_confirmation_email", "order_id": order_id})


def worker():
    while True:
        message = work_queue.get()        # waits until there is a message
        send_email(message["order_id"])
        work_queue.task_done()


def measure(name, confirm, order_id):
    start = time.perf_counter()
    confirm(order_id)
    seconds = time.perf_counter() - start
    print(f"[store] {name}: order {order_id} confirmed in {seconds:.2f} s")


threading.Thread(target=worker, daemon=True).start()

measure("Synchronous", confirm_sync, 1042)
measure("With queue", confirm_with_queue, 1043)
measure("With queue", confirm_with_queue, 1044)
print(f"[store] Messages pending in the queue: {work_queue.qsize()}")
work_queue.join()                         # waits for the worker to finish
print("[store] Queue empty")

Output:

    [email] Email for order 1042 sent
[store] Synchronous: order 1042 confirmed in 2.15 s
[store] With queue: order 1043 confirmed in 0.85 s
[store] With queue: order 1044 confirmed in 0.85 s
[store] Messages pending in the queue: 1
    [email] Email for order 1043 sent
    [email] Email for order 1044 sent
[store] Queue empty

Explanation:

  • confirm_sync charges and sends the email. The customer waits 2.15 seconds.
  • confirm_with_queue charges and leaves a message with work_queue.put. The customer waits 0.85 seconds: only the charge.
  • worker runs in a separate thread. work_queue.get() keeps it asleep until a message arrives.
  • Order 1044 is confirmed while the worker is still sending the email for 1043. That is why one message remains pending: the queue absorbs the difference in pace.
  • The emails are sent all the same, and in the same order. What changes is who waits.

This queue has two limitations that rule it out for production. It lives in the process's memory, so a restart loses the pending messages. And it only works inside one program, whereas the store and the service are two.

A Real Queue With RabbitMQ

Verdalia chose RabbitMQ, which covers what it needs with little complexity. The example uses the pika library, installed with pip install pika, and requires a running RabbitMQ.

The Queues

# queues.py: the same declaration in the store and in the service
EMAIL_QUEUE = "emails.confirmation"
FAILED_QUEUE = "emails.failed"


def declare_queues(channel):
    channel.queue_declare(queue=FAILED_QUEUE, durable=True)
    channel.queue_declare(
        queue=EMAIL_QUEUE,
        durable=True,
        arguments={
            "x-dead-letter-exchange": "",
            "x-dead-letter-routing-key": FAILED_QUEUE,
        },
    )

The Producer: A Third Adapter

# verdalia/notifications/queue_notifier.py
import json

import pika

from verdalia.orders.ports import Notifier


class QueueNotifier(Notifier):
    """Adapter: fulfills the Notifier port by publishing a message on the queue."""

    def __init__(self, channel):
        self._channel = channel
        declare_queues(channel)

    def send_confirmation(self, order):
        message = {
            "message_id": f"confirmation-ORD-{order.id}",
            "order_id": order.id,
            "customer_email": order.customer_email,
            "total": order.total,
            "shipping_cost": order.shipping_cost,
        }
        self._channel.basic_publish(
            exchange="",
            routing_key=EMAIL_QUEUE,
            body=json.dumps(message).encode("utf-8"),
            properties=pika.BasicProperties(delivery_mode=2),
        )

The Consumer: The Worker

# notification-service/worker.py
import json

import pika

processed = set()       # In production, in the service's own data store


def process(channel, method, properties, body):
    message = json.loads(body)
    if message["message_id"] in processed:
        print(f"[worker] Duplicate message: {message['message_id']}")
        channel.basic_ack(delivery_tag=method.delivery_tag)
        return
    try:
        send_email(message["customer_email"], f"Order {message['order_id']} confirmed")
    except EmailError:
        channel.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
        return
    processed.add(message["message_id"])
    channel.basic_ack(delivery_tag=method.delivery_tag)


connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
declare_queues(channel)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=EMAIL_QUEUE, on_message_callback=process)
print("[worker] Waiting for messages")
channel.start_consuming()

Expected output from the worker, if the same message arrives twice:

[worker] Waiting for messages
[worker] Email to [email protected]: Order 1042 confirmed
[worker] Duplicate message: confirmation-ORD-1042

Explanation:

  • Durability. durable=True makes the queue survive a broker restart, and delivery_mode=2 does the same for each message, which is saved to disk.
  • Publishing. basic_publish sends the message. With exchange="", the message goes directly to the queue named in routing_key. It is the point-to-point model.
  • Acknowledgment. basic_ack tells the broker that the message has been processed and can be deleted. If the worker dies before acknowledging, the broker delivers the message again. It is the at-least-once guarantee.
  • Idempotent consumer. message_id acts as the idempotency key. A duplicate message is acknowledged without sending another email.
  • Dead letters. basic_nack with requeue=False rejects the message without returning it to the queue. Since the queue was declared with the x-dead-letter-... arguments, the broker moves it to emails.failed.
  • Backpressure. basic_qos(prefetch_count=1) tells the broker not to deliver another message until the previous one is acknowledged.
  • start_consuming leaves the program waiting, indefinitely.

The Event and the Assembly

For the warehouse alert, a new subscriber forwards the event to the broker:

class EventQueueBridge:
    """Subscriber of the EventPublisher: forwards the event to the broker."""

    def __init__(self, channel):
        self._channel = channel
        channel.exchange_declare(exchange="verdalia.events", exchange_type="topic", durable=True)

    def order_confirmed(self, order):
        event = {"message_id": f"order_confirmed-ORD-{order.id}", "order_id": order.id}
        self._channel.basic_publish(
            exchange="verdalia.events",
            routing_key="order.confirmed",
            body=json.dumps(event).encode("utf-8"),
            properties=pika.BasicProperties(delivery_mode=2),
        )
# verdalia/app.py (excerpt)
publisher.subscribe("order_confirmed", inventory.deduct_stock)
publisher.subscribe("order_confirmed", EventQueueBridge(channel).order_confirmed)

order_service = OrderService(
    repository=PostgresOrderRepository(connection),
    gateway=gateway,
    notifier=QueueNotifier(channel),         # before: HttpNotifier
    publisher=publisher,
)

Explanation:

  • An exchange of type topic is a topic. The notification service binds its warehouse.alerts queue to it. If tomorrow analytics wants to know about confirmed orders, it will bind its own queue without the store changing.
  • In app.py, two lines change. OrderService has not been modified since Module 2, and it has already worked with three adapters: SmtpNotifier, HttpNotifier, and QueueNotifier.
  • The service's HTTP API is kept for queries and for manual resends from customer support.

Measurement and ADR-004

Before and After

Lucía measured order confirmation the week of January 11, and again after the deployment on Tuesday, January 26:

Step Before After
Read the order and calculate the cost 40 ms 40 ms
Charge at PagoRaíz 850 ms 850 ms
Save the order and deduct stock 60 ms 60 ms
Confirmation email 1,300 ms —
Warehouse alert 1,250 ms —
Publish two messages — 15 ms
Total, median 3,500 ms 965 ms
Total, 95th percentile 7.2 s 1.9 s

In the first week, the email went out 3 seconds after confirmation, at the median. None was lost, compared with the 7 in December, and 2 messages ended up in emails.failed because of invalid addresses. The time that remains depends almost entirely on PagoRaíz, and that step cannot leave the request.

ADR-004

ADR-004: Process the confirmation email and the warehouse alert in the background, through a message queue

Status: Accepted

Date: 2027-01-13

Participants: Marta decides; Íker and Lucía consulted; Andrés informed.

Context

Confirming an order takes 3.5 seconds at the median and 7.2 at the 95th percentile. Of that time, 2.55 seconds correspond to two emails whose result the customer does not need. When the notification service does not respond, the email is lost: it happened 7 times in December. The scenarios affected are QS-1, on performance, and QS-3, on availability.

Options considered

  • A. Keep the synchronous calls. No new pieces, but it solves neither of the two problems.
  • B. Background threads inside the store. Simple, but pending messages are lost on every restart.
  • C. A queue in a PostgreSQL table. No new pieces and durable messages, but it loads the database, which is already the most demanded resource.
  • D. A message broker, RabbitMQ. Durable messages, acknowledgments, and a dead-letter queue. Adds a piece to operate.

Decision

We will install RabbitMQ. The store will publish the confirmation email as a command on the emails.confirmation queue and the order_confirmed event on the verdalia.events topic. A notification-service worker will consume the messages, with at-least-once delivery and idempotent consumers. The charge, saving the order, and deducting stock will remain synchronous.

Consequences

Positive:

  • Confirmation drops from 3.5 seconds to under 1.
  • A failure of the service or of the email provider delays the emails, but does not lose them.
  • Adding reactions to a confirmed order does not require modifying the store.

Negative:

  • The broker is one more piece to install, watch, and update.
  • The complete flow is no longer visible in a single place.
  • The email arrives a few seconds after confirmation.

Risks:

  • If the broker is unavailable, the store cannot publish. The failure is written to the log and the order is confirmed anyway.
  • That nobody watches the dead-letter queue. Lucía will review it daily until an alert exists.

Review conditions

It will be reviewed if the emails.confirmation queue exceeds 500 pending messages, if failed messages exceed 10 per week, or when the store moves to the cloud, to consider a managed queue service.

RabbitMQ and the worker run on verdalia-prod-01, as independent processes.

Common Mistakes and Tips

  • Using a queue when the response is needed. If the customer has to know the result, as with the charge, the call must be synchronous.
  • Assuming each message arrives only once. Every consumer must be idempotent.
  • Acknowledging the message before processing it. If the worker fails afterwards, the message is lost. First the work is done, then it is acknowledged.
  • Retrying without limit a message that always fails. It blocks the queue. That is what the dead-letter queue is for.
  • Publishing before saving. If the store publishes the message and then fails to save the order, the customer will receive the confirmation of an order that does not exist. Publish after saving.
  • Not watching the queue lengths. It is the first indicator that something is wrong.
  • Practical tip. To decide whether a step can be asynchronous, ask yourself what the customer would see if that step took ten minutes. If the answer is “nothing serious,” it is a candidate.

Exercises

Exercise 1: A Consumer That Is Not Idempotent

A worker receives the order_confirmed event and adds 1 to a counter of the day's sales. On Monday, the counter read 68 and there were 66 orders in the database. Explain the cause and propose a solution.

Exercise 2: What Happens If...

With Verdalia's design, describe what the customer sees and what happens to the email in each case:

  1. The worker is stopped for 20 minutes.
  2. The email provider rejects the customer's address.
  3. The worker sends the email and stops before acknowledging the message.

Solutions

Solution to Exercise 1

Delivery is at least once, so two events arrived duplicated, and adding is not an idempotent operation. There are two solutions. The first, record the message_id of each processed event and discard duplicates. The second, store the set of the day's order identifiers and count its elements: adding the same identifier to a set twice does not change the result.

Solution to Exercise 2

  1. The customer sees their order confirmed in under a second. The messages wait in the queue, and the emails go out when the worker starts, with up to 20 minutes of delay. None is lost.
  2. The customer sees their order confirmed. The worker rejects the message, which moves to emails.failed for review.
  3. The broker does not receive the acknowledgment and delivers the message again when the worker comes back. If the service keeps the processed identifiers in a durable store, it detects the repetition and does not send another email. If it keeps them in memory, as in the example, the customer receives two. That is why the real service keeps them in its own data store.

Conclusion

In this lesson you have learned the concepts of asynchronous messaging: producers, consumers, queues, and brokers; the two distribution models and the difference between commands and events. You have seen why exactly-once delivery is misleading and how it is replaced by at-least-once delivery with idempotent consumers. And you have learned the decisions of an event-driven architecture: what each event contains, who directs the process, and how much delay is accepted.

At Verdalia, confirming an order has gone from 3.5 seconds to under 1. The problem we pointed out in the first lesson of the course, the customer waiting while an email is sent, is solved and recorded in ADR-004. The Notifier port has met its third adapter without OrderService changing a single line.

We have put in order the layers, the services, and their communications. One component remains that has appeared in every lesson: the data. The products table is still shared between catalog and inventory, the images take up the server's disk, and everything is stored in a single database. In the next lesson, “Databases and Storage,” we will see which kinds of data stores exist and decide where each piece of Verdalia's data should live.

© Copyright 2026. All rights reserved