IT313Systems IntegrationLecture notes · Modules 3–4
3Messaging & Events ⇄ 4Secure & Deploy
IT 313 Module 3 · Lecture notes

Messaging and Event-Driven Systems Integration

In Module 2, systems talked to each other directly through REST APIs. In Module 3, systems communicate through a message broker, so a sender and a receiver no longer need to be online at the same time.

18sections
2labs
21self-checks
~2.9 hreading
0%done
CO3
Course outcome 3

Implement asynchronous systems integration through messaging and event-driven approaches.

Lesson 3.12 lecture hours, 3 lab hours
Middleware and Message Queues
  • LO 3.1.1 Explain how middleware and message queues support asynchronous systems integration.
  • LO 3.1.2 Implement message-based communication between two applications.
Lesson 3.22 lecture hours, 3 lab hours
Event-Driven Integration
  • LO 3.2.1 Implement publish-subscribe communication among integrated applications.
  • LO 3.2.2 Test and manage failures in an event-driven integration solution.
Prerequisites

HTTP and REST APIs, JSON, and data validation (Module 2); basic Python; running a container with Docker.

Tools used in the labs

RabbitMQ (open-source message broker) with its management plugin, Python 3, and the pika client library. The concepts apply to any broker; RabbitMQ is used because it is free, light enough for a lab PC, and well documented.

Values

Integrity and Excellence. Integrity here means a system never silently loses or double-counts a customer's order. Excellence means designing for failure instead of hoping it will not happen.

Module 31 min read

#Running scenario: an online store

The same scenario is used throughout the module. An online store must share each order with other systems that were built and are run separately:

  • The online store (the ordering system) takes the customer's order.
  • A payment gateway, run by an outside provider, collects the payment and reports the result back to the store.
  • The warehouse management system (WMS) reserves the stock, then picks and packs the items.
  • The accounting system records the sale and issues the invoice.
  • The courier system books the delivery.
  • A small notification service sends the customer a confirmation by SMS or email. It supports the integration; it is not an information system of its own.

The flow has two parts, and you will meet both in this module:

  1. Checkout (dependent steps). The store records the order, the warehouse reserves the stock, and the customer pays through the gateway. These steps depend on each other: if payment fails, the reserved stock must be released. Lesson 3.2 shows how to keep such steps consistent with a saga.
  2. After payment (independent reactions). The store announces one Order Confirmed event. The warehouse, accounting, courier, and notification each react to it on their own, and none of them needs the others to succeed first. This is where publish-subscribe messaging fits best, and it is the focus of the labs.

In Module 2, the store would call each system through its REST API, one after another. In this module, the store publishes events through a message broker, and each system reacts in its own time.

Module 34 min read

#The big picture: integrating systems through a message broker

Where this module fits. This course follows one integration project from start to finish. Module 1 analyzed the systems to be integrated: their data, interfaces, gaps, and risks. Module 2 connected them directly, with one system calling another's REST API. Module 3 connects them indirectly, through a message broker that sits in the middle. Module 4 secures and deploys the result.

The systems being integrated. The systems in the running scenario were built separately, as real systems usually are. Product names are examples:

SystemOwnerTechnology (example)What it needs from the integration
Online store (ordering)E-commerce teamPHP web application, such as WooCommerceTo know whether stock is available and payment succeeded
Payment gatewayOutside provider, such as PayMongo or MayaThird-party web serviceThe amount to collect; it reports the result back by webhook
Warehouse management system (WMS)Warehouse officeJava application with its own databaseTo know which orders to reserve stock for, and which to pick and pack
Accounting systemAccounting officePackaged software, such as QuickBooks or an ERPTo record each confirmed sale and issue the invoice
Courier systemCourier partnerThe courier's booking APITo know what to pick up and where to deliver it
Notification service (supporting)E-commerce teamSmall Python service using an SMS or email gatewayWhom to message and what to say

These systems use different languages, run on different servers, are maintained by different organizations, and go down at different times. Integrating them means getting each business fact, such as "order ORD-10421 is paid," to every system that needs it reliably, even though they were never designed to work together.

The post office picture. Direct API calls are like phone calls: both sides must answer at the same moment. Messaging is like a post office:

  • The online store drops one letter, "Order ORD-10421 is confirmed," at the post office (the broker) and goes back to serving customers.
  • The sorting desk (the exchange) makes a copy for every system that registered interest.
  • Each system has its own mailbox (a queue) and collects letters when it is ready.
  • When a system finishes with a letter it signs for it (an acknowledgment), and only then is the letter thrown away.
  • If a mailbox's owner is closed for the day, letters wait. Nothing is lost, and the other systems are not affected.

Every idea in this module solves an integration problem. Use this table as the map of the module:

Integration problemWhat happens with direct API calls (Module 2)How messaging solves itSection
One system is downThe caller's request failsMessages wait in the down system's queue3.1.2, 3.1.5
One system is slow, or traffic spikesEvery caller slows downThe queue absorbs the backlog; the slow system catches up3.1.5
Systems use different languages and platformsEach pair must agree on an APIEvery system only talks to the broker using a standard protocol (AMQP)3.1.1, 3.1.4
A new system must be addedThe sender's code must be changed to call itThe new system binds its own queue; the sender is unchanged3.2.3, 3.2.4
Systems have different data formatsEach API maps fields its own wayOne agreed message format and schema (a contract)3.1.6
Data could be lost in transit or in a crashThe caller may not know whether the call workedPersistence, publisher confirms, and acknowledgments3.1.7
A system receives the same data twiceThe sale is recorded twice or the order shipped twiceIdempotent consumers3.2.7
A system sends bad dataThe receiving system errors on every requestThe bad message is dead-lettered for a person to fix3.2.6, 3.2.8
Steps in different systems depend on each otherA failure halfway leaves systems disagreeing, such as stock reserved for an unpaid orderA saga with compensating actions3.2.10
No one can see where data is stuckErrors are scattered across logsQueue monitoring shows which system is behind3.1.8

How to read these notes. Each section opens with an Integration problem box naming the problem it solves for the store and the systems it integrates with. Read that box and the main discussion first. Parts headed Going deeper give RabbitMQ settings and commands; they are needed for the labs but can be skipped on a first reading.

Lesson 3.1

Middleware and Message Queues

  • LO 3.1.1 Explain how middleware and message queues support asynchronous systems integration.
  • LO 3.1.2 Implement message-based communication between two applications.
10 parts0 of 10 done
Lesson 3.18 min read

#3.1.1Middleware concepts

Integration problem

The online store is a PHP web application. The warehouse system is a Java program with its own database. Accounting runs packaged software, and the courier exposes only a web API. None of them was built to talk to the others. Something has to sit between them and do the talking. That something is middleware.

It is 8:00 p.m. on 12.12, and the store's flash sale opens. In the first ten minutes, 3,000 orders arrive. In the Module 2 design, the store calls the warehouse, then accounting, then the courier, then the SMS service, one after another for every order. At 8:04 the courier's API slows down. Every checkout now waits for the courier, the store's web server runs out of free connections, and customers see an error page. Nothing was wrong with the store itself. It failed because it was wired directly to four other systems and had to wait on all of them.

The fix is not to make every system faster. The fix is to put a layer between them that takes the order from the store immediately and delivers it to the other systems when each one is ready. That layer is middleware.

What is middleware? Middleware is software that sits between applications and handles how they communicate, so that each application does not need to know how the others are built, where they run, or whether they are online right now. A useful way to remember it: middleware is the plumbing of integration. Users never see it, but every integrated system depends on it.

You have already used middleware. In Module 2, the web server, the HTTP protocol, and the JSON library that carried your REST calls were all middleware. In this module, you will use a different kind: middleware that carries messages.

What middleware does for integrated systems. Each service below solves a specific integration problem in the online store:

ServiceWhat it meansIn the online store
CommunicationMoves data between systems over the network using a standard protocolThe store and the warehouse both speak AMQP to the broker, even though one is PHP and the other is Java
Location transparencySenders do not need to know where receivers runThe store sends to "orders," not to the warehouse server's IP address; the warehouse can move to a new server without the store changing
RoutingDecides which systems receive which dataEvery confirmed order goes to the warehouse, accounting, courier, and notification; refunds go only to accounting
BufferingHolds data when the receiver is busy or downDuring the 12.12 rush, orders wait in line instead of failing
Reliable deliveryMakes sure data is not lost on the wayAn order accepted by the store is stored until the warehouse confirms it processed it
TransformationConverts data from one format to anotherThe store's orderId becomes the warehouse's order_no
SecurityControls who may send and receive whatOnly the accounting system may read the accounting queue
MonitoringShows where data is and where it is stuckOperators see that 2,000 orders are waiting for the courier

Types of middleware. "Middleware" is a family, not one product. Each type fits a different integration need:

TypeHow it worksIndustry examplesWhere it fits in the online store
Remote procedure call (RPC) and web APIsOne system calls a function or endpoint of another and waits for the answer (synchronous)gRPC, Java RMI, REST over HTTPThe store calls the payment gateway's API to start a payment
Message-oriented middleware (MOM)A broker stores messages and forwards them to receivers when they are ready (asynchronous)RabbitMQ, IBM MQ, Apache ActiveMQ, Amazon SQSThe store publishes OrderConfirmed; four systems receive it (this module)
Event streaming platformKeeps a long, ordered log of events that many readers can replayApache Kafka, Amazon KinesisKeeping a year of order events for analytics
Enterprise service bus (ESB) and integration platformsA central hub that routes, transforms, and coordinates data between many systemsMuleSoft Anypoint, WSO2, Apache CamelA hub that converts store orders into the accounting system's import format
API gatewayA single entry point in front of many APIs that adds security, rate limits, and loggingKong, AWS API Gateway, Azure API ManagementProtecting the store's webhook endpoint that the payment gateway calls
Database access middlewareA standard driver that lets programs talk to any databaseODBC, JDBCA reporting tool reading the warehouse system's database

This module focuses on message-oriented middleware (MOM). Its central component is the message broker, which you will study in 3.1.4.

Why a hub beats a web of links. Without middleware, every pair of systems that must share data needs its own connection. With n systems, that can be as many as:

direct links=n(n−1)2

With a broker in the middle, each system needs only one link, to the broker, so n links in total.

Systems to integrateDirect links (worst case)Links through a broker
333
5 (the online store's systems)105
104510
2019020
Point-to-point vs broker · the online store's five systems
Figure 3.1Point-to-point vs broker · the online store's five systems

Each direct link is code to write, credentials to manage, and something that can break. That is why integration teams in banks, hospitals, and large stores put middleware at the center instead of connecting everything to everything.

The standard vocabulary. The book Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf (Addison-Wesley) gave the industry its common language for integration. It describes four integration styles, which you can now compare from experience:

StyleHow systems share dataWhere you met it
File TransferOne system writes a file; another reads it laterExporting a CSV of orders for accounting to import
Shared DatabaseSystems read and write the same databaseTwo programs using one MySQL database
Remote Procedure InvocationOne system calls a function or API of anotherModule 2, REST APIs
MessagingSystems exchange messages through channels managed by middlewareThis module

The book also names the parts of a messaging system. You will meet these names throughout the module: Message Channel (the path a message travels), Message (header plus body), Message Endpoint (the code that sends or receives), Point-to-Point Channel (one receiver), Publish-Subscribe Channel (every interested receiver), Message Router, Message Translator, and Dead Letter Channel (where undeliverable messages go).

Middleware is not free. Adding it brings real costs you must plan for:

  • One more system to run. The broker needs a server, updates, backups, and monitoring.
  • A central dependency. If the only broker goes down, every integration stops. Production brokers therefore run as clusters of several servers.
  • Harder debugging. A message passes through several systems at different times, so finding where it got stuck takes tools and discipline (3.1.8).
  • A learning curve. Your team must understand queues, acknowledgments, and failure handling.
Common misconceptions
  • "Middleware is one product you buy." It is a category. RabbitMQ, Kafka, and an API gateway are all middleware with very different jobs.
  • "Middleware means an ESB." An ESB is one type. Many modern integrations use only a broker and APIs.
  • "Adding a broker makes the integration reliable automatically." Only if you use it correctly: durable queues, acknowledgments, and duplicate handling, which this module teaches.
Try this10 minutes, in pairs

Draw the five systems of the online store. First connect every system that must share data directly, and count the links. Then redraw them around a broker. For each link you removed, write one thing that would have had to be coded and maintained.

Check your understanding
  1. Name the middleware services that solved the 12.12 problem in the opening story.
  2. Your school wants to connect enrollment, accounting, the library, and the LMS. How many direct links could that need, and how many through a broker?
  3. Which type of middleware would you use for the store's call to the payment gateway, and which for informing the warehouse of a confirmed order? Why?
Show suggested answerHide suggested answerAdded in this edition
  1. Buffering (orders wait in a queue during the rush instead of failing), reliable delivery (the broker keeps each order until the receiving system confirms it), routing (one confirmed order reaches the warehouse, accounting, courier and notification) and location transparency (the store sends to a destination name, not to each server). Together they mean the store no longer waits on the slow courier API.
  2. Four systems: up to 4 × 3 ÷ 2 = 6 direct links, but only 4 links through a broker, one per system.
  3. Payment gateway: RPC / web API (synchronous), because the customer is actively paying and the store needs the gateway's answer to continue. Warehouse: message-oriented middleware (asynchronous), because the customer does not need the warehouse to finish before seeing "Thank you", and the message must wait safely if the warehouse is down.
Key points

Middleware is the software layer that lets independently built systems communicate without knowing each other's details. It comes in several types; this module uses message-oriented middleware, built around a message broker. Middleware reduces the number of integration links from up to n(n−1)/2 to n, at the cost of one more system to run and monitor.

Lesson 3.18 min read

#3.1.2Synchronous and asynchronous communication

Integration problem

Every time two integrated systems exchange data, you must decide one thing: does the sender wait for the receiver, or not? Choose "wait" in the wrong place and one slow system drags down all the others. Choose "don't wait" in the wrong place and the user never learns that something failed.

You need to tell a classmate that the lab moved to Room 204. You can call: you wait while it rings, and you can only deliver the news if they pick up right now. Or you can text: you send it, put your phone away, and they read it when they are free. If their phone is off, the text waits. Calling is synchronous communication. Texting is asynchronous communication. Integrated systems make the same choice millions of times a day.

Definitions.

  • Synchronous communication: the sender sends a request and blocks (waits) until it receives a response. Both systems must be available at the same moment. A REST API call in Module 2 is synchronous.
  • Asynchronous communication: the sender hands the message to an intermediary, usually middleware such as a message broker, and continues immediately. The receiver processes it later, when it is ready. A reply, if any, arrives separately.

Walk through one checkout both ways. The customer clicks "Place order" after paying.

StepSynchronous (Module 2)Asynchronous (Module 3)
1Store saves the orderStore saves the order
2Store calls the warehouse API and waitsStore publishes one OrderConfirmed message to the broker
3Store calls the accounting API and waitsStore shows "Thank you! Your order is confirmed."
4Store calls the courier API and waitsWarehouse, accounting, courier, and notification each take the message from their own queue when ready
5Store calls the SMS service and waitsIf the courier is down, only its message waits; the others finish
6Only now does the customer see "Thank you"
If one system is downThe whole checkout fails or hangsNothing visible to the customer; the message waits

Why waiting hurts: three kinds of coupling. "Coupling" means how much one system depends on another. Synchronous calls create three kinds:

  • Temporal coupling (time). Both systems must be running at the same moment. If the warehouse system is down for maintenance on Sunday night, the store cannot finish any order on Sunday night.
  • Availability coupling. Availability multiplies along a chain of calls. If four systems are each up 99% of the time, a checkout that needs all four works only about 0.99 × 0.99 × 0.99 × 0.99 ≈ 96% of the time. That is roughly one failed checkout in every 25, caused by systems the customer never sees.
  • Performance coupling (speed). The caller is only as fast as the slowest system it waits for. If the SMS service takes 8 seconds, checkout takes at least 8 seconds, even though the customer does not need the SMS to finish ordering.

When these combine, you get a failure cascade: one slow system makes callers wait, waiting requests pile up and use the caller's threads and connections, and soon the caller fails too. That is exactly what happened in the 12.12 story in 3.1.1.

What asynchronous communication gives you.

BenefitWhat it means for the online store
Independence in timeThe courier can be offline for an hour; orders still go through
Load leveling3,000 orders in ten minutes become a queue the warehouse works through at its own steady pace
Faster response to the userThe customer gets "Thank you" after one quick publish, not after four API calls
Easier to add systemsA new loyalty-points system just subscribes; the store does not change

What asynchronous communication costs you. It is not free:

  • Eventual consistency. Right after checkout, the order exists in the store but the warehouse may not know yet. A moment later it does. The systems are eventually consistent, not instantly. The design must make that short gap acceptable, for example by showing "Processing" instead of a delivery date.
  • No immediate error. If the courier rejects the order, the store does not find out during checkout. You need retries, dead-letter queues, and monitoring (Lesson 3.2).
  • Harder to trace. One order becomes several messages processed at different times by different systems.
  • Duplicates and ordering. Messages may arrive twice or out of order, so receivers must be written to cope (3.2.7).

Full comparison.

AspectSynchronousAsynchronous
Sender waits for the resultYesNo
Both systems online at onceRequiredNot required
What the user seesThe final result"Received, being processed"
Traffic spikesReceiver must keep up in real timeQueue absorbs the spike
Data consistencyImmediateEventual
ErrorsCaller sees them at onceSurface later; need retries and dead-letter queues
Tracing a requestOne call chainMust follow messages across systems
Typical integration technologyREST, gRPC, SOAPMessage brokers (RabbitMQ, Amazon SQS), event streams (Kafka)

Telling the user "accepted." When a web request starts asynchronous work, the standard HTTP answer is 202 Accepted ("I received your request and will process it"), not 200 OK or 201 Created. The response often includes a status URL the browser can check later, such as /orders/ORD-10421/status. This is known as the asynchronous request-reply pattern.

When the sender needs an answer: request-reply over messaging. Sometimes a system wants a reply but still benefits from a queue. AMQP messages carry two standard properties for this: reply_to, the queue where the answer should go, and correlation_id, a unique ID copied into the reply so the sender can match each answer to its question. RabbitMQ's RPC tutorial uses exactly these. Use it sparingly: if the sender just sits and waits for the reply, you have rebuilt a synchronous call with more moving parts.

Choosing, interaction by interaction. Real systems mix both styles. Ask: Does the caller truly need the result before it can continue?

Interaction in the online storeStyleWhy
Customer logs inSynchronousThe page cannot continue without knowing who the user is
Product page shows stock leftSynchronousThe customer needs the number now
Store sends the customer to the payment gatewaySynchronousThe customer is actively paying
Gateway reports the payment resultAsynchronous (webhook)The gateway calls back when payment completes
Warehouse, accounting, courier, notification learn of the confirmed orderAsynchronous (messages)None of them is needed to say "Thank you"
Monthly sales reportAsynchronous (batch or messages)Nobody waits on it
Common misconceptions
  • "Asynchronous is always faster." The total work may take just as long. What is faster is the caller's response, because it no longer waits.
  • "Asynchronous means there is no reply." There can be a reply; it just arrives separately (reply_to, a webhook, or a status page).
  • "Synchronous is old and bad." It is the right choice whenever the caller truly needs the answer now.
Example scenario: enrollment week

A university enrollment system lets you submit your subject load. If each submission is checked synchronously against the registrar, accounting, and scholarship systems, the site crawls when thousands enroll at once. A better design accepts the submission, shows "Enrollment submitted, status: pending," and places a message in a queue. Back-end systems process the queue at their own pace, and a few minutes later you see "Approved."

Try this15 minutes

List every call your Module 2 project makes from one system to another. Mark each one S (must stay synchronous) or A (could be asynchronous), and write one sentence of reasoning for each A.

Check your understanding
  1. Explain temporal, availability, and performance coupling using the courier as your example.
  2. Why should the store return HTTP 202 rather than 201 when it hands work to a queue?
  3. Give one interaction in your own school's systems that must stay synchronous and one that should be asynchronous.
Show suggested answerHide suggested answerAdded in this edition
  1. Temporal: if the courier system is offline, a synchronous checkout cannot finish at that moment. Availability: checkout availability is the product of every system it calls, so a courier that is up 99% of the time pulls the whole checkout down. Performance: if the courier API takes 8 seconds, every checkout takes at least 8 seconds.
  2. 201 Created says the work is done and the resource exists. When the work is only queued, that would be untrue. 202 Accepted says "received, will be processed", which is honest, and it usually comes with a status URL the client can check.
  3. Example: logging in to the student portal must stay synchronous (the page cannot continue without knowing who you are). Sending the enrollment confirmation email or syncing the student to the library system should be asynchronous (nobody waits on it, and it can catch up later).
Key points

Synchronous communication makes the sender wait and couples systems in time, availability, and speed. Asynchronous communication lets the sender continue and lets each receiver work at its own pace, at the cost of eventual consistency and harder error handling. Good integrations use synchronous calls only where the caller truly needs the answer now.

Lesson 3.15 min read

#3.1.3Message producers and consumers

Integration problem

In a messaging integration, no system calls another directly. So who starts the conversation, and who answers? Every integrated system must know its role for each kind of message: does it send this message, receive it, or both?

When an order is paid, the store has news to share. The warehouse, accounting, the courier, and notification all need that news. Later, the warehouse has news of its own ("parcel packed") that the courier needs. Notice that the warehouse receives one kind of message and sends another. "Producer" and "consumer" are therefore roles a system plays for a particular message, not fixed labels for the system.

Definitions.

  • A message producer (also called a publisher or sender) is the part of an application that creates a message and hands it to the middleware.
  • A message consumer (also called a subscriber or receiver) is the part of an application that takes messages from the middleware and processes them.
  • In Enterprise Integration Patterns, the code that connects an application to the messaging system is called a Message Endpoint. Producers and consumers are endpoints.

What a producer does, step by step.

  1. Detects a business fact or need, such as "order ORD-10421 is paid."
  2. Builds the message: the body (the order data, usually as JSON) and the properties (a unique message ID, content type, timestamp).
  3. Publishes it to the broker, naming where it should go (in RabbitMQ, an exchange and a routing key).
  4. Confirms delivery: waits for the broker to say "I have it" (a publisher confirm, 3.1.7).
  5. Handles failure: if the broker cannot be reached or refuses the message, the producer retries or records the problem. It must never silently lose business data.

What a consumer does, step by step.

  1. Subscribes to a queue and waits for messages.
  2. Receives a message from the broker.
  3. Validates it: is it valid JSON, does it have all required fields? Never trust input, even from another internal system.
  4. Processes it: the business work, such as creating a pick-and-pack job.
  5. Acknowledges it, telling the broker "done, you may delete it" (3.1.7).
  6. Handles failure: if processing fails, it rejects the message so it can be retried or set aside (Lesson 3.2).

In code, both roles are short. The full versions are in Lab 3.1.

Python
# Producer (online store)
channel.basic_publish(exchange="orders", routing_key="order.confirmed",
                      body=json.dumps(order))

# Consumer (warehouse system)
def on_message(ch, method, properties, body):
    order = json.loads(body)          # receive and validate
    create_pick_job(order)            # process
    ch.basic_ack(method.delivery_tag) # acknowledge

channel.basic_consume(queue="warehouse.order-confirmed",
                      on_message_callback=on_message)

Push or pull? There are two ways a consumer can get messages, and Enterprise Integration Patterns names both:

StyleHow it worksPattern nameRecommendation
PushThe consumer registers once; the broker sends messages as they arriveEvent-Driven ConsumerThe normal choice; RabbitMQ's basic_consume
PullThe consumer asks "any messages?" again and againPolling ConsumerRabbitMQ's documentation discourages it (basic_get) except for tests or occasional checks

How producers and consumers can be arranged.

ArrangementExample in the online storeCovered in
One producer, one consumerThe store sends invoice requests to accounting only3.1.5
One producer, many consumers sharing the workTwo warehouse instances share one queue of orders (competing consumers)3.1.5
One producer, many consumers each getting a copyOrderConfirmed goes to the warehouse, accounting, courier, and notification3.2.3
Many producers, one consumerThe store and the mobile app both send orders to the same warehouse queue3.1.5

What they do not know about each other, and what they must agree on. This is what makes the integration loosely coupled.

The producer does not need to knowBut both must agree on
Which systems will receive the message, or how manyThe broker's address and the exchange or queue name
Where the receivers run, or in what languageThe message format and fields (the contract, 3.1.6)
Whether the receivers are online right nowWhat the message means (for example, "paid," not just "placed")

Scaling. Because producers and consumers are independent, each side scales on its own. On 12.12, the store adds web servers (more producers) while the warehouse adds two more consumer instances to keep up. Neither team has to coordinate code changes with the other.

Common misconceptions
  • "A system is either a producer or a consumer." Most systems are both, for different messages.
  • "The consumer is like a server and the producer is like a client." In messaging, both connect to the broker as clients. Neither listens for the other.
  • "Once published, the producer's job is done." Not until the broker confirms it received the message.
Example scenario

The warehouse system consumes OrderConfirmed from its queue, creates the pick-and-pack job, and acknowledges the message. When the parcel is packed, the warehouse becomes a producer: it publishes ParcelPacked, which the courier system consumes to schedule pickup, and the notification service consumes to text the customer "Your order is packed."

Try this10 minutes

Make a table with four columns: System, Produces, Consumes, Message. Fill it in for the online store's five systems and the notification service. Which system produces the most messages? Which consumes the most?

Check your understanding
  1. Why are producer and consumer described as roles, not types of systems?
  2. List the five steps a consumer follows, and say what goes wrong if step 3 (validate) is skipped.
  3. What must a producer and consumer agree on, even though they never talk directly?
Show suggested answerHide suggested answerAdded in this edition
  1. Because one system usually plays both roles for different messages. The warehouse consumes OrderConfirmed and produces ParcelPacked. The role belongs to the system's relationship with a particular message, not to the system.
  2. Subscribe → receive → validate → process → acknowledge (and handle failures). If validation is skipped, bad data from another system goes straight into business logic. That can crash the consumer on every delivery, or quietly save wrong data, such as an order with no items or a negative quantity.
  3. The broker address, the destination name (exchange/queue and routing key), and the message contract: the format, the fields, and what the message means (for example, "paid", not just "placed").
Key points

Producers create and publish messages; consumers receive, validate, process, and acknowledge them. A system can play both roles. Producers and consumers never address each other directly; they agree only on the broker, the destination name, and the message contract, which is what lets each side change and scale independently.

Lesson 3.117 min read

#3.1.4Message brokers

Integration problem

The store publishes a message and moves on; the warehouse may read it an hour later. Something must hold the message in between, decide which systems get a copy, and make sure it is not lost if a server restarts. That something is the message broker: the central piece of every messaging integration.

Think of a parcel company's sorting hub. Senders drop parcels at the counter and leave. Inside, staff read each label, sort parcels into bins by destination, and keep them safe overnight. Each recipient's parcels wait in their own bin until a rider picks them up. If a rider is sick, that bin simply fills up; no parcel is lost and the other bins are not affected. The hub keeps records of what came in, what went out, and what is still waiting. A message broker is that hub for data.

Definition. A message broker is a server, a kind of message-oriented middleware, that receives messages from producers, stores them, routes each one to the right destinations, and delivers them to consumers. Enterprise Integration Patterns calls this the Message Broker pattern: one central component that knows where messages should go, so that senders do not have to.

What a broker is responsible for.

ResponsibilityWhat the broker doesIn the online store
AcceptReceives messages from producers and confirms receiptTells the store "I have OrderConfirmed for ORD-10421"
StoreKeeps messages, on disk if they must survive a restartOrders survive a broker reboot during the night
RouteDecides which queues receive a copyConfirmed orders go to four queues; refunds only to accounting's
DeliverSends messages to consumers, a few at a timeGives the warehouse consumer its next order
TrackRemembers which messages were acknowledgedDeletes an order message only after the warehouse says "done"
RedeliverRe-sends messages whose consumer crashedGives the order to another warehouse instance
ProtectAuthenticates users and checks permissionsOnly the accounting system may read the accounting queue
ReportExposes counts and ratesShows 2,000 orders waiting for the courier

Brokers used in industry.

BrokerTypeNotes
RabbitMQOpen source, self-hosted or managed (for example Amazon MQ, CloudAMQP)Flexible routing with exchanges; used in this module's labs
Apache ActiveMQOpen sourceLong used in Java enterprise systems (JMS)
IBM MQCommercialCommon in banks and large enterprises
Amazon SQS and SNSFully managed cloud servicesSQS queues and SNS topics; no servers to run
Azure Service BusFully managed cloud serviceQueues and topics with subscriptions
Google Cloud Pub/SubFully managed cloud serviceTopics and subscriptions
Apache KafkaOpen source event streaming platformA replayable log rather than a queue; compared in 3.2.3

How RabbitMQ routes a message. Every broker has its own model. RabbitMQ uses the AMQP 0-9-1 model, built from three parts:

  • Exchange: the sorting desk. Producers always publish to an exchange, never directly to a queue. The exchange decides where copies go.
  • Queue: a bin. It stores messages until a consumer takes them.
  • Binding: a rule that connects an exchange to a queue, such as "send messages with routing key order.confirmed to the warehouse's queue."

Each message carries a routing key, like the address on a parcel label. The exchange compares it with each binding to decide which queues receive a copy.

AMQP 0-9-1 routing · producer, exchange, bindings, queues, consumers
Figure 3.2AMQP 0-9-1 routing · producer, exchange, bindings, queues, consumers

The producer only knows the orders exchange. The exchange copies the message into each queue whose binding key matches order.confirmed, and each consumer reads only its own queue.

RabbitMQ has four exchange types. Each routes differently:

Exchange typeRouting ruleUse in the online store
DirectRouting key must equal the binding key exactlySending invoice requests only to accounting's queue
FanoutEvery bound queue gets a copy; the key is ignoredBroadcasting a price update to every channel
TopicRouting key matches a pattern such as order.*Letting each system choose the order events it wants (3.2.4)
HeadersMatches message header values instead of the keyRouting on several attributes, such as region and priority

RabbitMQ also has a default exchange with no name. Every queue is automatically bound to it by its own name, so publishing with exchange="" and routing_key="orders" delivers straight to the queue called orders. Lab 3.1 uses this shortcut.

Choosing a broker. There is no single best broker. Ask these questions:

QuestionIf the answer is yes, consider
Do you need flexible routing to many different consumers?RabbitMQ (exchanges and bindings)
Must consumers be able to re-read old events, weeks later?Kafka, or RabbitMQ streams
Do you want no servers to maintain?Managed services: Amazon SQS and SNS, Azure Service Bus, Google Pub/Sub
Is the organization already standardized on one product?Use it; integration is easier when everyone shares one broker

Two broker philosophies. People in the industry sometimes describe RabbitMQ as a smart broker with simple consumers: the broker routes, tracks every acknowledgment, and deletes finished messages. Kafka is the opposite, a simple broker with smart consumers: it just appends events to a log, and each consumer tracks its own reading position. Neither is better; they suit different integration needs.

The broker is now critical infrastructure. If the only broker is down, every integration stops. Production systems therefore run brokers as a cluster of several servers, usually three, and use replicated queues so that losing one server loses no messages. The Going deeper part below explains how RabbitMQ does this.

Common misconceptions
  • "The broker runs business logic." A broker moves and stores messages; it does not decide whether an order is valid. That stays in the producers and consumers.
  • "The broker is a database." Queues are for messages in transit. Brokers work best when queues stay short; long-term records belong in each system's database.
  • "Publishing to a queue name always works." In RabbitMQ you publish to an exchange. If no binding matches, the message is silently dropped unless you guard against it (see Going deeper: exchanges).
Example scenario

A province-wide pharmacy chain sends sales from 40 branches to head office. Each branch's point-of-sale system is a producer that publishes to a broker at head office. During a typhoon, ten branches lose their internet connection. Their point-of-sale systems keep selling and buffer sales locally; when the connection returns, they publish the backlog. At head office, the inventory and accounting systems simply see more messages in their queues for a while. No system had to know which branches were offline.

Try this10 minutes

Using the AMQP diagram above, trace an OrderConfirmed message from the store to the notification service. Name the exchange, the routing key, the binding, and the queue it passes through. Then add a new subscriber, a loyalty-points system, to the diagram. What do you add, and what stays unchanged?

Check your understanding
  1. List four responsibilities of a message broker.
  2. In RabbitMQ, why does a producer publish to an exchange and not to a queue?
  3. Your school wants a broker but has no one to maintain servers. Which type of broker would you recommend, and why?
Show suggested answerHide suggested answerAdded in this edition
  1. Any four of: accept (and confirm) messages, store them, route them to the right queues, deliver them to consumers, track acknowledgments, redeliver after a consumer crash, protect access (authentication and permissions), and report metrics.
  2. In AMQP 0-9-1 the exchange does the routing. Publishing to an exchange means the producer only names a destination and a routing key. Bindings, which the consumers control, decide which queues get a copy, so new subscribers can be added without changing the producer. (Even "publishing to a queue" really goes through the default exchange.)
  3. A fully managed cloud broker, such as Amazon SQS/SNS, Azure Service Bus, Google Pub/Sub, or a managed RabbitMQ like CloudAMQP or Amazon MQ. The provider handles servers, patching, clustering and backups, so the school only configures queues and pays for usage.
Key points

A message broker receives, stores, routes, and delivers messages between producers and consumers, and tracks which messages were processed. RabbitMQ routes through exchanges, bindings, and queues using routing keys. Because every integration depends on it, a production broker runs as a cluster.

Going deeperRabbitMQ overview and architectureOptional on a first read · needed for the labs

Introduction. RabbitMQ is the open-source message broker used in this module's labs. It is one of the most widely deployed brokers, and it is offered as a managed service by cloud providers such as Amazon MQ and CloudAMQP. To use it well, you need to know what is inside it, not only how to call it from code.

Discussion: background.

ItemDetail
OriginDeveloped by Rabbit Technologies Ltd., started in 2007 as a joint venture between LShift and CohesiveFT
Ownership sinceSpringSource / VMware (2010), Pivotal Software (2013), back to VMware (2019); now maintained under Broadcom
Written inErlang, on the Open Telecom Platform (OTP), a runtime built for telecom systems that must keep running through failures
LicenseOpen source, Mozilla Public License
ProtocolsAMQP 0-9-1 (used in our labs), AMQP 1.0, MQTT, and STOMP, plus a dedicated stream protocol
Client librariesOfficial clients for Java, .NET, and Erlang, and widely used clients for other languages, such as pika (Python), amqplib (Node.js), and amqp091-go (Go)

RabbitMQ 4.x, the current release series, changed several things that older tutorials still describe:

  • AMQP 1.0 became a core protocol that is always enabled. AMQP 0-9-1 remains fully supported; RabbitMQ's own concept guide now suggests AMQP 1.0 for new applications, but most course materials and client libraries still use 0-9-1.
  • Classic queue mirroring, the old way of replicating queues, was removed after three years of deprecation. Quorum queues and streams are now the replicated options.
  • Khepri, a new metadata store based on the Raft consensus algorithm, replaced the older Mnesia store as the supported direction.
  • Quorum queues got a default delivery limit of 20 and support for message priorities.

If a tutorial mentions "mirrored queues" or "HA policies," it was written for RabbitMQ 3.x.

Discussion: the parts of a RabbitMQ system.

  • Node: one running RabbitMQ server (one Erlang virtual machine). In the lab, the Docker container is one node.
  • Cluster: several nodes working as one broker. Metadata (users, virtual hosts, exchanges, queue definitions, bindings, policies) is replicated to every node. Message contents are not, unless the queue type replicates them: a classic queue lives on one node, while quorum queues and streams copy messages to several nodes. Nodes authenticate each other with a shared secret called the Erlang cookie. Clusters should have an odd number of nodes (3, 5, 7), because replicated features need a majority to keep working; a two-node cluster is strongly discouraged.
  • Virtual host (vhost): a logical partition inside a broker, like a separate namespace. Exchanges, queues, bindings, policies, and user permissions all belong to one vhost, and a connection works only inside the vhost it connected to. The default vhost is /. A school could run /enrollment, /library, and /canteen on one broker without name clashes. Vhosts separate names and permissions, not hardware: all vhosts share the same CPU, memory, and disk.
  • Connection: a long-lived TCP connection from an application to a node (port 5672, or 5671 with TLS).
  • Channel: a lightweight logical connection inside a TCP connection. Every AMQP 0-9-1 operation (declare, publish, consume, ack) happens on a channel. Channels let one TCP connection carry many independent streams of work, instead of opening many TCP connections. Closing a connection closes all its channels.
  • Users and permissions: each user is granted, per vhost, three regular expressions that match resource names: configure (declare or delete exchanges and queues), write (publish to an exchange, bind to a queue), and read (consume, get, or purge from a queue). For example, rabbitmqctl set_permissions -p /store warehouse_svc "^warehouse\..*" "^warehouse\..*" "^(orders|warehouse\..*)$" limits a service to its own queues.
  • Plugins: optional features, enabled with rabbitmq-plugins enable <name>. Common ones are rabbitmq_management (web UI and HTTP API), rabbitmq_prometheus (metrics), rabbitmq_shovel (move messages between queues or brokers), rabbitmq_federation (link brokers across sites), and rabbitmq_mqtt (IoT devices).
RabbitMQ architecture · connections, channels, node, virtual host, exchange, queues
Figure 3.3RabbitMQ architecture · connections, channels, node, virtual host, exchange, queues

Each application keeps one TCP connection and does its work on channels inside it. Everything it touches, the exchange, queues, and bindings, lives inside the one virtual host it connected to.

The default guest user. A fresh node creates user guest with password guest and full access to the / vhost. By default it can log in only from localhost, so a lab PC can use it but a remote application cannot. RabbitMQ recommends deleting guest or changing its password in any real deployment and creating one user per application.

Discussion: channel errors you will meet. Some errors close only the channel, not the whole connection. The application can open a new channel and continue:

CodeMeaningCommon cause in labs
404 NOT_FOUNDThe queue or exchange does not existConsumer started before the queue was declared; typo in a name
406 PRECONDITION_FAILEDRedeclared with different propertiesDeclared orders as durable in one script and non-durable in another; or acked the same message twice
403 ACCESS_REFUSEDUser lacks permissionWrong vhost, or permissions not granted
405 RESOURCE_LOCKEDQueue is exclusive to another connectionTwo programs using the same exclusive queue
Example scenario

A small online store runs a three-node RabbitMQ cluster in its data center. The online store and the warehouse, accounting, courier, and notification integrations each have their own user. All five connect to the /store vhost, and each one keeps a single long-lived connection with one channel per worker thread. The orders exchange and all queues exist on every node's metadata, while the queue contents are stored in quorum queues replicated on all three nodes. When one node is rebooted for patching, the other two still form a majority, so ordering continues without losing messages.

Check your understanding

Why does RabbitMQ use channels inside a connection instead of letting each thread open its own TCP connection?

Show suggested answerHide suggested answerAdded in this edition

Opening a TCP connection is expensive: network round trips, TLS and authentication, plus memory on the broker. Thousands of connections can exhaust a node. Channels are lightweight logical sessions multiplexed over one connection. Each thread gets its own channel (channels must not be shared between threads), and the application keeps one long-lived connection per process.

Going deeperRabbitMQ exchanges in depthOptional on a first read · needed for the labs

Introduction. In RabbitMQ, all routing decisions are made by exchanges. Choosing the right exchange type and binding keys is the main design decision in any RabbitMQ integration, so each type is examined here with code and a worked example.

Discussion: declaring an exchange. An exchange is declared with a name, a type, and a few properties:

Python
channel.exchange_declare(
    exchange="orders",       # name
    exchange_type="topic",   # direct | fanout | topic | headers
    durable=True,            # survives a broker restart
    auto_delete=False,       # True: deleted when its last binding is removed
    internal=False,          # True: producers cannot publish to it directly
    arguments=None,          # optional extras, e.g. an alternate exchange
)

An exchange stores nothing. If no binding matches a message, the message is dropped by default, which is why the mandatory flag and alternate exchanges (below) matter.

1. Direct exchange: exact match. A message goes to every queue whose binding key equals the routing key exactly.

Python
channel.exchange_declare(exchange="tasks", exchange_type="direct", durable=True)
channel.queue_bind(queue="invoice-queue", exchange="tasks", routing_key="invoice")
channel.queue_bind(queue="email-queue",   exchange="tasks", routing_key="email")
channel.basic_publish(exchange="tasks", routing_key="invoice", body=b"...")
Routing key publishedDelivered to
invoiceinvoice-queue
emailemail-queue
smsNowhere (dropped unless handled)

Use it to send different kinds of work to different workers. The default exchange ("") is a special direct exchange that every queue is bound to by its own name.

2. Fanout exchange: broadcast. The routing key is ignored; every bound queue gets a copy.

Python
channel.exchange_declare(exchange="price-updates", exchange_type="fanout", durable=True)
channel.queue_bind(queue="web-cache",    exchange="price-updates")
channel.queue_bind(queue="mobile-cache", exchange="price-updates")
channel.queue_bind(queue="pos-terminals", exchange="price-updates")

Use it when every subscriber needs every message, such as refreshing caches or broadcasting a system-wide announcement. It is the simplest and fastest type.

3. Topic exchange: pattern match. Routing keys are dot-separated words; binding keys may use * (exactly one word) and # (zero or more words). Topic exchanges are the usual choice for event-driven systems and are covered fully in 3.2.4.

Python
channel.exchange_declare(exchange="orders", exchange_type="topic", durable=True)
channel.queue_bind(queue="notification.order-events", exchange="orders", routing_key="order.*")
channel.queue_bind(queue="audit.all",                 exchange="orders", routing_key="#")

4. Headers exchange: match on header values. The routing key is ignored. Bindings list header values, and the x-match argument decides whether all or any of them must match.

Python
channel.exchange_declare(exchange="reports", exchange_type="headers", durable=True)
channel.queue_bind(queue="pdf-printer", exchange="reports",
                   arguments={"x-match": "all", "format": "pdf", "dept": "finance"})
channel.basic_publish(exchange="reports", routing_key="", body=b"...",
                      properties=pika.BasicProperties(
                          headers={"format": "pdf", "dept": "finance"}))

Use it when routing depends on several independent attributes that do not fit naturally into one dotted key. It is less common than topic exchanges.

Choosing an exchange type.

NeedExchange type
Send each message to one specific named queueDefault exchange ("")
Route different kinds of work to different workersDirect
Every subscriber receives every messageFanout
Subscribers choose events by categoryTopic
Route on several message attributesHeaders

Discussion: unroutable messages. A message that matches no binding is silently discarded by default. This is a common cause of "my message disappeared" in labs. Two protections exist:

  • The mandatory flag. When a publisher sets mandatory=True, RabbitMQ returns an unroutable message to the publisher instead of dropping it. In pika's blocking client with publisher confirms enabled, this raises UnroutableError, as in Lab 3.1.
  • Alternate exchange (AE). An exchange can name another exchange to receive anything it cannot route. RabbitMQ recommends setting it by policy:
Shell
rabbitmqctl set_policy orders-ae "^orders$" '{"alternate-exchange":"orders.unrouted"}' --apply-to exchanges

Bind a queue such as orders.unrouted.q to the orders.unrouted fanout exchange, and every misrouted order event is kept there for inspection. A message delivered through an AE counts as routed, so it is not also returned under mandatory.

Discussion: exchange-to-exchange bindings. RabbitMQ extends AMQP 0-9-1 so an exchange can be bound to another exchange with channel.exchange_bind(destination, source, routing_key). This builds routing layers; for example, a central orders topic exchange can feed a notifications fanout exchange that several notification channels (email, SMS, push) subscribe to.

Example scenario

A logistics company publishes parcel events with routing keys such as parcel.manila.delivered and parcel.cebu.delayed. The Cebu branch dashboard binds parcel.cebu.*. Customer service binds *.*.delayed to call affected customers. The data warehouse binds #. Months later, events for a new Davao branch start appearing with parcel.davao.* and reach the warehouse and customer service automatically, with no change to the producer.

Check your understanding

You publish to a topic exchange with routing key Order.Confirmed, but the queue is bound with order.confirmed. The message disappears with no error. Explain why, and name two ways you could have detected it.

Show suggested answerHide suggested answerAdded in this edition

Topic routing is case-sensitive: Order.Confirmed does not match the binding key order.confirmed. No binding matched, and by default RabbitMQ silently drops unroutable messages. Two ways to detect it:

  • Publish with mandatory=True (with publisher confirms), so the broker returns the message and pika raises UnroutableError.
  • Configure an alternate exchange on orders with a queue bound to it, so misrouted messages are kept for inspection.

Monitoring also helps: the exchange's publish rate rises while the queue's stays flat.

Lesson 3.110 min read

#3.1.5Queues and messages

Integration problem

The warehouse can pack 200 orders an hour, but on 12.12 the store confirms 3,000 orders in the first ten minutes. The data must wait somewhere safe, in order, until the warehouse catches up, and it must survive a server restart. In messaging, the data travels as messages, and it waits in queues.

At a busy counter, each order is written on a slip and placed on a rail. The kitchen takes the oldest slip first. When the lunch rush hits, the rail gets long, but no order is forgotten. Add a second cook and the rail empties twice as fast; each slip still goes to only one cook. The slip is a message, the rail is a queue, and the cooks are consumers.

#The message

Definition. A message is a self-contained packet of data sent from one system to another through middleware. Like a letter in an envelope, it has two parts:

  • Headers and properties (the envelope): information about the message, used by the broker and the receiver.
  • Body or payload (the letter): the business data itself, usually JSON. The broker treats the body as raw bytes; it never reads or validates it.

A real OrderConfirmed message, part by part.

PartPropertyExample valueWhy it matters for integration
Envelopemessage_id8f14e45f-ceea-...Lets receivers detect duplicates (3.2.7)
Envelopecontent_typeapplication/jsonTells the receiver how to read the body
Envelopedelivery_mode2 (persistent)Asks the broker to write it to disk
Envelopetimestamp1764728100When it was sent; useful for tracing
Envelopecorrelation_idORD-10421Links all messages about one order
Envelopetypeorder.confirmedWhat kind of message this is
Envelopeheaders{"source": "web-store"}Any extra custom information
Letterbody{"orderId": "ORD-10421", "items": [...], "totalAmount": 260.00}The business data the receivers need

Keep messages small. A message should carry what receivers need to act, not large files. If an order includes a 5 MB scanned purchase order, store the file elsewhere and put only its link in the message. Enterprise Integration Patterns calls this the Claim Check pattern, like leaving your bag at a counter and carrying only the claim ticket.

#The queue

Definition. A queue is a named buffer inside the broker that stores messages in arrival order until a consumer takes them. It is first in, first out (FIFO): the oldest message is delivered first.

A message's life inside a queue. In RabbitMQ, every message in a queue is in one of two states, which you will see in the management UI:

  1. Ready: waiting to be delivered.
  2. Unacknowledged (unacked): delivered to a consumer, which is still working on it.
  3. Then either removed (the consumer acknowledged it) or back to Ready (the consumer failed or disconnected), to be delivered again.

Point-to-point delivery. Each message in a queue goes to exactly one consumer. When several consumers read the same queue, they share the work: this is the Competing Consumers pattern. On 12.12, the warehouse starts three consumer instances on warehouse.order-confirmed; RabbitMQ hands out messages among them, and the backlog drains three times faster. Scaling a slow integration often means just adding consumers.

A warning about order. The queue keeps messages in order, but with several competing consumers, or when a failed message is put back, messages can be processed out of order. ORD-10422 may finish before ORD-10421. If strict order matters, for example two updates to the same customer's address, use a single consumer, or RabbitMQ's single active consumer option, which keeps one consumer active and the others on standby.

Surviving a restart: durability and persistence. Two separate settings decide whether messages survive when the broker restarts, and you need both:

Queue declared durable?Message published persistent?After a broker restart
NoNoQueue and messages are gone
NoYesQueue is gone, so its messages are gone too
YesNoQueue exists but is empty
YesYesQueue and messages are still there (use this for business data)

Limits: not every message should live forever. A queue can be given a message TTL (time to live), after which old messages are removed, and a maximum length, after which the oldest are dropped or new ones refused. Expired or dropped messages can be sent to a dead-letter queue instead of disappearing (3.2.8). Use limits where old data loses its value; never on queues of orders or payments.

Three queue types in RabbitMQ. Classic queues keep one copy on one server and suit temporary or lab use. Quorum queues copy every message to several servers and are RabbitMQ's recommended choice for important business queues like orders. Streams keep messages even after they are read, so they can be replayed. The Going deeper part below compares them in detail.

Common misconceptions
  • "An exchange and a queue are the same thing." The exchange routes; only the queue stores.
  • "Messages stay in the queue after they are read." In a normal queue, an acknowledged message is deleted. Only streams keep them.
  • "FIFO means messages are processed in order." They are delivered in order, but with several consumers they may finish out of order.
  • "A durable queue keeps my messages safe." Only if the messages are also persistent.
Example scenario

A food-delivery app sends "Your rider is nearby" notifications. A notification older than 5 minutes is useless, so its queue has a TTL of 300,000 milliseconds: stale messages are removed rather than sent late. Order messages are different. They must never be lost, so the orders queue is a durable quorum queue, and every order is published as persistent.

Try thisLab 3.1 preview

Publish five messages while the consumer is stopped. In the management UI, watch Ready rise to 5. Start the consumer and watch messages move to Unacked and then disappear. Then restart RabbitMQ with the consumer stopped and check: did your messages survive? Which two settings made that happen?

Check your understanding
  1. Name four properties of an OrderConfirmed message and why each helps the integration.
  2. Why can competing consumers process messages out of order, and how would you prevent it when order matters?
  3. A teammate declares a durable queue but publishes non-persistent messages. What happens after a restart?
Show suggested answerHide suggested answerAdded in this edition
  1. For example: message_id (lets consumers detect duplicates), content_type (tells the receiver how to parse the body), delivery_mode=2 (persistent, survives a restart), correlation_id (links every message about one order for tracing), timestamp (when it was sent) and type (what kind of message it is).
  2. Each consumer works at its own speed, and a failed or rejected message goes back to the queue, so ORD-10422 can finish before ORD-10421. When order matters, use a single consumer or the queue's single active consumer option (one active consumer, the others on standby).
  3. The queue definition survives the restart, but the non-persistent messages were only in memory, so the queue comes back empty. You need both a durable queue and persistent messages.
Key points

A message is an envelope of properties plus a body of business data; keep it small. A queue stores messages first in, first out until a consumer acknowledges them, and each message goes to one consumer. Business data needs a durable queue and persistent messages; limits like TTL suit only data that loses value over time.

Going deeperRabbitMQ queues in detailOptional on a first read · needed for the labs

Declaring a queue. A queue declaration combines four built-in properties with optional arguments:

Python
result = channel.queue_declare(
    queue="warehouse.order-confirmed",  # "" lets the broker generate a name
    durable=True,       # definition survives a restart
    exclusive=False,    # True: usable only by this connection, deleted when it closes
    auto_delete=False,  # True: deleted when its last consumer unsubscribes
    arguments={"x-queue-type": "quorum"},
)
print(result.method.queue, result.method.message_count, result.method.consumer_count)

Queue names can be up to 255 bytes; names starting with amq. are reserved. Declaring is idempotent: declaring an existing queue with identical settings does nothing, but declaring it with different settings fails with 406 PRECONDITION_FAILED. In the lab, this usually means two scripts disagree, so declare every queue the same way everywhere (or in one setup script, as in Lab 3.2).

Two kinds of subscriber queue.

Durable named queueTemporary server-named queue
Declared asqueue="warehouse.order-confirmed", durable=Truequeue="", exclusive=True
Survives consumer restartYes; messages wait while it is downNo; deleted with the connection, messages lost
Use forBusiness consumers that must not miss events (warehouse, accounting)Live dashboards, debugging tools, cache refreshes where missed messages do not matter

Common queue arguments.

ArgumentEffectExample
x-queue-typeclassic, quorum, or stream; fixed at declaration"quorum"
x-message-ttlMessages expire after this many milliseconds60000
x-expiresThe queue itself is deleted after being unused this long (ms)1800000
x-max-length / x-max-length-bytesMaximum number of messages / total bytes10000
x-overflowWhat happens when the limit is reached: drop-head (default, oldest dropped or dead-lettered), reject-publish (new messages refused)"reject-publish"
x-dead-letter-exchange / x-dead-letter-routing-keyWhere expired, rejected, or overflowing messages go"orders.dlx"
x-delivery-limitQuorum queues: failed deliveries allowed before dead-lettering (default 20 in 4.x)5
x-single-active-consumerOnly one consumer receives at a time, others are standby; keeps orderTrue
x-max-priorityClassic queues: enables message priorities up to this number10

Policies instead of hard-coded arguments. Most of these settings can also be applied by a policy: a rule, stored in the broker, that matches queue or exchange names by regular expression and applies settings to all of them. Policies can be changed at runtime without touching application code or recreating queues, which is why RabbitMQ's documentation recommends them for TTLs, length limits, and dead-lettering. Queue type cannot be set by policy; it is fixed when the queue is declared.

Shell
# Every queue whose name starts with "notification." keeps at most 50,000 messages
# and drops messages older than 10 minutes
rabbitmqctl set_policy -p /store notif-limits "^notification\." \
  '{"max-length":50000,"message-ttl":600000}' --apply-to queues --priority 1

Only one policy applies to each queue, chosen by highest priority. Administrators can also set operator policies, guardrails such as a maximum queue length that application teams cannot override.

Comparing the three queue types.

FeatureClassicQuorumStream
Copies of the dataOne nodeSeveral nodes (Raft consensus); works while a majority is upSeveral nodes
After a message is consumedDeletedDeletedKept until retention removes it; can be re-read
Poison-message protectionNone built inDelivery limit (default 20)Not applicable
Exclusive / auto-delete queuesSupportedNot supportedNot supported
Best forTemporary queues, non-critical work, single-node labsDurable business queues (orders, payments)Replay, very large fan-outs, large backlogs

Streams in practice. A stream is declared like a queue with x-queue-type: stream, but reading does not remove messages. Each consumer chooses where to start with the x-stream-offset argument: first (oldest kept), last, next (only new messages, the default), a numeric offset, or a timestamp. Streams require manual acks and a prefetch. Retention is set with x-max-age (for example 7D) or x-max-length-bytes; without it, a stream grows until the disk fills.

Python
channel.queue_declare(queue="order-history", durable=True,
                      arguments={"x-queue-type": "stream", "x-max-age": "7D"})
channel.basic_qos(prefetch_count=100)
channel.basic_consume(queue="order-history", on_message_callback=on_message,
                      arguments={"x-stream-offset": "first"})  # replay from the start

This gives RabbitMQ a Kafka-like replay capability, useful when a new reporting service must process every order from the past week.

Lesson 3.17 min read

#3.1.6Message formats

Integration problem

The online store calls it orderId, the warehouse system calls it order_no, and the accounting system expects amounts in centavos. Integrated systems can only understand each other if they agree on the shape and meaning of every message, and keep agreeing as each system changes. This is the data-mapping problem from Modules 1 and 2, now applied to messages.

The store sends "orderDate": "04/12/2026". The store's developers meant 4 December. The accounting system, set up by a different vendor, reads it as 12 April. Every December sale is booked in April, and nobody notices until the month-end report is wrong. No system crashed. Both sides worked exactly as written; they just did not agree on the format. Most integration bugs look like this.

Three words to keep apart.

  • Message format: the encoding used to write the body, such as JSON or XML.
  • Schema: the exact structure: which fields exist, their data types, and which are required.
  • Contract: the agreement between producer and consumers, made of the format, the schema, and the meaning of each field. In Module 2 the API had a contract; here every message type has one.

Common formats.

FormatStrengthsWeaknessesWhere you see it
JSONReadable, supported by every language, same as REST APIsLarger; schema is optional unless you add JSON SchemaMost web and cloud integrations
XMLStrict schemas (XSD), namespaces, mature toolsVerbose; slower to parseBanking, government systems, SOAP services
CSVSimple; opens in a spreadsheetNo nesting, no types, delimiter and quoting problemsFile transfer integrations and bulk imports
Apache AvroCompact binary with strict versioning rulesNot human-readable; needs toolingKafka data pipelines
Protocol BuffersCompact, fast, generates codeNot human-readable; needs .proto filesgRPC and high-volume internal services

In this course, use JSON, and set the message's content_type property to application/json.

The same order in JSON and XML.

JSON
{ "orderId": "ORD-10421", "totalAmount": 260.00, "currency": "PHP" }
XML
<order><orderId>ORD-10421</orderId><totalAmount currency="PHP">260.00</totalAmount></order>

Data-type traps in integration. Agree on these explicitly in every contract:

DataTrapIndustry practice
Dates and times04/12 is ambiguous; time zones get lostISO 8601 with a time zone: 2026-12-04T10:15:00+08:00
MoneyFloating-point rounding (0.1 + 0.2 is not exactly 0.3)Many payment APIs, such as Stripe's, send integer minor units (26000 centavos) plus a currency code
IDsLeading zeros lost when treated as numbers (00087 becomes 87)Send IDs as strings
NamesCharacters like ñ in "Dela Peña" become garbledUse UTF-8 everywhere
CodesOne system says "PAID," another "paid," another "3"List allowed values (an enumeration) in the schema
Missing dataIs a missing field "unknown," "none," or an error?State in the contract which fields are required

Writing the schema down: JSON Schema. A schema turns the contract into something a program can check. Consumers can validate every message against it before processing:

JSON
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "OrderConfirmed data",
  "type": "object",
  "required": ["orderId", "customerId", "items", "totalAmount", "currency"],
  "properties": {
    "orderId":     { "type": "string", "pattern": "^ORD-[0-9]+$" },
    "customerId":  { "type": "string" },
    "items": {
      "type": "array", "minItems": 1,
      "items": {
        "type": "object", "required": ["sku", "quantity"],
        "properties": {
          "sku":      { "type": "string" },
          "quantity": { "type": "integer", "minimum": 1 }
        }
      }
    },
    "totalAmount": { "type": "number", "minimum": 0 },
    "currency":    { "type": "string", "enum": ["PHP"] }
  }
}

When the format changes: versioning. Systems change, so messages change. The rules that keep an integration working:

ChangeSafe?What to do
Add a new optional fieldSafe (backward-compatible)Just add it; old consumers ignore it
Remove a field, rename it, or change its typeBreakingPublish a new version, such as order.confirmed.v2, and keep sending v1 until every consumer has moved
Make an optional field requiredBreaking for producers that do not send itTreat as a new version

Consumers should also be tolerant readers: ignore fields they do not recognize instead of rejecting the whole message.

Many systems, one shared format: the Canonical Data Model. With five systems each using its own field names, every pair would need its own translation. The Canonical Data Model pattern defines one shared format for each business object, such as a standard Order. Each system translates only between its own format and the canonical one, using a Message Translator, usually inside its producer or consumer code. This is exactly the data-mapping work you did in Modules 1 and 2.

A standard envelope: CloudEvents. CloudEvents is a specification from the Cloud Native Computing Foundation (CNCF) that describes event metadata the same way across brokers and clouds. Version 1.0 requires four attributes: id (unique per event from a source), source (where it happened), specversion ("1.0"), and type (the kind of event, which the specification says should start with a reverse-DNS name). Optional attributes include time, subject, and datacontenttype; the business content goes in data. The online store's OrderConfirmed event, with illustrative values:

JSON
{
  "specversion": "1.0",
  "type": "com.example.store.order.confirmed.v1",
  "source": "/store/ordering-service",
  "id": "8f14e45f-ceea-4e7b-9d3a-5b2c7a1d9e01",
  "time": "2026-12-04T10:15:00+08:00",
  "subject": "ORD-10421",
  "datacontenttype": "application/json",
  "data": {
    "orderId": "ORD-10421",
    "customerId": "CUST-0087",
    "items": [
      { "sku": "NB-A5-80", "quantity": 3, "unitPrice": 45.00 },
      { "sku": "PEN-BLK-05", "quantity": 10, "unitPrice": 12.50 }
    ],
    "totalAmount": 260.00,
    "currency": "PHP"
  }
}

In this course's examples, amounts are JSON numbers for simplicity. In production, follow the money rule in the table above.

Common misconceptions
  • "JSON is self-explanatory, so we don't need a schema." JSON says nothing about which fields are required or what status: 3 means.
  • "The broker checks the format." The broker never reads the body. Validation is the consumer's job.
  • "Renaming a field is a small change." For every consumer of that message, it is a breaking change.
Example scenario

The accounting team asks to rename totalAmount to grandTotal. Instead of changing it overnight, the store team publishes order.confirmed.v2 with the new name while still publishing v1. Accounting switches to v2; the warehouse, courier, and notification, which never read the amount, are unaffected. Three months later, when no queue is bound to v1 anymore, the store stops sending it.

Try this15 minutes, Data-Mapping Exercise

The store's message has orderId, orderDate (ISO 8601), and totalAmount (pesos). The accounting system expects order_no, txn_date (YYYYMMDD), and amount_centavos. Write the mapping table, then write the three lines of Python that translate one into the other.

Check your understanding
  1. Distinguish format, schema, and contract.
  2. Why is 04/12/2026 dangerous in an integration, and how should the date be written?
  3. Is adding an optional voucherCode field to OrderConfirmed a breaking change? Is renaming customerId to buyerId?
Show suggested answerHide suggested answerAdded in this edition
  1. Format is the encoding (JSON, XML). Schema is the exact structure: fields, types, and which are required. Contract is the whole agreement between producer and consumers: format plus schema plus the meaning of each field.
  2. It is ambiguous: 4 December (month first) or 12 April (day first)? Both systems "work", but the data is wrong. Write dates in ISO 8601 with a time zone, for example 2026-12-04T10:15:00+08:00.
  3. Adding an optional voucherCode is not breaking: tolerant readers ignore it. Renaming customerId to buyerId is breaking: every consumer that reads customerId gets nothing. Publish it as a new version alongside the old one.
Key points

A message format is the encoding; the schema is the structure; the contract is the full agreement including meaning. Agree explicitly on dates, money, IDs, encoding, and codes. Add fields safely, publish breaking changes as new versions, and validate every incoming message against its schema.

Lesson 3.19 min read

#3.1.7Message acknowledgments

Integration problem

Between the online store and the warehouse, an order can be lost in three places: on the way to the broker, inside the broker, or inside the warehouse system if it crashes halfway through. In an integration, "I sent it" is not the same as "they processed it." Each side needs proof.

When you send an important document by registered mail, the post office gives you a receipt when you drop it off, and the recipient signs when they receive it. If there is no signature, the post office tries again. Messaging works the same way: the broker gives the producer a receipt (a publisher confirm), and the consumer "signs" for each message (an acknowledgment, or ack). Until the ack arrives, the broker keeps the message.

Definition. An acknowledgment is a signal from a consumer to the broker that it has finished processing a message, so the broker may delete it. A negative acknowledgment says processing failed, so the broker should put the message back or set it aside.

The three places a message can be lost, and the protection for each.

HopWhat can go wrongProtectionCovered in
1. Producer to brokerThe network drops before the broker receives it, or no queue matches itPublisher confirms; mandatory flag or alternate exchangeThis section; 3.1.4
2. Inside the brokerThe broker server restarts or failsDurable queues, persistent messages, quorum queues3.1.5
3. Broker to consumerThe consumer crashes or loses its connection mid-processingManual consumer acknowledgmentsThis section

Hop 1: publisher confirms. After the producer turns on confirm mode, the broker replies to each published message once it has safely accepted it; for a persistent message in a durable queue, that means after writing it to disk. A producer that gets no confirm must treat the message as not sent and retry. Without confirms, a store that published an order just before a network drop has no way to know whether the order reached the broker.

Hop 3: consumer acknowledgments. RabbitMQ offers two modes:

ModeWhen the broker deletes the messageRiskUse for
Automatic ackAs soon as it sends the messageIf the consumer crashes, the message is lost; RabbitMQ's documentation calls this mode unsafe for many workloadsData you can afford to lose, such as live dashboard updates
Manual ackWhen the consumer sends an ackThe message may be delivered twice if the consumer crashes after finishing but before ackingAll business data: orders, invoices, deliveries

With manual acks, the consumer answers each message in one of three ways:

ReplyMeaningWhat the broker does
ack"Done."Deletes the message
nack or reject with requeue=True"Failed; try again."Puts the message back in the queue
nack or reject with requeue=False"Failed; do not retry."Sends it to a dead-letter queue if one is set up, otherwise discards it (3.2.8)

If a consumer's connection closes before it acks, RabbitMQ automatically returns all its unacknowledged messages to the queue and marks them redelivered=True, so another consumer gets them.

When to ack: the most important decision. Should the warehouse consumer ack before or after it saves the pick-and-pack job?

Ack timingIf the consumer crashes in betweenResult
Ack first, then saveThe broker already deleted the message; the job was never savedThe order is lost. The customer paid but nothing ships.
Save first, then ackThe job is saved; the broker redelivers the messageThe order arrives twice. Harmless if the consumer detects duplicates (3.2.7).

The industry answer is always: save first, then ack, and make the consumer idempotent. A duplicate can be detected and ignored; a lost order cannot be recovered.

Prefetch: how many messages a consumer may hold. Prefetch limits how many unacknowledged messages the broker sends to one consumer at a time. Think of the fast-food counter in 3.1.5: prefetch is how many order slips one cook may take from the rail at once. With no limit, one cook could grab every slip while the others stand idle. RabbitMQ's documentation notes that a prefetch of 1 is the safest but slowest, and that values around 100 to 300 usually give good throughput. The labs use 1 so that you can watch messages move one at a time.

Delivery guarantees. Together, these choices decide what the integration promises:

GuaranteeHow you get itWhat can happen
At-most-onceAutomatic ack, no publisher confirmsMessages can be lost, never duplicated
At-least-oncePublisher confirms, durable and persistent storage, manual ack after processingMessages are never lost, but may arrive twice
Exactly-onceNot guaranteed end-to-end by message brokers in generalAchieved in practice as at-least-once delivery plus idempotent consumers, sometimes called effectively once

Most business integrations, including the online store, choose at-least-once.

Beware the requeue loop. A message that can never succeed, such as one with invalid JSON, will fail, be requeued, fail again, and be requeued forever, using CPU and blocking the queue. Never requeue blindly; count attempts and set the message aside after a limit (3.2.6 and 3.2.8).

Common misconceptions
  • "The producer got no error, so the message was delivered." Without publisher confirms, the producer cannot know.
  • "Auto-ack is fine because our consumer never crashes." Servers restart, deployments happen, and networks drop.
  • "Acknowledging means the broker sends a reply to the producer." Consumer acks go only to the broker. The producer never learns which consumers processed its message.
Example scenario

The accounting consumer receives a confirmed order, records the sale, then crashes before sending its ack. RabbitMQ redelivers the message to another accounting consumer with redelivered=True. Because the consumer first checks whether this message ID was already processed, it acks without recording the sale again. Had it used automatic ack, the sale would have been recorded once, but any order that arrived just before a crash, before being recorded, would have been silently lost.

Try thisLab 3.1, experiment 4

Send one order and stop the consumer with CTRL+C during its 2-second sleep. Watch the Unacked count in the management UI drop back to Ready. Restart the consumer: what does redelivered show? Then change the consumer to auto_ack=True and repeat. What happens to the order now?

Check your understanding
  1. Name the three hops where a message can be lost and the protection for each.
  2. Explain why "save first, then ack" is safer than "ack first, then save," and what extra work it creates.
  3. What delivery guarantee does the online store use, and why is exactly-once delivery not simply turned on?
Show suggested answerHide suggested answerAdded in this edition
  1. Producer → broker: publisher confirms, plus the mandatory flag or an alternate exchange. Inside the broker: durable queues, persistent messages and quorum queues. Broker → consumer: manual consumer acknowledgments.
  2. With "ack first", a crash before saving means the broker has already deleted the message: the order is lost for good. With "save first", a crash before the ack means the message is redelivered: a duplicate, which can be detected. The extra work is making every consumer idempotent.
  3. At-least-once. Brokers in general cannot guarantee exactly-once end-to-end: a crash between processing and acking always leaves doubt. "Effectively once" is built from at-least-once delivery plus idempotent consumers.
Key points

Publisher confirms protect the producer-to-broker hop; durable, persistent storage protects messages in the broker; manual acks protect the broker-to-consumer hop. Ack only after the work is saved, and expect occasional duplicates. Together these give at-least-once delivery, the standard for business integrations.

Going deeperthe life of a message in RabbitMQOptional on a first read · needed for the labs

Putting 3.1.3 to 3.1.7 together, this is what happens to one OrderConfirmed message, and what can go wrong at each step:

StepWhat happensWhat can go wrongProtection
1. PublishProducer sends the message on a channel to the orders exchangeNetwork drops before the broker receives itPublisher confirms; retry unconfirmed messages
2. RouteExchange compares the routing key with bindingsNo binding matches; message silently droppedmandatory=True, alternate exchange
3. EnqueueA copy is stored in each matching queueBroker restarts; node failsDurable queue, persistent message, quorum queue
4. ConfirmBroker acks the publisher (after writing to disk for persistent messages, or after replicas accept for quorum queues)Broker under memory or disk alarm blocks publishersMonitor alarms; handle blocked connections
5. DeliverBroker pushes the message to a consumer, up to its prefetch limitConsumer is slow or absent; queue growsPrefetch, more consumers, monitoring
6. ProcessConsumer runs business logicCrash, bug, invalid data, downstream outageManual ack, retries, dead-letter queue
7. AcknowledgeConsumer acks; broker deletes the messageConnection lost before ack; message redeliveredIdempotent consumer

Acknowledgment calls in pika.

Python
ch.basic_ack(delivery_tag=method.delivery_tag)                     # success
ch.basic_ack(delivery_tag=method.delivery_tag, multiple=True)      # ack this and all earlier ones on the channel
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)      # failed, put back in the queue
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)     # failed, dead-letter or discard
ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)   # same as above, single message only

The delivery_tag is a number that identifies the delivery on that channel only. Acking on a different channel, or acking the same tag twice, closes the channel with an "unknown delivery tag" error (406 PRECONDITION_FAILED). The multiple=True option lets a fast consumer ack in batches.

Consumer features in RabbitMQ.

  • Push, not pull. basic_consume registers a long-lived consumer, and RabbitMQ pushes messages to it. The alternative, basic_get, fetches one message per request; RabbitMQ's documentation describes it as highly inefficient polling and discourages it outside of tests.
  • Consumer tag. Each subscription gets an ID (consumer_tag), used to cancel it later with basic_cancel.
  • Delivery acknowledgment timeout. If a consumer holds a message without acking for too long, RabbitMQ assumes it is stuck and returns the message to the queue. The default is 30 minutes. A consumer doing slow work, such as generating a large report, must ack within that time or the timeout must be raised (consumer-timeout policy or x-consumer-timeout argument). In RabbitMQ 4.3 and later this timeout applies to quorum queues.
  • Single active consumer. With the queue argument x-single-active-consumer: True, only one consumer receives messages at a time; the others wait as hot standbys and take over automatically if it disconnects. Use it when messages must be processed strictly in order but you still want failover.
  • Consumer priority. Higher-priority consumers receive messages first; lower-priority ones receive messages only when the higher ones are busy (at their prefetch limit). Consumers of equal priority share messages round-robin.
  • Exclusive consumer. On classic queues, a consumer can register with exclusive=True so no other consumer may attach. Quorum queues ignore this flag; use single active consumer instead.

Publisher confirms in code. In pika's blocking client, channel.confirm_delivery() puts the channel into confirm mode. After that, basic_publish waits for the broker's confirmation and raises NackError if the broker refuses the message, or UnroutableError if mandatory=True and nothing matched (see Lab 3.1). Waiting for each confirm is simple but slow; RabbitMQ recommends confirming in batches or asynchronously for high volumes.

Lesson 3.19 min read

#3.1.8Basic queue monitoring

Integration problem

In a synchronous integration, a broken system causes visible errors right away. In an asynchronous one, a broken consumer causes no error at all: its messages just pile up quietly in its queue. Unless someone watches the queues, an integration can be broken for days while every system reports "no errors."

On Friday night, a bad update crashes the notification service. The store keeps taking orders, the warehouse keeps packing, accounting keeps invoicing. Nothing shows an error. On Monday morning, customer service gets dozens of complaints: "I never got a confirmation text." The notification.order-confirmed queue now holds 18,000 messages and has zero consumers. A single alert on "consumers = 0" would have caught it on Friday night.

Why monitoring is different for messaging. Messaging protects the integration from failures by hiding them: messages wait instead of failing. That is a strength, but it also means problems show up as numbers in the broker, not as error pages. Monitoring the queues is how you see the health of every integration link at once.

The numbers that matter. For each queue, watch these:

MetricWhat it tells youHealthyWarning sign
Ready messagesMessages waiting to be deliveredRises and falls, returns toward zeroKeeps growing: consumers are too slow, stopped, or missing
Unacked messagesDelivered but not yet acknowledgedSmall, about consumers × prefetchStays high and unchanging: consumers are stuck or forgot to ack
ConsumersHow many consumers are attachedAt least one on every active queueZero
Publish rateMessages per second arrivingFollows business activityDrops to zero during business hours: the producer stopped
Deliver and ack ratesMessages per second leavingClose to the publish rate over timeFar below the publish rate: backlog building
Redelivered rateMessages delivered more than onceNear zeroHigh: consumers keep crashing or rejecting
Dead-letter queue depthMessages that failed for goodZeroAnything above zero needs a person (3.2.8)

And for the broker itself: memory and disk use. When either crosses its limit, RabbitMQ raises a resource alarm and blocks all publishers until it clears, which stops every integration at once.

These match a standard idea. Google's Site Reliability Engineering book recommends watching four "golden signals" for any service: latency, traffic, errors, and saturation. For a queue, they become: how long messages wait (latency), the publish rate (traffic), redeliveries and dead letters (errors), and queue depth or broker memory (saturation).

Reading the shape of a queue.

What you seeLikely causeFirst thing to check
Ready climbs steadily, consumers = 0Consumer crashed or was never startedIs the consumer process running? Its logs?
Ready climbs steadily, consumers > 0Consumers too slow for the traffic, or a downstream system is slowAdd consumer instances; check the system the consumer calls
Ready = 0, unacked high and frozenConsumer stuck mid-processing or never acksConsumer code: is basic_ack called on every path?
Ready jumps, then drains back to zeroNormal burst, such as the 12.12 saleNothing; the queue did its job
Publish rate drops to zeroProducer stopped or cannot reach the brokerProducer logs; broker connections tab

Where to look.

  • Management UI at http://localhost:15672: the Queues and Streams tab shows every number above, live.
  • Command line: rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers
  • HTTP API: the same data as JSON, for scripts. For example, this short script prints a health line for every queue:
Python
"""Print a health line for every queue, using the RabbitMQ HTTP API."""
import base64
import json
import urllib.request

API = "http://localhost:15672/api/queues"
AUTH = base64.b64encode(b"guest:guest").decode()

request = urllib.request.Request(API, headers={"Authorization": f"Basic {AUTH}"})
with urllib.request.urlopen(request) as response:
    queues = json.load(response)

for q in queues:
    ready = q.get("messages_ready", 0)
    unacked = q.get("messages_unacknowledged", 0)
    consumers = q.get("consumers", 0)
    status = "OK"
    if consumers == 0 and ready > 0:
        status = "ALERT: no consumers"
    elif ready > 1000:
        status = "WARNING: backlog"
    print(f"{q['name']:<35} ready={ready:<6} unacked={unacked:<5} "
          f"consumers={consumers:<3} {status}")

Sample output for the Monday-morning story:

Output
warehouse.order-confirmed           ready=0      unacked=1     consumers=2   OK
notification.order-confirmed        ready=18000  unacked=0     consumers=0   ALERT: no consumers
courier.order-confirmed             ready=1500   unacked=10    consumers=1   WARNING: backlog
  • Production monitoring: RabbitMQ's documentation describes the management UI as a convenience that keeps only recent data. For production it recommends its Prometheus plugin with Grafana dashboards, which keep history and send alerts.

Turning numbers into alerts. Watching dashboards is not enough; nobody watches at 2 a.m. Typical alert rules for the online store:

Alert whenFor at leastWhy
A business queue has 0 consumers5 minutesA whole integration link is down
Ready messages above 1,000 and rising10 minutesConsumers cannot keep up
Any dead-letter queue has messagesImmediatelyData needs a person
A resource alarm is activeImmediatelyAll publishing is blocked
Common misconceptions
  • "No errors in the logs means the integration is fine." In messaging, a dead consumer produces no errors at all.
  • "A long queue is always a problem." A spike that drains is the queue doing its job. A queue that only grows is the problem.
  • "The management UI is enough for production." It shows the present, not history, and it does not wake anyone up.
Example scenario

During the 12.12 sale, the dashboard shows courier.order-confirmed climbing to 1,500 ready messages while the other three queues stay near zero. The team checks the courier consumer's logs and sees the courier API responding slowly. They do nothing drastic: they add a second courier consumer instance and watch the queue drain within 20 minutes. Without the dashboard, they would have learned about it only from customers asking why their parcels were not picked up.

Try thisQueue Monitoring Activity

With Lab 3.1 running, stop the consumer, publish 20 messages, and screenshot the queue. Start the consumer with prefetch_count=1, screenshot again after 10 seconds. Then run the script above. Explain each number you see.

Check your understanding
  1. Why can a broken consumer go unnoticed in an asynchronous integration?
  2. A queue shows 0 ready and 250 unacked messages, unchanged for 20 minutes. What is the likely cause?
  3. Write two alert rules you would set for your own Module 3 project.
Show suggested answerHide suggested answerAdded in this edition
  1. Messaging hides failures: messages simply wait in the queue. The producer and the other consumers report no errors, so the only sign is a queue that keeps growing, or a consumer count of 0.
  2. The consumer is stuck mid-processing or never acks (a missing basic_ack on some code path, or a hung call to a downstream system). Check the consumer's code and logs.
  3. For example: "any business queue has 0 consumers for 5 minutes", "any DLQ has messages → alert immediately", "ready messages above 1,000 and rising for 10 minutes", "a resource alarm is active".
Key points

Asynchronous failures are silent; the queue numbers are where they show. Watch ready and unacked counts, consumers, rates, dead-letter queues, and broker alarms. Turn the important ones into alerts, because a queue that keeps growing is an integration that has stopped.

Going deeperoperating RabbitMQOptional on a first read · needed for the labs

A tour of the management UI. The web UI at port 15672 has these main tabs:

TabWhat to look at
OverviewTotals for ready and unacked messages, message rates, node memory and disk, alarms, enabled ports
ConnectionsEach client connection: user, vhost, client library, state (running, blocked), and data rates
ChannelsChannels per connection, prefetch, unacked count per channel, confirm mode
ExchangesAll exchanges with type and bindings; you can publish a test message here
Queues and StreamsEach queue's type, state, ready, unacked, rates, consumers, and policy; you can bind, get messages, purge, or delete
AdminUsers, virtual hosts, permissions, policies, limits

Resource alarms and flow control. RabbitMQ protects itself from running out of memory or disk:

  • Memory alarm: raised when the node uses more than its memory high watermark, by default 0.6, meaning 60% of the detected RAM.
  • Disk alarm: raised when free disk space falls below the limit, by default 50 MB. RabbitMQ's documentation suggests a more conservative setting in production, such as the amount of installed RAM.
  • Effect: while an alarm is active, RabbitMQ blocks all publishing connections in the cluster, shown as blocked in the UI. Consumers keep receiving, so the alarm clears as queues drain. Publishers that use confirms will notice the delay; those that do not may assume messages were sent.

An alarm in production usually means consumers stopped or fell behind, so the queue grew until the node ran short of memory or disk.

Command-line tools.

ToolUsed forExample
rabbitmqctlUsers, permissions, vhosts, policies, listingsrabbitmqctl list_queues -p /store name messages_ready messages_unacknowledged consumers
rabbitmq-diagnosticsHealth checks and troubleshootingrabbitmq-diagnostics status, rabbitmq-diagnostics alarms, rabbitmq-diagnostics ping
rabbitmq-pluginsEnable or disable pluginsrabbitmq-plugins enable rabbitmq_shovel_management
rabbitmq-queuesQuorum queue and stream maintenancerabbitmq-queues quorum_status orders -p /store
rabbitmqadminScriptable client for the HTTP APIrabbitmqadmin list, declare, publish, and get commands

In the lab, run these inside the container: docker exec rabbitmq rabbitmqctl list_queues.

HTTP API. Everything in the UI is also available as JSON, which is how monitoring scripts work:

Shell
curl -u guest:guest http://localhost:15672/api/queues/%2F/orders

(%2F is the URL-encoded name of the default vhost /.) The response includes messages_ready, messages_unacknowledged, consumers, and message rate details.

Users for operations. Management UI access is controlled by user tags, separate from vhost permissions:

TagCan do
managementUse the UI for vhosts the user has permissions on
policymakerAbove, plus manage policies and parameters
monitoringAbove management, plus see all connections, channels, and node data
administratorEverything, including users, vhosts, and permissions

A monitoring dashboard should use a monitoring user, not administrator.

Definitions: the broker's configuration as a file. Users, vhosts, permissions, exchanges, queues, bindings, and policies can be exported to and imported from a JSON definitions file, through the UI (Overview, Export definitions), rabbitmqctl export_definitions <file>, or the HTTP API. Teams keep this file in version control and import it on a new server so every environment has the same topology. It does not contain messages.

Lesson 3.1Lab4 min read

#Lab 3.1: Producer and consumer with RabbitMQ

Integration task

Integrate the ordering system with one receiving system through a queue, then prove the integration survives the receiver being offline, crashing, and receiving bad data.

Goal: send Order Confirmed messages from a producer to a consumer through a durable queue, using manual acknowledgments. Covers the Message Flow Trace, Queue Exercise, Producer-Consumer Lab, and Queue Monitoring Activity.

Requirements: Docker, Python 3.8 or later, and pika 1.3 or later (pip install pika).

1
Step 1: Start RabbitMQ.

This is the command given in RabbitMQ's download guide:

Shell
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:4-management

Port 5672 is for applications (AMQP); port 15672 is the management UI. Open http://localhost:15672 and log in with guest / guest (this default account works only from localhost).

2
Step 2: Create producer.py.
Python
"""Lab 3.1 producer: publishes Order Confirmed messages to a durable queue."""
import json
import sys
import uuid
from datetime import datetime, timezone

import pika

QUEUE = "orders"

connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
channel = connection.channel()

# Declare the queue the consumer reads from (safe to repeat).
channel.queue_declare(queue=QUEUE, durable=True,
                      arguments={"x-queue-type": "quorum"})

# Ask the broker to confirm every message it accepts.
channel.confirm_delivery()

order_id = sys.argv[1] if len(sys.argv) > 1 else "ORD-10421"
order = {
    "orderId": order_id,
    "customerId": "CUST-0087",
    "items": [{"sku": "NB-A5-80", "quantity": 3, "unitPrice": 45.00}],
    "totalAmount": 135.00,
    "currency": "PHP",
}

properties = pika.BasicProperties(
    content_type="application/json",
    delivery_mode=pika.DeliveryMode.Persistent,  # write to disk
    message_id=str(uuid.uuid4()),
    timestamp=int(datetime.now(timezone.utc).timestamp()),
    type="order.confirmed",
)

try:
    channel.basic_publish(exchange="",          # default exchange
                          routing_key=QUEUE,     # = queue name
                          body=json.dumps(order),
                          properties=properties,
                          mandatory=True)
    print(f"[x] Sent {order_id} (message_id={properties.message_id})")
except pika.exceptions.UnroutableError:
    print("[!] Broker could not route the message")
except pika.exceptions.NackError:
    print("[!] Broker refused the message")

connection.close()
3
Step 3: Create consumer.py.
Python
"""Lab 3.1 consumer: processes Order Confirmed messages with manual acks."""
import json
import time

import pika

QUEUE = "orders"

connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
channel = connection.channel()
channel.queue_declare(queue=QUEUE, durable=True,
                      arguments={"x-queue-type": "quorum"})

# Hold at most one unacknowledged message at a time.
channel.basic_qos(prefetch_count=1)


def on_message(ch, method, properties, body):
    try:
        order = json.loads(body)
        if "orderId" not in order or "items" not in order:
            raise ValueError("missing required field")
    except (json.JSONDecodeError, ValueError) as error:
        print(f"[!] Invalid message, rejecting: {error}")
        # Do not requeue: an invalid message will never succeed.
        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
        return

    print(f"[>] Received {order['orderId']} "
          f"(redelivered={method.redelivered})")
    time.sleep(2)  # simulate work, e.g. saving to the database
    ch.basic_ack(delivery_tag=method.delivery_tag)
    print(f"[✓] Done {order['orderId']}")


channel.basic_consume(queue=QUEUE, on_message_callback=on_message,
                      auto_ack=False)
print("[*] Waiting for messages. Press CTRL+C to exit.")
try:
    channel.start_consuming()
except KeyboardInterrupt:
    channel.stop_consuming()
connection.close()
4
Step 4: Run the experiments.

Record what you observe for each.

  1. Basic flow. Start consumer.py, then run python producer.py ORD-1. Trace the message in the management UI (Queues tab, orders).
  2. Receiver offline. Stop the consumer. Run the producer five times with different order IDs. Check the queue's Ready count, then start the consumer and watch it drain.
  3. Competing consumers. Open two consumer terminals and send six orders. Which consumer gets which order?
  4. Crash before ack. Send one order and stop the consumer with CTRL+C during the 2-second sleep. Watch Unacked in the UI, then restart the consumer. Is the message delivered again? What does redelivered show?
  5. Invalid message. In the management UI, publish hello to the orders queue. What does the consumer do, and where does the message go?
  6. Command line. Run docker exec rabbitmq rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers.

Deliverable: a short report with screenshots of each experiment and a one-paragraph explanation of what the acknowledgment did in experiments 4 and 5.

Note

these samples were written against the pika 1.3 API and checked for syntax, but not run against a live broker while preparing these notes. Test them on a lab PC before class.

Lesson 3.1Summary2 min read

#Lesson 3.1 summary

Key takeaways

  • Synchronous calls couple systems in time, availability, and speed. Messaging removes the need for both sides to be online together.
  • Middleware hides communication details; a message broker stores and routes messages between producers and consumers.
  • RabbitMQ is an Erlang-based, open-source broker. A node hosts virtual hosts; applications open one long-lived connection and work on channels inside it; users get configure, write, and read permissions per vhost.
  • In RabbitMQ (AMQP 0-9-1), producers publish to exchanges, bindings route copies to queues, and consumers read from queues. Direct, fanout, topic, and headers exchanges route differently; unroutable messages are dropped unless mandatory or an alternate exchange catches them.
  • Classic queues live on one node, quorum queues replicate across nodes and limit redeliveries, and streams keep messages for replay. RabbitMQ 4.x removed classic mirrored queues.
  • Durable queues plus persistent messages survive a broker restart; you need both. Policies apply TTLs, limits, and dead-lettering without changing code.
  • Message formats are contracts. Version them, add fields safely, and treat renames and removals as breaking changes.
  • Manual acknowledgments and publisher confirms give at-least-once delivery, which means consumers must tolerate duplicates.
  • Watch ready and unacked counts, consumers, and resource alarms; a growing queue is the first sign of trouble.

Review questions

  1. Give two reasons a checkout process might time out in a synchronous design but not in an asynchronous one.
  2. Explain the roles of an exchange, a queue, and a binding, using the online store as your example.
  3. What is the difference between a RabbitMQ connection and a channel? Why should an application not open a new connection for every message?
  4. What is a virtual host? Give one reason a school might create several on one broker.
  5. Which exchange type would you use to send every message to all bound queues? To route on several header values? To let subscribers choose events by pattern?
  6. Why does a message published to the default exchange with routing key orders reach the orders queue?
  7. A message published to a topic exchange disappears. List three possible causes and how the mandatory flag or an alternate exchange would help.
  8. Compare classic, quorum, and stream queues. Which would you use for incoming orders, a live dashboard, and a 7-day order history?
  9. What is the difference between a durable queue and a persistent message?
  10. Why are policies preferred over hard-coded queue arguments for TTLs and dead-lettering?
  11. Compare automatic and manual acknowledgment. Which delivery guarantee does each give?
  12. What does prefetch_count=1 do, and why is it useful in a lab but not always in production?
  13. A consumer receives a message with redelivered=true. What might have happened before?
  14. Write a CloudEvents JSON event for a Sale Recorded event published by the accounting system.
  15. RabbitMQ shows a memory alarm and all publishers are blocked. What happened, and what should operators check first?
  16. A queue has 0 consumers and 5,000 ready messages. List three possible causes and how you would check each.
Lesson 3.2

Event-Driven Integration

  • LO 3.2.1 Implement publish-subscribe communication among integrated applications.
  • LO 3.2.2 Test and manage failures in an event-driven integration solution.
12 parts0 of 12 done
Lesson 3.26 min read

#3.2.1Events and event messages

Integration problem

When the store sends a message, is it telling the warehouse what to do, or announcing what happened? The answer decides how tightly the systems are tied together. Commands tie the sender to one receiver that must obey. Events let any number of systems react without the sender knowing who they are, which is what lets an integration grow.

At 10:00 a.m. the school's PA system says: "Classes are suspended due to the typhoon signal." The principal does not phone each person with instructions. Teachers end their classes, the canteen closes early, parents come to fetch their children, and the guard opens the second gate, each reacting in their own way. The principal does not even need to know who is listening. The announcement is an event: a fact that has happened, broadcast to anyone who cares.

Definitions.

  • An event is a significant change in state, something that has happened in the business: an order was confirmed, a payment failed, a parcel was delivered.
  • An event message is a message that tells other systems about an event. Lesson 3.1 taught how messages travel; this lesson is about messages whose meaning is "this happened."

What makes something an event.

PropertyMeaningIn the online store
A fact in the pastNamed in the past tenseOrderConfirmed, not ConfirmOrder
Cannot be undoneReceivers cannot refuse it; a mistake is corrected by a new eventA wrong order is fixed by OrderCancelled, not by deleting OrderConfirmed
Timestamped and identifiedHas a time and a unique IDtime and id in the CloudEvents envelope (3.1.6)
Sender does not know the receiversZero, one, or many systems may reactThe store does not know analytics was added last month

Events, commands, and documents. Enterprise Integration Patterns separates messages by what the sender intends:

KindIntentNamingExampleReceivers
Command"Please do this."Imperative verbBookDelivery, SendSmsOne specific receiver, expected to act
Event"This happened."Past tenseOrderConfirmed, PaymentSucceededAny number; the sender does not care who
Document"Here is some data."NounCustomerDetailsWhoever receives it decides what to do

Martin Fowler warns against disguising a command as an event, for example publishing CourierPickupNeeded when the store really means "courier, book this now." If the sender expects a particular system to act, say so with a command.

How much data should an event carry? This is one of the first design decisions for every event.

A thin event (Fowler calls this style event notification) says only what happened and which item it was. Receivers call back for details:

JSON
{ "type": "order.confirmed", "orderId": "ORD-10421" }

A fat event (event-carried state transfer) carries the data receivers need, so they never call back:

JSON
{ "type": "order.confirmed", "orderId": "ORD-10421", "customerId": "CUST-0087",
  "items": [{ "sku": "NB-A5-80", "quantity": 3 }], "totalAmount": 260.00,
  "deliveryAddress": "Brgy. Pawing, Palo, Leyte" }
Thin eventFat event
Message sizeSmallLarger
Receivers must call the producer's APIYes, for detailsNo
Works while the producer is offlineNoYes
Risk of exposing too much dataLowHigher; include only what receivers need
Fits the online store becauseThe warehouse, courier, and notification all need items and address, and must work even if the store is down

Fowler's article "What do you mean by 'Event-Driven'?" (2017) also names two related ideas you will hear about: event sourcing, where a system stores every change as an event and rebuilds its current state from them, and CQRS, which separates the model used for writing data from the model used for reading it. Both are ways of designing one system; this module uses events to integrate many.

The online store's events. Listing every event, who produces it, and who reacts is the first step of designing an event-driven integration:

EventProduced byWhenConsumed by
OrderPlacedOnline storeCustomer submits an orderWarehouse (reserve stock)
StockReservedWarehouseStock is set asideOnline store (proceed to payment)
StockUnavailableWarehouseNot enough stockOnline store (cancel, inform customer)
PaymentSucceeded / PaymentFailedOnline store, from the gateway's webhookGateway reports the resultOnline store; accounting
OrderConfirmedOnline storePayment succeededWarehouse, accounting, courier, notification
OrderCancelledOnline storePayment failed or timed outWarehouse (release stock), notification
ParcelPackedWarehouseParcel is readyCourier, notification
ParcelDeliveredCourier systemCustomer receives the parcelOnline store, notification, accounting

Naming events well. Use the business's own words, in the past tense, and be specific. OrderUpdated is a poor event name: updated how? OrderAddressChanged tells receivers exactly what happened.

Common misconceptions
  • "Any message is an event." Only messages that state a fact that happened. A request to do something is a command.
  • "A receiver can reject an event." It can fail to process it, but the fact still happened. Mistakes are corrected with new events.
  • "Fat events are always better." They save callbacks but copy data into more places and can leak information receivers should not have.
Example scenario

In an e-wallet app, sending money could trigger a confirmation SMS, an in-app notification, a fraud check, and an update to the transaction history. An event-driven design publishes one TransferCompleted event, and each feature subscribes to it. Adding a rewards-points feature later means adding one subscriber, with no change to the transfer code. (This illustrates the pattern; it does not describe any company's actual architecture.)

Try this15 minutes, event listing

For your university's enrollment process, list at least eight events in the past tense, such as SubjectsSelected and FeesAssessed. For each, name the system that produces it and the systems that should react.

Check your understanding
  1. Classify as command or event: CancelOrder, OrderCancelled, GenerateInvoice, StockDepleted.
  2. Why is the store's OrderConfirmed better as a fat event than a thin one?
  3. A customer's order was confirmed by mistake. Why can't the store simply delete the OrderConfirmed event, and what should it do instead?
Show suggested answerHide suggested answerAdded in this edition
  1. CancelOrder: command. OrderCancelled: event. GenerateInvoice: command. StockDepleted: event. Imperative verbs are commands; past-tense facts are events.
  2. The warehouse, courier and notification all need the items and the delivery address. A fat event carries them, so the consumers never call back to the store and keep working even when the store is offline. Include only the fields they need.
  3. An event is a fact that has already happened, and other systems may already have acted on it. Deleting it would not undo their actions. Publish a new compensating event, OrderCancelled, so every system can reverse its own work (release stock, void the invoice, cancel the pickup).
Key points

An event is a fact that has happened, named in the past tense, that cannot be undone and is broadcast without knowing the receivers. Commands ask a specific system to act; events let many systems react independently. Decide for each event how much data it carries, and list all events, producers, and consumers before you build.

Lesson 3.26 min read

#3.2.2Event producers and consumers

Integration problem

Once systems are integrated through events, they depend on each other in a new way: not through API calls, but through the shape and meaning of the events. If the store team changes OrderConfirmed carelessly, the warehouse, accounting, courier, and notification can all break at once. Who owns an event, and what must each side do to keep the integration healthy?

The store team tidies its code over the weekend and renames deliveryAddress to shippingAddress in OrderConfirmed. Their own tests pass. On Monday, the courier system books every delivery with an empty address, and the notification service sends texts that say "Your order will be delivered to null." Nobody in the store team knew those systems read that field. This section is about preventing exactly this.

Definitions.

  • An event producer is the system where a business fact happens and is recorded. It is the source of truth for that fact: only the online store can say an order is confirmed; only the courier can say a parcel was delivered.
  • An event consumer is a system that subscribes to an event and reacts with its own logic.

As in 3.1.3, these are roles: the warehouse consumes OrderConfirmed and produces ParcelPacked.

Responsibilities on each side.

The event producer mustThe event consumer must
Publish only after its own data change is saved (see the transactional outbox, 3.2.7)Have its own queue and subscription; never share a queue with another system
Give every event a unique ID and a timestampValidate every event; never trust input blindly
Own the event's name, schema, and versions, and document themUse the event ID to detect duplicates (3.2.7)
Announce breaking changes and publish them as new versionsIgnore fields it does not need (tolerant reader)
Include only business facts, not internal detailsHandle its own failures without affecting other consumers
Never wait for, or depend on, any consumerAvoid calling back to the producer for every event, or the decoupling is lost

What a consumer can do with an event. Reactions fall into four kinds:

ReactionExample in the online store
Update its own dataAccounting records the sale from OrderConfirmed
Start its own processThe warehouse creates a pick-and-pack job
Publish a new eventThe warehouse publishes ParcelPacked when done
Notify a personThe notification service texts the customer

The event is a contract, and the producer owns it. Loose coupling does not mean zero coupling: consumers depend on the event's fields and meaning. Industry practice treats each event like a public API:

  • Document it in a shared place. AsyncAPI is the standard for describing message-driven interfaces, just as OpenAPI is for REST APIs in Module 2. An AsyncAPI document lists channels (where messages go), operations (whether an application sends or receives on a channel), and messages (their payload schemas). A minimal example for the store:
YAML
asyncapi: 3.0.0
info:
  title: Online Store Order Events
  version: 1.0.0
channels:
  orderConfirmed:
    address: order.confirmed
    messages:
      OrderConfirmed:
        $ref: '#/components/messages/OrderConfirmed'
operations:
  publishOrderConfirmed:
    action: send
    channel:
      $ref: '#/channels/orderConfirmed'
components:
  messages:
    OrderConfirmed:
      payload:
        type: object
        required: [orderId, customerId, items, deliveryAddress]
        properties:
          orderId: { type: string }
          customerId: { type: string }
          items: { type: array }
          deliveryAddress: { type: string }
  • Keep an event catalog: a list of every event, its owner, its current version, and its known consumers. Then the store team would have known the courier reads deliveryAddress.
  • Test the contract: consumer-driven contract tests (3.2.9) let each consumer state which fields it relies on, so the producer's build fails before a breaking change ships.

Do not leak the database. A common mistake is publishing an event that mirrors the producer's database table, with internal status codes and column names. Consumers then depend on the producer's internal design, and every database change becomes an integration change. Publish business facts in business terms instead.

Watch the chain. Because consumers can publish new events, one event can set off a chain: OrderConfirmed leads to ParcelPacked, which leads to ShipmentBooked, which leads to a customer text. Fowler notes that in such designs the overall flow is not written in any one program, so it can only be seen by watching the running system. Keep a diagram of your event flows and update it when you add a consumer.

Common misconceptions
  • "With events, systems are fully independent." They are independent in time, not in data: consumers still depend on the event's contract.
  • "Each consumer can tell the producer what to put in the event." The producer owns the event and publishes business facts; it should not add fields that only make sense for one consumer's internal logic.
  • "The consumer should ask the producer for details every time." Then every event becomes a synchronous call again.
Example scenario

The store team wants to change its internal order status codes from numbers (1, 2, 3) to words. Because OrderConfirmed exposes only documented business fields, not the internal status column, no consumer is affected and the change ships the same afternoon. In the Monday-morning story, an event catalog and a contract test would have stopped the rename before it reached production.

Try thisIntegration Flow Mapping, 15 minutes

Draw the online store's event flow: each system as a box, each event as a labeled arrow from producer to consumers. Mark which system is the source of truth for each event. Then add a loyalty-points system: which events does it consume, and does any existing system change?

Check your understanding
  1. Why is the online store, and not the warehouse, the source of truth for OrderConfirmed?
  2. List three producer responsibilities and three consumer responsibilities.
  3. How would an event catalog and a contract test have prevented the Monday-morning surprise?
Show suggested answerHide suggested answerAdded in this edition
  1. The order is confirmed in the store, when the store records the successful payment. Only the system where a fact happens and is recorded can say it happened. The warehouse only learns about it.
  2. Producer, any three: publish only after its own data is saved; give every event a unique ID and timestamp; own and document the schema and versions; announce breaking changes as new versions; publish business facts, not internal details; never depend on consumers. Consumer, any three: have its own queue; validate every event; detect duplicates by ID; ignore unknown fields; handle its own failures; avoid calling back for every event.
  3. The event catalog would have shown that the courier and notification consume deliveryAddress, so the store team would have known about them. A consumer-driven contract test would have failed the store's own build as soon as the field was renamed, before the change reached production.
Key points

The producer is the source of truth for its events and owns their schema, versions, and documentation. Consumers own their queues, validate input, tolerate extra fields, and handle duplicates and failures on their own. Treat every event as a public contract: document it with AsyncAPI, list it in an event catalog, and test it.

Lesson 3.28 min read

#3.2.3Publish-subscribe communication

Integration problem

One business fact, a confirmed order, must reach the warehouse, accounting, courier, and notification systems, and next month an analytics system too. If the store sends a separate message to each, it must know every receiver and change its code for every new one. How do you integrate one sender with many receivers without connecting them one by one?

When you subscribe to a video channel, the creator does not message you personally. They post a video once, and every subscriber is notified. The creator does not know you by name, does not wait for you to watch it, and gains new subscribers without changing anything. You can unsubscribe at any time without asking. That is publish-subscribe.

Definition. In publish-subscribe (pub-sub) communication, a publisher sends each message once to a channel (often called a topic), and the messaging system delivers a copy to every subscriber of that channel. Enterprise Integration Patterns calls this the Publish-Subscribe Channel, in contrast to the Point-to-Point Channel of Lesson 3.1, where each message goes to exactly one receiver.

Point-to-point (3.1.5)Publish-subscribe
Each message reachesOne consumerEvery subscriber
Several receivers meansThey share the workThey each get their own copy
Typical messageA command or task: "pack this order"An event: "this order was confirmed"
Adding a receiverSpeeds up processingAdds a new reaction to the same fact
Store exampleTwo warehouse instances sharing ordersWarehouse, accounting, courier, notification all receiving OrderConfirmed

How it works, step by step.

  1. Each subscribing system registers its interest in a channel (in RabbitMQ, by binding its own queue to an exchange).
  2. The publisher sends one message to the channel.
  3. The broker copies the message to every subscriber.
  4. Each subscriber processes its own copy, at its own pace. One subscriber being slow, offline, or broken does not affect the others.
  5. The publisher is never told who received the message or whether they succeeded.

Pub-sub in RabbitMQ: one queue per subscriber. RabbitMQ builds pub-sub from the parts you already know. The store publishes to the orders exchange; each subscribing system has its own queue bound to that exchange. The exchange copies each message into every bound queue. This gives two levels at once:

  • Between systems: broadcast. Warehouse, accounting, courier, and notification each get a copy.
  • Within one system: competing consumers. If the warehouse runs three instances on warehouse.order-confirmed, each order is packed once, by one of them.

Because every subscriber has a private queue, an offline courier system only lets its own queue grow. The Going deeper part below has the code and a diagram.

Durable and temporary subscriptions. A business subscriber, such as accounting, uses a durable, named queue so events published while it is down wait for it. A live dashboard that only cares about what is happening now can use a temporary queue that disappears when it disconnects; it simply misses events from while it was offline.

The same idea on other platforms.

PlatformPublish toEach subscriber getsNote
RabbitMQAn exchange (fanout or topic)Its own queue bound to the exchangeMessages are removed once acknowledged
Apache KafkaA topic, split into partitionsA consumer group that tracks its own reading positionEvents are kept for a retention period, not deleted when read; order is guaranteed only within a partition
Amazon SNS + SQSAn SNS topicAn SQS queue subscribed to the topic (the "fan-out" pattern)Fully managed
Google Cloud Pub/SubA topicA subscriptionFully managed
Azure Service BusA topicA subscription, optionally with filter rulesFully managed

Kafka is worth a closer look because many large companies use it. Since reading does not delete events, a new consumer group can start from the beginning and replay history, for example to fill a new analytics database with last year's orders.

When pub-sub is the wrong tool.

  • The steps depend on each other. "Reserve stock, then charge, and release the stock if payment fails" needs a saga (3.2.10), not independent subscribers.
  • Exactly one system must act. "Book this delivery" is a command to the courier: use point-to-point.
  • The sender needs the result now. Use a synchronous call (3.1.2).
Common misconceptions
  • "Subscribers can share one queue." Then they would compete, and each would see only some of the events.
  • "All subscribers process the event at the same moment." Each works at its own pace; one may finish hours after another.
  • "The publisher knows whether every subscriber succeeded." It does not. Each subscriber handles and reports its own failures.
Example scenario

After a customer pays, the online store publishes OrderConfirmed to the orders exchange. Four queues are bound to it, one each for the warehouse, accounting, courier, and notification, and each system receives its own copy. Months later, the business adds an analytics dashboard; the analytics team binds a fifth queue to the same exchange. The online store is not changed, retested, or redeployed.

Try thisPublish-Subscribe Exercise

In Lab 3.2, publish one order and confirm that all four services print a result. Then stop notification, publish two more orders, and restart it. Did it catch up? Were the other three affected? Finally, bind a new analytics queue in the management UI and publish again.

Check your understanding
  1. Contrast point-to-point and publish-subscribe using the warehouse as your example.
  2. Why does each subscribing system need its own queue in RabbitMQ?
  3. Give one integration in your school that suits pub-sub and one that does not, and explain why.
Show suggested answerHide suggested answerAdded in this edition
  1. Point-to-point: two warehouse instances share one queue, and each order is packed by only one of them (they split the work). Publish-subscribe: the warehouse, accounting, courier and notification each get their own copy of OrderConfirmed.
  2. If subscribers shared one queue they would compete, and each would see only some of the events. A queue per subscriber gives every system every event, lets each work at its own pace, and means an offline system only fills its own queue.
  3. Suits pub-sub: "StudentEnrolled", which the LMS, library, ID office and accounting each react to on their own. Does not suit it: "assess fees, then pay, then confirm enrollment", which are dependent steps that need a saga. Neither does a single-receiver command like "print this transcript" (point-to-point).
Key points

Publish-subscribe delivers one published message to every subscriber, so one fact can reach many systems without the publisher knowing them. In RabbitMQ, each subscribing system binds its own queue to an exchange; inside a system, instances compete for that queue's messages. Use pub-sub for independent reactions, not for dependent steps or single-receiver commands.

Going deeperpublish-subscribe in RabbitMQ, step by stepOptional on a first read · needed for the labs

The producer side never changes. It publishes to the exchange and does not know how many subscribers exist:

Python
channel.exchange_declare(exchange="orders", exchange_type="topic", durable=True)
channel.basic_publish(exchange="orders", routing_key="order.confirmed",
                      body=json.dumps(event),
                      properties=pika.BasicProperties(
                          content_type="application/json",
                          delivery_mode=pika.DeliveryMode.Persistent,
                          message_id=event["id"]))

Each subscriber declares and binds its own queue. The queue name identifies the subscriber, not the event:

Python
# warehouse service
channel.queue_declare(queue="warehouse.order-confirmed", durable=True,
                      arguments={"x-queue-type": "quorum"})
channel.queue_bind(queue="warehouse.order-confirmed", exchange="orders",
                   routing_key="order.confirmed")

# notification service: interested in all order events
channel.queue_declare(queue="notification.order-events", durable=True,
                      arguments={"x-queue-type": "quorum"})
channel.queue_bind(queue="notification.order-events", exchange="orders",
                   routing_key="order.*")

Who should declare what? A common convention: the producer declares the exchange it publishes to, and each consumer declares its own queue and bindings. In larger systems, the whole topology is declared once by a setup script or imported from a definitions file, and applications only check that it exists. Either way, declarations must match everywhere, or RabbitMQ refuses them with 406 PRECONDITION_FAILED.

Durable vs temporary subscriptions. A business subscriber must use a durable, named queue, so events published while it is down wait for it. A subscriber that only cares about live events, such as an operations dashboard showing orders as they arrive, can use a temporary queue: queue_declare(queue="", exclusive=True). RabbitMQ generates a name such as amq.gen-..., and the queue disappears when the dashboard disconnects. This is how RabbitMQ's official "Publish/Subscribe" tutorial demonstrates fanout.

Scaling a subscriber. Run two copies of the warehouse service. Both consume from warehouse.order-confirmed, so they become competing consumers and each order is handled by only one of them. Pub-sub between services and competing consumers within a service work together, as in the diagram below.

Replay with streams. A normal queue deletes events once they are acked, so a subscriber added next month cannot see last month's orders. If replay is needed, the producer can also publish into a stream (3.1.5). Any number of readers can then read the same stream from any point (first, a timestamp, or next) without each needing its own copy. This is RabbitMQ's answer to the replay feature that makes Kafka popular.

NeedRabbitMQ approachKafka approach
Each service gets every eventOne queue per service bound to an exchangeOne consumer group per service on the topic
Several instances share a service's workCompeting consumers on that service's queueInstances in the same consumer group split the partitions
Read old events againStream with an offsetReset the consumer group's offset
Ordered processing per key (e.g. per customer)Single active consumer, or super streams with partitionsSame key goes to the same partition
Publish-subscribe · one queue per subscriber, competing consumers within one
Figure 3.4Publish-subscribe · one queue per subscriber, competing consumers within one

While notification is offline, its queue holds the messages and the warehouse and accounting keep working. A new subscriber is just a new queue bound to the same exchange.

Lesson 3.25 min read

#3.2.4Event channels and topics

Integration problem

As the integration grows, so does the number of event kinds: orders placed, confirmed, and cancelled; parcels packed and delivered; refunds issued. Accounting needs money-related events, the courier needs parcel events, and analytics wants everything. If every event goes to every system, each one drowns in messages it must ignore. Events need to be organized so that each system can subscribe to exactly what it needs.

You do not get every message in the school. You are in your class group chat, your org's chat, and your family's chat, and you get only what is posted there. Each chat is a channel organized by subject. Joining a new org means joining one more chat, not asking everyone to message you individually.

Definitions.

  • An event channel is a named path that carries events. Enterprise Integration Patterns calls it a Message Channel, and recommends a Datatype Channel: each channel carries one kind of data, so receivers always know what they will get.
  • A topic is a channel organized by subject, such as "order events" or "parcel events." Subscribers choose topics instead of individual senders.

Three ways to lay out channels.

LayoutExampleAdvantageDrawback
One channel for everythingEvery event on one channelSimple to set upEvery consumer receives everything and must throw most of it away
One channel per event typeorder.confirmed, order.cancelled, parcel.packed, each separatePrecise subscriptionsMany channels to create and manage
One channel per business area, with routing keysOne orders topic exchange; routing keys pick the event typePrecise and manageable; new event types need no new channelNeeds a clear naming scheme

RabbitMQ's topic exchange supports the third layout directly, and it is the one used in this module.

How topic routing works in RabbitMQ. Each event is published with a routing key made of words separated by dots, such as order.confirmed or parcel.delivered. Each subscriber binds its queue with a binding key, which may contain two wildcards:

  • * matches exactly one word.
  • # matches zero or more words.

A binding of # receives everything; a binding with no wildcards matches one exact key. A queue receives each message only once, even if several of its bindings match.

Worked example: who receives what?

Routing key publishedWarehouse order.confirmedNotification order.*Accounting payment.#Analytics #
order.placedNoYesNoYes
order.confirmedYesYesNoYes
order.cancelledNoYesNoYes
payment.succeededNoNoYesYes
payment.refund.issuedNoNoYesYes

Designing the online store's topics. A good topic scheme names who owns the event and what happened:

Routing keyProduced byExample subscribers
order.placed, order.confirmed, order.cancelledOnline storeWarehouse, notification, analytics
payment.succeeded, payment.failedOnline store, from gateway webhooksAccounting, analytics
stock.reserved, stock.unavailableWarehouseOnline store
parcel.packedWarehouseCourier, notification
parcel.deliveredCourier systemOnline store, notification, accounting

Naming conventions. No single standard exists, but common industry practice is:

  • A consistent hierarchy, general to specific: <entity>.<event>, or <domain>.<entity>.<event> in larger organizations, such as store.order.confirmed.
  • Events in the past tense, never commands.
  • Lowercase, with one separator style throughout.
  • A version suffix when a breaking change is published, such as order.confirmed.v2, matching the CloudEvents type (3.1.6).
  • Queues named after the consumer and what it consumes, such as warehouse.order-confirmed, so the management UI shows at a glance who is behind.

Filter at the broker, not in the consumer. A consumer could receive every event and ignore the ones it does not need; Enterprise Integration Patterns calls that a Message Filter. It works, but every unwanted message still travels to the consumer and must be read. Binding keys let the broker do the filtering, so each system receives only its own events.

On other platforms. In Kafka, the topic name itself is the channel and there is no routing key, so teams usually create one topic per event type or business area. In Amazon SNS and Azure Service Bus, subscriptions can carry filter rules on message attributes, which plays the role of binding keys.

Common misconceptions
  • "A topic is a queue." A topic is where events are published; each subscriber still needs its own queue.
  • "More channels are always better." Too many makes the integration hard to manage; group related events by business area.
  • "Just bind # to be safe." Then the consumer receives everything and must filter it, defeating the purpose.
Example scenario

A school's learning management system publishes grade.posted, assignment.created, and assignment.due-soon. The mobile app's push service binds assignment.* and grade.posted; the parent portal binds only grade.posted; the registrar's archive binds #. When the LMS later adds attendance.recorded, only the archive receives it, because only the archive subscribed to everything. No other system changes.

Try this10 minutes

Which of these bindings receive order.item.removed: order.*, order.#, *.item.*, #.removed? Then design binding keys for a loyalty-points system that needs confirmed orders and delivered parcels only.

Check your understanding
  1. Compare one channel for everything with one topic exchange plus routing keys.
  2. What is the difference between * and #?
  3. Why is filtering by binding key better than filtering in the consumer?
Show suggested answerHide suggested answerAdded in this edition
  1. With one channel for everything, every consumer receives every event and must throw most of them away. With one topic exchange plus routing keys, each consumer binds only the keys it needs. It is precise, and new event types need no new channel, at the cost of needing a clear naming scheme.
  2. * matches exactly one word; # matches zero or more words. So order.* matches order.confirmed but not order.item.removed, while order.# matches both.
  3. The broker drops unwanted events before they travel to the consumer. That saves network, CPU and queue space, and keeps each consumer's queue focused on its own work.
Key points

Event channels organize events so each system receives only what it needs. RabbitMQ topic exchanges route by dotted routing keys, with * for one word and # for any number. Use a clear, past-tense naming hierarchy, filter at the broker with binding keys, and name queues after their consumers.

Lesson 3.26 min read

#3.2.5Event notifications

Integration problem

Events become useful when someone acts on them. Sometimes the one who must act is another system outside your broker, such as a payment gateway or a partner company. Sometimes it is a person, such as a customer waiting for an SMS. Both are event notifications, and both must be delivered reliably, securely, and only once.

A customer orders at 11:50 p.m. Because of a retry bug, the notification service sends "Your order is confirmed!" three times, at 11:51, 2:14 a.m., and 2:15 a.m. Meanwhile, the courier never receives the order, because the partner's system was not told. Notifications are where an integration meets the outside world, and mistakes there are the ones customers see.

Three kinds of event notification.

KindFrom and toHow it travelsIn the online store
Event notification between internal systemsSystem to system, inside your brokerA thin event; receivers call back for details (3.2.1)parcel.packed tells the courier integration to fetch parcel details
WebhookSystem to an outside system, over HTTPThe sender calls a URL the receiver registeredThe payment gateway calls the store's /webhooks/payment URL
User notificationSystem to a personSMS, email, push notification, in-app message"Your order is confirmed" to the customer

#Webhooks: event notifications across organizations

Your broker is private, so outside partners cannot subscribe to it. Instead they use webhooks: you give the partner a URL, and when an event happens on their side, they send an HTTP POST to that URL with the event in the body. Payment gateways, courier platforms, and e-commerce platforms all use webhooks. In Module 2 you called other systems' APIs; with a webhook, they call yours.

How the store should handle a payment webhook, step by step.

  1. Receive the POST over HTTPS only.
  2. Verify the signature. Providers sign each webhook with a secret you share, typically an HMAC, so you can prove it really came from them and was not altered. Never trust a webhook you have not verified.
  3. Store or publish it quickly, for example as a payment.succeeded event on your broker, and reply 2xx at once. Providers expect a fast answer.
  4. Process it asynchronously, through your normal queues and consumers.
  5. Expect retries and duplicates. If your reply is slow or an error, the provider sends the webhook again, so processing must be idempotent (3.2.7).

A signature check in Python, using an HMAC-SHA256 of the raw body. The header name and exact format differ by provider; follow your provider's documentation.

Python
import hashlib
import hmac

WEBHOOK_SECRET = b"shared-secret-from-the-provider"   # keep in an env variable


def is_genuine(raw_body: bytes, received_signature: str) -> bool:
    """Recompute the HMAC-SHA256 of the raw body and compare safely."""
    expected = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, received_signature)

hmac.compare_digest compares in constant time, which avoids leaking information through timing. Use it instead of ==.

#Notifying people

The notification service in the online store is a consumer like any other: it subscribes to events and turns them into messages for people. A well-built notification service does five things:

  1. Maps each event to a message. For example, order.confirmed becomes "Hi Ana, order ORD-10421 is confirmed. Total: PHP 260.00."
  2. Checks the person's preferences: SMS or email, language, and whether they opted out of non-essential messages.
  3. Chooses priority and timing. A one-time PIN must go out within seconds; a promotional message can wait, and should respect quiet hours.
  4. Sends through a provider, such as an SMS gateway or an email service, and records the provider's delivery status.
  5. Never sends the same notification twice, by recording which event IDs it has already notified on.
EventCustomer messageChannelPriority
order.confirmed"Your order ORD-10421 is confirmed."SMS and emailHigh
parcel.packed"Your order is packed and waiting for the courier."Push or SMSNormal
parcel.delivered"Your parcel was delivered. Rate your order?"EmailNormal
order.cancelled"Payment did not go through; your order was cancelled."SMS and emailHigh

Privacy. Notifications carry personal data: names, phone numbers, addresses, order contents. Under the Data Privacy Act of 2012 (RA 10173), personal data must be processed lawfully and only as needed for its purpose, so send only what the message needs, protect the provider credentials, and check with your institution's data protection officer before sending marketing messages. Security and privacy are covered further in Module 4.

Common misconceptions
  • "A webhook is just an API call, so it is synchronous." The HTTP call is synchronous, but the work should be done asynchronously after a quick 2xx reply.
  • "If the webhook URL is secret, signature checks are unnecessary." URLs leak. Always verify.
  • "Sending the same SMS twice is harmless." It confuses customers, costs money, and erodes trust in the system.
Example scenario

The payment gateway calls the store's webhook URL at 10:15:02. The store verifies the signature, publishes payment.succeeded to its broker, and replies 200 within 50 milliseconds. The gateway's network hiccups, so it does not see the reply and retries at 10:15:32. The store verifies it again, sees that the event ID was already handled, and replies 200 without publishing a second event. The customer gets exactly one confirmation.

Try this15 minutes

Design the notification rules for your school's enrollment system: list four events, the message each should send, the channel, and the priority. Mark which ones must never be sent twice, and which may be skipped if the student opted out.

Check your understanding
  1. Name the three kinds of event notification and give an example of each.
  2. Why should a webhook handler reply quickly and process the event asynchronously?
  3. Why must the notification service record which events it has already notified on?
Show suggested answerHide suggested answerAdded in this edition
  1. Internal event notification (parcel.packed tells the courier integration to fetch details), webhook (the payment gateway POSTs to the store's /webhooks/payment) and user notification ("Your order is confirmed" by SMS or email).
  2. Providers expect a fast 2xx. If the reply is slow, they time out and resend, creating duplicates. Verifying the event, publishing it to the broker and replying at once keeps the webhook reliable; the real work then goes through normal queues with retries.
  3. Under at-least-once delivery, retries and resent webhooks will deliver the same event again. Recording the event IDs already notified is what stops the customer from getting the same text two or three times.
Key points

Event notifications reach other internal systems through the broker, outside systems through webhooks, and people through a notification service. Verify every incoming webhook's signature, reply fast, and process it through your queues. Notify people from events with preferences, priorities, privacy, and exactly one message per event.

Lesson 3.29 min read

#3.2.6Message retries

Integration problem

Integrated systems depend on other systems they do not control: the courier's booking API, an SMS gateway, a bank. These fail for a few minutes at a time. The integration should wait and try again, without hammering the struggling system, without blocking every other message, and without retrying forever something that will never work.

You call a friend and the line is busy. You do not redial every second for an hour; you try again in a minute, then in five, then in fifteen. If the number does not exist, you do not redial at all. And after a few tries, you stop and send a text instead. Good retry logic is just this common sense, written down.

Definitions.

  • A retry is processing a failed message again, later.
  • A retry policy answers three questions: which failures to retry, how long to wait between attempts, and how many attempts before giving up.

Question 1: which failures? Transient vs permanent.

TypeMeaningExamplesRetry?
TransientTemporary; likely to succeed laterNetwork timeout; database deadlock; HTTP 503 Service Unavailable, 502, 504; HTTP 429 Too Many RequestsYes, after a delay
PermanentWill fail every time until someone fixes the data or codeInvalid JSON; missing required field; unknown product SKU; HTTP 400 Bad Request, 404, 422; a business rule broken, such as quantity -5No; send straight to the dead-letter queue (3.2.8)
Needs a personWill fail until configuration changesHTTP 401 or 403: credentials expired or wrongNo; alert someone

A consumer should classify each error before deciding. Retrying a permanent error wastes resources and delays every message behind it.

Question 2: how long to wait? Four strategies.

StrategyWaits (example)StrengthWeakness
Immediate0, 0, 0SimpleThe cause is usually still there; adds load to a struggling system
Fixed delay10 s, 10 s, 10 sEasy to reason aboutToo short for long outages, too long for brief blips
Exponential backoff1 s, 2 s, 4 s, 8 s, 16 s ... up to a capGives a struggling system more and more roomMany clients that failed together retry together
Exponential backoff with jitterRandom amounts within those growing limitsSpreads retries out so they do not arrive in burstsSlightly harder to predict

Why jitter matters: if the courier API goes down at 10:00 and 500 messages fail at once, plain backoff makes all 500 retry at 10:00:01, then 10:00:03, then 10:00:07, in synchronized waves that can knock the API down again. In the AWS Architecture Blog post "Exponential Backoff and Jitter" (Marc Brooker, 2015), adding randomness spread such clients out and reduced the total work. The "Full Jitter" approach from that post is:

sleep=random(0,min(cap,base×2attempt))

With base = 1 second and cap = 60 seconds, the upper limits for attempts 0 to 6 are 1, 2, 4, 8, 16, 32, and 60 seconds; each actual wait is a random time below that limit. If the failing system sends a Retry-After header, as HTTP allows with 429 and 503 responses, respect it.

Question 3: how many attempts? Always set a limit, for example 3 to 5 attempts or a maximum total time such as one hour. After the last attempt, move the message to a dead-letter queue and alert someone (3.2.8). Unlimited retries create the requeue loop from 3.1.7.

Where to retry.

LevelHowUse for
Inside the consumerTry again two or three times within a second, before giving up on this deliveryVery short blips, such as a dropped connection
Through the brokerReject the message; the broker holds it in a wait queue and delivers it again laterOutages of seconds to minutes
Dead-letter and manual replaySet the message aside; a person fixes the cause and replays itLong outages and permanent errors

Do not make the consumer sleep for minutes while holding a message. The message stays unacknowledged, the consumer's prefetch slots stay full, other messages wait, and RabbitMQ may eventually time the delivery out. Long waits belong in the broker, as the Going deeper part below shows.

When retries make things worse: the circuit breaker. If the courier API is completely down, every message will fail, and retrying each one only adds load. Many integrations add a circuit breaker: after a run of failures, the consumer stops calling the failing system for a while (the circuit is "open"), then tries one request to see if it has recovered. This idea, popularized by Michael Nygard's book Release It!, is a standard companion to retries.

Every retry can create a duplicate. If the courier actually booked the delivery but the reply was lost, the retry books it again. Retries are only safe when the consumer is idempotent (3.2.7).

Common misconceptions
  • "Retry everything; it can't hurt." Retrying permanent errors wastes resources and hides bugs.
  • "Requeueing the message is a retry policy." Plain requeueing retries immediately and forever.
  • "Sleeping in the consumer is the simplest way to wait." It blocks the consumer and every message behind it.
Example scenario

The courier consumer calls the courier's booking API, which returns HTTP 503 during the courier's maintenance window. The consumer rejects the message; it waits 10 seconds in a wait queue and comes back. After the third failure, it is moved to the courier's dead-letter queue and an alert is raised. Meanwhile, the warehouse, accounting, and notification process the same order normally, because each has its own queue. When maintenance ends, the team replays the parked messages.

Try this

(1) Using full jitter with base 2 seconds and cap 30 seconds, write the upper limit for attempts 0 to 5. (2) In Lab 3.2, run experiment 5 and record the time between each attempt from the consumer's output.

Check your understanding
  1. For each error, decide "retry" or "dead-letter now": HTTP 503 from the courier API, JSON missing orderId, a database deadlock, HTTP 401 from the SMS gateway, a quantity of -5.
  2. Why does exponential backoff need jitter?
  3. Why should long waits happen in the broker rather than inside the consumer?
Show suggested answerHide suggested answerAdded in this edition
  1. HTTP 503 from the courier: retry (transient). JSON missing orderId: dead-letter now (permanent). Database deadlock: retry. HTTP 401 from the SMS gateway: do not retry; dead-letter and alert a person (credentials must be fixed). Quantity of −5: dead-letter now (breaks a business rule).
  2. Without jitter, every message that failed at the same moment retries at the same moments too: synchronized waves that can knock the recovering system down again. Random delays spread the retries out.
  3. A consumer that sleeps holds the message unacknowledged. That fills its prefetch slots, blocks every message behind it, and risks RabbitMQ's delivery timeout. A wait queue (or delayed retry) in the broker frees the consumer to keep working.
Key points

A retry policy decides which failures to retry, how long to wait, and how many times. Retry only transient failures, with exponential backoff and jitter, and always with a limit after which the message is dead-lettered. Wait in the broker, not in the consumer, and make consumers idempotent because every retry can create a duplicate.

Going deeperretry techniques in RabbitMQ, with codeOptional on a first read · needed for the labs

Technique A: one wait queue (fixed delay). This is the design used in Lab 3.2. The main queue dead-letters rejected messages into a wait queue; the wait queue has a TTL and dead-letters expired messages back:

Python
# main queue -> wait queue on reject
channel.queue_declare(queue="courier.order-confirmed", durable=True, arguments={
    "x-queue-type": "quorum",
    "x-dead-letter-exchange": "",
    "x-dead-letter-routing-key": "courier.order-confirmed.wait"})

# wait queue -> main queue after 10 s
channel.queue_declare(queue="courier.order-confirmed.wait", durable=True, arguments={
    "x-queue-type": "quorum",
    "x-message-ttl": 10000,
    "x-dead-letter-exchange": "",
    "x-dead-letter-routing-key": "courier.order-confirmed"})

The consumer reads the x-death header to count attempts. Each entry records the queue, the reason (rejected, expired, maxlen, or delivery_limit), and a count.

Technique B: tiered wait queues (exponential backoff). Declare several wait queues with growing TTLs, and have the consumer choose one based on the attempt number. Instead of rejecting, it republishes the message to the right tier and acks the original:

AttemptWait queueTTL
1courier.retry.10s10,000 ms
2courier.retry.60s60,000 ms
3courier.retry.5m300,000 ms
4courier.order-confirmed.dlqnone, dead-lettered for good
Python
RETRY_TIERS = ["courier.retry.10s", "courier.retry.60s", "courier.retry.5m"]

def schedule_retry(ch, method, properties, body, attempt):
    headers = dict(properties.headers or {})
    headers["x-attempt"] = attempt
    target = RETRY_TIERS[attempt - 1] if attempt <= len(RETRY_TIERS) else "courier.order-confirmed.dlq"
    ch.basic_publish(exchange="", routing_key=target, body=body,
                     properties=pika.BasicProperties(
                         delivery_mode=pika.DeliveryMode.Persistent,
                         message_id=properties.message_id,
                         headers=headers))
    ch.basic_ack(delivery_tag=method.delivery_tag)  # original is replaced by the copy

Each tier's queue dead-letters back to courier.order-confirmed when its TTL expires. Because the attempt count travels in a custom header, this works the same on every queue type. Note the small risk: if the consumer crashes between publishing the copy and acking the original, the message exists twice, which the idempotent consumer handles (3.2.7).

Technique C: quorum queue delivery limit. With no extra queues at all, a quorum queue counts failed deliveries in x-delivery-count and dead-letters a message once it exceeds delivery-limit (default 20 in RabbitMQ 4.x). This protects against poison messages but retries immediately, with no delay. Set a lower limit by policy:

Shell
rabbitmqctl set_policy -p /store courier-limit "^courier\.order-confirmed$" \
  '{"delivery-limit":5,"dead-letter-exchange":"orders.dlx"}' --apply-to quorum_queues

Technique D: native delayed retry (RabbitMQ 4.3 and later). Quorum queues can delay redeliveries themselves, configured with the policy keys delayed-retry-type, delayed-retry-min, and delayed-retry-max (or matching x- queue arguments). The delay is min(min_delay × delivery_count, max_delay), so it grows linearly with each failure up to the maximum. RabbitMQ's dead-lettering guide recommends this over the TTL-cycle technique for quorum queues, because messages are not rewritten and cannot be lost in transit. It needs a recent broker, so check rabbitmq-diagnostics server_version before relying on it in the lab.

TechniqueDelayExtra queuesWorks on
A. One wait queueFixed1 per serviceAll RabbitMQ versions
B. Tiered wait queuesExponential (in steps)1 per tierAll versions
C. Delivery limitNone0Quorum queues
D. Native delayed retryLinear, capped0Quorum queues, RabbitMQ 4.3+
Lesson 3.29 min read

#3.2.7Duplicate-message handling

Integration problem

Reliable integrations deliver every message at least once, which means a receiving system will sometimes get the same message twice. Accounting must not record the sale twice, the warehouse must not ship twice, and the customer must not get two texts. The sending system also has to save its own data and notify the others without losing either one.

Pressing the elevator call button five times does not bring five elevators. The first press records the request; the extra presses change nothing. That property, where doing something again has no further effect, is called idempotence, and it is the key to handling duplicates in integration.

Why duplicates are normal, not a bug. Under at-least-once delivery (3.1.7), a message is delivered again whenever the broker is not sure it was processed:

  • The consumer finished the work but crashed or lost its connection before the ack reached the broker.
  • The producer published, the broker's confirm was lost in the network, and the producer published again.
  • A retry (3.2.6) replayed a message whose first attempt had actually succeeded.
  • The payment gateway resent a webhook because the store's reply was slow (3.2.5).
  • An operator replayed messages from a dead-letter queue (3.2.8).

Each of these is rare. But if one message in 10,000 is duplicated and the store handles a million messages a month, that is about 100 duplicates a month. At scale, "rare" means "certain."

Definition. An operation is idempotent if performing it several times has the same effect as performing it once. A consumer is idempotent if receiving the same message twice leaves the system in the same state as receiving it once.

You met this in Module 2. The HTTP standard defines GET, PUT, and DELETE as idempotent methods: putting the same resource twice, or deleting it twice, leaves the same result. POST is not idempotent: posting the same order twice creates two orders. The same thinking now applies to messages.

Technique 1: make the operation naturally idempotent. Rewrite the action so repeating it changes nothing:

Not idempotentIdempotent rewrite
"Add PHP 260 to the customer's total spending""Record sale ORD-10421 of PHP 260" (one row per order, keyed by order ID)
"Subtract 3 notebooks from stock""Set the reservation for ORD-10421 to 3 notebooks"
"Increase the loyalty points by 26""Award 26 points for ORD-10421" (once per order)
"Set status to the next stage""Set status of ORD-10421 to PACKED"

Technique 2: the Idempotent Consumer. When the operation cannot be made naturally idempotent, remember which messages were already processed. Enterprise Integration Patterns calls this the Idempotent Receiver; microservices.io calls it the Idempotent Consumer:

  1. Every message carries a unique ID (the message_id property, or the CloudEvents id).
  2. The consumer keeps a processed_messages table with that ID as the primary key.
  3. In one database transaction, the consumer inserts the message ID and makes its business change.
  4. If the insert fails because the ID already exists, the message is a duplicate: skip the work and ack it.

Step 3 is what makes it safe. If the ID were saved separately from the business change, a crash between the two would bring back the problem.

Which ID? Use an ID the producer assigns when the business event happens and reuses on every retry, such as the event's id. An ID generated fresh on each send would make a duplicate look new.

Technique 3: idempotency keys at the edges. When your consumer calls an outside API, the duplicate problem moves there. Payment providers such as Stripe let the caller send an idempotency key with a request, so a retried request does not charge twice. The online store passes the order ID as that key when it calls the payment gateway; the courier integration can do the same when booking deliveries, if the courier's API supports it.

Technique 4: version numbers for updates. When events update the same item, such as a customer's address, a duplicate or late message could overwrite newer data with older. Include a version number or timestamp in the event, and ignore any event older than the version already stored.

The producer side: the transactional outbox. Duplicates are not the only risk. When the online store confirms an order, it must save the order and publish OrderConfirmed. The database and the broker are two different systems and cannot share one transaction, so a crash in between leaves them disagreeing. This is the dual-write problem:

Order of stepsIf the store crashes in betweenResult
Publish, then saveThe event is out, but the order was never savedFour systems act on an order that does not exist
Save, then publishThe order is saved, but no one is toldThe customer paid; nothing ships

The transactional outbox pattern, described by Chris Richardson on microservices.io, solves it. The store writes the event into an outbox table in the same database transaction as the order. A separate message relay reads the outbox and publishes to the broker, then marks each row as sent. If the relay crashes after publishing but before marking, it publishes again, which is one more reason consumers must be idempotent. The code is in the Going deeper part below.

Common misconceptions
  • "We will just turn on exactly-once delivery." Message brokers in general do not guarantee it end-to-end; you get it by combining at-least-once delivery with idempotent consumers.
  • "Duplicates are rare, so we can ignore them." See the arithmetic above.
  • "Two messages with the same content are duplicates." A customer may really order the same items twice. Compare IDs, not content.
Example scenario

The warehouse consumer creates the pick-and-pack job for ORD-10421, commits, and then its server restarts before the ack is sent. RabbitMQ redelivers the message. The consumer tries to insert the message ID into processed_messages, hits a primary-key violation, recognizes the duplicate, and acks without creating a second job. The order is packed once.

Try this15 minutes

For each operation, say whether it is idempotent, and rewrite those that are not: (a) send a "thank you" SMS; (b) set the order status to DELIVERED; (c) add one to the count of orders today; (d) insert an invoice row for ORD-10421 with the order ID as primary key.

Check your understanding
  1. List three ways a duplicate message can arise.
  2. Why must the message ID and the business change be saved in the same transaction?
  3. Explain the dual-write problem and how the transactional outbox solves it.
Show suggested answerHide suggested answerAdded in this edition
  1. Any three of: the consumer finished but crashed before its ack arrived; the broker's publisher confirm was lost, so the producer published again; a retry replayed a message whose first attempt had succeeded; the payment gateway resent a webhook; an operator replayed messages from a DLQ.
  2. If they were saved separately, a crash between the two writes would leave them disagreeing: either the ID is recorded but the work was not done (the message is wrongly skipped as a duplicate), or the work was done but the ID was not recorded (it is done twice on redelivery). One transaction makes them succeed or fail together.
  3. The store must save the order and publish OrderConfirmed, but the database and the broker cannot share a transaction, so a crash in between loses either the event or the order. The transactional outbox writes the event into an outbox table in the same database transaction as the order. A separate relay publishes outbox rows and marks them sent, so nothing is lost, and any re-publish is caught by idempotent consumers.
Key points

At-least-once delivery makes duplicates normal, so every consumer must be idempotent. Make operations naturally idempotent where you can; otherwise record processed message IDs in the same transaction as the business change. Use idempotency keys for outside APIs, and the transactional outbox so producers never lose or invent events.

Going deeperimplementing idempotency and the outboxOptional on a first read · needed for the labs

Idempotent consumer with PostgreSQL. The deduplication record and the business change share one transaction. ON CONFLICT DO NOTHING makes a duplicate insert affect zero rows instead of raising an error:

SQL
CREATE TABLE processed_messages (
    message_id   TEXT PRIMARY KEY,
    processed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE stock_reservations (
    order_id TEXT NOT NULL,
    sku      TEXT NOT NULL,
    quantity INT  NOT NULL CHECK (quantity > 0),
    PRIMARY KEY (order_id, sku)          -- naturally idempotent per order
);
Python
def handle(conn, message_id, order):
    with conn.transaction():         # one transaction (psycopg 3)
        with conn.cursor() as cur:
            cur.execute("INSERT INTO processed_messages (message_id) VALUES (%s) "
                        "ON CONFLICT DO NOTHING", (message_id,))
            if cur.rowcount == 0:
                return "duplicate"   # already processed: caller just acks
            for item in order["items"]:
                cur.execute("INSERT INTO stock_reservations VALUES (%s, %s, %s)",
                            (order["orderId"], item["sku"], item["quantity"]))
    return "processed"

The callback acks the RabbitMQ message only after handle returns. If the process crashes before the commit, nothing is saved and the redelivery is processed normally. If it crashes after the commit but before the ack, the redelivery is recognized as a duplicate.

How long to keep message IDs? Long enough to cover any realistic redelivery or replay, for example 7 to 30 days, then delete old rows with a scheduled job. Duplicates older than the window would be processed again, so the window must exceed the longest time a message could sit in a DLQ before replay.

Transactional outbox: the producer side.

SQL
CREATE TABLE outbox (
    id           UUID PRIMARY KEY,           -- becomes the message_id
    routing_key  TEXT NOT NULL,              -- e.g. 'order.confirmed'
    payload      JSONB NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at TIMESTAMPTZ                 -- NULL until sent
);
Python
# 1. In the ordering service: save the order AND the event together
with conn.transaction():
    with conn.cursor() as cur:
        cur.execute("INSERT INTO orders (...) VALUES (...)", order_values)
        cur.execute("INSERT INTO outbox (id, routing_key, payload) VALUES (%s, %s, %s)",
                    (event_id, "order.confirmed", json.dumps(event)))

# 2. The relay (a separate loop or process): publish unsent rows, oldest first
with conn.transaction():
    with conn.cursor() as cur:
        cur.execute("SELECT id, routing_key, payload FROM outbox "
                    "WHERE published_at IS NULL ORDER BY created_at LIMIT 100 "
                    "FOR UPDATE SKIP LOCKED")
        for event_id, routing_key, payload in cur.fetchall():
            channel.basic_publish(exchange="orders", routing_key=routing_key,
                                  body=json.dumps(payload),
                                  properties=pika.BasicProperties(
                                      message_id=str(event_id),
                                      delivery_mode=pika.DeliveryMode.Persistent),
                                  mandatory=True)   # confirm mode is on
            cur.execute("UPDATE outbox SET published_at = now() WHERE id = %s",
                        (event_id,))

The relay marks a row only after RabbitMQ confirms it (the channel is in confirm mode, so basic_publish returns only after the broker accepts the message). This is the "polling publisher" form of the relay. Large systems often replace polling with change data capture tools such as Debezium, which read the database's transaction log instead.

The outbox's id is reused as the RabbitMQ message_id, so if the relay publishes a row twice, consumers recognize the second copy as a duplicate. Producer and consumer techniques work together.

Lesson 3.28 min read

#3.2.8Failed-message handling

Integration problem

Sometimes one system sends data another system can never accept, such as an order for a product the warehouse system does not know, or retries run out during a long outage. The integration must move that message out of the way so it does not block everything behind it, keep it safely instead of deleting customer data, tell a person, and let it be processed again once the cause is fixed.

When a letter has a wrong address, the post office does not throw it away, and it does not keep trying the same wrong house every day. It moves the letter to a separate shelf for undeliverable mail, notes why it failed, and someone decides whether to correct the address and resend it or return it. Messaging has the same shelf: the dead-letter queue.

Definitions.

  • A failed message is one that cannot be processed successfully, either because it can never succeed or because its retries ran out.
  • A poison message is one that makes its consumer fail every time it is delivered. Left in the queue, it is retried forever, wastes resources, and may crash consumers again and again.
  • A dead letter is a message set aside because it could not be delivered or processed; it goes to a dead-letter queue (DLQ).
  • Enterprise Integration Patterns names two such channels: the Dead Letter Channel for messages the system could not deliver, and the Invalid Message Channel for messages that arrived but make no sense to the receiver.

Why messages fail in an integration.

CauseExample in the online storeType
Bad data from the producerOrderConfirmed with no itemsPermanent
Unknown referenceSKU BAG-TOTE-02 not yet in the warehouse systemPermanent until data is fixed
Contract mismatchStore sent v2 fields; courier consumer expects v1Permanent until code is fixed
Bug in the consumerA crash on names with ñPermanent until code is fixed
Long outageCourier API down for three hours; retries ran outTransient, but exhausted
Message expiredA "rider is nearby" notification older than its TTLExpected
Queue fullLength limit reached during a floodCapacity problem

What to do when a message fails: the decision. Every consumer follows the same logic, drawn in the diagram in the Going deeper part below:

  1. Classify the error (3.2.6). Permanent? Go to step 3.
  2. Transient: retry with backoff. If retries run out, go to step 3.
  3. Dead-letter the message with a record of why, and ack the original so the queue keeps moving.
  4. Alert the team that owns this consumer.

What to record with every dead letter. A person will look at it later, often days later, without context. Keep:

  • the original message, unchanged, including its message_id and correlation_id;
  • why it failed (the error message), where (which queue and consumer), and how many attempts were made;
  • when it first and last failed.

RabbitMQ adds much of this automatically in an x-death header (Going deeper, below); your consumer adds the error reason.

How RabbitMQ dead-letters. A queue can name a dead-letter exchange (DLX). RabbitMQ then dead-letters a message when a consumer rejects it with requeue=False, when its TTL expires, when the queue exceeds its length limit, or when a quorum queue's delivery limit is exceeded. Set the DLX by policy rather than in code, so it can be changed without redeploying. Two cautions from RabbitMQ's documentation: if the DLX does not exist, dead-lettered messages are silently dropped; and classic queues dead-letter without internal confirms, so quorum queues are safer for important data.

Working the dead-letter queue. A DLQ is not a trash can; it is a to-do list. Teams follow a routine:

StepWhat happensExample
1. AlertA message arrives in a DLQ; the owning team is notifiedWarehouse on-call gets an alert at 9:12
2. TriageFind the cause and its scope: one message or a pattern?14 messages, all with SKU BAG-TOTE-02
3. Fix the causeCorrect the data, deploy a code fix, or update configurationWarehouse adds the new SKU
4. Replay or discardMove fixed messages back to the main queue; discard only with a written reasonReplay all 14
5. PreventAdd validation, a contract test, or a monitoring ruleStore now validates SKUs against the warehouse catalog

Messages that cannot be fixed soon can be moved to a separate parking-lot queue, so the DLQ stays clean for new problems.

Before replaying, ask three questions. Is the consumer idempotent, so a replay cannot double-process (3.2.7)? Does order matter, for example a cancellation replayed before its confirmation? And is the message still valid: should a three-day-old order still ship, or should the customer be contacted first?

Who owns the DLQ? The team that owns the consumer. Each consuming system should have its own DLQ, such as warehouse.order-confirmed.dlq, so a problem in one integration is not mixed with another's.

Common misconceptions
  • "The DLQ is where bad messages go to be deleted." It holds real customer orders; each one needs a decision.
  • "One DLQ for the whole company is simpler." Then nobody knows whose problem a message is.
  • "Just replay everything." Replaying without fixing the cause sends the messages straight back to the DLQ, and replaying without idempotency can double-process them.
Example scenario

A new product, SKU BAG-TOTE-02, goes on sale online before the warehouse adds it to its system. The warehouse consumer rejects OrderConfirmed events containing it as "unknown SKU," a permanent error, and they land in warehouse.order-confirmed.dlq without retries. The on-call staff member gets an alert, sees the reason, asks the warehouse to add the SKU, and replays the 14 messages. No order was lost, other products kept flowing normally, and the store team adds a check so the problem cannot recur.

Try thisFailure-Handling Exercise

In Lab 3.2, run experiment 4 (invalid message) and experiment 6 (replay). For the dead-lettered message, write down the five pieces of information a person would need to decide what to do, and find each one in the management UI.

Check your understanding
  1. What is a poison message, and why must it not stay in its queue?
  2. What should be recorded with every dead letter?
  3. Name three questions to ask before replaying messages from a DLQ.
Show suggested answerHide suggested answerAdded in this edition
  1. A message that makes its consumer fail every time. Left in the queue it is retried forever, wastes resources, can crash consumers repeatedly, and blocks the messages behind it. It must be moved aside to a DLQ.
  2. The original message unchanged (including message_id and correlation_id), why it failed (the error), where it failed (queue and consumer), how many attempts were made, and when it first and last failed.
  3. Is the consumer idempotent, so a replay cannot double-process? Does order matter (for example, a cancellation replayed before its confirmation)? Is the message still valid, or should the customer be contacted first?
Key points

Failed messages must be moved aside, not retried forever or silently deleted. Dead-letter permanent failures at once and transient ones after their retries run out, with a record of why. Treat every DLQ as a to-do list owned by its consumer's team: alert, triage, fix the cause, then replay or discard deliberately.

Going deeperworking with dead-letter queues in RabbitMQOptional on a first read · needed for the labs

Setting up dead-lettering with a policy. A common layout is one dead-letter exchange for the system, with routing keys that keep each service's failures separate:

Shell
# 1. A direct exchange for dead letters, and one DLQ per service
rabbitmqadmin declare exchange name=orders.dlx type=direct durable=true
rabbitmqadmin declare queue name=warehouse.order-confirmed.dlq durable=true
rabbitmqadmin declare binding source=orders.dlx destination=warehouse.order-confirmed.dlq routing_key=warehouse

# 2. A policy sends the warehouse queue's dead letters there
rabbitmqctl set_policy warehouse-dlx "^warehouse\.order-confirmed$" \
  '{"dead-letter-exchange":"orders.dlx","dead-letter-routing-key":"warehouse"}' \
  --apply-to queues

(rabbitmqadmin syntax differs between versions; the same objects can be created in the management UI or with pika as in the labs.) Declare the DLX before anything is dead-lettered, because RabbitMQ silently drops messages addressed to a DLX that does not exist.

Inspecting a dead letter. In the management UI, open the DLQ, expand Get messages, choose an ack mode that requeues (such as "Nack message requeue true") so the message is not removed, and click Get Message(s). You see the body and headers. A message dead-lettered by RabbitMQ has an x-death header like this (shown as JSON for readability):

JSON
"x-death": [
  {
    "queue": "warehouse.order-confirmed",
    "reason": "rejected",
    "count": 1,
    "exchange": "orders",
    "routing-keys": ["order.confirmed"],
    "time": "2026-12-03T10:15:07+08:00"
  }
],
"x-first-death-queue": "warehouse.order-confirmed",
"x-first-death-reason": "rejected"

This tells the operator which queue the message failed in, why, how many times, and which exchange and routing key it originally came through, which is enough to replay it to the right place.

Replaying dead letters. After the cause is fixed, move the messages back:

  • Management UI: with the rabbitmq_shovel and rabbitmq_shovel_management plugins enabled, a queue's page shows Move messages; enter the destination queue and RabbitMQ moves everything across.
  • Dynamic shovel from the command line: a shovel copies messages from a source to a destination; src-delete-after: queue-length stops it once the current backlog is moved.
Shell
rabbitmqctl set_parameter shovel replay-warehouse \
  '{"src-protocol":"amqp091","src-uri":"amqp://","src-queue":"warehouse.order-confirmed.dlq",
    "dest-protocol":"amqp091","dest-uri":"amqp://","dest-queue":"warehouse.order-confirmed",
    "src-delete-after":"queue-length"}'
  • A small replay script: useful when messages must be corrected first, for example fixing a wrong SKU before republishing. Replaying is safe only because the consumer is idempotent.

Dead letters in other brokers. The idea is universal; only the names change. Amazon SQS attaches a dead-letter queue through a redrive policy with maxReceiveCount, and offers a redrive feature to move messages back. Azure Service Bus gives every queue and subscription a built-in dead-letter sub-queue. Kafka has no built-in DLQ; applications publish failed records to a separate topic, often named with a .dlq or .DLT suffix.

Retry and dead-letter path · as built in Lab 3.2
Figure 3.5Retry and dead-letter path · as built in Lab 3.2

A transient failure loops through the wait queue at most twice. A permanent failure, or a third failed attempt, goes to the dead-letter queue, where a person decides whether to fix and replay it.

Lesson 3.29 min read

#3.2.9Testing event-driven integrations

Integration problem

In an event-driven integration, no single system shows the whole flow. The store publishes and moves on; four other systems react later, on their own. A bug can hide in the event's format, in the routing, in a consumer, or in how the systems behave together when something fails. You need tests that catch each kind of bug before customers do, without having to start every system in the company for every test.

Why testing is harder here. In a synchronous call, you send a request and check the response right away. With events:

  • The result is somewhere else. The store's test passes when it publishes; whether the courier was booked is visible only in the courier system.
  • The result comes later. A test that checks immediately may fail even though the system is correct. You must wait, with a time limit.
  • The order is not guaranteed, and duplicates are normal, so your tests must include them.
  • Two teams own the two ends. The store team can change an event and break the warehouse team's consumer without either noticing until production.

The levels of testing, from fastest to slowest. Industry practice follows the test pyramid: many small fast tests at the bottom, a few slow broad ones at the top.

LevelWhat it checksNeeds a broker?Example in the online store
Unit testThe handler's logic, given a messageNohandle_order_confirmed books one shipment for a valid order
Contract testThe event matches the agreed schema, on both sidesNoEvery OrderConfirmed the store produces validates against order-confirmed.v1.json; the courier consumer accepts the schema's example
Integration testReal publishing, routing and consuming through a real brokerYes, a test one (for example in Docker)Publish OrderConfirmed; the message appears in all four *.order-confirmed queues
End-to-end testThe whole business flow across systemsYes, plus test copies of the systemsA test order goes from checkout to confirmation email

Unit tests: test the handler without RabbitMQ. Keep your business logic in a plain function that receives the message body, as in Lab 3.2's handle_order_confirmed, and keep pika code thin around it. Then you can test the logic with ordinary pytest. Test at least: a valid message; the same message twice (3.2.7); a message with missing fields (should raise a permanent error); and a failing downstream API (should raise a transient error).

Contract tests: stop one team from breaking another. The event schema from 3.1.6 is the contract. The producer's test checks that every event it builds is valid; the consumer's test checks that it can handle the schema's examples. If the store team adds a required field or renames one, the producer's contract test fails in the store's own pipeline, before any warehouse code sees the change. Tools such as Pact support this style of consumer-driven contract testing for messages.

Integration tests: test the wiring. Many integration bugs are in the plumbing, not the code: a misspelled routing key, a missing binding, a queue declared without a dead-letter exchange. Start a throw-away RabbitMQ (for example with the official Docker image or Testcontainers), declare the real topology, publish, and check where messages land.

Test the failures on purpose. The happy path is the easiest to test and the least likely to break. Plan tests for:

FailureHow to cause itWhat should happen
Consumer downStop the courier consumer, publish, restartMessage waits in the queue; processed after restart
Downstream outageMake the courier API return 503 (SIMULATE_OUTAGE)Retries with delay, then success or DLQ
Invalid messagePublish one with no itemsGoes straight to the DLQ, others keep flowing
DuplicatePublish the same message_id twiceOne shipment booked
Broker restartRestart RabbitMQ with messages queuedDurable queue and persistent messages survive

This idea, injecting failures deliberately to see how the system copes, is the basis of chaos engineering, used by companies such as Netflix in production.

Waiting for asynchronous results. Do not use a fixed sleep(5); it is slow when things are fast and flaky when they are slow. Instead poll with a timeout: check every half second, pass as soon as the result appears, fail after, say, 10 seconds. Tag each test message with its own correlation_id so you check your message and not one from another test.

Common misconceptions
  • "If each system's tests pass, the integration works." The bugs often live between systems: a routing key, a schema change, a missing binding.
  • "End-to-end tests cover everything, so write only those." They are slow, fragile and hard to debug; use them for a few key flows.
  • "We tested the happy path." Integrations fail in the unhappy paths; test them on purpose.
Example scenario

The store team renames total to amount in OrderConfirmed. Without contract tests, the accounting consumer starts failing in production and fills its DLQ. With contract tests, the store's pipeline fails on the change, and the teams agree to publish version 2 alongside version 1 until accounting is updated.

Try thisEvent Flow Testing

Using Lab 3.2: write a unit test that calls handle_order_confirmed twice with the same message_id and asserts only one shipment is recorded; then run the five failure tests in the table above against your broker and record what you observed for each.

Check your understanding
  1. Why is testing an event-driven integration harder than testing a synchronous API call?
  2. What kind of bug does a contract test catch that a unit test does not?
  3. Why should a test poll with a timeout instead of sleeping for a fixed time?
Show suggested answerHide suggested answerAdded in this edition
  1. The result appears in another system, later, possibly out of order or duplicated, and the two ends are owned by different teams. A test cannot simply check a response.
  2. A contract mismatch between teams, such as a renamed, removed or newly required field. Each side's unit tests pass on their own code, but the producer's event no longer matches what the consumer expects.
  3. A fixed sleep is slow when the system is fast and flaky when it is slow. Polling passes as soon as the result appears and fails only after a clear timeout.
Key points

Test at several levels: fast unit tests for handler logic, contract tests for event schemas, integration tests for broker wiring, and a few end-to-end tests for key flows. Deliberately test failures, duplicates and outages, and wait for asynchronous results by polling with a timeout.

Going deepertesting in practiceOptional on a first read · needed for the labs

Unit tests without RabbitMQ. Keep the business logic in its own module, handlers.py, with no pika import:

Python
"""Business logic for the warehouse consumer, kept free of RabbitMQ code."""
import json
import sqlite3


class PermanentError(Exception):
    pass


def init_db(conn):
    conn.execute("CREATE TABLE IF NOT EXISTS processed_messages "
                 "(message_id TEXT PRIMARY KEY)")
    conn.execute("CREATE TABLE IF NOT EXISTS reservations "
                 "(order_id TEXT, sku TEXT, quantity INTEGER, "
                 "PRIMARY KEY (order_id, sku))")


def handle_order_confirmed(conn, message_id, body):
    """Reserve stock once per message. Returns 'processed' or 'duplicate'."""
    try:
        data = json.loads(body)["data"]
        items = data["items"]
        if not items:
            raise ValueError("no items")
    except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
        raise PermanentError(str(error)) from error
    with conn:  # one transaction
        try:
            conn.execute("INSERT INTO processed_messages VALUES (?)",
                         (message_id,))
        except sqlite3.IntegrityError:
            return "duplicate"
        for item in items:
            conn.execute("INSERT INTO reservations VALUES (?, ?, ?)",
                         (data["orderId"], item["sku"], item["quantity"]))
    return "processed"

Then test it with pytest and an in-memory SQLite database. These four tests run in a fraction of a second and need no broker:

Python
import json
import sqlite3

import pytest

from handlers import PermanentError, handle_order_confirmed, init_db

ORDER = json.dumps({"data": {"orderId": "ORD-1",
                             "items": [{"sku": "NB-A5-80", "quantity": 3}]}})


@pytest.fixture
def conn():
    connection = sqlite3.connect(":memory:")
    init_db(connection)
    yield connection
    connection.close()


def reserved(conn):
    return conn.execute("SELECT SUM(quantity) FROM reservations").fetchone()[0]


def test_reserves_stock(conn):
    assert handle_order_confirmed(conn, "msg-1", ORDER) == "processed"
    assert reserved(conn) == 3


def test_duplicate_message_is_ignored(conn):
    handle_order_confirmed(conn, "msg-1", ORDER)
    assert handle_order_confirmed(conn, "msg-1", ORDER) == "duplicate"
    assert reserved(conn) == 3          # not 6


def test_invalid_json_is_permanent_error(conn):
    with pytest.raises(PermanentError):
        handle_order_confirmed(conn, "msg-2", "not json")


def test_empty_items_is_permanent_error(conn):
    body = json.dumps({"data": {"orderId": "ORD-2", "items": []}})
    with pytest.raises(PermanentError):
        handle_order_confirmed(conn, "msg-3", body)

The pika callback then becomes a thin wrapper: call handle_order_confirmed, then basic_ack on success, dead-letter on PermanentError, and retry on transient errors.

Integration tests with a real broker. Testcontainers starts a throwaway RabbitMQ container for the test and removes it afterwards (pip install testcontainers pika, Docker must be running):

Python
import pika
from testcontainers.rabbitmq import RabbitMqContainer


def test_order_confirmed_reaches_every_subscriber():
    with RabbitMqContainer("rabbitmq:4-management") as rabbit:
        conn = pika.BlockingConnection(rabbit.get_connection_params())
        ch = conn.channel()
        ch.exchange_declare(exchange="orders", exchange_type="topic", durable=True)
        for q in ("warehouse.order-confirmed", "accounting.order-confirmed"):
            ch.queue_declare(queue=q, durable=True)
            ch.queue_bind(queue=q, exchange="orders", routing_key="order.confirmed")

        ch.basic_publish(exchange="orders", routing_key="order.confirmed", body=b"{}")

        for q in ("warehouse.order-confirmed", "accounting.order-confirmed"):
            method, _, body = ch.basic_get(queue=q, auto_ack=True)
            assert method is not None, f"{q} received nothing"
        conn.close()

This is one of the few places where basic_get is appropriate: a test that checks a queue's contents once. In longer tests, wrap such checks in a retry loop with a timeout, because consumers process messages asynchronously.

Failure tests with Docker commands. Several items on the checklist above can be run by hand during a lab:

Failure to simulateCommand
Broker restartdocker restart rabbitmq, then check messages are still there
Consumer crash before ackPress CTRL+C during processing, or kill the process
Broker unavailable to the producerdocker stop rabbitmq, run the producer, observe its error handling
Queue filling upStop all consumers and publish many messages; watch the queue and any length limit
Note

the unit tests above were run with pytest while preparing these notes (4 passed). The Testcontainers example was not run here; test it on a lab PC with Docker.

Lesson 3.25 min read

#3.2.10Sagas: keeping dependent steps consistent

This section is an addition beyond the topics listed in the course outline. It is included because the online store's checkout depends on several systems agreeing (stock, payment, order), which is exactly the problem sagas solve. Treat it as enrichment if time is short.

Integration problem

At checkout, three separately owned systems must agree: the store records the order, the warehouse reserves the stock, and the payment gateway collects the money. Each system has its own database, so no single transaction can cover all three. If payment fails after the stock was reserved, the systems disagree, unless the integration undoes the earlier step.

Introduction. Publish-subscribe works when each subscriber can act on its own. But some business processes are a sequence: step 2 should only happen if step 1 succeeded, and a failure at step 3 must undo steps 1 and 2. Across integrated systems, the standard way to do this is a saga.

Discussion: what a saga is. A saga breaks one business transaction into a sequence of local transactions, one per system. Each system commits its own change in its own database, then publishes an event or sends a message that triggers the next step. If a step fails, the saga runs compensating transactions that undo the steps already completed.

Why not one big transaction? A database transaction (with rollback) works inside one database. The store, the warehouse system, and the payment gateway are different systems from different owners, so a distributed transaction across them, such as two-phase commit, is usually not available. Sagas accept this and handle failure explicitly.

Three terms from the Microsoft Azure Architecture Center help you design a saga:

  • Compensable step: a step that can be undone by another action, such as reserving stock (undone by releasing it).
  • Pivot step: the point of no return. Once it succeeds, the saga must run to completion. At checkout, the pivot is the successful payment.
  • Retryable step: a step after the pivot that must eventually succeed, so it is retried until it does. It must be idempotent (3.2.7). Booking the courier is retryable.

Discussion: the checkout saga in the running scenario.

StepSystemActionEvent publishedIf it fails
1Online storeSaves the order as PENDINGOrderPlacedNothing to undo; show an error
2Warehouse systemReserves the stockStockReserved or StockUnavailableStore cancels the order
3Payment gatewayCollects payment; reports by webhook to the storeStore publishes PaymentSucceeded or PaymentFailedCompensate: store publishes OrderCancelled; warehouse releases the stock
4 (pivot passed)Online storeMarks the order CONFIRMEDOrderConfirmedNot allowed to fail back; later steps are retried
5Warehouse, accounting, courier, notificationReact independently (3.2.3)Their own events, such as ShipmentBookedRetries and dead-letter queues (3.2.6, 3.2.8)

Notice that the payment gateway is not a RabbitMQ consumer. It is an outside service that reports back through a webhook, an HTTP call to the store (Module 2). The store turns that webhook into an event. Real integrations often mix synchronous and asynchronous links like this.

Checkout saga, then OrderConfirmed fan-out
Figure 3.6Checkout saga, then OrderConfirmed fan-out

Stock and payment depend on each other, so they run as a saga with a compensating action. Only after payment succeeds does one event fan out to systems that can act independently.

Discussion: choreography or orchestration. There are two ways to coordinate a saga:

ChoreographyOrchestration
How it worksEach system reacts to events and publishes its own; no one is in chargeA central orchestrator tells each system what to do next and tracks the state
StrengthsSimple for a few steps; no extra component; no single point of failureEasier to follow and change as steps grow; clear responsibilities
WeaknessesHard to follow as steps are added; risk of cyclic dependenciesThe orchestrator is extra code to build and must itself be reliable
FitsThe 3-step checkout aboveLong processes such as loan approval or enrollment with many offices

The checkout above is choreographed: the warehouse listens for OrderPlaced and OrderCancelled; the store listens for StockReserved, StockUnavailable, and the gateway's webhook.

Discussion: rules for compensating actions.

  • A compensation is a new business action, not a database rollback. "Release 3 units reserved for ORD-10421" is recorded like any other change.
  • Compensations must be idempotent, because the OrderCancelled event may arrive twice.
  • Plan for timeouts. If the customer never finishes paying, no webhook arrives. The store should cancel orders still PENDING after a set time, such as 15 minutes, and publish OrderCancelled so the stock is released.
  • A compensation can also fail, for example if the warehouse system is down. It is then retried and, if it keeps failing, dead-lettered and alerted like any other message.

Discussion: in RabbitMQ. The same orders topic exchange carries every event. Each system binds only what it handles, for example:

QueueBinding keys
warehouse.order-placedorder.placed
warehouse.order-cancelledorder.cancelled
store.stock-eventsstock.reserved, stock.unavailable
warehouse.order-confirmed, accounting.order-confirmed, courier.order-confirmed, notification.order-confirmedorder.confirmed
Example scenario

A customer orders three notebooks. The warehouse reserves them, and the store redirects the customer to the payment gateway, but the card is declined. The gateway's webhook reports PaymentFailed. The store marks the order CANCELLED and publishes OrderCancelled. The warehouse consumer releases the three notebooks, so another customer can buy them. Accounting, the courier, and notification never hear about the order, because OrderConfirmed was never published.

Check your understanding

In the university enrollment process, which step is the pivot: assessing fees, paying fees, or adding the student to the LMS? What compensation would you need for the steps before it?

Show suggested answerHide suggested answerAdded in this edition

Paying fees is the pivot: once payment succeeds, enrollment must run to completion. Adding the student to the LMS comes after it and is a retryable step. The steps before the pivot need compensations, for example: release the reserved class slots (subject sectioning) and void or cancel the fee assessment if payment fails or times out.

Lesson 3.2Lab8 min read

#Lab 3.2: Event-driven Order Confirmed with retries, dead-letter queues, and idempotency

Integration task

Integrate the ordering system with three receiving systems through events, then prove the integration handles an offline system, duplicate data, bad data, and a temporary outage without losing or double-processing any order.

Goal: publish one Order Confirmed event to four subscribing services, then make the integration survive retries, invalid messages, and duplicates. Covers the Publish-Subscribe Exercise, Failure-Handling Exercise, and Event-Driven Integration Project.

Requirements: RabbitMQ running as in Lab 3.1, Python 3.8 or later, pika 1.3 or later. Each service stores its results in its own SQLite file, so no database server is needed.

Topology. Each service has three queues:

QueuePurpose
<service>.order-confirmedMain queue, bound to the orders topic exchange with order.confirmed
<service>.order-confirmed.waitHolds rejected messages for 10 seconds, then returns them to the main queue
<service>.order-confirmed.dlqMessages that failed permanently or used up their retries

The wait queue sends a message back through the default exchange to its own service's main queue. If it went back through the orders exchange, every subscriber would receive the retried message again.

1
Step 1: Create the topology, setup_topology.py.

Run it once.

Python
"""Lab 3.2: declare exchanges and queues for the Order Confirmed scenario."""
import pika

EXCHANGE = "orders"
SERVICES = ["warehouse", "accounting", "courier", "notification"]
RETRY_DELAY_MS = 10_000  # 10 seconds in the wait queue

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()

# Topic exchange that the online store publishes to.
channel.exchange_declare(exchange=EXCHANGE, exchange_type="topic",
                         durable=True)

for service in SERVICES:
    main_q = f"{service}.order-confirmed"
    wait_q = f"{main_q}.wait"
    dlq = f"{main_q}.dlq"

    # Main queue: a rejected message is dead-lettered to its wait queue.
    channel.queue_declare(queue=main_q, durable=True, arguments={
        "x-queue-type": "quorum",
        "x-dead-letter-exchange": "",            # default exchange
        "x-dead-letter-routing-key": wait_q,
    })
    channel.queue_bind(queue=main_q, exchange=EXCHANGE,
                       routing_key="order.confirmed")

    # Wait queue: no consumers; after the TTL the message returns
    # to this service's main queue only (not to every subscriber).
    channel.queue_declare(queue=wait_q, durable=True, arguments={
        "x-queue-type": "quorum",
        "x-message-ttl": RETRY_DELAY_MS,
        "x-dead-letter-exchange": "",
        "x-dead-letter-routing-key": main_q,
    })

    # Dead-letter queue: messages that failed for good.
    channel.queue_declare(queue=dlq, durable=True,
                          arguments={"x-queue-type": "quorum"})

    print(f"Declared {main_q}, {wait_q}, {dlq}")

connection.close()

In a real deployment, RabbitMQ recommends setting dead-letter options through policies instead of queue arguments, so they can be changed without recreating queues. Arguments are used here so the whole setup is visible in one file.

2
Step 2: Create the producer, publish_order.py.

It publishes a CloudEvents-style event and can also send a duplicate or an invalid message on purpose.

Python
"""Lab 3.2 producer: publishes an Order Confirmed event.

Usage:
  python publish_order.py ORD-1              normal event
  python publish_order.py ORD-2 --duplicate  same event sent twice
  python publish_order.py ORD-3 --invalid    malformed body
"""
import json
import sys
import uuid
from datetime import datetime, timezone

import pika

order_id = sys.argv[1] if len(sys.argv) > 1 else "ORD-1"
flags = sys.argv[2:]

event = {
    "specversion": "1.0",
    "type": "com.example.store.order.confirmed.v1",
    "source": "/store/ordering-service",
    "id": str(uuid.uuid4()),
    "time": datetime.now(timezone.utc).isoformat(),
    "datacontenttype": "application/json",
    "data": {
        "orderId": order_id,
        "customerId": "CUST-0087",
        "items": [{"sku": "NB-A5-80", "quantity": 3, "unitPrice": 45.00}],
        "totalAmount": 135.00,
        "currency": "PHP",
    },
}
body = "this is not json" if "--invalid" in flags else json.dumps(event)

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.confirm_delivery()

properties = pika.BasicProperties(
    content_type="application/json",
    delivery_mode=pika.DeliveryMode.Persistent,
    message_id=event["id"],
    correlation_id=order_id,
)

times = 2 if "--duplicate" in flags else 1
for _ in range(times):
    channel.basic_publish(exchange="orders", routing_key="order.confirmed",
                          body=body, properties=properties, mandatory=True)
    print(f"[x] Published order.confirmed {order_id} id={event['id']}")

connection.close()
3
Step 3: Create the subscriber, service.py.

The same file runs as any of the three services.

Python
"""Lab 3.2 consumer: one subscriber of the Order Confirmed event.

Usage:
  python service.py warehouse
  python service.py accounting
  python service.py courier
  python service.py notification
  SIMULATE_OUTAGE=1 python service.py courier   (transient failures)
"""
import json
import os
import sqlite3
import sys

import pika

MAX_ATTEMPTS = 3


class PermanentError(Exception):
    """Retrying will not help (bad data)."""


class TransientError(Exception):
    """Retrying later may help (outage, timeout)."""


service = sys.argv[1] if len(sys.argv) > 1 else "warehouse"
MAIN_Q = f"{service}.order-confirmed"
DLQ = f"{MAIN_Q}.dlq"

db = sqlite3.connect(f"{service}.db")
db.execute("CREATE TABLE IF NOT EXISTS processed_messages "
           "(message_id TEXT PRIMARY KEY)")
db.execute("CREATE TABLE IF NOT EXISTS results "
           "(order_id TEXT PRIMARY KEY, detail TEXT)")
db.commit()


def parse(body):
    """Decode and validate the event; raise PermanentError if invalid."""
    try:
        event = json.loads(body)
        data = event["data"]
        if not data["orderId"] or not data["items"]:
            raise ValueError("empty orderId or items")
        return event
    except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
        raise PermanentError(f"invalid event: {error}") from error


def handle_order_confirmed(event):
    """Business logic for this service. Returns a short result string."""
    data = event["data"]
    if service == "courier" and os.environ.get("SIMULATE_OUTAGE") == "1":
        raise TransientError("courier booking API returned HTTP 503")
    if service == "warehouse":
        units = sum(item["quantity"] for item in data["items"])
        return f"pick-and-pack job created for {units} units"
    if service == "accounting":
        return f"sale recorded: {data['totalAmount']} {data['currency']}"
    if service == "courier":
        return f"delivery booked for {data['orderId']}"
    return f"confirmation queued for {data['customerId']}"


def failed_attempts(properties):
    """Count earlier rejections of this message from the x-death header."""
    for death in (properties.headers or {}).get("x-death", []):
        if death.get("queue") == MAIN_Q and death.get("reason") == "rejected":
            return int(death.get("count", 0))
    return 0


def send_to_dlq(ch, body, properties, reason):
    # Copy our own headers, but not the broker-managed x-death header.
    headers = {k: v for k, v in (properties.headers or {}).items()
               if k != "x-death"}
    headers["x-failure-reason"] = reason
    headers["x-original-queue"] = MAIN_Q
    headers["x-failed-attempts"] = failed_attempts(properties) + 1
    ch.basic_publish(exchange="", routing_key=DLQ, body=body,
                     properties=pika.BasicProperties(
                         content_type=properties.content_type,
                         delivery_mode=pika.DeliveryMode.Persistent,
                         message_id=properties.message_id,
                         correlation_id=properties.correlation_id,
                         headers=headers))


def on_message(ch, method, properties, body):
    tag = method.delivery_tag
    msg_id = properties.message_id
    try:
        event = parse(body)
        with db:  # one transaction: dedupe record + business result
            try:
                db.execute("INSERT INTO processed_messages VALUES (?)",
                           (msg_id,))
            except sqlite3.IntegrityError:
                print(f"[=] Duplicate {msg_id}, skipping")
                ch.basic_ack(tag)
                return
            result = handle_order_confirmed(event)
            db.execute("INSERT OR REPLACE INTO results VALUES (?, ?)",
                       (event["data"]["orderId"], result))
        print(f"[✓] {event['data']['orderId']}: {result}")
        ch.basic_ack(tag)
    except PermanentError as error:
        print(f"[x] Permanent failure, to DLQ: {error}")
        send_to_dlq(ch, body, properties, str(error))
        ch.basic_ack(tag)
    except TransientError as error:
        attempt = failed_attempts(properties) + 1
        if attempt >= MAX_ATTEMPTS:
            print(f"[x] Attempt {attempt} failed, giving up: {error}")
            send_to_dlq(ch, body, properties, str(error))
            ch.basic_ack(tag)
        else:
            print(f"[!] Attempt {attempt} failed, retrying later: {error}")
            ch.basic_reject(tag, requeue=False)  # goes to the wait queue


connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=MAIN_Q, on_message_callback=on_message)
print(f"[*] {service} waiting on {MAIN_Q}. CTRL+C to exit.")
try:
    channel.start_consuming()
except KeyboardInterrupt:
    channel.stop_consuming()
connection.close()

How the key parts work:

  • Idempotency: the message ID and the business result are written in one SQLite transaction (with db:). A repeated ID fails the primary-key check, so the duplicate is acked and skipped. If processing raises an error, the transaction rolls back, so a retried message is not mistaken for a duplicate.
  • Permanent errors go straight to the DLQ with a reason header, and the original is acked.
  • Transient errors are rejected with requeue=False, wait 10 seconds in the wait queue, and come back. The x-death header tells the consumer how many times the message was already rejected. On the third failure, the message goes to the DLQ.
4
Step 4: Run the experiments.

Open one terminal per service.

  1. Pub-sub. Run setup_topology.py, start all three services, then python publish_order.py ORD-1. Confirm each service prints a result once.
  2. Subscriber offline. Stop notification, publish ORD-2 and ORD-3, then restart it. Did it catch up? Were the other three services affected?
  3. Duplicate. Run python publish_order.py ORD-4 --duplicate. Each service should process it once and print Duplicate once.
  4. Invalid message. Run python publish_order.py ORD-5 --invalid. Find the message in each .dlq queue in the management UI and read its x-failure-reason header.
  5. Transient failure. Restart courier with SIMULATE_OUTAGE=1 (on Windows PowerShell: $env:SIMULATE_OUTAGE="1"), publish ORD-6, and watch the message move between courier.order-confirmed and courier.order-confirmed.wait in the UI. After three attempts it should land in the courier DLQ, while the warehouse, accounting, and notification succeed at once.
  6. Replay. Restart courier without the outage. Use the management UI to move the message from the courier DLQ back to courier.order-confirmed (the UI's move feature needs the rabbitmq_shovel and rabbitmq_shovel_management plugins), or fetch it and republish it by hand. Confirm courier processes it.
  7. Add a subscriber. Bind a new queue analytics.order-confirmed to orders with binding key order.* in the UI. Publish an order. What changed in the producer? (Nothing.)

Deliverables (module output): the three scripts with your own changes, a message-flow diagram of your topology, a test table showing the expected and actual result of each experiment, and screenshots of the queues during experiments 2 and 5.

Note

the consumer logic (idempotency, retry counting, dead-lettering decisions) was checked with a stubbed broker while preparing these notes. The scripts were not run against a live RabbitMQ server. Run them on a lab PC before class.

Lesson 3.2Summary2 min read

#Lesson 3.2 summary

Key takeaways

  • An event states a fact that already happened, named in the past tense. A command asks a specific receiver to act. Do not disguise commands as events.
  • In publish-subscribe, each subscribing application gets its own queue, so one slow subscriber never blocks the others, and new subscribers can be added without changing the producer.
  • Topic exchanges route by dotted routing keys, with * for one word and # for zero or more words.
  • Retry only transient failures, with growing delays and a fixed limit. Send permanent failures straight to a dead-letter queue.
  • At-least-once delivery means duplicates will happen. Make consumers idempotent by recording message IDs in the same transaction as the business change.
  • The transactional outbox solves the producer's dual-write problem between its database and the broker. When steps in different systems depend on each other, use a saga: local steps plus compensating actions, such as releasing reserved stock when payment fails.
  • A dead-letter queue should be empty, monitored, and replayable.
  • Test failures on purpose: offline consumers, crashes before ack, duplicates, and invalid messages.

Review questions

  1. Explain the difference between an event and a command, with one example of each from the online store.
  2. Compare event notification and event-carried state transfer. Which one lets consumers work while the producer is offline?
  3. Why should each subscribing application have its own queue instead of sharing one?
  4. Which queues receive order.cancelled if they are bound with order.confirmed, order.*, and #?
  5. Compare RabbitMQ and Kafka: what happens to a message after it is consumed in each?
  6. Give two transient and two permanent errors a courier consumer might meet, and how each should be handled.
  7. Why does exponential backoff need jitter?
  8. List four situations that cause RabbitMQ to dead-letter a message.
  9. Describe the dual-write problem and how the transactional outbox solves it. Why must consumers still be idempotent?
  10. Design three test cases that prove your event-driven integration handles failure correctly.
Module 33 min read

#Appendix A: RabbitMQ best practices and common mistakes

Integration problem

A messaging integration that works in a demo can still fail in production, from leaked connections, unnoticed lost messages, or a queue that fills the disk. These practices keep the integration between systems reliable over time.

Introduction. Most RabbitMQ problems in class projects and in production come from a short list of mistakes. This section collects them, with the practice that RabbitMQ's documentation recommends instead.

Discussion: connections and channels.

MistakeWhy it hurtsDo this instead
Opening a new connection (or channel) for every messageEach open costs network round trips and broker resources; high "churn" can exhaust the nodeOpen one long-lived connection per process and reuse its channels
Sharing one channel between threadsConcurrent publishing on a shared channel can corrupt frames and close the connectionOne channel per thread
Channels opened but never closed (leaks)Channel count grows until limits are hitClose channels you no longer need; monitor channel counts
No reconnect logicA broker restart or network blip stops the applicationReconnect with backoff and redeclare topology; some clients (Java, .NET) do this automatically, pika does not
Hard-coding one broker addressThe application fails when that node is downGive clients a list of cluster nodes

Discussion: publishing.

  • Use publisher confirms for any message that matters, and treat an unconfirmed message as not sent.
  • Set mandatory=True or configure an alternate exchange so unroutable messages are noticed.
  • Publish business messages as persistent to durable queues; for critical data, use quorum queues.
  • Do not wait for a confirm after every single message in high-volume code; confirm in batches.

Discussion: consuming.

  • Always use manual acks for business data, and ack only after the work is saved.
  • Always set a prefetch. Unlimited prefetch can flood one consumer with the whole queue.
  • Never requeue=True forever on the same error; count attempts and dead-letter (3.2.6, 3.2.8).
  • Make every consumer idempotent (3.2.7), because redelivery will happen.
  • Use basic_consume, not a loop of basic_get.

Discussion: queues and topology.

  • Keep queues short. RabbitMQ works best when queues are near empty. A queue holding millions of messages uses memory and disk, slows recovery after restart, and can trigger alarms. A growing queue is a symptom: add consumers or fix the slow one.
  • Set limits. Use max-length and message-ttl policies on queues where old messages lose value, so a stopped consumer cannot fill the disk.
  • Use policies, not hard-coded arguments, for TTLs, limits, and dead-lettering, so operators can change them without redeploying.
  • Name things consistently, as in 3.2.4, so the management UI is readable.
  • Separate environments with vhosts (for example /store-dev and /store-prod), and give each application its own user with only the permissions it needs.

Discussion: security.

  • Delete or change the guest account; create one user per application.
  • Restrict permissions with the configure/write/read regular expressions.
  • Enable TLS (port 5671) when traffic leaves a trusted network.
  • Keep credentials out of source code, in environment variables or a secret store (Module 4).
Example scenario

Imagine your team's consumer runs fine in testing but falls over during your defense demo. Your code opens a new connection inside the message callback to publish a follow-up event, so every order creates a connection that is never closed. After a few hundred orders, the broker shows hundreds of open connections and the node runs short of resources. The fix is two lines: open the publishing channel once at start-up and reuse it.

Check your understanding

Review your Lab 3.1 code against the four tables and lists above. Which practices does it already follow, and which does it skip?

Show suggested answerHide suggested answerAdded in this edition

Compared with the Lab 3.1 code: it already follows publisher confirms, mandatory=True, a durable quorum queue, persistent messages, manual acks after the work, prefetch_count=1, basic_consume instead of basic_get, and rejecting invalid messages without requeue. It skips reconnect logic, a dead-letter exchange (rejected messages are discarded), idempotency, a dedicated user instead of guest, TLS, and credentials kept outside the code. It also opens a new connection on every producer run, which is fine for a lab script but not for a long-running service.

Module 33 min read

#Glossary

TermMeaning
Acknowledgment (ack)A consumer's signal that it finished a message, so the broker can delete it
Alternate exchange (AE)An exchange that receives messages another exchange could not route
AMQP 0-9-1The messaging protocol used in the labs: exchanges, queues, bindings
AsyncAPISpecification for documenting message-driven APIs, the counterpart of OpenAPI
At-least-once deliveryEvery message is delivered, possibly more than once
BindingA rule linking an exchange to a queue, optionally with a binding key
BrokerMiddleware that receives, stores, routes, and delivers messages
ChannelA lightweight logical connection inside a TCP connection; all AMQP 0-9-1 operations happen on a channel
CloudEventsCNCF specification for common event metadata (id, source, specversion, type)
ClusterSeveral RabbitMQ nodes acting as one broker; metadata is shared, message contents only for replicated queue types
CommandA message asking a specific receiver to do something
Competing consumersSeveral consumers reading one queue, sharing the work
ConnectionA long-lived TCP connection from an application to a RabbitMQ node
ConsumerAn application that receives and processes messages
Correlation IDAn ID that links related messages, such as a reply to its request
Dead-letter exchange / queue (DLX / DLQ)Where messages go after failing, expiring, or being rejected
DefinitionsA JSON export of a broker's users, vhosts, permissions, exchanges, queues, bindings, and policies
Delivery tagA number identifying one delivery on one channel, used to ack it
Durable queueA queue whose definition survives a broker restart
EventA message stating that something already happened
Eventual consistencySystems agree on the data after a short delay, not instantly
ExchangeRabbitMQ component that routes published messages to queues (direct, fanout, topic, headers)
IdempotenceProcessing a message twice gives the same result as processing it once
JitterRandomness added to retry delays so clients do not retry at the same moment
Mandatory flagPublish option asking the broker to return a message it cannot route
MiddlewareSoftware between applications that handles their communication
NodeOne running RabbitMQ server (one Erlang virtual machine)
Persistent messageA message written to disk (delivery_mode=2)
Poison messageA message that makes its consumer fail every time
PolicyA broker-side rule that applies settings (TTL, limits, dead-lettering) to queues or exchanges matched by name
PrefetchLimit on unacknowledged messages a consumer may hold
Producer / publisherAn application that sends messages
Publisher confirmThe broker's acknowledgment to a producer that it accepted a message
Publish-subscribeEach message is delivered to every subscriber
QueueAn ordered buffer that holds messages until consumed
Quorum queueA replicated RabbitMQ queue type based on Raft consensus, with a delivery limit
Resource alarmRabbitMQ blocking publishers because memory or free disk crossed a limit
Routing keyA string on each message that exchanges compare with binding keys
ShovelA RabbitMQ plugin that moves messages from one queue or broker to another
Single active consumerQueue setting where only one consumer receives at a time, others on standby
StreamA RabbitMQ queue type that keeps messages after reading, so they can be replayed
Topic exchangeAn exchange that routes by matching routing keys against patterns
Transactional outboxSaving an event in the same database transaction as the data change, then publishing it separately
TTL (time to live)How long a message may stay in a queue before expiring
Virtual host (vhost)A logical namespace in a broker holding its own exchanges, queues, policies, and permissions
Module 31 min read

#References

Official documentation and specifications checked while writing these notes:

Additional RabbitMQ guides used for the RabbitMQ sections:

Sources for the saga section (3.2.10):

End of Module 3

You've reached the end of Module 3

Next is Module 4: Secure Integration, Testing, and Deployment. It takes the integration you built and makes it safe to run for real customers.

  • Lesson 4.1 Integration Security and Testing
  • Lesson 4.2 Deployment, Monitoring, and Evaluation
0 of 0 Module 3 sections marked done