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.
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.
Implement asynchronous systems integration through messaging and event-driven approaches.
- 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.
- 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.
HTTP and REST APIs, JSON, and data validation (Module 2); basic Python; running a container with Docker.
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.
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.
#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:
- 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.
- 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.
#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:
| System | Owner | Technology (example) | What it needs from the integration |
|---|---|---|---|
| Online store (ordering) | E-commerce team | PHP web application, such as WooCommerce | To know whether stock is available and payment succeeded |
| Payment gateway | Outside provider, such as PayMongo or Maya | Third-party web service | The amount to collect; it reports the result back by webhook |
| Warehouse management system (WMS) | Warehouse office | Java application with its own database | To know which orders to reserve stock for, and which to pick and pack |
| Accounting system | Accounting office | Packaged software, such as QuickBooks or an ERP | To record each confirmed sale and issue the invoice |
| Courier system | Courier partner | The courier's booking API | To know what to pick up and where to deliver it |
| Notification service (supporting) | E-commerce team | Small Python service using an SMS or email gateway | Whom 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 problem | What happens with direct API calls (Module 2) | How messaging solves it | Section |
|---|---|---|---|
| One system is down | The caller's request fails | Messages wait in the down system's queue | 3.1.2, 3.1.5 |
| One system is slow, or traffic spikes | Every caller slows down | The queue absorbs the backlog; the slow system catches up | 3.1.5 |
| Systems use different languages and platforms | Each pair must agree on an API | Every system only talks to the broker using a standard protocol (AMQP) | 3.1.1, 3.1.4 |
| A new system must be added | The sender's code must be changed to call it | The new system binds its own queue; the sender is unchanged | 3.2.3, 3.2.4 |
| Systems have different data formats | Each API maps fields its own way | One agreed message format and schema (a contract) | 3.1.6 |
| Data could be lost in transit or in a crash | The caller may not know whether the call worked | Persistence, publisher confirms, and acknowledgments | 3.1.7 |
| A system receives the same data twice | The sale is recorded twice or the order shipped twice | Idempotent consumers | 3.2.7 |
| A system sends bad data | The receiving system errors on every request | The bad message is dead-lettered for a person to fix | 3.2.6, 3.2.8 |
| Steps in different systems depend on each other | A failure halfway leaves systems disagreeing, such as stock reserved for an unpaid order | A saga with compensating actions | 3.2.10 |
| No one can see where data is stuck | Errors are scattered across logs | Queue monitoring shows which system is behind | 3.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.
#3.1.1Middleware concepts
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.
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:
| Service | What it means | In the online store |
|---|---|---|
| Communication | Moves data between systems over the network using a standard protocol | The store and the warehouse both speak AMQP to the broker, even though one is PHP and the other is Java |
| Location transparency | Senders do not need to know where receivers run | The store sends to "orders," not to the warehouse server's IP address; the warehouse can move to a new server without the store changing |
| Routing | Decides which systems receive which data | Every confirmed order goes to the warehouse, accounting, courier, and notification; refunds go only to accounting |
| Buffering | Holds data when the receiver is busy or down | During the 12.12 rush, orders wait in line instead of failing |
| Reliable delivery | Makes sure data is not lost on the way | An order accepted by the store is stored until the warehouse confirms it processed it |
| Transformation | Converts data from one format to another | The store's orderId becomes the warehouse's order_no |
| Security | Controls who may send and receive what | Only the accounting system may read the accounting queue |
| Monitoring | Shows where data is and where it is stuck | Operators 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:
| Type | How it works | Industry examples | Where it fits in the online store |
|---|---|---|---|
| Remote procedure call (RPC) and web APIs | One system calls a function or endpoint of another and waits for the answer (synchronous) | gRPC, Java RMI, REST over HTTP | The 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 SQS | The store publishes OrderConfirmed; four systems receive it (this module) |
| Event streaming platform | Keeps a long, ordered log of events that many readers can replay | Apache Kafka, Amazon Kinesis | Keeping a year of order events for analytics |
| Enterprise service bus (ESB) and integration platforms | A central hub that routes, transforms, and coordinates data between many systems | MuleSoft Anypoint, WSO2, Apache Camel | A hub that converts store orders into the accounting system's import format |
| API gateway | A single entry point in front of many APIs that adds security, rate limits, and logging | Kong, AWS API Gateway, Azure API Management | Protecting the store's webhook endpoint that the payment gateway calls |
| Database access middleware | A standard driver that lets programs talk to any database | ODBC, JDBC | A 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:
With a broker in the middle, each system needs only one link, to the broker, so n links in total.
| Systems to integrate | Direct links (worst case) | Links through a broker |
|---|---|---|
| 3 | 3 | 3 |
| 5 (the online store's systems) | 10 | 5 |
| 10 | 45 | 10 |
| 20 | 190 | 20 |
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:
| Style | How systems share data | Where you met it |
|---|---|---|
| File Transfer | One system writes a file; another reads it later | Exporting a CSV of orders for accounting to import |
| Shared Database | Systems read and write the same database | Two programs using one MySQL database |
| Remote Procedure Invocation | One system calls a function or API of another | Module 2, REST APIs |
| Messaging | Systems exchange messages through channels managed by middleware | This 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.
- "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.
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.
- Name the middleware services that solved the 12.12 problem in the opening story.
- 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?
- 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
- 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.
- Four systems: up to 4 × 3 ÷ 2 = 6 direct links, but only 4 links through a broker, one per system.
- 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.
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.
#3.1.2Synchronous and asynchronous communication
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.
| Step | Synchronous (Module 2) | Asynchronous (Module 3) |
|---|---|---|
| 1 | Store saves the order | Store saves the order |
| 2 | Store calls the warehouse API and waits | Store publishes one OrderConfirmed message to the broker |
| 3 | Store calls the accounting API and waits | Store shows "Thank you! Your order is confirmed." |
| 4 | Store calls the courier API and waits | Warehouse, accounting, courier, and notification each take the message from their own queue when ready |
| 5 | Store calls the SMS service and waits | If the courier is down, only its message waits; the others finish |
| 6 | Only now does the customer see "Thank you" | |
| If one system is down | The whole checkout fails or hangs | Nothing 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.
| Benefit | What it means for the online store |
|---|---|
| Independence in time | The courier can be offline for an hour; orders still go through |
| Load leveling | 3,000 orders in ten minutes become a queue the warehouse works through at its own steady pace |
| Faster response to the user | The customer gets "Thank you" after one quick publish, not after four API calls |
| Easier to add systems | A 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.
| Aspect | Synchronous | Asynchronous |
|---|---|---|
| Sender waits for the result | Yes | No |
| Both systems online at once | Required | Not required |
| What the user sees | The final result | "Received, being processed" |
| Traffic spikes | Receiver must keep up in real time | Queue absorbs the spike |
| Data consistency | Immediate | Eventual |
| Errors | Caller sees them at once | Surface later; need retries and dead-letter queues |
| Tracing a request | One call chain | Must follow messages across systems |
| Typical integration technology | REST, gRPC, SOAP | Message 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 store | Style | Why |
|---|---|---|
| Customer logs in | Synchronous | The page cannot continue without knowing who the user is |
| Product page shows stock left | Synchronous | The customer needs the number now |
| Store sends the customer to the payment gateway | Synchronous | The customer is actively paying |
| Gateway reports the payment result | Asynchronous (webhook) | The gateway calls back when payment completes |
| Warehouse, accounting, courier, notification learn of the confirmed order | Asynchronous (messages) | None of them is needed to say "Thank you" |
| Monthly sales report | Asynchronous (batch or messages) | Nobody waits on it |
- "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.
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."
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.
- Explain temporal, availability, and performance coupling using the courier as your example.
- Why should the store return HTTP 202 rather than 201 when it hands work to a queue?
- 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
- 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.
- 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.
- 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).
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.
#3.1.3Message producers and consumers
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.
- Detects a business fact or need, such as "order ORD-10421 is paid."
- Builds the message: the body (the order data, usually as JSON) and the properties (a unique message ID, content type, timestamp).
- Publishes it to the broker, naming where it should go (in RabbitMQ, an exchange and a routing key).
- Confirms delivery: waits for the broker to say "I have it" (a publisher confirm, 3.1.7).
- 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.
- Subscribes to a queue and waits for messages.
- Receives a message from the broker.
- Validates it: is it valid JSON, does it have all required fields? Never trust input, even from another internal system.
- Processes it: the business work, such as creating a pick-and-pack job.
- Acknowledges it, telling the broker "done, you may delete it" (3.1.7).
- 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.
# 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:
| Style | How it works | Pattern name | Recommendation |
|---|---|---|---|
| Push | The consumer registers once; the broker sends messages as they arrive | Event-Driven Consumer | The normal choice; RabbitMQ's basic_consume |
| Pull | The consumer asks "any messages?" again and again | Polling Consumer | RabbitMQ's documentation discourages it (basic_get) except for tests or occasional checks |
How producers and consumers can be arranged.
| Arrangement | Example in the online store | Covered in |
|---|---|---|
| One producer, one consumer | The store sends invoice requests to accounting only | 3.1.5 |
| One producer, many consumers sharing the work | Two warehouse instances share one queue of orders (competing consumers) | 3.1.5 |
| One producer, many consumers each getting a copy | OrderConfirmed goes to the warehouse, accounting, courier, and notification | 3.2.3 |
| Many producers, one consumer | The store and the mobile app both send orders to the same warehouse queue | 3.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 know | But both must agree on |
|---|---|
| Which systems will receive the message, or how many | The broker's address and the exchange or queue name |
| Where the receivers run, or in what language | The message format and fields (the contract, 3.1.6) |
| Whether the receivers are online right now | What 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.
- "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.
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."
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?
- Why are producer and consumer described as roles, not types of systems?
- List the five steps a consumer follows, and say what goes wrong if step 3 (validate) is skipped.
- What must a producer and consumer agree on, even though they never talk directly?
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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.
- 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").
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.
#3.1.4Message brokers
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.
| Responsibility | What the broker does | In the online store |
|---|---|---|
| Accept | Receives messages from producers and confirms receipt | Tells the store "I have OrderConfirmed for ORD-10421" |
| Store | Keeps messages, on disk if they must survive a restart | Orders survive a broker reboot during the night |
| Route | Decides which queues receive a copy | Confirmed orders go to four queues; refunds only to accounting's |
| Deliver | Sends messages to consumers, a few at a time | Gives the warehouse consumer its next order |
| Track | Remembers which messages were acknowledged | Deletes an order message only after the warehouse says "done" |
| Redeliver | Re-sends messages whose consumer crashed | Gives the order to another warehouse instance |
| Protect | Authenticates users and checks permissions | Only the accounting system may read the accounting queue |
| Report | Exposes counts and rates | Shows 2,000 orders waiting for the courier |
Brokers used in industry.
| Broker | Type | Notes |
|---|---|---|
| RabbitMQ | Open source, self-hosted or managed (for example Amazon MQ, CloudAMQP) | Flexible routing with exchanges; used in this module's labs |
| Apache ActiveMQ | Open source | Long used in Java enterprise systems (JMS) |
| IBM MQ | Commercial | Common in banks and large enterprises |
| Amazon SQS and SNS | Fully managed cloud services | SQS queues and SNS topics; no servers to run |
| Azure Service Bus | Fully managed cloud service | Queues and topics with subscriptions |
| Google Cloud Pub/Sub | Fully managed cloud service | Topics and subscriptions |
| Apache Kafka | Open source event streaming platform | A 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.
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 type | Routing rule | Use in the online store |
|---|---|---|
| Direct | Routing key must equal the binding key exactly | Sending invoice requests only to accounting's queue |
| Fanout | Every bound queue gets a copy; the key is ignored | Broadcasting a price update to every channel |
| Topic | Routing key matches a pattern such as order.* | Letting each system choose the order events it wants (3.2.4) |
| Headers | Matches message header values instead of the key | Routing 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:
| Question | If 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.
- "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).
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.
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?
- List four responsibilities of a message broker.
- In RabbitMQ, why does a producer publish to an exchange and not to a queue?
- 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
- 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.
- 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.)
- 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.
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.
| Item | Detail |
|---|---|
| Origin | Developed by Rabbit Technologies Ltd., started in 2007 as a joint venture between LShift and CohesiveFT |
| Ownership since | SpringSource / VMware (2010), Pivotal Software (2013), back to VMware (2019); now maintained under Broadcom |
| Written in | Erlang, on the Open Telecom Platform (OTP), a runtime built for telecom systems that must keep running through failures |
| License | Open source, Mozilla Public License |
| Protocols | AMQP 0-9-1 (used in our labs), AMQP 1.0, MQTT, and STOMP, plus a dedicated stream protocol |
| Client libraries | Official 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).
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:
| Code | Meaning | Common cause in labs |
|---|---|---|
| 404 NOT_FOUND | The queue or exchange does not exist | Consumer started before the queue was declared; typo in a name |
| 406 PRECONDITION_FAILED | Redeclared with different properties | Declared orders as durable in one script and non-durable in another; or acked the same message twice |
| 403 ACCESS_REFUSED | User lacks permission | Wrong vhost, or permissions not granted |
| 405 RESOURCE_LOCKED | Queue is exclusive to another connection | Two programs using the same exclusive queue |
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.
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:
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.
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 published | Delivered to |
|---|---|
| invoice | invoice-queue |
| email-queue | |
| sms | Nowhere (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.
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.
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.
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.
| Need | Exchange type |
|---|---|
| Send each message to one specific named queue | Default exchange ("") |
| Route different kinds of work to different workers | Direct |
| Every subscriber receives every message | Fanout |
| Subscribers choose events by category | Topic |
| Route on several message attributes | Headers |
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:
rabbitmqctl set_policy orders-ae "^orders$" '{"alternate-exchange":"orders.unrouted"}' --apply-to exchangesBind 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.
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.
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 raisesUnroutableError. - Configure an alternate exchange on
orderswith 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.
#3.1.5Queues and messages
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.
| Part | Property | Example value | Why it matters for integration |
|---|---|---|---|
| Envelope | message_id | 8f14e45f-ceea-... | Lets receivers detect duplicates (3.2.7) |
| Envelope | content_type | application/json | Tells the receiver how to read the body |
| Envelope | delivery_mode | 2 (persistent) | Asks the broker to write it to disk |
| Envelope | timestamp | 1764728100 | When it was sent; useful for tracing |
| Envelope | correlation_id | ORD-10421 | Links all messages about one order |
| Envelope | type | order.confirmed | What kind of message this is |
| Envelope | headers | {"source": "web-store"} | Any extra custom information |
| Letter | body | {"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:
- Ready: waiting to be delivered.
- Unacknowledged (unacked): delivered to a consumer, which is still working on it.
- 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 |
|---|---|---|
| No | No | Queue and messages are gone |
| No | Yes | Queue is gone, so its messages are gone too |
| Yes | No | Queue exists but is empty |
| Yes | Yes | Queue 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.
- "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.
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.
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?
- Name four properties of an OrderConfirmed message and why each helps the integration.
- Why can competing consumers process messages out of order, and how would you prevent it when order matters?
- A teammate declares a durable queue but publishes non-persistent messages. What happens after a restart?
Show suggested answerHide suggested answerAdded in this edition
- 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) andtype(what kind of message it is). - 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).
- 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.
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:
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 queue | Temporary server-named queue | |
|---|---|---|
| Declared as | queue="warehouse.order-confirmed", durable=True | queue="", exclusive=True |
| Survives consumer restart | Yes; messages wait while it is down | No; deleted with the connection, messages lost |
| Use for | Business consumers that must not miss events (warehouse, accounting) | Live dashboards, debugging tools, cache refreshes where missed messages do not matter |
Common queue arguments.
| Argument | Effect | Example |
|---|---|---|
| x-queue-type | classic, quorum, or stream; fixed at declaration | "quorum" |
| x-message-ttl | Messages expire after this many milliseconds | 60000 |
| x-expires | The queue itself is deleted after being unused this long (ms) | 1800000 |
| x-max-length / x-max-length-bytes | Maximum number of messages / total bytes | 10000 |
| x-overflow | What 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-key | Where expired, rejected, or overflowing messages go | "orders.dlx" |
| x-delivery-limit | Quorum queues: failed deliveries allowed before dead-lettering (default 20 in 4.x) | 5 |
| x-single-active-consumer | Only one consumer receives at a time, others are standby; keeps order | True |
| x-max-priority | Classic queues: enables message priorities up to this number | 10 |
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.
# 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 1Only 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.
| Feature | Classic | Quorum | Stream |
|---|---|---|---|
| Copies of the data | One node | Several nodes (Raft consensus); works while a majority is up | Several nodes |
| After a message is consumed | Deleted | Deleted | Kept until retention removes it; can be re-read |
| Poison-message protection | None built in | Delivery limit (default 20) | Not applicable |
| Exclusive / auto-delete queues | Supported | Not supported | Not supported |
| Best for | Temporary queues, non-critical work, single-node labs | Durable 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.
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 startThis gives RabbitMQ a Kafka-like replay capability, useful when a new reporting service must process every order from the past week.
#3.1.6Message formats
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.
| Format | Strengths | Weaknesses | Where you see it |
|---|---|---|---|
| JSON | Readable, supported by every language, same as REST APIs | Larger; schema is optional unless you add JSON Schema | Most web and cloud integrations |
| XML | Strict schemas (XSD), namespaces, mature tools | Verbose; slower to parse | Banking, government systems, SOAP services |
| CSV | Simple; opens in a spreadsheet | No nesting, no types, delimiter and quoting problems | File transfer integrations and bulk imports |
| Apache Avro | Compact binary with strict versioning rules | Not human-readable; needs tooling | Kafka data pipelines |
| Protocol Buffers | Compact, fast, generates code | Not human-readable; needs .proto files | gRPC 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.
{ "orderId": "ORD-10421", "totalAmount": 260.00, "currency": "PHP" }<order><orderId>ORD-10421</orderId><totalAmount currency="PHP">260.00</totalAmount></order>Data-type traps in integration. Agree on these explicitly in every contract:
| Data | Trap | Industry practice |
|---|---|---|
| Dates and times | 04/12 is ambiguous; time zones get lost | ISO 8601 with a time zone: 2026-12-04T10:15:00+08:00 |
| Money | Floating-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 |
| IDs | Leading zeros lost when treated as numbers (00087 becomes 87) | Send IDs as strings |
| Names | Characters like ñ in "Dela Peña" become garbled | Use UTF-8 everywhere |
| Codes | One system says "PAID," another "paid," another "3" | List allowed values (an enumeration) in the schema |
| Missing data | Is 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:
{
"$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:
| Change | Safe? | What to do |
|---|---|---|
| Add a new optional field | Safe (backward-compatible) | Just add it; old consumers ignore it |
| Remove a field, rename it, or change its type | Breaking | Publish a new version, such as order.confirmed.v2, and keep sending v1 until every consumer has moved |
| Make an optional field required | Breaking for producers that do not send it | Treat 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:
{
"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.
- "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.
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.
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.
- Distinguish format, schema, and contract.
- Why is 04/12/2026 dangerous in an integration, and how should the date be written?
- Is adding an optional voucherCode field to OrderConfirmed a breaking change? Is renaming customerId to buyerId?
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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. - Adding an optional
voucherCodeis not breaking: tolerant readers ignore it. RenamingcustomerIdtobuyerIdis breaking: every consumer that readscustomerIdgets nothing. Publish it as a new version alongside the old one.
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.
#3.1.7Message acknowledgments
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.
| Hop | What can go wrong | Protection | Covered in |
|---|---|---|---|
| 1. Producer to broker | The network drops before the broker receives it, or no queue matches it | Publisher confirms; mandatory flag or alternate exchange | This section; 3.1.4 |
| 2. Inside the broker | The broker server restarts or fails | Durable queues, persistent messages, quorum queues | 3.1.5 |
| 3. Broker to consumer | The consumer crashes or loses its connection mid-processing | Manual consumer acknowledgments | This 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:
| Mode | When the broker deletes the message | Risk | Use for |
|---|---|---|---|
| Automatic ack | As soon as it sends the message | If the consumer crashes, the message is lost; RabbitMQ's documentation calls this mode unsafe for many workloads | Data you can afford to lose, such as live dashboard updates |
| Manual ack | When the consumer sends an ack | The message may be delivered twice if the consumer crashes after finishing but before acking | All business data: orders, invoices, deliveries |
With manual acks, the consumer answers each message in one of three ways:
| Reply | Meaning | What 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 timing | If the consumer crashes in between | Result |
|---|---|---|
| Ack first, then save | The broker already deleted the message; the job was never saved | The order is lost. The customer paid but nothing ships. |
| Save first, then ack | The job is saved; the broker redelivers the message | The 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:
| Guarantee | How you get it | What can happen |
|---|---|---|
| At-most-once | Automatic ack, no publisher confirms | Messages can be lost, never duplicated |
| At-least-once | Publisher confirms, durable and persistent storage, manual ack after processing | Messages are never lost, but may arrive twice |
| Exactly-once | Not guaranteed end-to-end by message brokers in general | Achieved 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).
- "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.
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.
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?
- Name the three hops where a message can be lost and the protection for each.
- Explain why "save first, then ack" is safer than "ack first, then save," and what extra work it creates.
- 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
- 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.
- 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.
- 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.
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:
| Step | What happens | What can go wrong | Protection |
|---|---|---|---|
| 1. Publish | Producer sends the message on a channel to the orders exchange | Network drops before the broker receives it | Publisher confirms; retry unconfirmed messages |
| 2. Route | Exchange compares the routing key with bindings | No binding matches; message silently dropped | mandatory=True, alternate exchange |
| 3. Enqueue | A copy is stored in each matching queue | Broker restarts; node fails | Durable queue, persistent message, quorum queue |
| 4. Confirm | Broker acks the publisher (after writing to disk for persistent messages, or after replicas accept for quorum queues) | Broker under memory or disk alarm blocks publishers | Monitor alarms; handle blocked connections |
| 5. Deliver | Broker pushes the message to a consumer, up to its prefetch limit | Consumer is slow or absent; queue grows | Prefetch, more consumers, monitoring |
| 6. Process | Consumer runs business logic | Crash, bug, invalid data, downstream outage | Manual ack, retries, dead-letter queue |
| 7. Acknowledge | Consumer acks; broker deletes the message | Connection lost before ack; message redelivered | Idempotent consumer |
Acknowledgment calls in pika.
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 onlyThe 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.
#3.1.8Basic queue monitoring
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:
| Metric | What it tells you | Healthy | Warning sign |
|---|---|---|---|
| Ready messages | Messages waiting to be delivered | Rises and falls, returns toward zero | Keeps growing: consumers are too slow, stopped, or missing |
| Unacked messages | Delivered but not yet acknowledged | Small, about consumers × prefetch | Stays high and unchanging: consumers are stuck or forgot to ack |
| Consumers | How many consumers are attached | At least one on every active queue | Zero |
| Publish rate | Messages per second arriving | Follows business activity | Drops to zero during business hours: the producer stopped |
| Deliver and ack rates | Messages per second leaving | Close to the publish rate over time | Far below the publish rate: backlog building |
| Redelivered rate | Messages delivered more than once | Near zero | High: consumers keep crashing or rejecting |
| Dead-letter queue depth | Messages that failed for good | Zero | Anything 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 see | Likely cause | First thing to check |
|---|---|---|
| Ready climbs steadily, consumers = 0 | Consumer crashed or was never started | Is the consumer process running? Its logs? |
| Ready climbs steadily, consumers > 0 | Consumers too slow for the traffic, or a downstream system is slow | Add consumer instances; check the system the consumer calls |
| Ready = 0, unacked high and frozen | Consumer stuck mid-processing or never acks | Consumer code: is basic_ack called on every path? |
| Ready jumps, then drains back to zero | Normal burst, such as the 12.12 sale | Nothing; the queue did its job |
| Publish rate drops to zero | Producer stopped or cannot reach the broker | Producer 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:
"""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:
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 when | For at least | Why |
|---|---|---|
| A business queue has 0 consumers | 5 minutes | A whole integration link is down |
| Ready messages above 1,000 and rising | 10 minutes | Consumers cannot keep up |
| Any dead-letter queue has messages | Immediately | Data needs a person |
| A resource alarm is active | Immediately | All publishing is blocked |
- "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.
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.
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.
- Why can a broken consumer go unnoticed in an asynchronous integration?
- A queue shows 0 ready and 250 unacked messages, unchanged for 20 minutes. What is the likely cause?
- Write two alert rules you would set for your own Module 3 project.
Show suggested answerHide suggested answerAdded in this edition
- 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.
- The consumer is stuck mid-processing or never acks (a missing
basic_ackon some code path, or a hung call to a downstream system). Check the consumer's code and logs. - 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".
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:
| Tab | What to look at |
|---|---|
| Overview | Totals for ready and unacked messages, message rates, node memory and disk, alarms, enabled ports |
| Connections | Each client connection: user, vhost, client library, state (running, blocked), and data rates |
| Channels | Channels per connection, prefetch, unacked count per channel, confirm mode |
| Exchanges | All exchanges with type and bindings; you can publish a test message here |
| Queues and Streams | Each queue's type, state, ready, unacked, rates, consumers, and policy; you can bind, get messages, purge, or delete |
| Admin | Users, 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.
| Tool | Used for | Example |
|---|---|---|
| rabbitmqctl | Users, permissions, vhosts, policies, listings | rabbitmqctl list_queues -p /store name messages_ready messages_unacknowledged consumers |
| rabbitmq-diagnostics | Health checks and troubleshooting | rabbitmq-diagnostics status, rabbitmq-diagnostics alarms, rabbitmq-diagnostics ping |
| rabbitmq-plugins | Enable or disable plugins | rabbitmq-plugins enable rabbitmq_shovel_management |
| rabbitmq-queues | Quorum queue and stream maintenance | rabbitmq-queues quorum_status orders -p /store |
| rabbitmqadmin | Scriptable client for the HTTP API | rabbitmqadmin 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:
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:
| Tag | Can do |
|---|---|
| management | Use the UI for vhosts the user has permissions on |
| policymaker | Above, plus manage policies and parameters |
| monitoring | Above management, plus see all connections, channels, and node data |
| administrator | Everything, 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.
#Lab 3.1: Producer and consumer with RabbitMQ
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.
This is the command given in RabbitMQ's download guide:
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:4-managementPort 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).
"""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()"""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()Record what you observe for each.
- Basic flow. Start consumer.py, then run python producer.py ORD-1. Trace the message in the management UI (Queues tab, orders).
- 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.
- Competing consumers. Open two consumer terminals and send six orders. Which consumer gets which order?
- 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?
- Invalid message. In the management UI, publish hello to the orders queue. What does the consumer do, and where does the message go?
- Command line. Run docker exec rabbitmq rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers.
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.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
- Give two reasons a checkout process might time out in a synchronous design but not in an asynchronous one.
- Explain the roles of an exchange, a queue, and a binding, using the online store as your example.
- What is the difference between a RabbitMQ connection and a channel? Why should an application not open a new connection for every message?
- What is a virtual host? Give one reason a school might create several on one broker.
- 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?
- Why does a message published to the default exchange with routing key orders reach the orders queue?
- A message published to a topic exchange disappears. List three possible causes and how the mandatory flag or an alternate exchange would help.
- Compare classic, quorum, and stream queues. Which would you use for incoming orders, a live dashboard, and a 7-day order history?
- What is the difference between a durable queue and a persistent message?
- Why are policies preferred over hard-coded queue arguments for TTLs and dead-lettering?
- Compare automatic and manual acknowledgment. Which delivery guarantee does each give?
- What does prefetch_count=1 do, and why is it useful in a lab but not always in production?
- A consumer receives a message with redelivered=true. What might have happened before?
- Write a CloudEvents JSON event for a Sale Recorded event published by the accounting system.
- RabbitMQ shows a memory alarm and all publishers are blocked. What happened, and what should operators check first?
- A queue has 0 consumers and 5,000 ready messages. List three possible causes and how you would check each.
#3.2.1Events and event messages
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.
| Property | Meaning | In the online store |
|---|---|---|
| A fact in the past | Named in the past tense | OrderConfirmed, not ConfirmOrder |
| Cannot be undone | Receivers cannot refuse it; a mistake is corrected by a new event | A wrong order is fixed by OrderCancelled, not by deleting OrderConfirmed |
| Timestamped and identified | Has a time and a unique ID | time and id in the CloudEvents envelope (3.1.6) |
| Sender does not know the receivers | Zero, one, or many systems may react | The store does not know analytics was added last month |
Events, commands, and documents. Enterprise Integration Patterns separates messages by what the sender intends:
| Kind | Intent | Naming | Example | Receivers |
|---|---|---|---|---|
| Command | "Please do this." | Imperative verb | BookDelivery, SendSms | One specific receiver, expected to act |
| Event | "This happened." | Past tense | OrderConfirmed, PaymentSucceeded | Any number; the sender does not care who |
| Document | "Here is some data." | Noun | CustomerDetails | Whoever 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:
{ "type": "order.confirmed", "orderId": "ORD-10421" }A fat event (event-carried state transfer) carries the data receivers need, so they never call back:
{ "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 event | Fat event | |
|---|---|---|
| Message size | Small | Larger |
| Receivers must call the producer's API | Yes, for details | No |
| Works while the producer is offline | No | Yes |
| Risk of exposing too much data | Low | Higher; include only what receivers need |
| Fits the online store because | The 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:
| Event | Produced by | When | Consumed by |
|---|---|---|---|
| OrderPlaced | Online store | Customer submits an order | Warehouse (reserve stock) |
| StockReserved | Warehouse | Stock is set aside | Online store (proceed to payment) |
| StockUnavailable | Warehouse | Not enough stock | Online store (cancel, inform customer) |
| PaymentSucceeded / PaymentFailed | Online store, from the gateway's webhook | Gateway reports the result | Online store; accounting |
| OrderConfirmed | Online store | Payment succeeded | Warehouse, accounting, courier, notification |
| OrderCancelled | Online store | Payment failed or timed out | Warehouse (release stock), notification |
| ParcelPacked | Warehouse | Parcel is ready | Courier, notification |
| ParcelDelivered | Courier system | Customer receives the parcel | Online 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.
- "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.
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.)
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.
- Classify as command or event: CancelOrder, OrderCancelled, GenerateInvoice, StockDepleted.
- Why is the store's OrderConfirmed better as a fat event than a thin one?
- 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
- CancelOrder: command. OrderCancelled: event. GenerateInvoice: command. StockDepleted: event. Imperative verbs are commands; past-tense facts are events.
- 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.
- 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).
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.
#3.2.2Event producers and consumers
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 must | The 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 timestamp | Validate every event; never trust input blindly |
| Own the event's name, schema, and versions, and document them | Use the event ID to detect duplicates (3.2.7) |
| Announce breaking changes and publish them as new versions | Ignore fields it does not need (tolerant reader) |
| Include only business facts, not internal details | Handle its own failures without affecting other consumers |
| Never wait for, or depend on, any consumer | Avoid 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:
| Reaction | Example in the online store |
|---|---|
| Update its own data | Accounting records the sale from OrderConfirmed |
| Start its own process | The warehouse creates a pick-and-pack job |
| Publish a new event | The warehouse publishes ParcelPacked when done |
| Notify a person | The 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:
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.
- "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.
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.
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?
- Why is the online store, and not the warehouse, the source of truth for OrderConfirmed?
- List three producer responsibilities and three consumer responsibilities.
- How would an event catalog and a contract test have prevented the Monday-morning surprise?
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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.
- 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.
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.
#3.2.3Publish-subscribe communication
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 reaches | One consumer | Every subscriber |
| Several receivers means | They share the work | They each get their own copy |
| Typical message | A command or task: "pack this order" | An event: "this order was confirmed" |
| Adding a receiver | Speeds up processing | Adds a new reaction to the same fact |
| Store example | Two warehouse instances sharing orders | Warehouse, accounting, courier, notification all receiving OrderConfirmed |
How it works, step by step.
- Each subscribing system registers its interest in a channel (in RabbitMQ, by binding its own queue to an exchange).
- The publisher sends one message to the channel.
- The broker copies the message to every subscriber.
- Each subscriber processes its own copy, at its own pace. One subscriber being slow, offline, or broken does not affect the others.
- 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.
| Platform | Publish to | Each subscriber gets | Note |
|---|---|---|---|
| RabbitMQ | An exchange (fanout or topic) | Its own queue bound to the exchange | Messages are removed once acknowledged |
| Apache Kafka | A topic, split into partitions | A consumer group that tracks its own reading position | Events are kept for a retention period, not deleted when read; order is guaranteed only within a partition |
| Amazon SNS + SQS | An SNS topic | An SQS queue subscribed to the topic (the "fan-out" pattern) | Fully managed |
| Google Cloud Pub/Sub | A topic | A subscription | Fully managed |
| Azure Service Bus | A topic | A subscription, optionally with filter rules | Fully 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).
- "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.
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.
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.
- Contrast point-to-point and publish-subscribe using the warehouse as your example.
- Why does each subscribing system need its own queue in RabbitMQ?
- 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
- 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.
- 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.
- 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).
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:
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:
# 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.
| Need | RabbitMQ approach | Kafka approach |
|---|---|---|
| Each service gets every event | One queue per service bound to an exchange | One consumer group per service on the topic |
| Several instances share a service's work | Competing consumers on that service's queue | Instances in the same consumer group split the partitions |
| Read old events again | Stream with an offset | Reset the consumer group's offset |
| Ordered processing per key (e.g. per customer) | Single active consumer, or super streams with partitions | Same key goes to the same partition |
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.
#3.2.4Event channels and topics
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.
| Layout | Example | Advantage | Drawback |
|---|---|---|---|
| One channel for everything | Every event on one channel | Simple to set up | Every consumer receives everything and must throw most of it away |
| One channel per event type | order.confirmed, order.cancelled, parcel.packed, each separate | Precise subscriptions | Many channels to create and manage |
| One channel per business area, with routing keys | One orders topic exchange; routing keys pick the event type | Precise and manageable; new event types need no new channel | Needs 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 published | Warehouse order.confirmed | Notification order.* | Accounting payment.# | Analytics # |
|---|---|---|---|---|
| order.placed | No | Yes | No | Yes |
| order.confirmed | Yes | Yes | No | Yes |
| order.cancelled | No | Yes | No | Yes |
| payment.succeeded | No | No | Yes | Yes |
| payment.refund.issued | No | No | Yes | Yes |
Designing the online store's topics. A good topic scheme names who owns the event and what happened:
| Routing key | Produced by | Example subscribers |
|---|---|---|
| order.placed, order.confirmed, order.cancelled | Online store | Warehouse, notification, analytics |
| payment.succeeded, payment.failed | Online store, from gateway webhooks | Accounting, analytics |
| stock.reserved, stock.unavailable | Warehouse | Online store |
| parcel.packed | Warehouse | Courier, notification |
| parcel.delivered | Courier system | Online 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.
- "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.
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.
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.
- Compare one channel for everything with one topic exchange plus routing keys.
- What is the difference between * and #?
- Why is filtering by binding key better than filtering in the consumer?
Show suggested answerHide suggested answerAdded in this edition
- 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.
*matches exactly one word;#matches zero or more words. Soorder.*matchesorder.confirmedbut notorder.item.removed, whileorder.#matches both.- 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.
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.
#3.2.5Event notifications
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.
| Kind | From and to | How it travels | In the online store |
|---|---|---|---|
| Event notification between internal systems | System to system, inside your broker | A thin event; receivers call back for details (3.2.1) | parcel.packed tells the courier integration to fetch parcel details |
| Webhook | System to an outside system, over HTTP | The sender calls a URL the receiver registered | The payment gateway calls the store's /webhooks/payment URL |
| User notification | System to a person | SMS, 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.
- Receive the POST over HTTPS only.
- 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.
- 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.
- Process it asynchronously, through your normal queues and consumers.
- 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.
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:
- Maps each event to a message. For example, order.confirmed becomes "Hi Ana, order ORD-10421 is confirmed. Total: PHP 260.00."
- Checks the person's preferences: SMS or email, language, and whether they opted out of non-essential messages.
- Chooses priority and timing. A one-time PIN must go out within seconds; a promotional message can wait, and should respect quiet hours.
- Sends through a provider, such as an SMS gateway or an email service, and records the provider's delivery status.
- Never sends the same notification twice, by recording which event IDs it has already notified on.
| Event | Customer message | Channel | Priority |
|---|---|---|---|
| order.confirmed | "Your order ORD-10421 is confirmed." | SMS and email | High |
| parcel.packed | "Your order is packed and waiting for the courier." | Push or SMS | Normal |
| parcel.delivered | "Your parcel was delivered. Rate your order?" | Normal | |
| order.cancelled | "Payment did not go through; your order was cancelled." | SMS and email | High |
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.
- "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.
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.
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.
- Name the three kinds of event notification and give an example of each.
- Why should a webhook handler reply quickly and process the event asynchronously?
- Why must the notification service record which events it has already notified on?
Show suggested answerHide suggested answerAdded in this edition
- 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).
- 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.
- 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.
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.
#3.2.6Message retries
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.
| Type | Meaning | Examples | Retry? |
|---|---|---|---|
| Transient | Temporary; likely to succeed later | Network timeout; database deadlock; HTTP 503 Service Unavailable, 502, 504; HTTP 429 Too Many Requests | Yes, after a delay |
| Permanent | Will fail every time until someone fixes the data or code | Invalid JSON; missing required field; unknown product SKU; HTTP 400 Bad Request, 404, 422; a business rule broken, such as quantity -5 | No; send straight to the dead-letter queue (3.2.8) |
| Needs a person | Will fail until configuration changes | HTTP 401 or 403: credentials expired or wrong | No; 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.
| Strategy | Waits (example) | Strength | Weakness |
|---|---|---|---|
| Immediate | 0, 0, 0 | Simple | The cause is usually still there; adds load to a struggling system |
| Fixed delay | 10 s, 10 s, 10 s | Easy to reason about | Too short for long outages, too long for brief blips |
| Exponential backoff | 1 s, 2 s, 4 s, 8 s, 16 s ... up to a cap | Gives a struggling system more and more room | Many clients that failed together retry together |
| Exponential backoff with jitter | Random amounts within those growing limits | Spreads retries out so they do not arrive in bursts | Slightly 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:
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.
| Level | How | Use for |
|---|---|---|
| Inside the consumer | Try again two or three times within a second, before giving up on this delivery | Very short blips, such as a dropped connection |
| Through the broker | Reject the message; the broker holds it in a wait queue and delivers it again later | Outages of seconds to minutes |
| Dead-letter and manual replay | Set the message aside; a person fixes the cause and replays it | Long 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).
- "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.
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.
(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.
- 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.
- Why does exponential backoff need jitter?
- Why should long waits happen in the broker rather than inside the consumer?
Show suggested answerHide suggested answerAdded in this edition
- 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).
- 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.
- 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.
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:
# 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:
| Attempt | Wait queue | TTL |
|---|---|---|
| 1 | courier.retry.10s | 10,000 ms |
| 2 | courier.retry.60s | 60,000 ms |
| 3 | courier.retry.5m | 300,000 ms |
| 4 | courier.order-confirmed.dlq | none, dead-lettered for good |
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 copyEach 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:
rabbitmqctl set_policy -p /store courier-limit "^courier\.order-confirmed$" \
'{"delivery-limit":5,"dead-letter-exchange":"orders.dlx"}' --apply-to quorum_queuesTechnique 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.
| Technique | Delay | Extra queues | Works on |
|---|---|---|---|
| A. One wait queue | Fixed | 1 per service | All RabbitMQ versions |
| B. Tiered wait queues | Exponential (in steps) | 1 per tier | All versions |
| C. Delivery limit | None | 0 | Quorum queues |
| D. Native delayed retry | Linear, capped | 0 | Quorum queues, RabbitMQ 4.3+ |
#3.2.7Duplicate-message handling
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 idempotent | Idempotent 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:
- Every message carries a unique ID (the message_id property, or the CloudEvents id).
- The consumer keeps a processed_messages table with that ID as the primary key.
- In one database transaction, the consumer inserts the message ID and makes its business change.
- 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 steps | If the store crashes in between | Result |
|---|---|---|
| Publish, then save | The event is out, but the order was never saved | Four systems act on an order that does not exist |
| Save, then publish | The order is saved, but no one is told | The 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.
- "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.
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.
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.
- List three ways a duplicate message can arise.
- Why must the message ID and the business change be saved in the same transaction?
- Explain the dual-write problem and how the transactional outbox solves it.
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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.
- 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.
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:
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
);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.
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
);# 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.
#3.2.8Failed-message handling
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.
| Cause | Example in the online store | Type |
|---|---|---|
| Bad data from the producer | OrderConfirmed with no items | Permanent |
| Unknown reference | SKU BAG-TOTE-02 not yet in the warehouse system | Permanent until data is fixed |
| Contract mismatch | Store sent v2 fields; courier consumer expects v1 | Permanent until code is fixed |
| Bug in the consumer | A crash on names with ñ | Permanent until code is fixed |
| Long outage | Courier API down for three hours; retries ran out | Transient, but exhausted |
| Message expired | A "rider is nearby" notification older than its TTL | Expected |
| Queue full | Length limit reached during a flood | Capacity 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:
- Classify the error (3.2.6). Permanent? Go to step 3.
- Transient: retry with backoff. If retries run out, go to step 3.
- Dead-letter the message with a record of why, and ack the original so the queue keeps moving.
- 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:
| Step | What happens | Example |
|---|---|---|
| 1. Alert | A message arrives in a DLQ; the owning team is notified | Warehouse on-call gets an alert at 9:12 |
| 2. Triage | Find the cause and its scope: one message or a pattern? | 14 messages, all with SKU BAG-TOTE-02 |
| 3. Fix the cause | Correct the data, deploy a code fix, or update configuration | Warehouse adds the new SKU |
| 4. Replay or discard | Move fixed messages back to the main queue; discard only with a written reason | Replay all 14 |
| 5. Prevent | Add validation, a contract test, or a monitoring rule | Store 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.
- "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.
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.
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.
- What is a poison message, and why must it not stay in its queue?
- What should be recorded with every dead letter?
- Name three questions to ask before replaying messages from a DLQ.
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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.
- 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?
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:
# 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):
"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.
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.
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.
#3.2.9Testing event-driven integrations
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.
| Level | What it checks | Needs a broker? | Example in the online store |
|---|---|---|---|
| Unit test | The handler's logic, given a message | No | handle_order_confirmed books one shipment for a valid order |
| Contract test | The event matches the agreed schema, on both sides | No | Every OrderConfirmed the store produces validates against order-confirmed.v1.json; the courier consumer accepts the schema's example |
| Integration test | Real publishing, routing and consuming through a real broker | Yes, a test one (for example in Docker) | Publish OrderConfirmed; the message appears in all four *.order-confirmed queues |
| End-to-end test | The whole business flow across systems | Yes, plus test copies of the systems | A 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:
| Failure | How to cause it | What should happen |
|---|---|---|
| Consumer down | Stop the courier consumer, publish, restart | Message waits in the queue; processed after restart |
| Downstream outage | Make the courier API return 503 (SIMULATE_OUTAGE) | Retries with delay, then success or DLQ |
| Invalid message | Publish one with no items | Goes straight to the DLQ, others keep flowing |
| Duplicate | Publish the same message_id twice | One shipment booked |
| Broker restart | Restart RabbitMQ with messages queued | Durable 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.
- "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.
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.
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.
- Why is testing an event-driven integration harder than testing a synchronous API call?
- What kind of bug does a contract test catch that a unit test does not?
- Why should a test poll with a timeout instead of sleeping for a fixed time?
Show suggested answerHide suggested answerAdded in this edition
- 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.
- 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.
- 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.
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:
"""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:
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):
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 simulate | Command |
|---|---|
| Broker restart | docker restart rabbitmq, then check messages are still there |
| Consumer crash before ack | Press CTRL+C during processing, or kill the process |
| Broker unavailable to the producer | docker stop rabbitmq, run the producer, observe its error handling |
| Queue filling up | Stop all consumers and publish many messages; watch the queue and any length limit |
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.
#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.
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.
| Step | System | Action | Event published | If it fails |
|---|---|---|---|---|
| 1 | Online store | Saves the order as PENDING | OrderPlaced | Nothing to undo; show an error |
| 2 | Warehouse system | Reserves the stock | StockReserved or StockUnavailable | Store cancels the order |
| 3 | Payment gateway | Collects payment; reports by webhook to the store | Store publishes PaymentSucceeded or PaymentFailed | Compensate: store publishes OrderCancelled; warehouse releases the stock |
| 4 (pivot passed) | Online store | Marks the order CONFIRMED | OrderConfirmed | Not allowed to fail back; later steps are retried |
| 5 | Warehouse, accounting, courier, notification | React independently (3.2.3) | Their own events, such as ShipmentBooked | Retries 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.
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:
| Choreography | Orchestration | |
|---|---|---|
| How it works | Each system reacts to events and publishes its own; no one is in charge | A central orchestrator tells each system what to do next and tracks the state |
| Strengths | Simple for a few steps; no extra component; no single point of failure | Easier to follow and change as steps grow; clear responsibilities |
| Weaknesses | Hard to follow as steps are added; risk of cyclic dependencies | The orchestrator is extra code to build and must itself be reliable |
| Fits | The 3-step checkout above | Long 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:
| Queue | Binding keys |
|---|---|
| warehouse.order-placed | order.placed |
| warehouse.order-cancelled | order.cancelled |
| store.stock-events | stock.reserved, stock.unavailable |
| warehouse.order-confirmed, accounting.order-confirmed, courier.order-confirmed, notification.order-confirmed | order.confirmed |
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.
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.
#Lab 3.2: Event-driven Order Confirmed with retries, dead-letter queues, and idempotency
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.
Topology. Each service has three queues:
| Queue | Purpose |
|---|---|
| <service>.order-confirmed | Main queue, bound to the orders topic exchange with order.confirmed |
| <service>.order-confirmed.wait | Holds rejected messages for 10 seconds, then returns them to the main queue |
| <service>.order-confirmed.dlq | Messages 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.
Run it once.
"""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.
It publishes a CloudEvents-style event and can also send a duplicate or an invalid message on purpose.
"""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()The same file runs as any of the three services.
"""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.
Open one terminal per service.
- Pub-sub. Run setup_topology.py, start all three services, then python publish_order.py ORD-1. Confirm each service prints a result once.
- Subscriber offline. Stop notification, publish ORD-2 and ORD-3, then restart it. Did it catch up? Were the other three services affected?
- Duplicate. Run python publish_order.py ORD-4 --duplicate. Each service should process it once and print Duplicate once.
- 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.
- 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.
- 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.
- 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.)
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.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
- Explain the difference between an event and a command, with one example of each from the online store.
- Compare event notification and event-carried state transfer. Which one lets consumers work while the producer is offline?
- Why should each subscribing application have its own queue instead of sharing one?
- Which queues receive order.cancelled if they are bound with order.confirmed, order.*, and #?
- Compare RabbitMQ and Kafka: what happens to a message after it is consumed in each?
- Give two transient and two permanent errors a courier consumer might meet, and how each should be handled.
- Why does exponential backoff need jitter?
- List four situations that cause RabbitMQ to dead-letter a message.
- Describe the dual-write problem and how the transactional outbox solves it. Why must consumers still be idempotent?
- Design three test cases that prove your event-driven integration handles failure correctly.
#Appendix A: RabbitMQ best practices and common mistakes
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.
| Mistake | Why it hurts | Do this instead |
|---|---|---|
| Opening a new connection (or channel) for every message | Each open costs network round trips and broker resources; high "churn" can exhaust the node | Open one long-lived connection per process and reuse its channels |
| Sharing one channel between threads | Concurrent publishing on a shared channel can corrupt frames and close the connection | One channel per thread |
| Channels opened but never closed (leaks) | Channel count grows until limits are hit | Close channels you no longer need; monitor channel counts |
| No reconnect logic | A broker restart or network blip stops the application | Reconnect with backoff and redeclare topology; some clients (Java, .NET) do this automatically, pika does not |
| Hard-coding one broker address | The application fails when that node is down | Give 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).
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.
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.
#Glossary
| Term | Meaning |
|---|---|
| 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-1 | The messaging protocol used in the labs: exchanges, queues, bindings |
| AsyncAPI | Specification for documenting message-driven APIs, the counterpart of OpenAPI |
| At-least-once delivery | Every message is delivered, possibly more than once |
| Binding | A rule linking an exchange to a queue, optionally with a binding key |
| Broker | Middleware that receives, stores, routes, and delivers messages |
| Channel | A lightweight logical connection inside a TCP connection; all AMQP 0-9-1 operations happen on a channel |
| CloudEvents | CNCF specification for common event metadata (id, source, specversion, type) |
| Cluster | Several RabbitMQ nodes acting as one broker; metadata is shared, message contents only for replicated queue types |
| Command | A message asking a specific receiver to do something |
| Competing consumers | Several consumers reading one queue, sharing the work |
| Connection | A long-lived TCP connection from an application to a RabbitMQ node |
| Consumer | An application that receives and processes messages |
| Correlation ID | An 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 |
| Definitions | A JSON export of a broker's users, vhosts, permissions, exchanges, queues, bindings, and policies |
| Delivery tag | A number identifying one delivery on one channel, used to ack it |
| Durable queue | A queue whose definition survives a broker restart |
| Event | A message stating that something already happened |
| Eventual consistency | Systems agree on the data after a short delay, not instantly |
| Exchange | RabbitMQ component that routes published messages to queues (direct, fanout, topic, headers) |
| Idempotence | Processing a message twice gives the same result as processing it once |
| Jitter | Randomness added to retry delays so clients do not retry at the same moment |
| Mandatory flag | Publish option asking the broker to return a message it cannot route |
| Middleware | Software between applications that handles their communication |
| Node | One running RabbitMQ server (one Erlang virtual machine) |
| Persistent message | A message written to disk (delivery_mode=2) |
| Poison message | A message that makes its consumer fail every time |
| Policy | A broker-side rule that applies settings (TTL, limits, dead-lettering) to queues or exchanges matched by name |
| Prefetch | Limit on unacknowledged messages a consumer may hold |
| Producer / publisher | An application that sends messages |
| Publisher confirm | The broker's acknowledgment to a producer that it accepted a message |
| Publish-subscribe | Each message is delivered to every subscriber |
| Queue | An ordered buffer that holds messages until consumed |
| Quorum queue | A replicated RabbitMQ queue type based on Raft consensus, with a delivery limit |
| Resource alarm | RabbitMQ blocking publishers because memory or free disk crossed a limit |
| Routing key | A string on each message that exchanges compare with binding keys |
| Shovel | A RabbitMQ plugin that moves messages from one queue or broker to another |
| Single active consumer | Queue setting where only one consumer receives at a time, others on standby |
| Stream | A RabbitMQ queue type that keeps messages after reading, so they can be replayed |
| Topic exchange | An exchange that routes by matching routing keys against patterns |
| Transactional outbox | Saving 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 |
#References
Official documentation and specifications checked while writing these notes:
- RabbitMQ. AMQP 0-9-1 Model Explained
- RabbitMQ. Consumer Acknowledgements and Publisher Confirms
- RabbitMQ. Dead Letter Exchanges
- RabbitMQ. Quorum Queues
- RabbitMQ. Monitoring
- RabbitMQ. Downloading and Installing RabbitMQ
- RabbitMQ tutorials (Python): Work Queues and Topics
- CloudEvents. CloudEvents Specification
- AsyncAPI Initiative. AsyncAPI Specification
- Apache Kafka. Introduction
- Amazon Web Services. Fanout Amazon SNS notifications to Amazon SQS queues
- Brooker, M. (2015). Exponential Backoff and Jitter. AWS Architecture Blog.
- Fowler, M. (2017). What do you mean by "Event-Driven"?
- Richardson, C. Pattern: Transactional outbox. microservices.io.
- Hohpe, G., & Woolf, B. (2003). Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley. Pattern catalog: enterpriseintegrationpatterns.com
Additional RabbitMQ guides used for the RabbitMQ sections:
- RabbitMQ. Channels and Connections and Publishers
- RabbitMQ. Consumers
- RabbitMQ. Virtual Hosts and Authentication, Authorisation, Access Control
- RabbitMQ. Clustering Guide
- RabbitMQ. Policies
- RabbitMQ. Alternate Exchanges
- RabbitMQ. Streams
- RabbitMQ. Resource Alarms, Memory Threshold, and Disk Alarms
- RabbitMQ. Management Plugin
- RabbitMQ. RabbitMQ 4.0.1 release notes
- Wikipedia. RabbitMQ (history and ownership)
Sources for the saga section (3.2.10):
- Richardson, C. Pattern: Saga. microservices.io
- Microsoft. Saga design pattern. Azure Architecture Center
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
From Module 3 to Module 4
Module 3 made the store's integration work: messages flow through RabbitMQ, failures are retried or dead-lettered, and duplicates are harmless. Module 4 asks whether it is safe and ready for real customers: secured, tested, deployed, monitored, documented and evaluated. Almost everything you built in Module 3 comes back in Module 4, now from a different angle.
#Where each Module 3 idea returns in Module 4
| What you built or learned in Module 3 | Module 4 | How Module 4 takes it further |
|---|---|---|
| RabbitMQ users, virtual hosts and configure/write/read permissions 3.1.4 Going deeper | 4.1.1 | Authentication and authorization: one broker user per service, least privilege |
| The default guest account; credentials kept out of code Appendix A | 4.1.5 | Credential and secret management |
| AMQP on port 5672, TLS on 5671 3.1.4, Appendix A | 4.1.3 | Secure data transmission: AMQPS and certificate checks |
| Webhook HMAC signature checks 3.2.5 | 4.1.3 | Timestamped signatures that stop replays |
| Consumers validate every message; JSON Schema contracts 3.1.3, 3.1.6 | 4.1.4 | Input and data validation at every trust boundary |
| Data-type traps: dates, money, IDs, encodings 3.1.6 | 4.1.7 | Interoperability testing across platforms |
| Unit, contract and integration tests for events 3.2.9 | 4.1.6 | Integration testing with sandboxes and stubs |
| Retries, dead-letter queues, idempotent consumers 3.2.6–3.2.8 | 4.1.8 | Failure and recovery testing against RTO and RPO |
| The 12.12 spike, competing consumers, prefetch 3.1.5, 3.1.7 | 4.1.9 | Basic performance testing: p95, throughput, queue depth |
| Personal data in notifications; RA 10173 3.2.5 | 4.1.10 | Security and data-privacy considerations |
| Running RabbitMQ with docker run Lab 3.1 | 4.2.3 | Deploying every system together with Docker Compose |
| Availability coupling (0.99⁴ ≈ 96%); broker clusters 3.1.2, 3.1.4 | 4.2.4 | Service availability, SLOs, liveness and readiness |
| The correlation_id message property 3.1.5 | 4.2.5 | System logs that follow one order across systems |
| Queue monitoring and alert rules 3.1.8 | 4.2.6 | Error and performance monitoring |
| Versioned messages (order.confirmed.v2) 3.1.6, 3.2.4 | 4.2.7 | API and service versioning, deprecation |
| AsyncAPI and the event catalog 3.2.2 | 4.2.8 | Integration documentation, ADRs and runbooks |
#Before you start Module 4, check that you can…
These ticks are saved in this browser only. Anything you cannot tick yet is worth revisiting in Module 3 first: Module 4's labs build directly on Lab 3.2.
Secure Integration, Testing, and Deployment
Secure, test, deploy, and evaluate an integrated information system.
- LO 4.1.1 Apply appropriate security controls to protect integrated systems and exchanged data.
- LO 4.1.2 Perform integration, interoperability, security, and failure-recovery tests.
- LO 4.2.1 Deploy and monitor an integrated system in a suitable environment.
- LO 4.2.2 Evaluate and document the performance, reliability, security, and maintainability of an integration solution.
Each lesson: 2 lecture hours and 3 laboratory hours per meeting, over several meetings
Integrity and Excellence
Where this module fits. You have followed one integration project through the whole course. In Module 1 you analyzed the systems and their gaps. In Module 2 you connected them directly with REST APIs. In Module 3 you connected them indirectly through RabbitMQ, with events, retries, and dead-letter queues. Your integration now works on your laptop. Module 4 answers the questions anyone asks before trusting it with real customers: Is it safe? Does it really work, even when things break? Can it run somewhere other than your laptop? Will you know when it fails? Can someone else maintain it?
The same online store. Module 4 keeps Module 3's scenario. An online store sells products to customers. When an order is placed and paid, these systems must work together:
| System | Who runs it | How it connects | What could go wrong if it is not secured or tested |
|---|---|---|---|
| Online store | Your team | REST API; publishes events to RabbitMQ | Anyone could call its API and read other customers' orders |
| Payment gateway | An outside provider | Calls the store's webhook over the internet | An attacker could fake a "payment succeeded" webhook |
| Warehouse management system | Warehouse IT | Consumes order.confirmed | A malformed message could stop picking and packing |
| Accounting system | Finance | Consumes order.confirmed | A duplicate could record a sale twice |
| Courier booking | Courier partner's API, called by your consumer | Outbound HTTPS with an API key | A leaked API key lets others book deliveries on your account |
| Notification service | Marketing | Consumes order.confirmed; sends SMS and email | Customer phone numbers and addresses could leak |
Look at the picture as an attacker, a tester, and an operator would. Every arrow is a connection that must be authenticated and encrypted (Lesson 4.1, security). Every box is a system whose behavior with the others must be tested, including when another box fails (Lesson 4.1, testing). And all of it must be deployed, watched, versioned, documented, and evaluated (Lesson 4.2).
Why integration makes security and operations harder. A single application has one front door. An integrated system has a door at every connection, and each door is guarded by a different team. Industry reports keep showing the same pattern: APIs and integrations are now a leading target for attacks, because they expose data directly to other programs. That is why OWASP, the global open security community, keeps a separate API Security Top 10 list in addition to its web application list.
The map of this module. Every section solves one problem you will face when your integration leaves the laptop:
| Problem when the integration goes live | What you do about it | Section |
|---|---|---|
| How does a system know who is calling it, and what they may do? | Authentication and authorization | 4.1.1 |
| How does one program prove its identity to another? | API keys and access tokens | 4.1.2 |
| Can someone read or change data on the way? | TLS, signatures | 4.1.3 |
| What if another system sends bad or dangerous data? | Validation at every boundary | 4.1.4 |
| Where do passwords and keys live safely? | Secret management | 4.1.5 |
| Do the systems really work together? | Integration testing | 4.1.6 |
| Do systems built on different platforms understand each other? | Interoperability testing | 4.1.7 |
| What happens when a system, the network, or a message fails? | Failure and recovery testing | 4.1.8 |
| Will it keep up with a sale-day rush? | Basic performance testing | 4.1.9 |
| Are we protecting customers' personal data as the law requires? | Security and data-privacy considerations | 4.1.10 |
| Where does the system run before and after release? | Deployment environments | 4.2.1 |
| How does the same code run in every environment? | Application configuration | 4.2.2 |
| How do you package and start all the systems together? | Containers or a platform | 4.2.3 |
| How much downtime is acceptable, and how do you avoid it? | Service availability | 4.2.4 |
| How do you find out what happened to one order? | System logs | 4.2.5 |
| How do you know something is wrong before customers complain? | Error and performance monitoring | 4.2.6 |
| How do you change an API or event without breaking other systems? | API and service versioning | 4.2.7 |
| How does another team learn to connect to yours? | Integration documentation | 4.2.8 |
| Is the solution good enough, and how is it kept healthy? | System evaluation and maintenance | 4.2.9 |
How to read these notes. Each section follows the same pattern as Module 3: an Integration problem box, a story or comparison to begin, definitions, tables, common misconceptions, an example from the store, a Try this activity, a Check your understanding box, and Key points. Code examples use Python (Flask for the store's API, pika for RabbitMQ) and Docker, the same tools as Module 3.
Everything here is about systems you own or have permission to test. Never scan, attack, or load-test a system you do not own or have written permission for, including a provider's sandbox beyond what its terms allow. This is part of the value of integrity in this course.
#4.1.1Authentication and authorization
The store's order API is now reachable by the warehouse, the courier consumer, the payment gateway, and the store's own website. If it answers anyone who asks, a stranger can read customers' addresses or create fake orders. Every system that receives a call or a message must answer two questions: Who is this? and Are they allowed to do this?
At the gate, the guard checks your school ID: are you really a student of this school? That is authentication. Inside, your ID lets you into your classroom and the library, but not the registrar's records room or the faculty lounge. That is authorization. Passing the gate does not mean you may enter every room. Integrated systems work the same way, except that the "visitors" are mostly other programs.
Definitions.
- Identity: who or what is acting, such as a person (Maria, the warehouse supervisor) or a system (the warehouse management system).
- Authentication (AuthN): proving an identity, with something the caller knows (a password, a client secret), has (a private key, a phone), or is (a fingerprint).
- Authorization (AuthZ): deciding what an authenticated identity may do with which data.
- Principal: the authenticated identity that a request runs as.
| Authentication | Authorization | |
|---|---|---|
| Question | Who are you? | What may you do? |
| Happens | First | After authentication, on every request |
| Typical evidence | Password, client secret, certificate, signed token | Roles, scopes, ownership of the record |
| HTTP status on failure | 401 Unauthorized (really "unauthenticated") | 403 Forbidden |
| In the store | Is this token really from the warehouse system? | May the warehouse cancel orders? (No.) |
Two kinds of callers in an integration. In a single web application, nearly every caller is a person logging in. In an integration, most callers are machines:
| Caller | Example in the store | How it usually authenticates |
|---|---|---|
| A person through an app | A customer checking an order on the website | Login (often with an identity provider and MFA); the app then calls APIs on the person's behalf |
| A system calling an API | The warehouse system reading order details | Client credentials, an access token, or an API key (4.1.2) |
| A system pushing to you | The payment gateway calling the store's webhook | A shared secret used to sign each request (4.1.3) |
| A system connecting to the broker | The accounting consumer reading its queue | Its own RabbitMQ username and password, or a client certificate |
A program has no fingers for a fingerprint and no phone for a one-time code, so machine identities rely on secrets and keys. That is why protecting those secrets (4.1.5) matters so much.
Ways to make authorization decisions.
- Role-based access control (RBAC): permissions belong to roles, and identities get roles. The accounting role may read orders and payments.
- Scopes: with OAuth 2.0 tokens, a token carries a list of permissions such as orders:read. The API checks the scope on every call (4.1.2).
- Attribute-based access control (ABAC): the decision uses attributes of the caller, the record, and the situation, for example "a branch may read orders only for its own region."
- Object-level checks: even with the right role, may this caller touch this record? A customer may read their own order ORD-10421, not order ORD-10422. Forgetting this check is the number-one risk in the OWASP API Security Top 10 (2023), called Broken Object Level Authorization (BOLA).
Least privilege. Give each system only the permissions its job needs, and nothing "just in case." Applied to the store:
| System | Needs | Should not have |
|---|---|---|
| Warehouse system | Read orders; publish ParcelPacked | Create or cancel orders; read payment details |
| Courier consumer | Read its own queue; call the courier API | Read any other queue; delete queues |
| Accounting system | Read orders and payments | Change stock |
| Store website | Create orders; read the customer's own orders | Read all customers' orders |
The same principle applies inside RabbitMQ. In Module 3 every lab used guest. In a real deployment each service gets its own user in its own virtual host, with configure, write, and read permissions limited by regular expressions to the resources it uses. If the courier consumer's password leaks, the attacker can read courier messages, but not payments.
- "It's an internal system, so it doesn't need authentication." Internal networks get breached too; modern practice (often called zero trust) authenticates every call, inside or outside.
- "Logged in means allowed." Authentication without authorization lets any valid user read everyone's data.
- "One admin account for all integrations is simpler." Then one leak exposes everything, and the logs cannot tell you which system did what.
- "Hiding the URL protects the API." Attackers find URLs quickly; security cannot depend on secrecy of an address.
The store's API originally had GET /orders/{id} with no checks, because "only the warehouse calls it." A student project partner notices that changing the number in the URL shows other customers' names and addresses. This is BOLA. The fix has two parts: the warehouse system now authenticates with its own client credentials and a token with the orders:read scope, and customer-facing calls check that the order belongs to the logged-in customer.
For your own course project, list every caller of every API and queue in a table with four columns: caller, what it needs, how it will authenticate, and which permissions or scopes it gets. Mark anything that currently uses a shared or admin account.
- Which HTTP status code should an API return for a missing token, and which for a valid token without permission?
- Give an example of BOLA in the online store.
- Why should each consumer have its own RabbitMQ user?
Show suggested answerHide suggested answerAdded in this edition
- 401 Unauthorized for a missing or invalid token (we do not know who you are). 403 Forbidden for a valid token without permission (we know who you are; you may not do this).
- A logged-in customer calls
GET /orders/ORD-10422by changing the number in the URL and sees another customer's name and address. The API checked the role but not whether this caller owns that order. - So each service gets only the permissions its job needs (least privilege). A leaked password then exposes one queue, not everything; the service can be rotated or revoked alone; and the broker's logs show which system did what.
Authentication proves who is calling; authorization decides what they may do, on every request and for every record. In an integration most callers are machines, so give each system its own identity and only the permissions its job needs.
#4.1.2API keys and access tokens
The warehouse system calls the store's API thousands of times a day, with no person there to type a password. The courier consumer calls the courier partner's API. Each program needs a way to prove who it is on every call, one that can be limited, can expire, and can be cancelled if it leaks, without changing the other systems.
A company ID that never expires opens the door every day until someone takes it back; if you lose it, whoever finds it is "you" until security notices. A visitor's pass is printed at the lobby after you show your ID, says which floors you may visit, and stops working at 5 p.m. An API key is like the company ID. An access token is like the visitor's pass. Both are useful; they fit different situations.
API keys. An API key is a long random string that a provider gives a client, sent with each request, usually in a header:
GET /v1/bookings/BK-5521 HTTP/1.1
Host: api.courier.example.ph
X-API-Key: ck_live_7f3a...e91bAPI keys are simple, so many providers use them, including SMS gateways, map services, and courier platforms. Their weaknesses come from being long-lived, all-powerful bearer secrets: anyone who has the string is you. Good practice:
- Send keys in a header, never in the URL; URLs end up in logs, browser history, and analytics tools.
- Use separate keys for test and production, and for each system, so one can be revoked alone.
- Restrict each key if the provider allows it: by permission, IP address, or domain.
- Rotate keys on a schedule and immediately when someone leaves or a leak is suspected.
- Store the key on the server side only (4.1.5). Never put it in a mobile app, browser JavaScript, or a Git repository.
Access tokens and OAuth 2.0. OAuth 2.0 (RFC 6749) is the industry-standard framework for issuing access tokens. Its roles map neatly onto an integration:
| OAuth 2.0 role | Meaning | In the online store |
|---|---|---|
| Resource server | The API that holds the data | The store's order API |
| Client | The program that wants access | The warehouse system |
| Authorization server | Issues tokens after checking the client | An identity provider such as Keycloak, Microsoft Entra ID, or Auth0; in Lab 4.1, a small token endpoint |
| Scope | A named permission inside the token | orders:read, orders:write |
OAuth 2.0 defines several grant types (ways to get a token). Two matter most for integration:
- Client credentials grant: a system gets a token for itself, with its client ID and client secret. This is the normal choice for system-to-system integration, such as the warehouse calling the store.
- Authorization code grant with PKCE: an app gets a token on behalf of a person who logs in and agrees. This is used when a customer lets an app act for them.
The client credentials flow, step by step.
- The warehouse system sends its client_id and client_secret to the token endpoint, asking for the scope orders:read.
- The authorization server checks the secret and the allowed scopes, then returns a short-lived access token, for example valid for 15 minutes.
- The warehouse calls the store's API with the header Authorization: Bearer <token> (RFC 6750).
- The store's API checks the token's signature, expiry, audience, and scope on every request.
- When the token expires, the warehouse simply asks for a new one. The secret travelled once; the token is what travels with every call.
In Python, the client side is two requests:
import os
import requests
resp = requests.post("https://store.example.ph/oauth/token", data={
"grant_type": "client_credentials",
"client_id": "warehouse",
"client_secret": os.environ["STORE_CLIENT_SECRET"],
"scope": "orders:read",
}, timeout=10)
resp.raise_for_status()
token = resp.json()["access_token"]
order = requests.get("https://store.example.ph/v1/orders/ORD-10421",
headers={"Authorization": f"Bearer {token}"}, timeout=10)What is inside a token: JWT. Many access tokens are JSON Web Tokens (JWT, RFC 7519): three Base64url parts separated by dots, a header, a payload of claims, and a signature. The claims for the warehouse's token look like this:
{
"iss": "https://store.example.ph",
"aud": "store-api",
"sub": "warehouse",
"scope": "orders:read",
"iat": 1764829200,
"exp": 1764830100,
"jti": "5d1c0b6e-..."
}| Claim | Meaning | Why the API checks it |
|---|---|---|
| iss (issuer) | Who issued the token | Accept tokens only from your own authorization server |
| aud (audience) | Which API the token is for | A token meant for the payment API must not work on the order API |
| sub (subject) | Who the token represents | Used for authorization and for logs |
| exp (expiry) | When it stops working | A stolen token is useful only briefly |
| scope | Permissions granted | The authorization check |
Two facts surprise many students. First, a JWT is signed, not encrypted: anyone holding it can decode and read the claims (try pasting one into a JWT decoder), so never put secrets or sensitive personal data in it. The signature only proves nobody changed it. Second, the API must decide which signing algorithm it accepts and must not trust the alg written inside the token; old libraries were tricked by tokens claiming "alg": "none". Lab 4.1's check does all of this in one call:
claims = jwt.decode(token, TOKEN_SIGNING_KEY,
algorithms=["HS256"], # fixed list: never the token's own alg
audience=AUDIENCE, issuer=ISSUER) # also checks exp
if scope not in claims["scope"].split():
return jsonify(error="insufficient_scope", required=scope), 403The lab signs with HS256, a shared secret, to keep the setup small. Real identity providers sign with a private key (RS256 or ES256) and publish the public keys at a JWKS URL, so APIs can verify tokens without ever holding the signing key.
API keys or tokens?
| API key | OAuth 2.0 access token | |
|---|---|---|
| Lifetime | Long (until revoked) | Short (minutes to an hour) |
| Permissions | Often all-or-nothing | Scopes per token |
| If leaked | Works until someone notices and revokes | Expires on its own soon |
| Setup | Very simple | Needs an authorization server |
| Common use | Calling third-party services such as SMS, maps, couriers | System-to-system APIs you control; acting for users |
In practice you will use both: the store calls the courier with the API key the courier gave you, while the store's own API issues tokens to the warehouse and accounting systems.
- "The token is encrypted, so it's safe to put the customer's address in it." A JWT is readable by anyone who has it.
- "Long-lived tokens mean fewer calls, so they're better." They also mean a longer window for a thief.
- "Checking the token once at login is enough." The API checks it on every request.
- "A 'test' API key can sit in the repo." Test keys leak into production habits, and bots scan public repositories for keys within minutes.
A student pushes the courier API key to a public GitHub repository during the project. Within the day, unknown bookings appear on the courier account. The team revokes the key in the courier portal, issues a new one, stores it as an environment secret, adds the file to .gitignore, and turns on secret scanning. The lesson: revoke first, then clean up, because the key is already copied.
In Lab 4.1, get a token as warehouse, then: (a) read an order (works), (b) try to create one (403), (c) edit one character of the token (401), (d) decode the token at a JWT decoder and list its claims. Explain each result.
- Which OAuth 2.0 grant fits the warehouse system calling the store, and why?
- Name three claims an API must check in a JWT.
- Give two reasons an API key should never be placed in the URL.
Show suggested answerHide suggested answerAdded in this edition
- The client credentials grant. It is machine-to-machine with no user present: the warehouse authenticates with its own client ID and secret and receives a short-lived, scoped token for itself.
- Any three of: signature (with the expected algorithm),
iss(issuer),aud(audience),exp(expiry), andscope(permission for this operation). - URLs are recorded in server and proxy logs, browser history and analytics tools, and are often shared or copied. Put keys in a header instead.
API keys are simple long-lived secrets; access tokens are short-lived, scoped, and issued by an authorization server. For system-to-system integration, use the OAuth 2.0 client credentials grant, send tokens as Bearer headers, and verify signature, issuer, audience, expiry, and scope on every call.
#4.1.3Secure data transmission
Data between the store and its partners crosses networks you do not control: the internet, a cloud provider's network, a shared office Wi-Fi. Without protection, anyone on the path can read customers' names and addresses, change an amount or an address in transit, or pretend to be the payment gateway. You must protect every connection: store to payment gateway, store to RabbitMQ, consumers to RabbitMQ, courier consumer to courier API.
A postcard can be read by every person who handles it, and changed with a pen. A letter in a sealed envelope with a tamper-proof seal hides the contents, and anyone can tell if it was opened. A wax seal with the sender's crest also proves who sent it. Secure transmission gives you all three: confidentiality (nobody can read it), integrity (nobody can change it unnoticed), and authenticity (you know who is on the other end).
TLS: the standard for data in transit. Transport Layer Security (TLS) encrypts a connection between two programs. HTTPS is HTTP over TLS; AMQPS is AMQP over TLS. Current guidance (for example from NIST and Mozilla) is to use TLS 1.3, or TLS 1.2 where needed, and to disable older versions (SSL, TLS 1.0, TLS 1.1).
When the courier consumer connects to https://api.courier.example.ph:
- The server presents its certificate: a document saying "this public key belongs to api.courier.example.ph," signed by a certificate authority (CA) that the client already trusts.
- The client checks the CA's signature, the expiry date, and that the name matches the host it meant to reach.
- Both sides agree on fresh encryption keys for this session.
- Every byte that follows is encrypted and integrity-checked.
Step 2 is the part that actually stops impostors. Code that turns off certificate verification (for example verify=False in Python's requests) still encrypts, but to anyone, including an attacker in the middle. Never ship it, even "temporarily."
Protecting each connection in the store.
| Connection | Protection | Notes |
|---|---|---|
| Customers to the store website and API | HTTPS with a public CA certificate | Free certificates from Let's Encrypt are standard; add HSTS so browsers never use plain HTTP |
| Payment gateway to the store's webhook | HTTPS plus a signature on each request | TLS protects the pipe; the signature proves the gateway sent it |
| Store and consumers to RabbitMQ | AMQPS (TLS on port 5671) | Plain AMQP on 5672 should not be reachable from outside the private network |
| Courier consumer to courier API | HTTPS with certificate verification | Use the system's trusted CA list; pin nothing unless the provider asks |
| Between internal services | TLS, optionally mutual TLS (mTLS) | In mTLS both sides present certificates, so each proves its identity |
TLS for RabbitMQ. RabbitMQ supports TLS natively. On the server, rabbitmq.conf gets a TLS listener and the certificate files:
listeners.ssl.default = 5671
ssl_options.cacertfile = /etc/rabbitmq/certs/ca_certificate.pem
ssl_options.certfile = /etc/rabbitmq/certs/server_certificate.pem
ssl_options.keyfile = /etc/rabbitmq/certs/server_key.pem
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = falseSetting fail_if_no_peer_cert = true turns this into mutual TLS: every client must present its own certificate. On the client side, a pika consumer connects like this:
import os
import ssl
import pika
context = ssl.create_default_context(cafile="/certs/ca_certificate.pem")
params = pika.ConnectionParameters(
host="rabbitmq.store.internal",
port=5671,
credentials=pika.PlainCredentials("courier-svc", os.environ["RABBITMQ_PASSWORD"]),
ssl_options=pika.SSLOptions(context, "rabbitmq.store.internal"),
)
connection = pika.BlockingConnection(params)create_default_context verifies the server's certificate and host name by default, which is exactly what you want.
Signing messages: protection that travels with the data. TLS protects a message only while it is on one connection. Once the payment gateway's webhook arrives, TLS is gone; the store still needs to know the request came from the gateway and not from someone who found the webhook URL. The standard answer is an HMAC signature: the sender computes a keyed hash of the exact body using a secret only the two parties share, and sends it in a header. Payment providers such as Stripe and PayMongo sign webhooks this way, each with its own header names; some other providers send a fixed verification token instead, which proves less because it never changes. Always follow your provider's documentation. Lab 4.1's store verifies them like this:
raw = request.get_data() # verify the exact bytes received
timestamp = request.headers.get("X-Signature-Timestamp", "")
signature = request.headers.get("X-Signature", "")
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > WEBHOOK_TOLERANCE_SECONDS:
return jsonify(error="stale_or_missing_timestamp"), 401
expected = hmac.new(WEBHOOK_SECRET, timestamp.encode() + b"." + raw,
hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
return jsonify(error="bad_signature"), 401Three details make this secure. The signature covers the raw bytes, because re-encoding JSON changes the bytes. The timestamp is part of what is signed, and old requests are refused, so a captured request cannot be replayed later. And hmac.compare_digest compares in constant time, so an attacker cannot guess the signature one character at a time by measuring response times.
Encrypting data at rest. Transmission is only half the journey: data also sits in queues, databases, logs, and backups. RabbitMQ writes persistent messages to disk, so the server's disk should be encrypted, and very sensitive fields can be encrypted inside the message itself so that only the final receiver can read them.
- "It's on our private network, so plain HTTP is fine." Internal traffic is exactly what an intruder who got in will read.
- "HTTPS means the request is from who it says." HTTPS authenticates the server to the client; it says nothing about who the client is. That is why webhooks are signed.
- "Self-signed certificates are insecure." They are fine inside your own system if clients are configured to trust your CA. What is insecure is turning verification off.
- "Encrypted means safe forever." Certificates expire; an expired certificate takes the integration down, so track and automate renewal.
During testing, the payment gateway's sandbox sends a webhook to http:// instead of https://, and a teammate "fixes" the courier consumer's certificate error by adding verify=False. A security review catches both: the webhook URL is changed to HTTPS with signature checking, and the courier error turns out to be a missing intermediate CA certificate, which is fixed properly.
Using Lab 4.1's tests, show that a webhook signed with the wrong secret and a webhook with a one-hour-old timestamp are both refused. Then explain in two sentences why TLS alone would not have stopped either one.
- Name the three protections that secure transmission provides.
- What does verify=False actually turn off, and why is it dangerous?
- Why must a webhook signature include a timestamp?
Show suggested answerHide suggested answerAdded in this edition
- Confidentiality (no one can read the data in transit), integrity (no one can change it unnoticed) and authentication of the server (you are talking to the real party).
- It turns off certificate verification. The connection is still encrypted, but to anyone. An attacker in the middle can present their own certificate, read and change everything, and the client will not notice.
- Without a timestamp, an attacker who captures one genuine signed webhook can replay it later and the signature still checks. Signing the timestamp and rejecting old requests limits the window for replay.
Encrypt every connection with TLS 1.2 or 1.3 and always verify certificates; use AMQPS for RabbitMQ. TLS protects the connection, not the message, so sign webhooks and messages that cross organizations with HMAC over the raw body and a timestamp. Protect stored data too.
#4.1.4Input and data validation
Every system in the store trusts data it did not create: the API receives orders from the website, the store receives webhooks from the gateway, each consumer receives events from RabbitMQ, the courier consumer receives replies from the courier API. If any of them accepts data without checking it, one bad record, whether a bug or an attack, can corrupt a database, crash a consumer, or leak data into another system. Validation is how each system protects itself and everything downstream.
When a delivery truck arrives, a good clerk does not just sign. They check the delivery receipt against the purchase order: right supplier, right items, right quantities, nothing damaged, nothing extra. Anything wrong is set aside and reported, not mixed into the stock. Each system in an integration needs its own receiving clerk at its door.
Definitions.
- Input validation checks that data is well-formed and acceptable before a system uses it.
- Syntactic validation checks form: Is it JSON? Is quantity an integer? Does customer_id match CUST- followed by digits?
- Semantic validation checks meaning against business rules: Does this SKU exist? Is the delivery date after the order date? Does the payment amount match the order total?
- A trust boundary is any point where data enters a system from somewhere it does not control. In an integration, every connection is a trust boundary, including ones from "friendly" internal systems.
Validate at every boundary in the store.
| Boundary | What to check | If invalid |
|---|---|---|
| Website to store API (POST /v1/orders) | Schema, field formats, limits, no unknown fields | Reject with 400 or 422 and a clear message |
| Payment gateway to webhook | Signature and timestamp first (4.1.3), then schema; amount equals the order total | 401 for a bad signature; log and alert on amount mismatch |
| RabbitMQ to each consumer | Message schema and version (Module 3, 3.1.6) | Send to the dead-letter queue, not an endless retry (3.2.8) |
| Courier API reply to courier consumer | Expected fields present; status is a known value | Treat as a failed call; do not store unknown data |
| Any input to a database query | Use parameterized queries, never string building | Prevents SQL injection |
That last row of the API layer is the one many integrations forget: data coming back from a third-party API must be validated too. OWASP lists this as API10:2023 Unsafe Consumption of APIs: developers tend to trust partner data more than user input, and attackers exploit that by compromising or impersonating the partner.
Rules that make validation strong.
- Allowlist, not blocklist. Describe what is allowed ("sku is 3 to 30 characters of A-Z, 0-9, and hyphen") instead of trying to list every bad input. Attackers are better at inventing bad input than you are at listing it.
- Validate on the server or the receiving system. Checks in the website's JavaScript or the sending system are convenient for users but can be bypassed.
- Reject unknown fields. If a client sends "is_admin": true or "status": "PAID" and your code copies all fields into the database, the client has just changed something it should not. This is mass assignment, part of OWASP's API3:2023 Broken Object Property Level Authorization.
- Set limits. Maximum body size, string length, list length, and numeric ranges. OWASP's API4:2023 Unrestricted Resource Consumption covers APIs that let one request exhaust memory or trigger thousands of operations.
- Fail closed and explain safely. Reject the whole request, return which fields failed, and never echo stack traces, SQL errors, or internal paths.
Validation with a schema. In Module 3 you used JSON Schema as the contract for events. The same tool validates API input. Lab 4.1's order schema encodes the allowlist, the limits, and the "no unknown fields" rule:
ORDER_SCHEMA = {
"type": "object",
"additionalProperties": False, # rejects is_admin, status, ...
"required": ["customer_id", "items", "shipping_address"],
"properties": {
"customer_id": {"type": "string", "pattern": "^CUST-[0-9]{4,10}$"},
"items": {
"type": "array", "minItems": 1, "maxItems": 50,
"items": {
"type": "object", "additionalProperties": False,
"required": ["sku", "quantity"],
"properties": {
"sku": {"type": "string", "pattern": "^[A-Z0-9-]{3,30}$"},
"quantity": {"type": "integer", "minimum": 1, "maximum": 100},
},
},
},
"shipping_address": {"type": "string", "minLength": 10, "maxLength": 300},
},
}The endpoint collects all errors at once, so the calling team can fix everything in one round, and the Flask setting MAX_CONTENT_LENGTH = 64 * 1024 rejects oversized bodies before they are even parsed:
errors = [f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}"
for e in order_validator.iter_errors(body)]
if errors:
return jsonify(error="validation_failed", details=errors[:10]), 422For example, an order with "quantity": -5 gets items/0/quantity: -5 is less than the minimum of 1. Libraries such as Pydantic (Python) or the validation built into frameworks like FastAPI and Spring do the same job with classes instead of dictionaries.
400 or 422? Both mean "the client sent something wrong." Many APIs use 400 Bad Request for anything malformed. Others, as in this lab, use 400 when the body is not readable JSON at all and 422 Unprocessable Content when it is valid JSON that breaks the rules. Either is acceptable if it is consistent and documented (4.2.8).
Validation does not replace safe handling. Even validated text must be handled safely when used: use parameterized queries for SQL (cursor.execute("SELECT * FROM orders WHERE id = %s", (order_id,)), never an f-string), and encode output for where it goes (HTML-escape a name before it appears in an email or web page). A name like O'Brien is valid input but breaks string-built SQL.
- "The website already validates it." Anyone can call your API directly with tools like curl or Postman.
- "It comes from our own warehouse system, so it's clean." Internal systems have bugs and can be compromised; validate anyway.
- "Strip out bad characters and keep going." Silently "fixing" data hides problems and can create new ones. Reject and report.
- "Validation is only for security." It is equally about data quality: one consumer accepting a bad address leads to a failed delivery days later.
A bug in a new version of the website sends quantity as the string "2" instead of the number 2. Without validation, the accounting consumer's code concatenates strings and records a quantity of "22" after an update. With schema validation at the API, the website's requests fail immediately with a clear 422 in testing, and the bug never reaches production.
List at least six invalid inputs for POST /v1/orders (missing field, wrong type, out of range, unknown field, oversized body, injection-shaped text) and the response you expect for each. Run them against Lab 4.1 and record the actual responses.
- What is the difference between syntactic and semantic validation? Give one store example of each.
- Why should a consumer validate messages even though the producer validated them?
- What is mass assignment, and which schema setting prevents it?
Show suggested answerHide suggested answerAdded in this edition
- Syntactic checks form: is it JSON, is quantity an integer, does customer_id match
CUST-followed by digits? Semantic checks meaning against business rules: does this SKU exist, does the payment amount match the order total? - Every connection is a trust boundary. The producer may have a bug, may be an older or newer version, may be compromised, or the message may have been altered or replayed. The consumer is the one that gets hurt by bad data.
- Copying every incoming field straight into the database, so a client can set fields it should not, such as
"status": "PAID"or"is_admin": true. Setting"additionalProperties": falsein the JSON Schema rejects unknown fields.
Treat every connection as a trust boundary and validate there, including data from partners and internal systems. Use allowlists, schemas, and limits; reject unknown fields; fail clearly and safely. Validation complements, but does not replace, parameterized queries and output encoding.
#4.1.5Credential and secret management
An integrated system is full of secrets: the store's database password, a RabbitMQ password for each service, the courier API key, the payment webhook secret, the token signing key. Each system needs its secrets at run time, yet they must never be visible to people or places that do not need them. One leaked secret can undo every control in 4.1.1 to 4.1.4.
A store owner does not tape the vault key to the front door, photocopy it for every new hire, or leave it in the cash register "for convenience." Keys live in a locked key cabinet; each staff member gets only the keys for their job; a log shows who took which key; and when an employee leaves, the locks are changed. Secret management applies exactly these habits to passwords and keys.
Definitions.
- A credential proves identity: a password, client secret, API key, or private key.
- A secret is any value that would cause harm if exposed: credentials, signing keys, encryption keys, connection strings containing passwords.
- Secret management is the practice of storing, distributing, rotating, and auditing secrets so that only the right system gets the right secret at the right time.
Where secrets leak in integration projects.
| Leak path | Example | Why it is dangerous |
|---|---|---|
| Hard-coded in source code | API_KEY = "ck_live_7f3a..." in courier.py | Everyone with the code has the key, forever, through Git history |
| Committed config files | .env or config.json pushed to GitHub | Bots scan public repositories for keys within minutes |
| Container images | ENV DB_PASSWORD=... in a Dockerfile | Anyone who pulls the image can read it with docker inspect |
| Logs and error messages | Logging the full connection URL or request headers | Logs are copied to many places and read by many people |
| Chat and documents | Pasting a key into Messenger or a shared doc | No control over who sees it or where it is copied |
| Shared accounts | One RabbitMQ admin password used by all services | A leak anywhere exposes everything; you cannot rotate one service alone |
The basic rule: configuration from the environment, secrets never in code. The widely used Twelve-Factor App method says code and configuration must be strictly separated: the same code runs everywhere, and each environment supplies its own values, usually as environment variables (more in 4.2.2). Lab 4.1's store reads every secret from the environment and refuses to start without them:
TOKEN_SIGNING_KEY = os.environ["TOKEN_SIGNING_KEY"] # no default: fail fast
WEBHOOK_SECRET = os.environ["PAYMENT_WEBHOOK_SECRET"].encode()Using os.environ[...] instead of os.environ.get(..., "changeme") is deliberate: a missing secret stops the service at start-up with a clear error, instead of silently running in production with a default password that is printed in the code.
For local development, values go in a .env file that is listed in .gitignore, and the repository contains only a .env.example with names and fake values, so teammates know what to set:
# .env.example (commit this one; copy it to .env and fill in real values)
TOKEN_SIGNING_KEY=change-me-to-a-long-random-value
PAYMENT_WEBHOOK_SECRET=copy-from-payment-gateway-dashboard
RABBITMQ_PASSWORD=change-me
COURIER_API_KEY=copy-from-courier-portalGenerate real values randomly, never by typing a "strong-looking" word: python -c "import secrets; print(secrets.token_urlsafe(32))".
Levels of secret management. As a system grows, teams move up these levels:
| Level | How secrets are supplied | Good enough for |
|---|---|---|
| 1. Environment variables from an untracked .env file | Developer copies values by hand | Local development, class labs |
| 2. Platform secrets | Docker Compose or Docker Swarm secrets, Kubernetes Secrets, GitHub Actions secrets, or the hosting platform's secret settings | Small deployments, CI/CD pipelines, the final project |
| 3. A dedicated secret manager | HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or Google Secret Manager; services fetch secrets at start-up with their own identity | Production systems with many services and teams |
A dedicated secret manager adds what the key cabinet had: access control per secret, an audit log of who read what, automatic rotation, and sometimes dynamic secrets (for example, a database password created for one service and valid for one hour).
Rotation and revocation. Secrets should be changed on a schedule, and immediately when a leak is suspected or a person with access leaves. Design for it: support two valid keys during a changeover (old and new) so you can rotate without downtime, and keep a list of where each secret is used. If you cannot answer "what breaks if we change this key?", you will hesitate to rotate it after a leak.
Storing secrets you only need to check. Some secrets the system only needs to verify, not use: user passwords and client secrets. Store a hash, never the value. For passwords people choose, use a slow password-hashing algorithm such as Argon2id or bcrypt, as OWASP recommends. Lab 4.1 stores clients' long random secrets as SHA-256 hashes; a fast hash is acceptable only because those secrets are long and random, not chosen by people.
Catching leaks before they happen. Turn on secret scanning and push protection in GitHub (which blocks pushes that contain known key formats), or run a scanner such as gitleaks before each commit. If a secret is ever committed, treat it as leaked: revoke and replace it first, then clean the history. Deleting the file in a new commit does not remove it from Git history.
- "Our repository is private, so it's fine." Private repositories are cloned to laptops, shared with new members, and sometimes made public by accident.
- "Environment variables are perfectly secret." They are better than code, but other processes, crash dumps, and debug pages can expose them; that is why higher levels exist.
- "Base64 hides the password." Base64 is an encoding anyone can reverse, not encryption.
- "We'll rotate it if something happens." Rotation that was never practiced fails during an incident.
The accounting consumer's log line prints Connecting to amqp://accounting:S3cretPass@rabbitmq:5672/, and the logs are shipped to a dashboard the whole class can read. The team (1) changes the RabbitMQ password for accounting only, which is possible because every service has its own user, (2) changes the code to log the host and user but never the password, and (3) adds a log-review step to the deployment checklist.
Make a secrets inventory for your project: every secret, which system uses it, where it is stored now, who can read it, and how you would rotate it. Then run git log -p | grep -iE "password|secret|api_key" on your repository and fix anything you find.
- Name four places where secrets commonly leak.
- Why should a service fail to start when a secret is missing instead of using a default?
- A key was committed to Git yesterday. What is the first thing to do?
Show suggested answerHide suggested answerAdded in this edition
- Any four of: hard-coded in source code; committed config files such as
.env; container images (ENVin a Dockerfile); logs and error messages; chat and shared documents; shared accounts. - A silent default (an empty or well-known password) can run in production unnoticed, insecurely, or against the wrong system. Failing at start-up makes the problem obvious immediately, at deploy time, instead of later in front of customers.
- Revoke and replace the key, treating it as leaked. Cleaning the Git history comes after; deleting the file in a new commit does not remove it from history.
Keep secrets out of code, repositories, images, and logs. Supply them through the environment, platform secrets, or a secret manager; give each service its own credentials; hash what you only need to verify; and be ready to rotate any secret quickly.
#4.1.6Integration testing
Each team tested its own system, and every test passed. Yet the first real order fails: the store sends order_id, the warehouse expects orderId; the payment webhook arrives before the order is saved; the courier consumer uses the wrong queue name. Most integration failures happen between systems, in places no single team's tests look. Integration testing checks the connections themselves.
Each runner can be fast alone, and the team can still lose: the baton is dropped at the handover, or a runner starts too early. Relay teams practice the handovers, not just the running. Integration testing is practicing the handovers between your systems.
Definitions.
- Unit testing checks one piece of code alone, such as a validation function.
- Integration testing checks that two or more components or systems work correctly together: their data exchange, protocols, and timing. The ISTQB, the international software-testing body, distinguishes component integration testing (parts within one system) from system integration testing (between separate systems, including external ones). This course is about the second.
- End-to-end (E2E) testing follows a whole business flow, such as checkout to delivery booking, across every system.
- A test double stands in for a real system during testing: a stub returns fixed answers, a mock also checks how it was called, and service virtualization tools such as WireMock simulate a whole HTTP API.
What integration tests look for. Every connection can fail in the same families of ways:
| What can go wrong at the handover | Example in the store | How a test catches it |
|---|---|---|
| Data format and mapping | order_id vs orderId; peso amounts as "1,250.00" vs 1250.0 | Send a real order; check each receiving system's stored record |
| Protocol and configuration | Wrong URL, port, queue name, routing key | Run against real or containerized services, not only mocks |
| Authentication between systems | Warehouse token lacks orders:read; expired API key | Test each caller's credentials and scopes (4.1.1, 4.1.2) |
| Timing and ordering | Webhook arrives before the order is saved | Send events in unusual orders; add delays |
| Error responses | Courier returns 409 "duplicate booking"; the consumer crashes | Use a stub that returns each documented error |
| Business flow | Paid order never reaches the courier | E2E test that follows one order with its correlation_id |
Strategies for putting systems together.
| Strategy | How it works | Good for | Weakness |
|---|---|---|---|
| Big bang | Connect everything, then test | Very small systems | When it fails, you cannot tell where |
| Incremental | Add one connection at a time: store to RabbitMQ, then warehouse, then courier | Most projects, including yours | Needs stubs for systems not yet added |
| Contract-based | Each pair agrees on a contract (OpenAPI, JSON Schema, AsyncAPI) and tests both sides against it (Module 3, 3.2.9) | Teams that deploy separately | Does not prove the whole flow works |
What to use for each partner system.
| Partner | Test with | Why |
|---|---|---|
| Systems you own (store, consumers, RabbitMQ) | Real instances in containers (Docker Compose or Testcontainers) | Real behavior, cheap to start fresh for every run |
| Payment gateway | The provider's sandbox with test cards, plus a stub for error cases the sandbox cannot produce | Never test against real money |
| Courier API | A stub or WireMock for daily tests; the courier's test environment before release | Partners limit test calls, and their test systems may be down |
Designing integration test cases. A good test case can be run by someone else and gives the same result. Industry test cases usually record these fields:
| ID | Integration point | Preconditions | Steps and input | Expected result |
|---|---|---|---|---|
| IT-01 | Website to store API | storefront client has orders:write | POST a valid order | 201; status PENDING_PAYMENT; order stored |
| IT-02 | Gateway webhook to store | Order IT-01 exists | Send signed payment.succeeded from the sandbox | 200; order CONFIRMED; one order.confirmed event published |
| IT-03 | Store to RabbitMQ to four consumers | IT-02 done; consumers running | Observe queues | Each *.order-confirmed queue receives the event once; each consumer acks it |
| IT-04 | Courier consumer to courier API | Courier stub running | Process the event | One booking created; booking ID saved with the order |
| IT-05 | Same webhook twice | IT-02 done | Resend the identical webhook | 200 duplicate_ignored; no second event |
| IT-06 | Courier API error | Stub returns 503 | Process an event | Retried with backoff; booked after the stub recovers (3.2.6) |
| IT-07 | Warehouse reads order | warehouse token with orders:read | GET the order | 200 with only order_id, status, items |
| IT-08 | Warehouse tries to create | warehouse token | POST an order | 403 insufficient_scope |
When you run them, add Actual result, Pass/Fail, Date, and Tester columns, and attach evidence such as a screenshot or log lines. These results are a required part of your final project.
Test data. Use realistic but fake data: invented names, addresses, and the payment provider's published test card numbers. Never copy real customer records into a test environment (more in 4.1.10). Make each test create the data it needs and give it unique IDs, so tests do not depend on each other or on the order they run in.
Automating it. Integration tests that only run by hand stop being run. Put them in code, for example with pytest, and run them in your CI pipeline (such as GitHub Actions) on every push, against services started fresh in containers. Lab 4.1 starts with the store's own tests: its 15 tests check authentication, authorization, validation, and webhooks automatically in under a second.
- "We mocked every partner, so the integration is tested." Mocks only behave the way you think the partner behaves; test against real or sandbox systems before release.
- "Integration testing is done once, at the end." Test each connection as soon as it exists, and again on every change.
- "If the API returned 200, the test passed." Check the effect in the receiving system: the record, the event, the booking.
- "Testing the happy path is enough." Most integration bugs live in errors, duplicates, and timing (4.1.8).
IT-03 passes for the warehouse, accounting, and notification queues, but nothing reaches courier.order-confirmed. Inspecting RabbitMQ's management UI shows the courier queue was bound with the routing key order.confirm instead of order.confirmed. Every system's unit tests had passed; only an integration test could find this.
Write at least ten integration test cases for your own project in the table format above, covering every connection, at least two error cases, and one duplicate case. Run them and record the results.
- What is the difference between unit, integration, and end-to-end testing?
- Why test against a payment provider's sandbox instead of only a stub?
- Why should an integration test check the receiving system and not just the HTTP status?
Show suggested answerHide suggested answerAdded in this edition
- Unit tests one component's logic in isolation. Integration tests the handover between real components (formats, protocols, credentials, errors). End-to-end tests a whole business flow across all systems.
- A stub only behaves the way you think the provider behaves. The sandbox is the provider's real implementation: real authentication, signatures, formats, error codes and webhooks. It catches the misunderstandings a stub would hide.
- A 200 or 202 only proves the request was accepted. The integration works only if the data arrived correctly and with the right meaning in the receiving system, for example the order is in the warehouse queue with the right items.
Integration testing checks the handovers: formats, protocols, credentials, timing, and errors between systems. Build up one connection at a time, use real or containerized services for systems you own and sandboxes or stubs for partners, write repeatable test cases, and automate them.
#4.1.7Interoperability testing
The store is written in Python, the warehouse system in Java, the accounting system is a packaged product, and the courier's API runs on who-knows-what. They agree on JSON over HTTPS and AMQP, yet small differences still break things: a customer named Peñaflorida becomes Peñaflorida, an order placed at 9:00 a.m. shows as 1:00 a.m., ₱1,250.10 becomes ₱1,250.0999. Interoperability testing checks that systems built differently understand each other correctly, not just that they can connect.
A Filipino and a British colleague agree to meet on "04/05." The British colleague, who writes day first, comes on May 4; the Filipino, who writes month first, comes on April 5. Both understood every word; they read the meaning differently. Systems do this constantly with dates, money, names, and codes.
Definitions.
- Interoperability is the degree to which two or more systems can exchange information and use the information exchanged. The ISO/IEC 25010 software quality model lists it under compatibility.
- Interoperability testing checks this across different platforms, languages, libraries, and versions, using real implementations on both sides.
- Integration testing (4.1.6) asks "does our flow work?"; interoperability testing asks "does it work with every kind of system that has to take part, and does the data keep its meaning?"
Levels of interoperability. A common way to break the problem down:
| Level | Question | Store example | Typical failures |
|---|---|---|---|
| Technical | Can they connect and exchange bytes? | Java warehouse connects to RabbitMQ over AMQPS | TLS version mismatch; AMQP 0-9-1 client vs AMQP 1.0 broker settings; firewall |
| Syntactic | Can each parse the other's format? | JSON event parsed by Java's Jackson library | Encoding, number types, null vs missing field, date format |
| Semantic | Do they mean the same thing? | amount is pesos, not centavos; status: "SHIPPED" means handed to the courier | Units, time zones, code lists, different meanings of the same word |
| Organizational | Do the processes fit together? | Who fixes a rejected order; cut-off times | Unclear ownership, mismatched business hours |
The usual suspects: what to test explicitly.
| Area | The rule to agree on | Test with |
|---|---|---|
| Character encoding | UTF-8 everywhere, declared in Content-Type: application/json; charset=utf-8 | Names with ñ, é, and emoji in addresses and notes |
| Dates and times | ISO 8601 / RFC 3339 with an offset or in UTC: 2026-12-04T09:00:00+08:00 | An order just before midnight Philippine time; daylight-saving partners abroad |
| Money | Integer centavos (125010) or a decimal string ("1250.10") plus an ISO 4217 code ("PHP"), never a binary float | ₱0.10, ₱1,250.10, very large totals |
| Numbers | Integers within the receiver's range | IDs above 2,147,483,647 for a Java int; JavaScript loses precision above 2^53 |
| Missing and empty values | Is a missing field the same as null or ""? | An order without a landmark or apartment number |
| Code lists | Shared, documented values for status, province, payment method | An unknown future value such as "RETURNED" |
| Size limits | Maximum lengths that every system can store | A 300-character address into a 100-character database column |
| Protocol versions | TLS 1.2+; HTTP/1.1 or HTTP/2; one API version (4.2.7) | An older client that only speaks TLS 1.0 |
Why no binary floats for money? Most languages store 0.1 as a binary fraction that is not exactly one tenth, so sums drift:
>>> 0.1 + 0.2
0.30000000000000004
>>> from decimal import Decimal
>>> Decimal("0.10") + Decimal("0.20")
Decimal('0.30')An accounting system that adds thousands of float amounts will not balance to the centavo. Agreeing on integer centavos or decimal strings is a semantic agreement that must be written into the contract.
How interoperability testing is done.
- Write the agreements down in the contract: OpenAPI for HTTP, JSON Schema or AsyncAPI for events (Module 3, 3.1.6), plus a data dictionary for units, time zones, and code lists (4.2.8).
- Build a test matrix of the real combinations: each producer with each consumer, each client library and version that will be used.
- Use edge-case data from the table above, run it through the real systems, and compare what each one stores and displays with what was sent.
- Round-trip data where possible: send it, read it back from the receiver, and compare field by field.
- Repeat whenever any side upgrades a library, runtime, or API version.
An example matrix for the store's order.confirmed event:
| Consumer (platform) | Library | Encoding (Peñaflorida) | Time (23:30 +08:00) | Amount (125010 centavos) | Unknown field ignored |
|---|---|---|---|---|---|
| Warehouse (Java 21) | RabbitMQ Java client, Jackson | ? | ? | ? | ? |
| Accounting (packaged product) | Vendor's AMQP connector | ? | ? | ? | ? |
| Courier consumer (Python 3.12) | pika 1.3 | ? | ? | ? | ? |
| Notification (Node.js) | amqplib | ? | ? | ? | ? |
The last column matters for future changes: consumers should ignore fields they do not know, so producers can add fields without breaking them (4.2.7). This is sometimes summarized as "be conservative in what you send, be liberal in what you accept" (Postel's law), applied with care: accept unknown extra fields, but never accept invalid values (4.1.4).
- "It's JSON, so every system will read it the same way." JSON does not define dates, money, or integer limits; each library decides.
- "We tested with our Python client, so the Java team will be fine." Test with the real client of each consumer.
- "Time zones don't matter, we're all in the Philippines." Cloud servers, databases, and many libraries default to UTC.
- "Interoperability is only a technical problem." The hardest failures are semantic: two systems using the same word for different things.
The warehouse's Java consumer reads "placed_at": "2026-12-04 09:00:00" with no offset and assumes UTC, so orders appear eight hours later than they were placed and miss the morning pick-up. The fix is semantic, not technical: the contract now requires RFC 3339 timestamps with an offset, the producer sends 2026-12-04T09:00:00+08:00, and an interoperability test with an order at 23:30 runs against the Java consumer on every release.
Pick one event or API in your project. Fill in a test matrix like the one above for every system that reads it, run the edge-case values through each, and record what each system actually stored.
- Give one example each of a technical, syntactic, and semantic interoperability problem.
- Why should money not be sent as a binary floating-point number?
- Why should consumers ignore unknown fields but reject invalid ones?
Show suggested answerHide suggested answerAdded in this edition
- Technical: a TLS version mismatch stops the Java warehouse connecting to RabbitMQ. Syntactic: the receiver's parser treats
nulland a missing field differently, or misreads the date format. Semantic:amountis read as pesos when it was sent in centavos. - Binary floats cannot store most decimal fractions exactly (0.1 + 0.2 ≠ 0.3), so totals drift and accounts do not balance to the centavo. Use integer minor units or a decimal string plus an ISO 4217 currency code.
- Ignoring unknown fields lets producers add fields without breaking consumers (the tolerant reader). Invalid known fields, such as a wrong type or an out-of-range value, mean the data cannot be trusted and must be rejected, not guessed at.
Interoperability means data keeps its meaning across different platforms, not just that systems connect. Agree on UTF-8, RFC 3339 times with offsets, exact money representation, code lists, and limits; write them into the contract; and test every real producer-consumer combination with edge-case data.
#4.1.8Failure and recovery testing
In an integration, some part is always failing somewhere: the courier API is down for maintenance, the warehouse server restarts, Wi-Fi drops in the middle of a request, a bad message arrives. The question is not whether parts fail but what happens to customers' orders when they do. Failure and recovery testing breaks parts on purpose, in a controlled way, to prove that no order is lost, none is processed twice, and the system returns to normal by itself or with a known procedure.
Schools do not wait for a real fire to find out whether the exits work. They ring the alarm on a planned day, time how long the building takes to empty, count everyone at the assembly point, and fix what went wrong: a locked door, a class that did not hear. Failure testing is a fire drill for your integration.
Definitions.
- Failure testing (also fault injection) deliberately causes a failure to observe how the system behaves.
- Recovery testing checks that the system returns to correct operation afterwards, and how long it takes.
- Resilience is the ability to keep serving, perhaps in a reduced way, while parts fail, and to recover afterwards.
- Graceful degradation means losing a feature instead of the whole service: if the courier API is down, orders are still accepted and delivery booking happens later.
- Recovery Time Objective (RTO): the longest acceptable time to restore a service. Recovery Point Objective (RPO): the most data, measured in time, that may be lost. For the store, a reasonable target might be RTO 30 minutes and RPO zero for paid orders.
- Chaos engineering is the practice, made known by Netflix, of running such experiments regularly, even in production, with a hypothesis and a small blast radius.
What can fail in the store's integration.
| Failure type | Example | Expected safe behavior (from Modules 2 and 3) |
|---|---|---|
| A consumer is down | Warehouse system stopped for an update | Messages wait in warehouse.order-confirmed; processed after restart |
| A partner API is down or slow | Courier API returns 503 or takes 60 seconds | Timeout, retry with backoff, then DLQ (3.2.6, 3.2.8); other consumers unaffected |
| The broker restarts | RabbitMQ server reboots | Durable queues and persistent messages survive; clients reconnect |
| The network drops or slows | Connection lost between store and RabbitMQ | Publisher confirms tell the store what was not saved; it retries without losing orders |
| A process crashes mid-work | Accounting consumer killed before ack | Message redelivered; idempotency prevents a double entry (3.2.7) |
| Bad data | An event with an unknown SKU | Goes to the DLQ; the queue keeps flowing |
| A database fails | Store's database restarts | API returns 503 with Retry-After; no half-saved orders (transactions, outbox) |
| Credentials expire | Courier API key revoked, TLS certificate expired | Clear error, alert, no endless retry |
How to run a failure experiment. Follow the scientific method, the same way chaos engineering does:
- Define the steady state: what "healthy" looks like in numbers. Example: every paid order reaches all four consumers within 30 seconds; no messages in any DLQ.
- Write a hypothesis: "If the courier API is down for 5 minutes, all orders are still accepted, other consumers are unaffected, and every courier booking completes within 2 minutes after the API returns."
- Limit the blast radius: run in a test environment, with test data, and decide in advance how to stop the experiment.
- Inject the failure and keep normal traffic flowing (a small load from 4.1.9).
- Observe: queue depths, error logs, response times, DLQ contents.
- Remove the failure and verify recovery: queues drain, the steady state returns, and the data is correct.
- Record and fix: what happened, how long recovery took, and what to change.
Injecting failures with Docker. With all systems in Docker Compose (Lab 4.2), simple commands simulate most failures:
docker compose stop warehouse # consumer down (graceful stop)
docker compose kill accounting # process crash (no clean shutdown)
docker compose pause rabbitmq # broker frozen: connections hang, then time out
docker compose unpause rabbitmq
docker compose restart rabbitmq # broker restart
docker network disconnect store_default store-courier-1 # network cut for one service
docker network connect store_default store-courier-1The courier outage uses Module 3's switch: start the courier consumer with SIMULATE_OUTAGE=1 so its calls fail with HTTP 503. Specialized tools such as Toxiproxy add latency, bandwidth limits, and dropped connections between two services.
Recovery is about the data, not just the service. "The container is running again" is not recovery. After every experiment, check the data:
| Check | How | Pass when |
|---|---|---|
| Nothing lost | Count paid orders in the store vs. records in each consumer | Counts match exactly |
| Nothing duplicated | Look for repeated order_id in accounting entries and courier bookings | No duplicates |
| Queues drained | RabbitMQ management UI or the monitoring script from Module 3 (3.1.8) | Ready and unacked return to normal |
| Dead letters handled | Inspect each DLQ | Empty, or each message explained |
| Recovery time | Time from failure removal to steady state | Within the RTO |
Test the recovery procedures themselves. Some failures need people: restoring a database from a backup, replaying a DLQ, rotating a leaked key. A procedure that was never practiced usually fails when it is needed. Restore a backup into a test environment at least once, and time it; that measures your real RTO.
- "We added retries, so failures are handled." Only a test shows whether retries, timeouts, and idempotency actually work together.
- "Failure testing means breaking production." Start in a test environment with test data; production experiments come much later, with safeguards.
- "The service restarted, so we recovered." Recovery is proven by correct data, not a green status.
- "Backups are our recovery plan." A backup that has never been restored is a hope, not a plan.
The team stops RabbitMQ for two minutes while orders are being placed. Hypothesis: no paid order is lost. Result: three orders are missing from every consumer. The logs show the store published without publisher confirms, so messages sent while the broker was going down were lost silently. The fix (confirms plus the transactional outbox from Module 3) is retested with the same experiment: zero lost orders.
Run at least four experiments from the failure table against your project: one consumer down, one partner API down, one broker restart, one crash before ack. For each, write the hypothesis, what you observed, the recovery time, and the data checks.
- What is the difference between RTO and RPO? Suggest values for the store's paid orders.
- Why is "the service is running again" not enough to call a recovery successful?
- List the seven steps of a failure experiment.
Show suggested answerHide suggested answerAdded in this edition
- RTO is how long a service may take to be restored. RPO is how much data, measured in time, may be lost. For paid orders: RTO about 30 minutes, RPO zero.
- Recovery means the data is right, not just that the process is up: nothing lost, nothing duplicated, queues drained, the steady state back, all within the RTO.
- (1) Define the steady state; (2) write a hypothesis; (3) limit the blast radius; (4) inject the failure with normal traffic flowing; (5) observe; (6) remove the failure and verify recovery; (7) record and fix.
Break parts on purpose, in a controlled environment, with a hypothesis and a defined steady state. Prove recovery by checking the data: nothing lost, nothing duplicated, queues drained, within the recovery time objective. Practice the human recovery procedures too.
#4.1.9Basic performance testing
On an ordinary day the store gets a few orders an hour. On a 12.12 sale it may get hundreds in the first minutes. An integration that works for one order can still fail under many: the API slows down, tokens are requested too often, RabbitMQ queues grow faster than consumers empty them, the courier API starts refusing calls. Performance testing measures how the integrated system behaves under a realistic workload before customers find the limits.
At 10 a.m., jeepneys leave half full and nobody waits. At 5:30 p.m., the line grows longer than jeepneys can carry people away. What matters is not how fast one jeepney drives but how many people per minute the terminal moves, how long each person waits, and whether the line ever shrinks. Integrations have the same measures.
What you measure.
| Measure | Meaning | In the store |
|---|---|---|
| Response time (latency) | Time from request to response | How long POST /v1/orders takes |
| Percentiles | p50 = half of requests were faster; p95 = 95% were faster | "p95 under 500 ms" says more than an average, which hides the slow ones |
| Throughput | Work done per unit of time | Orders per second accepted; messages per second consumed |
| Error rate | Share of requests that fail | 5xx responses, timeouts, rejected connections |
| Queue depth and age | Messages waiting, and how long the oldest has waited | courier.order-confirmed growing during the sale |
| End-to-end latency | Time from order paid to all four systems done | Track with the correlation_id and timestamps in logs |
| Resource use | CPU, memory, connections, disk | RabbitMQ memory and disk alarms (Module 3) |
Why percentiles? If 99 orders take 100 ms and one takes 10 seconds, the average is about 200 ms, which looks fine. But that one customer waited 10 seconds, and on a busy day "one in a hundred" is many customers. Industry targets are written as percentiles, for example "p95 below 500 ms at 20 orders per second."
Types of performance tests.
| Type | Question | Shape of the load |
|---|---|---|
| Load test | Does it meet the target at the expected busy load? | Ramp up to the expected peak, hold steady |
| Stress test | Where does it break, and how? | Keep increasing until errors or timeouts appear |
| Spike test | What happens with a sudden burst? | Jump from low to very high instantly, like a sale opening at midnight |
| Soak (endurance) test | Does it stay healthy for hours? | Moderate load for a long time; finds memory leaks and growing queues |
The course asks for basic performance testing under a manageable workload: a load test at your expected peak, and a small spike test, is enough.
Performance in a messaging integration. Module 3 moved slow work behind queues, so the store answers customers quickly even when consumers are slow. That changes what you test: the API's response time stays good, but you must check that consumers keep up. If orders arrive at 20 per second and the courier consumer handles 5 per second, the courier queue grows by 15 messages every second. That is fine for a short spike if the queue drains afterwards; it is a failure if it never does. Watch the queue's publish rate versus ack rate in the management UI: when ack is lower for a long time, add consumer instances, raise prefetch (3.1.7), or speed up the slow call.
Tools. Common open-source tools are Locust (tests written in Python), k6 (JavaScript), and Apache JMeter (graphical). RabbitMQ provides PerfTest for load-testing the broker itself. Lab 4.1 uses Locust, so the test is ordinary Python:
class StorefrontClient(HttpUser):
wait_time = between(1, 3) # each simulated client pauses 1-3 s between calls
def on_start(self):
resp = self.client.post("/oauth/token", data={
"grant_type": "client_credentials",
"client_id": "storefront",
"client_secret": os.environ["STOREFRONT_CLIENT_SECRET"],
})
self.headers = {"Authorization": f"Bearer {resp.json()['access_token']}"}
self.order_ids = []
@task(1)
def create_order(self):
resp = self.client.post("/v1/orders", json=ORDER, headers=self.headers)
if resp.status_code == 201:
self.order_ids.append(resp.json()["order_id"])
@task(3) # reads are three times as common as creates
def read_order(self):
if self.order_ids:
self.client.get(f"/v1/orders/{self.order_ids[-1]}", headers=self.headers,
name="/v1/orders/[id]") # group all IDs in one result rowRun 50 simulated clients, adding 5 per second, for 5 minutes, saving results to CSV files:
locust -f locustfile.py --host http://localhost:8000 --headless -u 50 -r 5 -t 5m --csv resultsNotice the test gets one token per simulated client and reuses it. A client that requested a new token before every call would load the token endpoint as much as the API itself, a real performance bug found in many integrations.
A simple procedure.
- Set a target from the business, for example: "During a sale, accept 10 orders per second with p95 under 500 ms and under 1% errors; every order reaches all consumers within 60 seconds."
- Prepare a test environment like production (4.2.1), test data, and stubs for partners. Never load-test a payment gateway or courier API you do not own; they will block you, and their terms usually forbid it.
- Measure a baseline with very light load.
- Run the load test while watching the API's response times, RabbitMQ's queues, and CPU and memory.
- Find the bottleneck: the first resource to reach its limit (a slow database query, too few consumers, a prefetch of 1, a partner rate limit).
- Change one thing at a time and re-run, so you know what helped.
- Report the results against the target.
An example report row, the format your project's results should use:
| Test | Load | p50 | p95 | Errors | Max queue depth | Drained after | Target met? |
|---|---|---|---|---|---|---|---|
| Load, 1 courier consumer | 50 users, 5 min | ||||||
| Load, 3 courier consumers | 50 users, 5 min |
- "It was fast on my laptop." One user on a laptop tells you nothing about fifty at once on a server.
- "Average response time is good, so we're fine." Look at p95 and p99.
- "The API is fast, so the integration is fast." With messaging, check that consumers keep up and queues drain.
- "More servers will fix it." Only if the bottleneck is the thing you added; find it first.
In a spike test, the store API stays fast, but courier.order-confirmed grows to 2,000 messages and takes 40 minutes to drain. The logs show each courier call takes about 1 second and the consumer uses prefetch 1 with one instance. Running three courier consumer instances drains the same spike in about a third of the time; the team also asks the courier partner about a bulk-booking endpoint.
Define a target for your project, run a 5-minute load test and a short spike test with Locust (or k6 or JMeter), and fill in the report table. Explain the bottleneck you found and one change you tried.
- Why report p95 instead of only the average?
- In a messaging integration, what two rates tell you whether a consumer is keeping up?
- Why must you never load-test a partner's production API?
Show suggested answerHide suggested answerAdded in this edition
- An average hides the slow tail: many fast requests can mask a few very slow ones. p95 says "95% of requests were at least this fast", which reflects what real customers experience.
- The publish rate and the ack rate (with queue depth). If acks keep up with publishes over time, the consumer is keeping up; if not, a backlog is building.
- You do not own it and have no permission. Load-testing it can disrupt real customers, breach the provider's terms, and look like a denial-of-service attack. Use a sandbox within its terms, or a stub.
Measure response-time percentiles, throughput, error rate, queue depth, and end-to-end time against a target set by the business. Test with a manageable, realistic load in a production-like environment, find the bottleneck, change one thing at a time, and never load-test systems you do not own.
#4.1.10Security and data-privacy considerations
Integration exists to move data between systems, and much of the store's data is personal: names, phone numbers, addresses, order histories. Each connection copies that data into another system, run by another team or company, with its own logs, backups, and staff. Integration therefore multiplies both security risk and legal responsibility. This section pulls the previous sections together into the risks and duties you must plan for.
A note passed from the back row to the front goes through many hands. Every hand could read it, copy it, or lose it. If the note had only what the friend in front needed ("meet at 4") instead of your whole diary, a lost note would hurt much less. Integration design asks the same question at every connection: does the next system really need this data?
Security risks: the OWASP API Security Top 10 (2023). OWASP's list is the industry's common reference for API risks. Every integration that exposes or calls an API should be checked against it:
| Risk | What it means | Where it appears in this module |
|---|---|---|
| API1 Broken Object Level Authorization | Changing an ID in the request returns someone else's record | 4.1.1 (BOLA) |
| API2 Broken Authentication | Weak or missing checks of who is calling | 4.1.1, 4.1.2 |
| API3 Broken Object Property Level Authorization | Exposing or allowing changes to fields the caller should not see or set | 4.1.4 (mass assignment); return only needed fields |
| API4 Unrestricted Resource Consumption | No limits on size, rate, or cost of requests | 4.1.4 limits; rate limiting (4.2.3) |
| API5 Broken Function Level Authorization | A normal client can call admin functions | 4.1.1 scopes |
| API6 Unrestricted Access to Sensitive Business Flows | Automating a flow in a harmful way, such as bots buying all sale stock | Rate limits, bot checks on checkout |
| API7 Server Side Request Forgery (SSRF) | Making your server fetch a URL an attacker chose | Never fetch caller-supplied URLs without an allowlist |
| API8 Security Misconfiguration | Default passwords, verbose errors, missing TLS | 4.1.3, 4.1.5; the RabbitMQ guest account |
| API9 Improper Inventory Management | Old, forgotten API versions and test endpoints still running | 4.2.7 versioning, 4.2.8 documentation |
| API10 Unsafe Consumption of APIs | Trusting data from third-party APIs too much | 4.1.4 |
The law: the Data Privacy Act of 2012 (RA 10173). In the Philippines, processing personal information is governed by Republic Act 10173, its Implementing Rules and Regulations, and the circulars of the National Privacy Commission (NPC). Key ideas for integrators:
- Personal information identifies a person: name, address, phone number, email. Sensitive personal information includes, among others, health, education, government-issued identifiers such as SSS or TIN numbers, religious and political affiliations, and age and marital status. Sensitive information needs stronger justification and protection.
- Personal information controller (PIC): decides why and how personal data is processed; for the store's customers, the store. Personal information processor (PIP): processes it on the controller's behalf, such as a hosting provider or an SMS service. When data goes to an outside company, the relationship should be covered by an outsourcing or data-sharing agreement.
- General privacy principles: transparency (customers are told what is collected and shared), legitimate purpose (data is used only for declared, lawful purposes), and proportionality (only the data that is adequate, relevant, and necessary).
- Data subjects' rights include the rights to be informed, to access, to object, to correct, to erasure or blocking, to data portability, and to damages. An integration must make these possible: if a customer asks for correction, every system holding a copy must be updated.
- Security: the law requires organizational, physical, and technical security measures; NPC Circular 2023-06 sets the current minimum requirements.
- Breach notification: under NPC Circular 16-03, when a breach must be reported, the NPC and affected data subjects must be notified within 72 hours of knowing or reasonably believing it happened. Logging and monitoring (4.2.5, 4.2.6) are how you find out in time.
These notes explain the ideas for system design; they are not legal advice. Real projects consult the organization's Data Protection Officer.
Privacy by design in the store's integration. Turn proportionality into design decisions, connection by connection:
| Receiving system | Needs | Should not receive |
|---|---|---|
| Warehouse | Order ID, items, quantities, packing notes | Customer email, payment details |
| Accounting | Order ID, amounts, tax, payment reference | Delivery landmark notes |
| Courier | Name, delivery address, phone, parcel size | Items bought, order total, email |
| Notification | Name, phone or email, order status | Full address, items' prices |
This is data minimization. A fat event (Module 3, 3.2.1) that carries the entire order to every consumer is convenient but spreads personal data to systems that do not need it. Options include separate events per consumer, a thin event plus an authorized API call for details, or removing fields before publishing.
Other privacy practices for integrations.
- Mask personal data in logs: log customer_id and order_id, never full names, phone numbers, addresses, or card data. Logs are copied widely (4.2.5).
- Set retention periods: delete data from queues, DLQs, logs, and test copies when they are no longer needed.
- Never use real customer data in development or testing (4.1.6); use invented or properly anonymized data.
- Encrypt in transit and at rest (4.1.3).
- Keep a record of data flows: which system sends which personal data to which system, and why. Your integration diagram and documentation (4.2.8) become part of this record.
Security testing for integrations. Beyond the functional security tests of Lab 4.1, teams commonly run:
- Dependency scanning (pip-audit, GitHub Dependabot) for known vulnerabilities in libraries.
- Secret scanning (4.1.5).
- Dynamic scanning of the running API with a tool such as OWASP ZAP, only on your own deployment.
- Configuration review against checklists: TLS on, default accounts removed, management UI not public, debug mode off.
- "Security is the security team's job." Integrators decide what data flows where; most risks above are design and coding decisions.
- "The data is just names and addresses, not sensitive." It is still personal information under RA 10173, and it is enough for scams and identity fraud.
- "The partner company is responsible for data we send them." The controller remains accountable for choosing processors and protecting what it shares.
- "Privacy slows the project." Sending fewer fields to each system also makes integrations simpler, cheaper, and easier to change.
The notification service's logs contain lines like SMS sent to 0917-555-0142: Hi Ana, your order of 2 x Tote Bag is on its way to 12 Rizal St. The logs are kept forever on a shared dashboard. The review leads to three changes: the notification event carries only what the message needs, logs record customer_id and message_id instead of the text, and log retention is set to 30 days.
Draw your project's data flow and, for each connection, list the personal data it carries and whether the receiver needs every field. Then check your API against the OWASP API Security Top 10 table and note which risks are handled and how.
- What is BOLA, and how do you prevent it?
- State the three general privacy principles of RA 10173 and apply proportionality to the courier integration.
- Within how many hours must a reportable personal data breach be notified to the NPC?
Show suggested answerHide suggested answerAdded in this edition
- Broken Object Level Authorization: an API returns or changes a record just because the caller supplied its ID. Prevent it with an object-level check on every request: does this caller own this record, or have a role allowed to access it?
- Transparency, legitimate purpose and proportionality. Proportionality for the courier: send only what delivery needs, such as the recipient name, delivery address, contact number and parcel details. Do not send order contents, prices, email or payment data.
- 72 hours from knowing or reasonably believing the breach happened (NPC Circular 16-03).
Every integration copies data to more systems, so it multiplies risk and responsibility. Check APIs against the OWASP API Security Top 10, follow RA 10173's principles of transparency, legitimate purpose, and proportionality, send each system only the data it needs, keep personal data out of logs and test environments, and be able to detect and report breaches within 72 hours.
#Lab 4.1: Securing and testing the store's integration API
Secure the connections into the online store, the API that the warehouse and website call and the webhook that the payment gateway calls, then prove with automated tests that every control works: authentication, authorization, validation, signed webhooks, and duplicate handling.
pip install flask pyjwt jsonschema python-dotenv requests pytest locustCommands below are for a Bash shell (Linux, macOS, or Git Bash on Windows). In PowerShell, curl behaves differently; use Git Bash or Postman instead.
Files. Create a folder store/ with four files: app.py (the API), test_app.py (the tests), register_client.py, and send_webhook.py (helpers), plus locustfile.py from 4.1.9.
Read the comments: each block corresponds to a section of this lesson.
"""Lab 4.1: the online store's integration API, secured.
Shows: OAuth 2.0 client-credentials tokens (JWT), scopes, input validation,
HMAC-signed payment webhooks, and configuration from environment variables.
For teaching: a real system would use a dedicated identity provider (such as
Keycloak) instead of issuing its own tokens.
"""
import hashlib
import hmac
import json
import logging
import os
import time
import uuid
from datetime import datetime, timedelta, timezone
from functools import wraps
import jwt
from flask import Flask, g, jsonify, request
from jsonschema import Draft202012Validator
# ---- Configuration: every secret and setting comes from the environment ----
TOKEN_SIGNING_KEY = os.environ["TOKEN_SIGNING_KEY"] # no default: fail fast
WEBHOOK_SECRET = os.environ["PAYMENT_WEBHOOK_SECRET"].encode()
TOKEN_TTL_SECONDS = int(os.environ.get("TOKEN_TTL_SECONDS", "900"))
WEBHOOK_TOLERANCE_SECONDS = int(os.environ.get("WEBHOOK_TOLERANCE_SECONDS", "300"))
ISSUER = os.environ.get("TOKEN_ISSUER", "https://store.example.ph")
AUDIENCE = "store-api"
# Registered client systems: client_id -> (hash of client_secret, allowed scopes).
# Secrets are stored only as SHA-256 hashes; the real values live in each
# client's secret store. Loaded from an environment variable as JSON.
CLIENTS = json.loads(os.environ.get("CLIENTS_JSON", "{}"))
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 # reject bodies over 64 KB
log = logging.getLogger("store")
ORDERS = {} # in-memory store for the lab
SEEN_WEBHOOK_IDS = set()
# ---------------------------- Authentication --------------------------------
@app.post("/oauth/token")
def issue_token():
"""OAuth 2.0 client credentials grant (RFC 6749, section 4.4)."""
if request.form.get("grant_type") != "client_credentials":
return jsonify(error="unsupported_grant_type"), 400
client_id = request.form.get("client_id", "")
client_secret = request.form.get("client_secret", "")
client = CLIENTS.get(client_id)
given = hashlib.sha256(client_secret.encode()).hexdigest()
if client is None or not hmac.compare_digest(given, client["secret_sha256"]):
return jsonify(error="invalid_client"), 401
asked = set(request.form.get("scope", "").split()) or set(client["scopes"])
if not asked <= set(client["scopes"]):
return jsonify(error="invalid_scope"), 400
now = datetime.now(timezone.utc)
claims = {
"iss": ISSUER, "aud": AUDIENCE, "sub": client_id,
"scope": " ".join(sorted(asked)),
"iat": now, "exp": now + timedelta(seconds=TOKEN_TTL_SECONDS),
"jti": str(uuid.uuid4()),
}
token = jwt.encode(claims, TOKEN_SIGNING_KEY, algorithm="HS256")
return jsonify(access_token=token, token_type="Bearer",
expires_in=TOKEN_TTL_SECONDS, scope=claims["scope"])
def require_scope(scope):
"""Authorization: the caller must present a valid token holding `scope`."""
def decorator(view):
@wraps(view)
def wrapper(*args, **kwargs):
header = request.headers.get("Authorization", "")
if not header.startswith("Bearer "):
return jsonify(error="missing_token"), 401
try:
claims = jwt.decode(header[7:], TOKEN_SIGNING_KEY,
algorithms=["HS256"], # never trust the token's own alg
audience=AUDIENCE, issuer=ISSUER)
except jwt.ExpiredSignatureError:
return jsonify(error="token_expired"), 401
except jwt.InvalidTokenError:
return jsonify(error="invalid_token"), 401
if scope not in claims["scope"].split():
return jsonify(error="insufficient_scope", required=scope), 403
g.client_id = claims["sub"]
return view(*args, **kwargs)
return wrapper
return decorator
# ------------------------------ Validation ----------------------------------
ORDER_SCHEMA = {
"type": "object",
"additionalProperties": False,
"required": ["customer_id", "items", "shipping_address"],
"properties": {
"customer_id": {"type": "string", "pattern": "^CUST-[0-9]{4,10}$"},
"items": {
"type": "array", "minItems": 1, "maxItems": 50,
"items": {
"type": "object", "additionalProperties": False,
"required": ["sku", "quantity"],
"properties": {
"sku": {"type": "string", "pattern": "^[A-Z0-9-]{3,30}$"},
"quantity": {"type": "integer", "minimum": 1, "maximum": 100},
},
},
},
"shipping_address": {"type": "string", "minLength": 10, "maxLength": 300},
},
}
order_validator = Draft202012Validator(ORDER_SCHEMA)
@app.post("/v1/orders")
@require_scope("orders:write")
def create_order():
body = request.get_json(silent=True)
if body is None:
return jsonify(error="body must be JSON"), 400
errors = [f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}"
for e in order_validator.iter_errors(body)]
if errors:
return jsonify(error="validation_failed", details=errors[:10]), 422
order_id = f"ORD-{uuid.uuid4().hex[:8].upper()}"
ORDERS[order_id] = {**body, "order_id": order_id, "status": "PENDING_PAYMENT",
"created_by": g.client_id}
return jsonify(ORDERS[order_id]), 201
@app.get("/v1/orders/<order_id>")
@require_scope("orders:read")
def get_order(order_id):
order = ORDERS.get(order_id)
if order is None:
return jsonify(error="not_found"), 404
# Return only the fields this integration needs (data minimization).
return jsonify({k: order[k] for k in ("order_id", "status", "items")})
# --------------------------- Signed webhooks --------------------------------
@app.post("/webhooks/payment")
def payment_webhook():
raw = request.get_data() # verify the exact bytes received
timestamp = request.headers.get("X-Signature-Timestamp", "")
signature = request.headers.get("X-Signature", "")
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > WEBHOOK_TOLERANCE_SECONDS:
return jsonify(error="stale_or_missing_timestamp"), 401
expected = hmac.new(WEBHOOK_SECRET, timestamp.encode() + b"." + raw,
hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
return jsonify(error="bad_signature"), 401
event = json.loads(raw)
if event["id"] in SEEN_WEBHOOK_IDS: # providers retry: be idempotent
return jsonify(status="duplicate_ignored"), 200
SEEN_WEBHOOK_IDS.add(event["id"])
order = ORDERS.get(event.get("order_id"))
if order is None:
return jsonify(error="unknown_order"), 404
if event["type"] == "payment.succeeded":
order["status"] = "CONFIRMED" # in Module 3, the store now publishes OrderConfirmed
return jsonify(status="ok"), 200
@app.get("/health")
def health():
return jsonify(status="ok")The lab keeps orders in memory so you can focus on security. In your project, orders live in a database, and the webhook publishes OrderConfirmed through the outbox from Module 3.
register_client.py creates a client ID and secret for a system, the way an identity provider's admin console does:
"""Lab 4.1: create a client ID and secret for a system that will call the store.
Usage: python register_client.py warehouse orders:read
Prints the secret ONCE (give it to that system) and the entry for CLIENTS_JSON.
"""
import hashlib
import json
import secrets
import sys
client_id, scopes = sys.argv[1], sys.argv[2:]
secret = secrets.token_urlsafe(32)
entry = {client_id: {"secret_sha256": hashlib.sha256(secret.encode()).hexdigest(),
"scopes": scopes}}
print(f"Client secret for {client_id} (store it safely, it is not shown again):\n {secret}")
print("Add to CLIENTS_JSON:\n ", json.dumps(entry))send_webhook.py plays the payment gateway, signing a payment.succeeded webhook:
"""Lab 4.1: act as the payment gateway and send a signed webhook.
Usage: python send_webhook.py ORDER_ID [--secret WRONG] [--age SECONDS]
"""
import argparse
import hashlib
import hmac
import json
import os
import time
import uuid
import requests
try: # read .env if python-dotenv is installed
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
parser = argparse.ArgumentParser()
parser.add_argument("order_id")
parser.add_argument("--secret", default=os.environ["PAYMENT_WEBHOOK_SECRET"])
parser.add_argument("--age", type=int, default=0, help="pretend the request is this old")
parser.add_argument("--event-id", default=f"evt_{uuid.uuid4().hex[:12]}")
args = parser.parse_args()
body = json.dumps({"id": args.event_id, "type": "payment.succeeded",
"order_id": args.order_id}).encode()
timestamp = str(int(time.time()) - args.age)
signature = hmac.new(args.secret.encode(), timestamp.encode() + b"." + body,
hashlib.sha256).hexdigest()
resp = requests.post("http://localhost:8000/webhooks/payment", data=body, timeout=10,
headers={"Content-Type": "application/json",
"X-Signature-Timestamp": timestamp,
"X-Signature": signature})
print(resp.status_code, resp.text.strip(), f"(event id {args.event_id})")Add the same try: from dotenv import load_dotenv ... block after the imports in locustfile.py, so it can read the .env file too.
Register two client systems:
python register_client.py warehouse orders:read
python register_client.py storefront orders:read orders:writeCreate .env in the store/ folder, then add .env to .gitignore before your first commit. Combine the two printed entries into one JSON object:
TOKEN_SIGNING_KEY=<output of: python -c "import secrets; print(secrets.token_urlsafe(32))">
PAYMENT_WEBHOOK_SECRET=<another random value, as the gateway dashboard would give you>
CLIENTS_JSON='{"warehouse": {"secret_sha256": "...", "scopes": ["orders:read"]}, "storefront": {"secret_sha256": "...", "scopes": ["orders:read", "orders:write"]}}'
STOREFRONT_CLIENT_SECRET=<storefront's secret, used only by the load test>
WAREHOUSE_CLIENT_SECRET=<warehouse's secret, used in Step 6>Notice that the store keeps only hashes of the client secrets; the real secrets belong to the warehouse and storefront systems. In this lab one .env holds both sides for convenience.
These tests set their own fake secrets, so they do not need .env:
"""Lab 4.1 tests: run with pytest -v"""
import hashlib
import hmac
import json
import os
import time
import pytest
os.environ.update({
"TOKEN_SIGNING_KEY": "test-only-signing-key-at-least-32-bytes!!",
"PAYMENT_WEBHOOK_SECRET": "test-only-webhook-secret",
"CLIENTS_JSON": json.dumps({
"warehouse": {"secret_sha256": hashlib.sha256(b"wh-secret").hexdigest(),
"scopes": ["orders:read"]},
"storefront": {"secret_sha256": hashlib.sha256(b"sf-secret").hexdigest(),
"scopes": ["orders:read", "orders:write"]},
}),
})
import app as store # noqa: E402 (import after the environment is set)
VALID_ORDER = {"customer_id": "CUST-0042",
"items": [{"sku": "BAG-TOTE-01", "quantity": 2}],
"shipping_address": "12 Rizal St., Tacloban City, Leyte"}
@pytest.fixture
def client():
store.ORDERS.clear()
store.SEEN_WEBHOOK_IDS.clear()
return store.app.test_client()
def token_for(client, client_id, secret, scope=None):
form = {"grant_type": "client_credentials", "client_id": client_id,
"client_secret": secret}
if scope:
form["scope"] = scope
resp = client.post("/oauth/token", data=form)
assert resp.status_code == 200, resp.json
return {"Authorization": f"Bearer {resp.json['access_token']}"}
def signed(body: dict, secret=b"test-only-webhook-secret", ts=None):
raw = json.dumps(body).encode()
ts = str(int(time.time()) if ts is None else ts)
sig = hmac.new(secret, ts.encode() + b"." + raw, hashlib.sha256).hexdigest()
return raw, {"X-Signature-Timestamp": ts, "X-Signature": sig,
"Content-Type": "application/json"}
# ---- Authentication ----
def test_wrong_client_secret_is_rejected(client):
resp = client.post("/oauth/token", data={"grant_type": "client_credentials",
"client_id": "warehouse",
"client_secret": "guess"})
assert resp.status_code == 401
def test_no_token_gives_401(client):
assert client.get("/v1/orders/ORD-1").status_code == 401
def test_tampered_token_gives_401(client):
headers = token_for(client, "warehouse", "wh-secret")
headers["Authorization"] = headers["Authorization"][:-2] + "xx"
assert client.get("/v1/orders/ORD-1", headers=headers).status_code == 401
def test_expired_token_gives_401(client, monkeypatch):
monkeypatch.setattr(store, "TOKEN_TTL_SECONDS", -1)
headers = token_for(client, "warehouse", "wh-secret")
resp = client.get("/v1/orders/ORD-1", headers=headers)
assert resp.status_code == 401 and resp.json["error"] == "token_expired"
# ---- Authorization ----
def test_client_cannot_ask_for_scope_it_was_not_given(client):
resp = client.post("/oauth/token", data={"grant_type": "client_credentials",
"client_id": "warehouse",
"client_secret": "wh-secret",
"scope": "orders:write"})
assert resp.status_code == 400
def test_read_only_client_cannot_create_orders(client):
headers = token_for(client, "warehouse", "wh-secret")
resp = client.post("/v1/orders", json=VALID_ORDER, headers=headers)
assert resp.status_code == 403
# ---- Validation ----
def test_valid_order_is_created(client):
headers = token_for(client, "storefront", "sf-secret")
resp = client.post("/v1/orders", json=VALID_ORDER, headers=headers)
assert resp.status_code == 201 and resp.json["status"] == "PENDING_PAYMENT"
@pytest.mark.parametrize("bad", [
{**VALID_ORDER, "items": []}, # no items
{**VALID_ORDER, "items": [{"sku": "BAG-TOTE-01", "quantity": -5}]},
{**VALID_ORDER, "customer_id": "1 OR 1=1"}, # injection-shaped
{**VALID_ORDER, "is_admin": True}, # unexpected field
])
def test_invalid_orders_are_rejected(client, bad):
headers = token_for(client, "storefront", "sf-secret")
assert client.post("/v1/orders", json=bad, headers=headers).status_code == 422
# ---- Signed webhooks ----
def make_order(client):
headers = token_for(client, "storefront", "sf-secret")
return client.post("/v1/orders", json=VALID_ORDER, headers=headers).json["order_id"]
def test_genuine_webhook_confirms_order(client):
order_id = make_order(client)
raw, headers = signed({"id": "evt_1", "type": "payment.succeeded", "order_id": order_id})
assert client.post("/webhooks/payment", data=raw, headers=headers).status_code == 200
assert store.ORDERS[order_id]["status"] == "CONFIRMED"
def test_forged_webhook_is_rejected(client):
order_id = make_order(client)
raw, headers = signed({"id": "evt_2", "type": "payment.succeeded", "order_id": order_id},
secret=b"attacker-guess")
assert client.post("/webhooks/payment", data=raw, headers=headers).status_code == 401
assert store.ORDERS[order_id]["status"] == "PENDING_PAYMENT"
def test_replayed_old_webhook_is_rejected(client):
order_id = make_order(client)
raw, headers = signed({"id": "evt_3", "type": "payment.succeeded", "order_id": order_id},
ts=int(time.time()) - 3600)
assert client.post("/webhooks/payment", data=raw, headers=headers).status_code == 401
def test_duplicate_webhook_is_processed_once(client):
order_id = make_order(client)
raw, headers = signed({"id": "evt_4", "type": "payment.succeeded", "order_id": order_id})
client.post("/webhooks/payment", data=raw, headers=headers)
second = client.post("/webhooks/payment", data=raw, headers=headers)
assert second.json["status"] == "duplicate_ignored"Run pytest -v. You should see 15 passed (the parametrized test counts four times). Then break the code on purpose to see a test catch it: change "additionalProperties": False to True at the top level, re-run, and note which test fails. Change it back.
Start the API; Flask reads .env automatically when python-dotenv is installed:
flask --app app run --port 8000In a second terminal (also in store/), act as the website: get a token and create an order.
source .env
TOKEN=$(curl -s -X POST localhost:8000/oauth/token \
-d grant_type=client_credentials -d client_id=storefront \
-d client_secret="$STOREFRONT_CLIENT_SECRET" | python -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
curl -s -X POST localhost:8000/v1/orders -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"customer_id":"CUST-0042","items":[{"sku":"BAG-TOTE-01","quantity":2}],"shipping_address":"12 Rizal St., Tacloban City, Leyte"}'Copy the order_id from the response, then act as the payment gateway:
python send_webhook.py ORD-XXXXXXXX --event-id evt_test_1 # 200 ok
python send_webhook.py ORD-XXXXXXXX --event-id evt_test_1 # 200 duplicate_ignored
python send_webhook.py ORD-XXXXXXXX --secret wrong-secret # 401 bad_signature
python send_webhook.py ORD-XXXXXXXX --age 3600 # 401 stale_or_missing_timestampGet a token with client_id=warehouse and its secret, then (a) read the order, (b) try to create an order, (c) send the token with one character changed, (d) paste the token into a JWT decoder and list its claims. Record the status code and error for each.
With the API still running:
locust -f locustfile.py --host http://localhost:8000 --headless -u 50 -r 5 -t 2m --csv resultsOpen results_stats.csv and record the request count, failure count, median, and 95th percentile for each endpoint. Flask's built-in server is for development only, so treat these numbers as a baseline; in Lab 4.2 you will repeat the test against the deployed system.
this lab's code was run and its 15 tests pass with Flask 3.1, PyJWT 2.15, jsonschema 4.26, and pytest 9, and the manual webhook steps were run against the live API. The Locust file was checked for syntax only. If a command behaves differently on your machine, check the package versions first.
#Lesson 4.1 summary
Key takeaways
- In an integration, every connection is a door. Authenticate every caller, most of which are machines, and authorize every request and every record; give each system its own identity and least privilege (4.1.1).
- Use API keys for simple calls to third-party services and OAuth 2.0 client-credentials tokens for system-to-system APIs; verify a JWT's signature, issuer, audience, expiry, and scope on every call (4.1.2).
- Encrypt every connection with TLS and verify certificates; sign webhooks with HMAC over the raw body and a timestamp (4.1.3).
- Validate at every trust boundary, including data from partners, with allowlists, schemas, and limits (4.1.4).
- Keep secrets out of code, repositories, images, and logs; supply them from the environment or a secret manager and be able to rotate them (4.1.5).
- Integration tests check the handovers between systems; interoperability tests check that data keeps its meaning across platforms (4.1.6, 4.1.7).
- Break things on purpose to prove that no order is lost or duplicated and that recovery meets its targets (4.1.8).
- Measure percentiles, throughput, errors, and queue depth under a realistic load against a business target (4.1.9).
- Integration multiplies risk and legal duty: check the OWASP API Security Top 10, follow RA 10173, and send each system only the data it needs (4.1.10).
Review questions
- The warehouse's token is valid but it receives 403 when calling POST /v1/orders. Is this an authentication or an authorization result? Is it correct behavior?
- Explain BOLA using the store's order API, and describe the check that prevents it.
- Compare an API key and an OAuth 2.0 access token on lifetime, permissions, and what happens if each one leaks.
- Why is a JWT not a safe place for a customer's address?
- HTTPS already encrypts the payment gateway's webhook. Why must the store still verify a signature?
- Give three rules that make input validation strong, with a store example of each.
- A teammate commits the courier API key to GitHub and deletes it in the next commit. Is the problem solved? What should be done?
- Write two integration test cases and one interoperability test case for the order.confirmed event.
- Describe a failure experiment for a RabbitMQ restart: steady state, hypothesis, injection, and the data checks after recovery.
- During a load test, the API's p95 is 120 ms, but the courier queue keeps growing. Is the system meeting its goals? What would you investigate?
- Apply RA 10173's principle of proportionality to the data the store sends the courier and the notification service.
#4.2.1Deployment environments
Your integration must run somewhere other than your laptop, and you need places to try changes safely before customers see them. But an integration is not one program: each environment needs its own store, its own RabbitMQ, its own consumers, and the matching version of every partner: the payment gateway's sandbox in testing and its live system in production. Mixing them up is one of the most common and most costly integration mistakes: a test that charges a real card, or a demo that sends SMS messages to real customers.
A theater group does not open on its first read-through. Lines are learned at home (development), scenes are rehearsed in a practice room (testing), and a full dress rehearsal happens on the real stage with costumes and lights but no paying audience (staging). Only then comes opening night (production). Each step is closer to the real thing, and mistakes found early are cheap.
Definitions.
- A deployment environment is a complete, separate set of running systems, configuration, data, and connections used for one purpose.
- Deployment is the process of installing a version of the software into an environment and making it run.
- Promotion means moving the same tested version from one environment to the next.
The usual environments.
| Environment | Purpose | Data | Partner connections | Who uses it |
|---|---|---|---|---|
| Development (dev) | Write and try code | Small fake data | Stubs, or partners' sandboxes | Each developer, often on a laptop with Docker |
| Test / QA | Automated and manual tests, integration tests (4.1.6) | Fake test data, reset often | Sandboxes and stubs | CI pipeline, testers |
| Staging (pre-production) | Final check in a copy of production | Realistic but fake or anonymized | Partners' test environments | Team, sometimes the client for acceptance |
| Production (prod) | Serves real customers | Real data | Partners' live systems | Customers |
Small projects often combine test and staging; your course project needs at least a development environment and one deployed environment that others can reach.
What changes between environments, and what must not.
| Changes per environment | Stays the same in every environment |
|---|---|
| Host names and URLs (rabbitmq.dev vs rabbitmq.prod) | The code |
| Credentials and secrets | The container image or build (4.2.3) |
| Partner endpoints: sandbox vs live | The queue and exchange design, schemas, and contracts |
| Sizes: number of consumer instances, memory | The deployment steps |
| Log level (DEBUG in dev, INFO in prod) | The tests that must pass |
The left column is configuration, covered in 4.2.2. The right column is why industry practice says build once, deploy many: the exact image tested in staging is the one promoted to production, never a fresh rebuild that might pick up a different library version.
Environment parity. The Twelve-Factor App calls for keeping development, staging, and production as similar as possible. "It works on my machine" usually means the environments differ: Python 3.12 on the laptop and 3.9 on the server, SQLite in dev and PostgreSQL in prod, RabbitMQ with guest locally and with real users in prod. Containers (4.2.3) are the usual way to keep parity: the same images run everywhere.
Keep integrations pointed at the right partner. Every partner connection must be configured per environment and checked at deployment:
| Partner | Dev and test | Production | Guard against mistakes |
|---|---|---|---|
| Payment gateway | Sandbox keys (test cards, no real money) | Live keys | Live keys exist only in production's secret store; key prefixes such as test_ and live_ make mix-ups visible |
| SMS and email | A sandbox, or an allowlist of team numbers | Real sending | Block real numbers outside production |
| Courier | Courier's test API or a stub | Live API | Different base URLs and keys per environment |
Where environments run. The same environments can be hosted in different ways:
| Option | Examples | You manage | Fits |
|---|---|---|---|
| On-premises server | A server in the school's or company's data room | Everything: hardware, OS, network, backups | Data that must stay on site |
| Virtual private server or cloud VM (IaaS) | Amazon EC2, Azure VMs, DigitalOcean, local VPS providers | OS and everything above it | Docker Compose deployments like Lab 4.2 |
| Platform as a Service (PaaS) | Render, Railway, Heroku, Google Cloud Run, Azure App Service | Your code and configuration | Web APIs without managing servers |
| Managed services | CloudAMQP or Amazon MQ for RabbitMQ; managed databases | Only how you use them | Brokers and databases you do not want to operate |
| Container orchestration | Kubernetes (EKS, AKS, GKE, or self-hosted) | Cluster and workloads | Many services, large teams |
Moving a version through the environments: CI/CD. Continuous integration (CI) builds and tests every change automatically. Continuous delivery (CD) packages each passing build so it can be deployed at any time, usually with an approval before production. A simple pipeline for the store, written in a tool such as GitHub Actions or GitLab CI:
- On every push: run unit tests and Lab 4.1's security tests.
- Build the container images and tag them with the version (4.2.7).
- Start the whole system with Docker Compose and run integration tests.
- Deploy the same images to staging; run smoke tests (a few quick checks that the main flow works).
- After approval, deploy the same images to production; run smoke tests; be ready to roll back.
Deployment strategies. How the new version replaces the old matters for availability (4.2.4):
| Strategy | How it works | Downtime | Rollback |
|---|---|---|---|
| Recreate | Stop old, start new | Yes, briefly | Redeploy the old version |
| Rolling | Replace instances one at a time | None if several instances | Roll back the same way |
| Blue-green | Run new (green) beside old (blue), then switch traffic | None | Switch back |
| Canary | Send a small share of traffic to the new version first | None | Stop the canary |
In a messaging integration, consumers are often the easiest to update: stop one, start the new version, and the queue simply holds messages for a moment. That is another benefit of Module 3's design.
- "Staging is just another name for test." Staging should mirror production's configuration and size as closely as possible.
- "We'll rebuild for production with the production settings." Then production runs something nobody tested; promote the same build and change only configuration.
- "Real data makes testing more realistic." It also puts customers' personal data in a less protected place, against RA 10173's principles (4.1.10).
- "Deployment is the last step of the project." Deploy early and often; the first deployment always reveals problems.
During a staging demo, customers of a real courier partner receive booking notifications for test orders, because staging's courier URL was copied from production. The team adds a start-up check that refuses to run if APP_ENV is not production but the courier URL is the live one, and moves the live key into production's secret store only.
For your project, fill in an environment table: for each environment (at least dev and one deployed environment), list where it runs, its URL, which partner endpoints it uses, where its secrets are stored, and who may deploy to it.
- Name the four common environments and the purpose of each.
- What does "build once, deploy many" mean, and why does it matter?
- Give two ways to keep a test environment from contacting a partner's live system.
Show suggested answerHide suggested answerAdded in this edition
- Development (write and try code), Test/QA (automated and integration tests), Staging (final check in a production-like copy) and Production (serves real customers).
- Build the artifact (image) once, then promote that same build through test, staging and production, changing only configuration. What reaches production is exactly what was tested.
- Configure each environment with the partner's sandbox or a stub base URL and test keys, never live credentials. For SMS and email, use a sandbox or an allowlist of team numbers and addresses that blocks real recipients outside production.
Use separate environments, from development to production, each a complete copy of the integration with its own configuration, data, credentials, and matching partner endpoints. Keep them as similar as possible, promote the same tested build, automate the path with CI/CD, and choose a deployment strategy that fits your availability needs.
#4.2.2Application configuration
The same courier consumer must talk to the courier's sandbox in testing and its live API in production, use 1 instance on a laptop and 3 during a sale, wait 5 seconds for a reply in one place and 10 in another. If those values are written into the code, every environment needs a different version of the code, and every change of a URL or password needs a new release. Configuration lets one tested build run correctly in every environment.
The same rice cooker cooks white rice, brown rice, and lugaw. You do not buy a new cooker for each; you change the settings: water level, cooking mode, timer. The machine (the code) is the same; the settings (the configuration) change with what you need.
Definitions.
- Configuration is everything that is likely to vary between deployments, as the Twelve-Factor App defines it: addresses of backing services, credentials, partner endpoints, sizes, limits, timeouts, and feature switches.
- Code is the logic that stays the same everywhere.
- A backing service is anything the application uses over the network, such as RabbitMQ, a database, or the courier API. Twelve-Factor treats each as an attached resource that configuration can swap without code changes.
What is configuration in the store's integration?
| Setting | Example value | Why it varies |
|---|---|---|
| Broker address and user | RABBITMQ_HOST=rabbitmq, RABBITMQ_USER=courier | Different broker per environment |
| Secrets | RABBITMQ_PASSWORD, COURIER_API_KEY | Never the same across environments (4.1.5) |
| Partner endpoints | COURIER_API_URL=https://sandbox.courier.example.ph | Sandbox vs live (4.2.1) |
| Timeouts | COURIER_TIMEOUT_S=5 | Tuned from monitoring (4.2.6) |
| Retry behavior | MAX_ATTEMPTS=3, retry delay 10 s | Tuned per partner's reliability |
| Capacity | PREFETCH=10, number of consumer instances | Bigger in production |
| Logging | LOG_LEVEL=INFO | More detail in development |
| Feature flags | SEND_SMS=false | Turn a feature on or off without a release |
Not configuration: the queue's design (which exchange, which routing keys), the event schema, business rules. Those are part of the code and contracts, change through releases, and must be the same everywhere.
Where configuration comes from. Applications usually combine several sources, with a clear order of precedence (later wins):
| Source | Good for | Notes |
|---|---|---|
| Safe defaults in code | Non-secret values that rarely change, such as MAX_ATTEMPTS=3 | Never a default for secrets or partner URLs |
| Configuration files in Git | Larger, structured settings: rabbitmq.conf, logging setup | Reviewed like code; no secrets |
| Environment variables | Per-environment values and secrets | The Twelve-Factor recommendation; supported by every platform |
| Secret store | Secrets in production (4.1.5) | Injected as variables or files at start-up |
| Remote configuration and feature-flag services | Changing behavior at run time | Used by larger systems |
Load, check, and fail fast. Read all configuration once, at start-up, convert it to the right types, and check it. A typo such as COURIER_TIMEOUT_S=5s or a staging service pointed at the live courier should stop the service with a clear message, not fail at 2 a.m. on the first order:
@dataclass(frozen=True)
class Config:
app_env: str
rabbitmq_host: str
rabbitmq_password: str
courier_api_url: str
courier_timeout_s: float
max_attempts: int
def load_config() -> Config:
env = os.environ
cfg = Config(
app_env=env.get("APP_ENV", "development"),
rabbitmq_host=env["RABBITMQ_HOST"], # required
rabbitmq_password=env["RABBITMQ_PASSWORD"], # required secret
courier_api_url=env["COURIER_API_URL"], # required, differs per environment
courier_timeout_s=float(env.get("COURIER_TIMEOUT_S", "5")),
max_attempts=int(env.get("MAX_ATTEMPTS", "3")),
)
if cfg.app_env not in {"development", "test", "staging", "production"}:
raise ValueError(f"APP_ENV has an unknown value: {cfg.app_env!r}")
if not 0 < cfg.courier_timeout_s <= 30:
raise ValueError("COURIER_TIMEOUT_S must be between 0 and 30 seconds")
live = "api.courier.example.ph"
if (cfg.app_env == "production") != (live in cfg.courier_api_url):
raise ValueError("courier URL does not match APP_ENV (live API only in production)")
return cfg
CONFIG = load_config() # a bad setting stops the service here, with a clear messageLibraries such as pydantic-settings (Python) or Spring Boot's @ConfigurationProperties (Java) do the same with less code.
Configuration in Docker Compose. Lab 4.2 shows the common pattern. Values that differ per environment live in a .env file next to docker-compose.yml (never committed); Compose substitutes them into the file, and each service receives only the variables it needs:
courier:
<<: *consumer
environment:
<<: *rabbitmq-env
SERVICE_NAME: courier
DATA_DIR: /data
RABBITMQ_USER: courier
RABBITMQ_PASSWORD: ${RABBITMQ_COURIER_PASSWORD}
SIMULATE_OUTAGE: ${SIMULATE_OUTAGE:-0}Notice that the courier consumer never sees the store's token signing key or the warehouse's password: least privilege applies to configuration too. ${SIMULATE_OUTAGE:-0} means "use the variable if set, otherwise 0."
Configuring the broker itself. RabbitMQ separates three kinds of configuration, and knowing which is which saves time:
| Kind | Where | Examples |
|---|---|---|
| Server settings | rabbitmq.conf file, environment variables | Listeners and TLS (4.1.3), memory and disk limits |
| Runtime policies | Set with rabbitmqctl set_policy or the management UI; can change without restart | Dead-lettering, TTL, max length, matched by queue-name pattern |
| Definitions | Users, virtual hosts, permissions, exchanges, queues, bindings; exportable as a JSON file | Lab 4.2's setup service creates them; production teams keep them in Git and import them |
Configuration drift. When people change settings by hand on a server ("I just bumped the timeout in the UI"), environments slowly become different and nobody knows why production behaves differently from staging. The cure is configuration as code: keep every non-secret setting in files under version control, deploy them the same way every time, and treat a hand change as an emergency fix to be written back into Git.
- "Configuration means a big config.py with an if production: branch." That puts every environment's settings, and often secrets, into the code.
- "Defaults make life easier." Defaults for secrets or partner URLs make it easy to run production with a test value. Require them.
- "Everything should be configurable." Too many settings make systems hard to understand and test; configure what truly varies.
- "It's only a config change, so it doesn't need testing." A wrong URL or timeout breaks an integration as surely as a code bug.
The courier consumer's timeout was hard-coded to 2 seconds. During a sale, the courier API slowed to 3 seconds per call, and every booking timed out, retried, and ended in the DLQ. With the timeout as configuration (COURIER_TIMEOUT_S), the on-call student raised it to 8 seconds and restarted only the courier consumer, without a new release; the team later wrote the new value into the production configuration file in Git.
List every configuration value in your project. For each, record the variable name, whether it is a secret, its value in dev and in your deployed environment, and whether it is required. Make your services fail at start-up when a required value is missing.
- What makes a value "configuration" rather than code? Give two examples of each from the store.
- Why should a service validate its configuration at start-up?
- What is configuration drift, and how do teams prevent it?
Show suggested answerHide suggested answerAdded in this edition
- Configuration is anything that varies between environments; code is the logic that stays the same everywhere. Configuration:
RABBITMQ_HOST,COURIER_API_URL,COURIER_TIMEOUT_S,PREFETCH. Code: the order-validation rules, the retry and idempotency logic. - To fail fast, with a clear message, at deploy time. A missing or invalid setting otherwise shows up later as a confusing runtime error, or as silent wrong behavior in front of customers.
- Environments slowly becoming different because settings were changed by hand. Teams prevent it with configuration as code: settings in version-controlled files, applied automatically by the deployment, never edited by hand on a server.
Keep everything that varies between environments out of the code: addresses, credentials, partner endpoints, sizes, timeouts, and flags. Supply it through environment variables and secret stores, give each service only what it needs, validate it at start-up, and keep non-secret configuration in version control.
#4.2.3Container-based or platform-based deployment
The store's integration is now six programs (the store API, RabbitMQ, and four consumers), each with its own language version, libraries, settings, and start-up order. Installing all of that by hand on a server, and again identically on the next server, is slow and error-prone, and "it worked on my laptop" becomes "it fails on the server." You need a repeatable way to package each system and start them all together, correctly connected.
Before standard shipping containers, every cargo (sacks, barrels, crates) was loaded by hand in its own way, and each port handled it differently. The standard steel container changed that: whatever is inside, every ship, crane, and truck handles the box the same way. Software containers do the same for programs: whatever language is inside, every server runs the container the same way.
Definitions.
- A container image is a read-only package of a program plus everything it needs to run: the runtime (such as Python 3.12), libraries, and code. It is built from a recipe called a Dockerfile.
- A container is a running instance of an image, isolated from other containers but sharing the host's operating system kernel. That makes containers much lighter than virtual machines.
- A registry stores images so servers can download them: Docker Hub, GitHub Container Registry, or a cloud provider's registry.
- Docker Compose describes and runs a multi-container application from one YAML file.
- Platform-based deployment (PaaS) means you give the platform your code or image and it runs, scales, and restarts it for you.
Packaging one system: the store's Dockerfile. Each line is a deliberate choice:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py publisher.py jsonlog.py ./
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
# One worker, because the lab keeps orders in memory; a real store uses a database.
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "1", "app:app"]| Line | Why |
|---|---|
| python:3.12-slim | An official, small base image with a fixed Python version; same everywhere |
| COPY requirements.txt before the code | Docker caches layers: dependencies are reinstalled only when requirements.txt changes |
| requirements.txt with versions (pika==1.3.*) | Builds do not silently pick up a breaking new version |
| useradd + USER appuser | Do not run as root: if the app is compromised, the attacker has fewer rights |
| No ENV with secrets | Secrets are supplied at run time (4.1.5, 4.2.2); anything in an image can be read by whoever pulls it |
| gunicorn instead of flask run | Flask's built-in server is for development only; Gunicorn is a production server |
Add a .dockerignore file listing .env, .git, __pycache__, and test databases, so they are never copied into the image by accident.
Running the whole integration: Docker Compose. One file declares every system and how they connect. The key ideas, using Lab 4.2's file:
services:
rabbitmq:
image: rabbitmq:4-management
hostname: rabbitmq # RabbitMQ stores data per host name; keep it fixed
ports:
- "127.0.0.1:15672:15672" # management UI: only from this machine
volumes:
- rabbitmq-data:/var/lib/rabbitmq
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
timeout: 10s
retries: 6
start_period: 30s
restart: unless-stopped
store:
build: ./store
image: store-api:${APP_VERSION}
ports:
- "8000:8000"
depends_on:
setup:
condition: service_completed_successfully
restart: unless-stopped| Compose feature | What it solves for the integration |
|---|---|
| Service names as host names | Containers on the same Compose network find each other by name: the store connects to rabbitmq:5672, not an IP address |
| Ports | Only what outsiders need is published. AMQP (5672) is not published at all; the management UI is bound to 127.0.0.1 only |
| Volumes | RabbitMQ's messages and the consumers' dedupe databases survive container restarts and upgrades |
| Health checks + depends_on | Services start in the right order: the setup job waits until RabbitMQ is healthy; the store and consumers wait for setup to finish |
| Restart policy | A crashed consumer is restarted automatically (4.2.4) |
| image: with a version tag | The built image is named store-api:1.0.0, so you know exactly what is running (4.2.7) |
With one command, docker compose up -d --build, any teammate or server gets the same six-system integration.
The front door: reverse proxy or API gateway. Customers and partners should not reach the store's container directly. In production a reverse proxy or API gateway sits in front and handles cross-cutting concerns once, for every API:
- HTTPS termination with automatic certificates. With Caddy, two lines do it:
store.example.ph {
reverse_proxy store:8000
}- Rate limiting, the defense against OWASP API4 (4.1.10). In Nginx, for example:
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /v1/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://store:8000;
}
}- Request size limits, access logs, and routing of /v1/ and /v2/ to different versions (4.2.7).
Dedicated API gateways such as Kong, Tyk, AWS API Gateway, or Azure API Management add API keys, quotas, and analytics on top.
Container-based or platform-based?
| Containers on your own server or VM (Docker Compose) | Platform as a Service | Container orchestration (Kubernetes) | |
|---|---|---|---|
| You manage | The server, Docker, updates, backups | Only your app and its settings | The cluster and every workload |
| Scaling | Manual (docker compose up --scale courier=3) | A slider or automatic | Automatic, with many options |
| Restarts and health | Restart policies, health checks | Built in | Built in, with self-healing |
| Running RabbitMQ | A container you operate | Usually a managed broker such as CloudAMQP or Amazon MQ | A container, often with the RabbitMQ Cluster Operator |
| Cost and effort | Low cost, more effort | Higher cost, least effort | Highest effort; worth it at large scale |
| Fits | This course's project; small companies | Teams that want to focus on code | Many services and teams |
For your final project, Docker Compose on a VM, a school server, or a PaaS that supports containers is the expected level.
- "Containers are lightweight virtual machines." They share the host's kernel; they isolate processes, not whole operating systems.
- "Data in a container is safe." A container's own files are lost when it is removed; anything that must survive goes in a volume or a managed database.
- "Publish every port so it's easy to debug." Every published port is an entry point; publish only what clients must reach.
- "latest is a fine tag." latest changes over time; production should run a specific version.
A team deploys with docker compose up and everything works, until the VM reboots. RabbitMQ comes back empty: no queues, no messages. The cause: no volume for /var/lib/rabbitmq, and no fixed hostname, so RabbitMQ started a new data directory. Adding the named volume and hostname: rabbitmq, then rerunning the broker-restart experiment from 4.1.8, confirms that queues and persistent messages survive.
Write a Dockerfile for one system in your project following the table above, add it to a Compose file with your broker, and show that docker compose down followed by docker compose up -d keeps your queued messages.
- What is the difference between an image and a container?
- Why should the RabbitMQ AMQP port not be published to the internet?
- Name two things a reverse proxy or API gateway does for an integration.
Show suggested answerHide suggested answerAdded in this edition
- An image is the built, read-only package (code, runtime, dependencies). A container is a running instance of an image. One image can run as many containers.
- Only the services inside the deployment need it. Exposing it invites password guessing and attacks on the broker, and it bypasses the network boundary. Keep it on the internal network, and use TLS if it must cross networks.
- Any two of: HTTPS termination with automatic certificates, rate limiting, routing to the right service or version, authentication checks, and request logging.
Package each system as a container image with fixed versions, a non-root user, and no secrets; run the integration with Docker Compose using service names, volumes, health checks, and restart policies; put a reverse proxy or API gateway in front for HTTPS and rate limiting; and choose containers, PaaS, or orchestration by how much you want to manage.
#4.2.4Service availability
Customers expect to order at any hour, and partners expect the store's webhook to answer whenever a payment completes. But the integration depends on many parts, each of which will sometimes be down. How much downtime is acceptable? How do you keep the whole integrated service available when its parts are not? And how do you tell a platform which parts are healthy?
A hospital cannot promise the city's electricity never fails. Instead it plans: a backup generator starts automatically, critical rooms are on separate circuits, fuel is checked every month, and the target ("emergency power within 10 seconds") is written down. Availability engineering is the same: you cannot stop failures, so you set a target, remove single points of failure, detect problems quickly, and recover automatically.
Definitions.
- Availability is the share of time a service is working as expected, usually as a percentage over a month or a year.
- Downtime is time when it is not. Planned downtime (maintenance) and unplanned downtime (failures) both count, unless an agreement says otherwise.
- A single point of failure (SPOF) is a part whose failure stops the whole service.
- Redundancy means having more than one of something so that one can fail without an outage.
What the percentages mean. "Nines" sound similar but differ greatly:
| Availability | Allowed downtime per 30-day month | Per year |
|---|---|---|
| 99% ("two nines") | about 7.2 hours | about 3.65 days |
| 99.5% | about 3.6 hours | about 1.83 days |
| 99.9% ("three nines") | about 43 minutes | about 8.8 hours |
| 99.99% ("four nines") | about 4.3 minutes | about 53 minutes |
Each extra nine costs much more: more servers, automation, and people on call. Choose the target from business need: a school enrollment system may accept 99.5%; a payment webhook during a sale needs more.
SLI, SLO, and SLA. Google's Site Reliability Engineering practice gave the industry three terms:
| Term | Meaning | Store example |
|---|---|---|
| SLI (service level indicator) | A measurement of service health | Share of POST /v1/orders requests that succeed within 500 ms |
| SLO (service level objective) | The internal target for an SLI | 99.5% of order requests succeed within 500 ms, measured over 30 days |
| SLA (service level agreement) | A contract with consequences if the target is missed | The courier partner promises 99.9% API availability, or gives service credits |
The gap between 100% and the SLO is the error budget: with a 99.5% SLO, about 3.6 hours a month of failure is acceptable. Teams use it to decide between releasing new features (which risks failures) and spending time on reliability.
Availability in an integration: chains multiply. When systems call each other synchronously (Module 2 style), the caller is available only when all of them are. If the store, payment check, and courier booking each have 99.9% availability and checkout calls all three in a row:
0.999 × 0.999 × 0.999 ≈ 0.997, so the checkout is only about 99.7% available: roughly three times the downtime of any single part.
This is one of the strongest arguments for Module 3's design. With asynchronous messaging, the store accepts the order and publishes an event; if the courier system is down, its messages wait in its queue. The customer-facing service no longer depends on the courier being up at that moment. Decoupling turns many "the whole checkout is down" incidents into "courier bookings are delayed for 20 minutes."
Removing single points of failure in the store's integration.
| Part | Single point of failure? | How to make it redundant |
|---|---|---|
| Store API | Yes, with one container | Run two or more instances behind the reverse proxy (requires a shared database instead of in-memory orders) |
| RabbitMQ | Yes, with one node | A three-node RabbitMQ cluster with quorum queues, which keep working if one node fails; or a managed broker |
| Consumers | Less critical: messages wait | Two instances per consumer for faster recovery and throughput |
| Database | Yes | Managed database with automatic failover and backups |
| Server or VM | Yes, in Lab 4.2 | Several servers, or a platform that reschedules containers |
| Partner API | You cannot control it | Timeouts, retries, circuit breaker, and a queue in front (Module 3) |
For the course project, a single server is acceptable, but your evaluation (4.2.9) should name the single points of failure and how production would remove them.
Health checks: telling the platform what is healthy. Platforms restart or stop sending traffic to services based on health checks. Industry practice, from Kubernetes, separates two questions:
| Check | Question | If it fails | Store endpoint |
|---|---|---|---|
| Liveness | Is the process alive, or stuck? | Restart the container | /health/live: answers if the app can respond |
| Readiness | Can it do its job right now? | Stop sending it traffic until ready; do not restart | /health/ready: also checks it can reach RabbitMQ |
@app.get("/health/live")
def live():
"""Liveness: the process is running and can answer."""
return jsonify(status="ok", version=os.environ.get("APP_VERSION", "dev"))
@app.get("/health/ready")
def ready():
"""Readiness: the store can do its job, which needs RabbitMQ."""
if publisher.ready():
return jsonify(status="ready", rabbitmq="ok")
return jsonify(status="not_ready", rabbitmq="unreachable"), 503Keep liveness simple: if it also checked RabbitMQ, a broker outage would make the platform restart every store container over and over, which helps nothing. Docker Compose has one healthcheck per service; Lab 4.2 uses readiness for it.
Automatic recovery. Simple measures recover most failures without a person:
- Restart policies (restart: unless-stopped) restart crashed containers; Lab 4.2's consumers simply exit when they lose the broker and are restarted.
- Reconnection in clients: the store's publisher reopens its RabbitMQ connection when it finds it closed.
- Graceful shutdown: on stop, finish or hand back in-flight work. A consumer that is stopped before acking does not lose the message; RabbitMQ redelivers it.
- Timeouts and circuit breakers (Module 3) stop one slow partner from tying up every worker.
- Graceful degradation: if the courier is down, keep accepting orders and book deliveries later.
Planned downtime. Deployments, upgrades, and certificate renewals also cause downtime unless planned: use rolling or blue-green deployments (4.2.1), schedule broker upgrades in a maintenance window announced to partners, and automate certificate renewal.
- "99% sounds almost perfect." It allows more than three and a half days of downtime a year.
- "Our part is 99.9% available, so the integration is." Synchronous chains multiply; the whole is less available than each part.
- "A health check that returns 200 proves the service works." Only if it checks what the service needs; and liveness and readiness answer different questions.
- "Redundancy is just running two copies." Two copies that share the same server, database, or network still share its failure.
The store's original health check called RabbitMQ and the database. During a 3-minute broker upgrade, the platform declared every store container dead and restarted them in a loop, so even order lookups failed. After splitting liveness from readiness, the next upgrade only paused order confirmation; customers could still browse and check their orders.
Write an SLO for two parts of your project (one API, one asynchronous flow such as "paid orders reach every consumer within 60 seconds"). List every single point of failure in your deployment and how a production version would remove it.
- How much downtime per month does 99.9% allow?
- Why is a synchronous chain of three 99.9% services less available than each one, and how does messaging help?
- What is the difference between a liveness check and a readiness check?
Show suggested answerHide suggested answerAdded in this edition
- About 43 minutes per 30-day month.
- Availability multiplies along a synchronous chain: 0.999³ ≈ 0.997, so the chain fails whenever any one part fails, about three times the downtime of a single service. With messaging, the store accepts the order and the work waits in a queue, so a downstream outage does not fail the checkout.
- Liveness: is the process alive or stuck? If not, restart it. Readiness: can it do its job right now (for example, reach RabbitMQ)? If not, stop sending it traffic, but do not restart it.
Set availability targets as SLOs from business need, and know what each "nine" allows. Synchronous chains multiply downtime, while asynchronous messaging contains it. Find and remove single points of failure, separate liveness from readiness, and let restart policies, reconnection, timeouts, and graceful degradation handle most failures automatically.
#4.2.5System logs
A customer messages: "I paid for order ORD-1A2B3C4D an hour ago, but no rider has contacted me." The order touched the store, the payment gateway, RabbitMQ, and four consumers, each running in its own container and writing its own log. Without a plan, finding what happened means opening six logs, guessing at times, and searching by hand. Good logging lets you follow one order across every system in a minute.
After an incident, investigators do not guess; they read what each system recorded, in order, with times. A ship's logbook has a fixed format: date, time, position, event, so any officer can read any page. System logs are your integration's logbook, and a shared format is what makes them readable across systems.
Definitions.
- A log is a time-ordered record of events written by a running program.
- A log level marks importance. The common levels:
| Level | Use for | Store example |
|---|---|---|
| DEBUG | Detail for developers; off in production | Full parsed event content |
| INFO | Normal, meaningful events | Order created; event processed |
| WARNING | Something unexpected but handled | Courier returned 503; retry scheduled |
| ERROR | An operation failed and needs attention | Message dead-lettered; publish failed |
| CRITICAL | The service cannot continue | Cannot read required configuration |
- Structured logging writes each entry as data with named fields (usually one JSON object per line) instead of free text.
- A correlation ID is an identifier carried by every request and message that belongs to the same business transaction, so its log lines can be joined across systems.
Free text versus structured logs.
2026-12-04 09:00:25 ERROR courier failed for ORD-1A2B3C4D after 3 tries (503){"time": "2026-12-04T01:00:25.400+00:00", "level": "ERROR", "service": "courier", "message": "dead_lettered", "message_id": "m1", "correlation_id": "ORD-1A2B3C4D", "queue": "courier.order-confirmed", "reason": "courier booking API returned HTTP 503", "attempt": 3}People can read both. But only the second can be searched reliably by a program ("every ERROR where service is courier in the last hour", "count dead_lettered per queue") without fragile text matching, and every system in the integration can use the same field names. Lab 4.2 uses a small formatter shared by the store and all consumers:
class JsonFormatter(logging.Formatter):
def format(self, record):
entry = {
"time": datetime.fromtimestamp(record.created, timezone.utc)
.isoformat(timespec="milliseconds"),
"level": record.levelname,
"service": SERVICE_NAME,
"message": record.getMessage(),
}
entry.update(getattr(record, "fields", {})) # extra={"fields": {...}}
if record.exc_info:
entry["error"] = self.formatException(record.exc_info)
return json.dumps(entry, ensure_ascii=False)Times are in UTC with milliseconds, in ISO 8601 format, so lines from different servers sort correctly (4.1.7). A consumer then logs with named fields:
log.info("processed", extra={"fields": {**ctx, "result": result,
"duration_ms": round((time.perf_counter() - started) * 1000, 1)}})Correlation IDs: one thread through every system. The ID must travel with the work:
- The store gives each order an ID and uses it as the correlation ID; for other requests it reuses an incoming X-Correlation-ID header or creates one, and returns it in the response.
- When it publishes OrderConfirmed, it puts the same value in the AMQP message's correlation_id property.
- Every consumer reads properties.correlation_id and includes it in every log line about that message, and passes it on in any message or API call it makes next.
For larger systems, the W3C Trace Context standard (the traceparent header) and OpenTelemetry carry trace IDs automatically across HTTP and messaging, and tools then draw each request's path as a timeline, called distributed tracing.
What to log, and what never to log.
| Log | Never log |
|---|---|
| Every incoming request: method, path, status, duration, caller (client_id), correlation ID | Passwords, API keys, tokens, webhook secrets, connection strings with passwords |
| Every event published and consumed, with message_id and correlation ID | Full request bodies containing personal data |
| Retries, dead-lettering, and their reasons | Customer names, phone numbers, addresses, card data (use IDs instead) (4.1.10) |
| Authentication and authorization failures (who, what, when) | Whole tokens, even when they fail |
| Start-up: version and non-secret configuration | Anything "just in case" with no clear use |
Security teams also rely on logs: OWASP's Top 10 for web applications has for years included a category for security logging and monitoring failures, because attacks that are not logged cannot be noticed or investigated.
Where logs go. The Twelve-Factor App says an application should write logs to standard output as an event stream and let the platform collect them, not manage log files itself. Docker does exactly that:
docker compose logs -f courier # follow one service
docker compose logs --since 30m store courier # several services, last 30 minutesIn production, logs from every server are shipped to one central log platform where they can be searched together and kept for a set period: for example Grafana Loki, the Elastic Stack (Elasticsearch, Logstash, Kibana) or OpenSearch, or a cloud service such as Amazon CloudWatch Logs or Google Cloud Logging. Set a retention period (for example 30 or 90 days) and limit who can read logs.
Analyzing logs: following one order. Lab 4.2's tools/log_report.py reads the JSON lines from all services. Tracing the customer's order gives its whole journey (sample output):
docker compose logs --no-log-prefix | python tools/log_report.py ORD-1A2B3C4D2026-12-04T01:00:00.100+00:00 store INFO request /v1/orders
2026-12-04T01:00:05.200+00:00 store INFO order_confirmed
2026-12-04T01:00:05.300+00:00 warehouse INFO processed pick-and-pack job created for 2 units
2026-12-04T01:00:05.310+00:00 courier WARNING retry_scheduled courier booking API returned HTTP 503
2026-12-04T01:00:25.400+00:00 courier ERROR dead_lettered courier booking API returned HTTP 503In seconds you can answer the customer's question: payment arrived, the warehouse is packing, but the courier booking failed after three attempts and the message is in courier.order-confirmed.dlq. The fix (replay after the courier recovers, 3.2.8) is now obvious. If jq is installed, the same searches work in one line, for example docker compose logs --no-log-prefix courier | jq -c 'select(.level=="ERROR")'.
- "More logs are always better." Noise hides the important lines and costs storage; log meaningful events at the right level.
- "print() is logging." It has no level, no time, no structure, and no control over where it goes.
- "Logs are only for errors." INFO lines on successful steps are what let you see where a flow stopped.
- "Logs are private, so personal data is fine there." Logs are copied widely and kept long; they are a common source of data leaks.
Before Lab 4.2's changes, each consumer printed free text without IDs. A missing delivery took a student two hours to explain by comparing timestamps across four terminals. After adding JSON logs with correlation IDs, the same question took one command, and the team added an alert for every dead_lettered line (4.2.6).
In Lab 4.2, run the courier outage experiment, then use log_report.py (or jq) to answer: (1) How many orders were dead-lettered, and why? (2) What was the full path of one affected order? (3) How long did the slowest request take? Write down which fields made each answer possible.
- Why is structured logging better than free text for an integration?
- How does a correlation ID travel from the store to the courier consumer?
- List four things that must never appear in logs.
Show suggested answerHide suggested answerAdded in this edition
- Structured (JSON) logs have consistent named fields, so lines from many systems can be searched, filtered and joined by
correlation_id,message_id,client_idor status. Free text has to be guessed at with fragile text searches. - The store uses the order ID (or an incoming
X-Correlation-ID) as the correlation ID, puts it in the AMQPcorrelation_idproperty of OrderConfirmed, and the courier consumer reads it, logs it on every line, and passes it on in its next call or message. - Any four of: passwords, API keys, tokens, webhook secrets, connection strings with passwords, full request bodies containing personal data, customer names, phone numbers, addresses, card data.
Write structured JSON logs to standard output with consistent fields, UTC times, and the right levels. Carry one correlation ID through every request and message so an order can be followed across systems. Log meaningful events and failures, never secrets or personal data, and collect logs centrally with a retention period.
#4.2.6Error and performance monitoring
Logs explain what happened once you know where to look. But who tells you to look? In an asynchronous integration, failures are quiet: the store keeps answering customers happily while the courier queue grows for three hours and 400 orders wait for riders. Monitoring watches the numbers that matter, continuously, and alerts a person before customers notice.
You do not open the engine every kilometer. The dashboard shows a few numbers that matter (speed, fuel, temperature), and warning lights come on only when something needs action. A good monitoring setup is a dashboard for your integration: few numbers, clearly shown, with warning lights that mean "do something now."
Definitions.
- Monitoring is collecting and watching measurements of a running system and alerting when they show a problem.
- Observability is how well you can understand a system's internal state from its outputs. Its three usual signals: logs (events, 4.2.5), metrics (numbers over time, such as requests per second), and traces (one request's path across services).
- A metric is a numeric measurement recorded over time; a dashboard displays metrics; an alert notifies a person when a rule on a metric is broken.
What to measure: proven frameworks.
| Framework | Signals | Apply to |
|---|---|---|
| Google SRE's four golden signals | Latency, traffic, errors, saturation | Any user-facing service, such as the store API |
| RED method | Rate, Errors, Duration | Each service and endpoint |
| USE method | Utilization, Saturation, Errors | Resources: CPU, memory, disk, connections |
The integration's own signals. Services can each look healthy while the integration between them fails, so also watch the connections:
| Signal | Where to get it | Healthy | Problem looks like |
|---|---|---|---|
| Queue depth (ready messages) per queue | RabbitMQ management UI or HTTP API; Module 3's queue_check.py (3.1.8) | Near zero, or rising briefly and draining | Keeps rising: a consumer is down or too slow |
| Consumers per queue | Same | At least 1 per queue | 0: nobody is processing |
| Publish rate vs. ack rate | Same | About equal over time | Ack rate lower for minutes |
| Messages in any DLQ | Same | 0 | Above 0: a person must look (3.2.8) |
| Age of the oldest message | Consumer logs, or Prometheus metrics | Seconds | Minutes or hours |
| End-to-end latency, payment to all four consumers | Correlation IDs and timestamps in logs (4.2.5) | Within the SLO, for example 60 s | Above the SLO |
| Partner API errors and latency | Consumer logs (retry_scheduled, duration) | Rare retries | Many 5xx or timeouts |
| Security signals | Store logs | Few 401/403 | A burst of 401s, bad webhook signatures, or 403s from one client |
| Broker resources | RabbitMQ memory and disk alarms (Module 3) | No alarms | Alarm raised: publishers are blocked |
Tools. A typical open-source monitoring stack, which you will meet at many companies:
- Prometheus collects metrics by "scraping" HTTP endpoints. RabbitMQ's built-in Prometheus plugin serves its metrics on port 15692 (/metrics for totals, /metrics/per-object for each queue). Python services can expose their own with the prometheus_client library.
- Grafana draws dashboards from Prometheus (and logs from Loki); the RabbitMQ team publishes ready-made Grafana dashboards.
- Alertmanager (with Prometheus) or Grafana alerting sends alerts to email, Slack, Microsoft Teams, or SMS.
- Error tracking tools such as Sentry collect application exceptions with stack traces and group them.
- Uptime or synthetic monitoring (such as Uptime Kuma or a cloud uptime check) calls your public endpoints from outside every minute, the way a customer would.
For the course project, the RabbitMQ management UI, queue_check.py, log_report.py, and one external uptime check are enough; Prometheus and Grafana are a strong addition if time allows.
Alerts that people will trust. Alerts that fire too often get ignored (alert fatigue), and an ignored alert is worse than none. Industry guidance:
- Alert on symptoms that affect users or data, tied to SLOs: "orders not reaching the courier," not "CPU at 70%."
- Every alert must be actionable: it says what is wrong and links to what to do (a runbook, 4.2.8).
- Use severities: page someone for urgent problems; send a ticket or message for things that can wait until morning.
- Include a duration to avoid flapping: "for 5 minutes," not "at any moment."
Example alert rules for the store:
| Alert | Rule | Severity | First action |
|---|---|---|---|
| Orders stuck | Any *.order-confirmed queue depth above 100 for 10 minutes | Page | Check that queue's consumer and partner API |
| No consumer | A main queue has 0 consumers for 2 minutes | Page | Check the consumer container's logs and restart policy |
| Dead letters | Any DLQ above 0 | Ticket (page if above 20) | Triage with the DLQ procedure (3.2.8) |
| Checkout errors | More than 1% of POST /v1/orders fail for 5 minutes | Page | Check the store's logs and RabbitMQ readiness |
| Webhook signature failures | More than 10 in 5 minutes | Ticket | Check for a rotated secret, or an attack |
| Broker alarm | RabbitMQ memory or disk alarm | Page | Free space, drain queues, or add resources |
| Certificate expiry | TLS certificate expires in under 14 days | Ticket | Renew, and fix the automation |
Performance monitoring in production. The performance test (4.1.9) measured capacity once; monitoring measures it every day with real traffic. Watch the trends: if p95 latency or the courier consumer's processing time creeps up week by week, you can add capacity or fix a slow query before the next sale, not during it.
- "We have logs, so we have monitoring." Logs need someone to read them; monitoring tells you when to read them.
- "Monitor everything and alert on everything." That creates noise; alert on a few user-impacting symptoms.
- "Green containers mean the integration works." Every container can be running while messages pile up in a queue.
- "Monitoring is the operations team's job." The team that built the integration knows which numbers matter.
On a Friday night the courier partner changes its TLS certificate chain, and every booking call fails. The store, warehouse, and accounting are fine. Ten minutes later the "Orders stuck" alert pages the on-call student, the dashboard shows courier.order-confirmed rising with 1 consumer and an ack rate of zero, and the logs show certificate errors. The team updates the trusted CA bundle, the queue drains, and the 230 waiting orders are booked before morning, without a single customer complaint.
For your project, build a simple dashboard (the management UI plus a short script, or Grafana) showing at least: request rate and errors for your API, depth and consumers of each queue, and DLQ counts. Write five alert rules in the table format above.
- Name Google's four golden signals and give a store example of each.
- Why can every service look healthy while the integration is failing? Which metrics reveal it?
- What makes an alert actionable?
Show suggested answerHide suggested answerAdded in this edition
- Latency (p95 time of
POST /v1/orders), traffic (orders per minute), errors (rate of 5xx responses on checkout) and saturation (CPU or memory of the store container, or RabbitMQ memory). - Each service is up and answering, but the connections between them fail: a consumer is stopped, messages pile up, or a partner keeps returning errors. Queue depth, consumer count, publish vs ack rate, DLQ count, end-to-end latency and partner API errors reveal it.
- It reports a real symptom that affects customers or data, says clearly what is wrong, and links to a runbook with what to do. If nobody needs to act, it should not be an alert.
Monitor services with the golden signals and the integration with queue depth, consumers, publish versus ack rate, DLQ counts, end-to-end latency, and partner errors. Alert on symptoms that affect customers or data, make every alert actionable, and watch trends so you add capacity before you need it.
#4.2.7API and service versioning
The store team wants to rename totalAmount to amount and split customer into first and last names. But the warehouse, accounting, courier, and notification systems, plus the website and a partner's app, all depend on today's API and events, and each team updates on its own schedule. If the store simply deploys the change, four integrations break at once. Versioning lets a system change without forcing everyone else to change on the same day.
When a phone maker changes its charging port, millions of old chargers stop working. The kind approach: keep the old port for a while, sell adapters, announce the change early, and give a date after which the old port is gone. Versioning is the adapter and the announcement for your API and events.
Definitions.
- A contract is what consumers rely on: endpoints, fields, types, meanings, status codes, event names, and routing keys.
- A breaking change forces consumers to change their code; a non-breaking (backward-compatible) change does not.
- A version identifies one form of the contract, so producers and consumers can agree on which one they use.
Breaking or not? This table is worth memorizing:
| Change | Breaking? | Why |
|---|---|---|
| Add an optional field to a response or event | No | Consumers that ignore unknown fields are unaffected (4.1.7) |
| Add a new endpoint or a new event type | No | Nobody uses it yet |
| Add an optional request parameter | No | Old requests still work |
| Remove or rename a field | Yes | Code reading totalAmount gets nothing |
| Change a field's type or format (number to string, local time to UTC) | Yes | Parsing fails or the meaning changes |
| Make an optional request field required | Yes | Old requests are now rejected |
| Change the meaning of a value (amount now in centavos) | Yes, and the most dangerous | Nothing fails; the numbers are silently wrong |
| Add a new value to a code list (status: RETURNED) | Often | Consumers with a fixed list may crash; design them to handle unknown values |
| Change a routing key, queue name, or exchange | Yes | Messages stop reaching consumers |
Semantic Versioning. The most widely used scheme for releases is Semantic Versioning (SemVer) 2.0.0: MAJOR.MINOR.PATCH, for example 2.4.1.
- MAJOR increases for breaking changes (1.x to 2.0.0).
- MINOR increases for new, backward-compatible features (2.3 to 2.4).
- PATCH increases for backward-compatible bug fixes (2.4.0 to 2.4.1).
Use SemVer for your releases and images (store-api:2.4.1, a Git tag v2.4.1) so everyone knows exactly what is running (4.2.3). APIs usually expose only the major version to clients (/v2/), because minor and patch changes do not require clients to act.
Ways to version an HTTP API.
| Approach | Example | Used by | Notes |
|---|---|---|---|
| URL path | GET /v2/orders/ORD-10421 | Most public APIs | Visible, simple to route at the gateway (4.2.3); the course default |
| Request header or media type | Accept: application/vnd.store.v2+json | Some large APIs | Keeps URLs clean; harder to test in a browser |
| Query parameter | /orders/ORD-10421?version=2 | Some cloud APIs | Easy to forget |
| Date-based version | A header such as Stripe-Version: 2024-06-20 | Stripe | Each client is pinned to the date it integrated |
Whatever you choose, run old and new side by side for a published period. The store would keep /v1/orders while adding /v2/orders, sharing the same business logic underneath.
Versioning events. Events are harder than APIs: once published, a message may sit in a queue for hours, and every subscriber reads it. Common practice, building on Module 3:
- Put the version in the event type: com.example.store.order.confirmed.v1 (CloudEvents type, 3.1.6), and validate against a versioned schema.
- Prefer additive changes inside a version; consumers must ignore unknown fields (the tolerant reader pattern).
- For a breaking change, publish both versions for a while, on different routing keys such as order.confirmed and order.confirmed.v2; each consumer moves when ready; stop publishing v1 only when no queue is bound to it.
- Large systems keep schemas in a schema registry that rejects incompatible changes automatically.
Deprecation: retiring a version politely. A version should end in steps, never by surprise:
- Announce the new version and a sunset date, with a migration guide (4.2.8).
- Mark the old version in every response. Two standard HTTP headers exist for this: Deprecation (RFC 9745) says the endpoint is deprecated, and Sunset (RFC 8594) says when it will stop working:
HTTP/1.1 200 OK
Deprecation: @1799020800
Sunset: Wed, 30 Jun 2027 23:59:59 GMT
Link: <https://docs.store.example.ph/migrate-v2>; rel="deprecation"- Watch who still calls the old version, using client_id in the logs (4.2.5), and contact those teams.
- Remove it after the sunset date, and remove it from the API inventory.
Forgotten old versions are OWASP's API9:2023 Improper Inventory Management: an old /v1/ without today's security fixes is an easy way in. Keep a list of every version and endpoint that is running.
Contract tests protect versions. Consumer-driven contract tests (3.2.9) let each consumer declare the fields it depends on. If the store's change breaks any consumer's contract, the store's build fails before release, which is the fastest possible warning that a "small" change is actually breaking.
- "Renaming a field is a small change." For every consumer, it is a breaking change.
- "We'll just tell the other teams to update on Monday." Teams have their own priorities and releases; give them a version and time.
- "Version numbers are for public APIs only." Internal integrations break just as easily, and internal teams are often slower to update.
- "Keep every old version forever, to be safe." Old versions cost maintenance and become security risks; deprecate and remove them on schedule.
The store needs to send amounts as integer centavos instead of decimal strings. Changing totalAmount in place would make the accounting system record ₱90,000 for a ₱900 sale, with no error anywhere. Instead, the team adds com.example.store.order.confirmed.v2 with a new field totalCentavos, publishes v1 and v2 side by side, updates the accounting consumer to v2 first, then the others, and stops v1 after the last queue moves, three months later as announced.
List five changes your team might make to your project's API or events. Classify each as breaking or non-breaking, and for each breaking one write the version plan: new version name, how long both run, how consumers are told, and how you will know when the old one can be removed.
- Give two breaking and two non-breaking changes to the order.confirmed event.
- What do MAJOR, MINOR, and PATCH mean in Semantic Versioning?
- Describe the four steps of deprecating an API version.
Show suggested answerHide suggested answerAdded in this edition
- Breaking: rename or remove
totalAmount; change the amount to centavos; change the routing key. Non-breaking: add an optional field such asvoucherCode; add a new event type. - MAJOR: breaking changes. MINOR: new backward-compatible features. PATCH: backward-compatible bug fixes.
- (1) Announce the new version and a sunset date with a migration guide; (2) mark the old version in every response with the
DeprecationandSunsetheaders; (3) watch who still calls it and contact them; (4) remove it after the sunset date and update the API inventory.
Know which changes break consumers; prefer additive changes and tolerant readers. Version releases with SemVer, APIs with a major version (usually in the path), and events in their type name. For breaking changes, run old and new side by side, announce and mark deprecation with standard headers, watch usage, and remove old versions on schedule.
#4.2.8Integration documentation
A new partner, a pharmacy delivery company, wants to receive the store's order.confirmed events. Their developers cannot read your mind or your code: they need to know the exchange, the routing key, the message fields and their meaning, how to authenticate, and what happens when something fails. Months later, an on-call student facing a 2 a.m. alert needs to know what to do. An integration is only as usable, and as maintainable, as its documentation.
Passengers need the route sign: where the jeepney goes and where it stops. The driver needs a different document: how to check the brakes, what to do when the engine overheats. Integration documentation also serves different readers, and each needs a different document.
Who reads integration documentation, and what they need.
| Reader | Needs to know | Document |
|---|---|---|
| Developers of a connecting system | Endpoints, events, fields, authentication, errors, versions | Interface specifications (OpenAPI, AsyncAPI), integration guide |
| Your own future team | Why the system is built this way | Architecture overview, decision records |
| On-call operators | What to do when an alert fires | Runbooks |
| Whoever deploys it | How to install, configure, and update | Deployment guide (README), configuration reference |
| Testers and evaluators | What was tested and the results | Test plan and test report |
| Data Protection Officer, auditors | What personal data flows where, and why | Data flow inventory (4.1.10) |
1. Architecture overview. One or two diagrams and a page of text: which systems exist, how they connect (API, queue, webhook), and who owns each. The C4 model is a popular way to draw this at levels of detail: a context diagram (your system and its partners) and a container diagram (the store API, RabbitMQ, the four consumers, like the picture in this module's overview). Keep diagrams in the repository and update them with the code.
2. Interface specifications: machine-readable contracts. Industry standards let you describe interfaces in a file that both people and tools can read:
- OpenAPI describes HTTP APIs; version 3.1 is the most widely supported by tools, and 3.2 was released in 2025. Tools such as Swagger UI and Redoc turn it into interactive documentation, and it can generate client code and contract tests.
- AsyncAPI (currently version 3.0) does the same for event-driven interfaces: channels, messages, and protocol bindings such as AMQP.
Part of the store's OpenAPI description, including its OAuth 2.0 security (4.1.2):
openapi: 3.1.0
info:
title: Online Store Integration API
version: 1.2.0
servers:
- url: https://store.example.ph
paths:
/v1/orders:
post:
summary: Create an order
security:
- storeOAuth: [orders:write]
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewOrder'
responses:
'201': {description: Order created, status PENDING_PAYMENT}
'401': {description: Missing, invalid, or expired token}
'403': {description: Token lacks the orders:write scope}
'422': {description: Validation failed; details lists each problem}
components:
securitySchemes:
storeOAuth:
type: oauth2
flows:
clientCredentials:
tokenUrl: https://store.example.ph/oauth/token
scopes:
orders:read: Read order status and items
orders:write: Create ordersAnd the order.confirmed event in AsyncAPI, including how it is routed in RabbitMQ:
asyncapi: 3.0.0
info:
title: Online Store Events
version: 1.0.0
channels:
orderConfirmed:
address: order.confirmed
messages:
orderConfirmed:
$ref: '#/components/messages/OrderConfirmed'
bindings:
amqp:
is: routingKey
exchange:
name: orders
type: topic
durable: true
operations:
publishOrderConfirmed:
action: send
channel:
$ref: '#/channels/orderConfirmed'
components:
messages:
OrderConfirmed:
name: OrderConfirmed
contentType: application/json
payload:
$ref: './schemas/order-confirmed.v1.json'The JSON Schema from Module 3 (3.1.6) plugs in as the payload. With these files, the pharmacy's developers can see everything they need, and your contract tests can check that the store still matches what it promises.
3. Data dictionary and mapping. For each field: name, type, required or optional, meaning, units and format, allowed values, and example. Add the mapping to each partner's fields where names differ (orderId here, ref_no in the courier's API). This is where the semantic agreements of 4.1.7 (UTC times, decimal-string pesos, status codes) are written down.
4. Architecture decision records (ADRs). Short notes, one per important decision, describing the context, the decision, and its consequences, a format popularized by Michael Nygard. Example: "ADR-004: Use RabbitMQ quorum queues for order events. Context: orders must survive a node failure. Decision: all order queues are quorum queues. Consequences: slightly lower throughput; requires a three-node cluster in production." Future team members learn why, not just what.
5. Runbooks. Step-by-step instructions for each alert (4.2.6), written so a teammate who did not build the system can follow them at 2 a.m.:
Alert: any *.order-confirmed queue above 100 messages for 10 minutes. (1) Open the management UI; note which queue, its consumer count, and its publish and ack rates. (2) If consumers = 0: docker compose ps, then docker compose logs --since 30m <service>; restart the service and confirm consumers reappear. (3) If consumers exist but ack rate is low: check retry_scheduled lines for partner errors and the partner's status page. (4) If the partner is down: no action on messages; they wait; notify the business owner. (5) After recovery, confirm the queue drains and check the DLQ (3.2.8). Escalate to the team lead if not resolved in 30 minutes.
6. Deployment guide and configuration reference. A README.md that takes a new teammate from clone to running system: prerequisites, .env variables with meanings (from 4.2.2, never real values), commands, and how to verify it works. Lab 4.2 is an example.
7. Changelog and versions. A CHANGELOG.md listing each version's additions, changes, fixes, and deprecations, so partners can see what changed (4.2.7). The Keep a Changelog format is widely used.
Docs as code. Keep documentation in the same Git repository as the code, in Markdown, OpenAPI, and AsyncAPI files, reviewed in the same pull requests. Documentation stored somewhere separate drifts out of date quickly; a change that alters an interface without updating its specification should not pass review.
- "The code is the documentation." Partners cannot see your code, and code does not explain why.
- "We'll write the documentation at the end." By then nobody remembers the decisions; write specifications first and update them with each change.
- "More pages are better." Readers need accurate, findable answers; a short, current document beats a long, outdated one.
- "A Word file emailed to the partner is enough." It is outdated the moment you change anything; publish versioned specifications.
The pharmacy delivery partner integrates in two days instead of two weeks because the store sends them the AsyncAPI file, the JSON Schema, a sandbox RabbitMQ user, and the integration guide. Their only question is about time zones, which leads the store team to add "all times are RFC 3339 with offset" to the data dictionary, where it should have been from the start.
Write the documentation set for your project: an architecture diagram, an OpenAPI or AsyncAPI file for at least one interface, a data dictionary for one message, one ADR, one runbook for your most likely failure, and a README that a classmate can follow to run your system. Then ask a classmate from another group to try the README and record where they got stuck.
- Which standard describes HTTP APIs, and which describes event-driven interfaces?
- What is an architecture decision record, and why is it useful?
- What makes a runbook good?
Show suggested answerHide suggested answerAdded in this edition
- OpenAPI describes HTTP APIs; AsyncAPI describes event-driven (message) interfaces.
- A short note per important decision (context, decision, consequences). It tells future team members why the system is built this way, so decisions are not reversed by accident or argued again.
- Clear, numbered steps for one specific alert that a teammate who did not build the system can follow at 2 a.m.: what to check, commands to run, how to fix, and how to confirm it worked. It must be kept up to date with the system.
Document for each reader: architecture overviews, machine-readable interface specifications (OpenAPI, AsyncAPI) with schemas, a data dictionary, decision records, runbooks, a deployment guide, and a changelog. Keep documentation in the repository with the code and update it in the same change.
#4.2.9System evaluation and maintenance
The integration is deployed and demonstrated. Is it actually good? "It works" is not an answer a client, an adviser, or an evaluator can check. And it will not stay good on its own: partners change their APIs, certificates expire, libraries get security fixes, traffic grows. Evaluation measures the solution against defined criteria with evidence; maintenance keeps it meeting them over time.
Before registration, a car is inspected against fixed criteria: brakes, lights, emissions, each with a measurable limit. After that, it needs oil changes every 5,000 km, new tires every few years, and repairs when something breaks. Nobody calls a car "done" when it leaves the factory. Integrations are the same.
Definitions.
- System evaluation is judging a system against stated criteria using evidence: measurements, test results, reviews.
- Quality characteristics are the dimensions being judged. The international standard ISO/IEC 25010 lists, among others, functional suitability, performance efficiency, compatibility (including interoperability), reliability (including availability and recoverability), security, and maintainability.
- Maintenance is everything done to a system after delivery to keep it working, correct, secure, and useful.
Evaluating with defined technical criteria. This module's learning outcome names four areas: performance, reliability, security, and maintainability. For each, a criterion must be measurable, and backed by evidence from your work. An evaluation table for the store (your project needs one like it, with your own numbers):
| Area | Criterion (target) | Evidence | Result | Notes |
|---|---|---|---|---|
| Functional | Every paid order reaches all four consumers exactly once | Integration tests IT-01 to IT-08 (4.1.6) | ||
| Performance | p95 of POST /v1/orders below 500 ms at 50 users | Locust report (4.1.9) | ||
| Performance | Courier queue drains within 10 min after a 5-min spike | Spike test + queue graph | ||
| Reliability | No order lost or duplicated in four failure experiments | Failure test records (4.1.8) | ||
| Reliability | Recovery within RTO of 30 min after broker restart | Timed experiment | ||
| Interoperability | Edge-case data (ñ, 23:30 +08:00, ₱0.10) correct in all consumers | Interoperability matrix (4.1.7) | ||
| Security | Authentication and authorization on every endpoint; each service has its own least-privilege broker user | Lab 4.1 tests; RabbitMQ permissions screenshot | ||
| Security | No secrets in the repository or images; TLS on public endpoints | Secret scan output; TLS check | ||
| Security and privacy | Each system receives only the personal data it needs; none in logs | Data flow table (4.1.10); log sample | ||
| Maintainability | A classmate deploys from the README in under 30 min | Timed trial (4.2.8) | ||
| Maintainability | Interfaces documented in OpenAPI/AsyncAPI; versioning plan exists | Specification files; version plan (4.2.7) | ||
| Operability | Alerts exist for stuck queues, DLQs, and API errors; runbook for each | Alert table; runbooks (4.2.6, 4.2.8) |
A result of "not met" is not a failure of the evaluation: an honest "not met, because the courier stub is single-threaded; production would run three instances" shows understanding. Inventing a "met" without evidence is a failure of integrity, one of this module's values.
Other evaluation methods used in industry.
- Architecture review: walk through the design against quality scenarios ("if a RabbitMQ node fails during a sale, then...") to find risks; formal methods such as ATAM do this systematically.
- Code review and static analysis: linters and security scanners (4.1.10) on every change.
- Comparing against the original requirements: go back to the integration requirements you wrote in Module 1. Which are met, partly met, or not met?
- Post-incident reviews (postmortems): after every real failure, a blameless write-up of what happened, why, and what will change. Blameless means the focus is on fixing the system and process, not punishing a person, so people report problems honestly.
Kinds of maintenance. The software maintenance standard ISO/IEC 14764 describes four types:
| Type | Purpose | Store integration example |
|---|---|---|
| Corrective | Fix faults found in use | The courier consumer crashes on addresses with emoji |
| Adaptive | Keep working in a changed environment | The courier partner releases API v3 and retires v2; Python 3.12 reaches end of support |
| Perfective | Improve performance or add features | Add a second courier partner; speed up the accounting consumer |
| Preventive | Prevent future problems | Rotate keys, update libraries, add a missing alert, pay down technical debt |
Integrations need more adaptive maintenance than standalone systems, because they depend on partners that change on their own schedule. Subscribe to every partner's change notices, status page, and deprecation announcements.
A maintenance calendar. Routine tasks only happen if they are scheduled:
| How often | Task |
|---|---|
| Daily | Check alerts and dashboards; review DLQs (3.2.8) |
| Weekly | Review error trends and slow requests; apply urgent security updates |
| Monthly | Update dependencies (pip list --outdated, Dependabot); review access lists and remove unused accounts |
| Quarterly | Rotate secrets and API keys (4.1.5); test a backup restore (4.1.8); review capacity against growth |
| Before expiry | Renew TLS certificates (automate it); migrate off deprecated partner API versions |
| Every release | Run all tests; update documentation and the changelog; check the API inventory (4.2.7) |
Technical debt. Shortcuts taken to meet a deadline (in-memory orders, one worker, no TLS inside the network, a single RabbitMQ node) are technical debt: acceptable for a prototype, as long as they are written down with the plan to repay them. Your evaluation should list them honestly; it shows you know the difference between a prototype and a production system.
- "It passed the demo, so it's evaluated." A demo shows one happy path once; evaluation uses criteria and evidence.
- "Maintenance is just fixing bugs." Corrective work is often the smallest part; adaptive and preventive work keep integrations alive.
- "If nothing changes on our side, nothing will break." Partners, certificates, and libraries change without asking you.
- "Admitting weaknesses lowers the grade." Hidden weaknesses are worse; documented ones with a plan show expertise.
Six months after launch, the courier partner emails a notice that API v2 will be retired in 90 days. Because the team has a partner-change process, an adapter in the courier consumer, contract tests, and a runbook, the migration is a planned two-week task (adaptive maintenance) instead of an emergency on day 91. The team's evaluation table is updated with the new version's test results.
Build the evaluation table for your own project with at least ten criteria covering performance, reliability, security, and maintainability, fill in the evidence and results honestly, and list your technical debt with a repayment plan. Then write a one-page maintenance plan using the calendar above.
- Why must evaluation criteria be measurable and backed by evidence?
- Name the four types of maintenance and give a store example of each.
- Why do integrations need more adaptive maintenance than standalone systems?
Show suggested answerHide suggested answerAdded in this edition
- So the results can be checked and repeated: "fast" or "secure" cannot be proven, but "p95 under 500 ms at 20 orders/s, from test run X" can. Evidence keeps the evaluation honest.
- Corrective: fix the courier consumer crashing on emoji in addresses. Adaptive: migrate to courier API v3 before v2 is retired. Perfective: add a second courier partner or speed up accounting. Preventive: rotate keys, update libraries, add a missing alert.
- Integrations depend on partners that change on their own schedule: new API versions, retired endpoints, new certificates and formats. Every such change forces your side to adapt, even when your own code has not changed.
Evaluate against measurable criteria for performance, reliability, security, and maintainability, with evidence from your tests, monitoring, and documentation, and report results honestly. Plan corrective, adaptive, perfective, and preventive maintenance on a calendar, watch partners for changes, and record technical debt with a plan to repay it.
#Lab 4.2: Deploy, monitor, and analyze the integrated store
Package the store API, RabbitMQ, and the four consumers as containers; deploy them together with one command, with per-service credentials, health checks, restart policies, and structured logs; then push orders through, break things on purpose, and use logs and queue metrics to find and explain every failed transaction.
Folder layout.
lab42/
├── docker-compose.yml
├── .env.example # committed; copy to .env (never committed)
├── store/ # Dockerfile, requirements.txt, .dockerignore, app.py, publisher.py, jsonlog.py
├── consumer/ # Dockerfile, requirements.txt, .dockerignore, service.py, setup_topology.py, jsonlog.py
└── tools/ # register_client.py, send_webhook.py, locustfile.py, log_report.pyThe store/ and consumer/ Dockerfiles, .dockerignore files, and most of docker-compose.yml were shown in 4.2.3; the complete files are below.
Put the same file in both store/ and consumer/:
"""Structured (JSON) logging shared by the store and the consumers.
Every log line is one JSON object, so tools can search and count by field:
{"time": "...", "level": "INFO", "service": "store", "message": "request", ...}
"""
import json
import logging
import os
import sys
from datetime import datetime, timezone
SERVICE_NAME = os.environ.get("SERVICE_NAME", "unknown")
class JsonFormatter(logging.Formatter):
def format(self, record):
entry = {
"time": datetime.fromtimestamp(record.created, timezone.utc)
.isoformat(timespec="milliseconds"),
"level": record.levelname,
"service": SERVICE_NAME,
"message": record.getMessage(),
}
entry.update(getattr(record, "fields", {})) # extra={"fields": {...}}
if record.exc_info:
entry["error"] = self.formatException(record.exc_info)
return json.dumps(entry, ensure_ascii=False)
def get_logger(name):
"""Log to standard output: the platform (Docker) collects it, not the app."""
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logger = logging.getLogger(name)
logger.handlers[:] = [handler]
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
logger.propagate = False
return loggerOne connection per process, with publisher confirms, reopened if the broker closed it:
"""Lab 4.2: publishes the store's events to RabbitMQ with publisher confirms.
One connection per process, opened lazily and reopened if the broker
closed it. All settings come from environment variables.
"""
import json
import os
import pika
EXCHANGE = "orders"
class Publisher:
def __init__(self):
self._connection = None
self._channel = None
def _connect(self):
params = pika.ConnectionParameters(
host=os.environ["RABBITMQ_HOST"],
port=int(os.environ.get("RABBITMQ_PORT", "5672")),
virtual_host=os.environ.get("RABBITMQ_VHOST", "/"),
credentials=pika.PlainCredentials(os.environ["RABBITMQ_USER"],
os.environ["RABBITMQ_PASSWORD"]),
heartbeat=30,
blocked_connection_timeout=30,
)
self._connection = pika.BlockingConnection(params)
self._channel = self._connection.channel()
self._channel.confirm_delivery()
def _is_open(self):
return (self._connection is not None and self._connection.is_open
and self._channel is not None and self._channel.is_open)
def ready(self):
"""Used by the readiness check: can we reach the broker right now?"""
try:
if not self._is_open():
self._connect()
return True
except pika.exceptions.AMQPError:
return False
def publish(self, routing_key, event, correlation_id):
"""Publish one event; raises if the broker did not confirm it."""
properties = pika.BasicProperties(
content_type="application/json",
delivery_mode=pika.DeliveryMode.Persistent,
message_id=event["id"],
correlation_id=correlation_id,
)
body = json.dumps(event)
for attempt in (1, 2): # one reconnect if the old connection died
try:
if not self._is_open():
self._connect()
self._channel.basic_publish(exchange=EXCHANGE, routing_key=routing_key,
body=body, properties=properties,
mandatory=True)
return
except (pika.exceptions.AMQPConnectionError,
pika.exceptions.AMQPChannelError):
self._connection = None
if attempt == 2:
raiseStart from Lab 4.1's app.py and make five changes.
(a) Imports and logger: remove import logging, add from decimal import Decimal, and replace the log = logging.getLogger("store") line:
from jsonlog import get_logger
from publisher import Publisher
...
log = get_logger("store")
publisher = Publisher()(b) A catalog and request logging with correlation IDs, after SEEN_WEBHOOK_IDS = set():
CATALOG = {"BAG-TOTE-01": "450.00", "NB-A5-80": "45.00"} # SKU -> unit price (PHP)
@app.before_request
def start_request():
g.started = time.perf_counter()
# Reuse the caller's correlation ID, or start a new one for this request.
g.correlation_id = request.headers.get("X-Correlation-ID") or str(uuid.uuid4())
@app.after_request
def log_request(response):
response.headers["X-Correlation-ID"] = g.correlation_id
if not request.path.startswith("/health"): # keep health checks quiet
log.info("request", extra={"fields": {
"method": request.method, "path": request.path,
"status": response.status_code,
"duration_ms": round((time.perf_counter() - g.started) * 1000, 1),
"client_id": g.get("client_id"), "correlation_id": g.correlation_id,
}})
return response(c) In create_order, after the schema check, a semantic check, and the order ID as correlation ID:
unknown = [i["sku"] for i in body["items"] if i["sku"] not in CATALOG]
if unknown: # semantic check: SKU must exist
return jsonify(error="validation_failed",
details=[f"unknown sku: {sku}" for sku in unknown]), 422
order_id = f"ORD-{uuid.uuid4().hex[:8].upper()}"
g.correlation_id = order_id # one ID for this order everywhere(d) Replace the end of payment_webhook, from event = json.loads(raw), so a paid order publishes OrderConfirmed, and add the event builder:
event = json.loads(raw)
if event["id"] in SEEN_WEBHOOK_IDS: # providers retry: be idempotent
return jsonify(status="duplicate_ignored"), 200
order = ORDERS.get(event.get("order_id"))
if order is None:
return jsonify(error="unknown_order"), 404
if event["type"] == "payment.succeeded":
g.correlation_id = order["order_id"] # follow this order through every system
try:
publisher.publish("order.confirmed", order_confirmed_event(order),
correlation_id=order["order_id"])
except Exception:
log.exception("publish_failed", extra={"fields": {
"order_id": order["order_id"], "correlation_id": order["order_id"]}})
return jsonify(error="temporarily_unavailable"), 503 # gateway will retry
order["status"] = "CONFIRMED"
log.info("order_confirmed", extra={"fields": {
"order_id": order["order_id"], "correlation_id": order["order_id"]}})
SEEN_WEBHOOK_IDS.add(event["id"]) # only after the work succeeded
return jsonify(status="ok"), 200
def order_confirmed_event(order):
"""The OrderConfirmed event from Module 3, as a CloudEvents 1.0 envelope.
Money is sent as decimal strings, never binary floats (4.1.7)."""
items = [{**i, "unitPrice": CATALOG[i["sku"]]} for i in order["items"]]
total = sum(Decimal(i["unitPrice"]) * i["quantity"] for i in items)
return {
"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["order_id"], "customerId": order["customer_id"],
"items": items, "totalAmount": f"{total:.2f}", "currency": "PHP"},
}If publishing fails, the webhook answers 503 and does not mark the event as seen, so the gateway's retry tries again. (A production store would save the event in an outbox in the same database transaction, as in Module 3.)
(e) Replace /health with the liveness and readiness endpoints from 4.2.4 (/health/live and /health/ready).
Start from Lab 3.2's service.py and change four things: read SERVICE_NAME and the RABBITMQ_* settings from the environment instead of sys.argv and localhost; keep the SQLite file in DATA_DIR (a volume); log JSON lines; and let the process exit if the connection drops, so Docker restarts it. The parts that change:
from jsonlog import get_logger
service = os.environ["SERVICE_NAME"]
log = get_logger(service)
MAIN_Q = f"{service}.order-confirmed"
DLQ = f"{MAIN_Q}.dlq"
db = sqlite3.connect(os.path.join(os.environ.get("DATA_DIR", "."), f"{service}.db"))def on_message(ch, method, properties, body):
tag = method.delivery_tag
msg_id = properties.message_id
ctx = {"message_id": msg_id, "correlation_id": properties.correlation_id,
"queue": MAIN_Q}
started = time.perf_counter()
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:
log.info("duplicate_skipped", extra={"fields": ctx})
ch.basic_ack(tag)
return
result = handle_order_confirmed(event)
db.execute("INSERT OR REPLACE INTO results VALUES (?, ?)",
(event["data"]["orderId"], result))
ch.basic_ack(tag)
log.info("processed", extra={"fields": {**ctx, "result": result,
"duration_ms": round((time.perf_counter() - started) * 1000, 1)}})
except PermanentError as error:
send_to_dlq(ch, body, properties, str(error))
ch.basic_ack(tag)
log.error("dead_lettered", extra={"fields": {**ctx, "reason": str(error)}})
except TransientError as error:
attempt = failed_attempts(properties) + 1
if attempt >= MAX_ATTEMPTS:
send_to_dlq(ch, body, properties, str(error))
ch.basic_ack(tag)
log.error("dead_lettered", extra={"fields": {
**ctx, "reason": str(error), "attempt": attempt}})
else:
ch.basic_reject(tag, requeue=False) # goes to the wait queue
log.warning("retry_scheduled", extra={"fields": {
**ctx, "reason": str(error), "attempt": attempt}})
params = pika.ConnectionParameters(
host=os.environ["RABBITMQ_HOST"],
port=int(os.environ.get("RABBITMQ_PORT", "5672")),
virtual_host=os.environ.get("RABBITMQ_VHOST", "/"),
credentials=pika.PlainCredentials(os.environ["RABBITMQ_USER"],
os.environ["RABBITMQ_PASSWORD"]),
heartbeat=30,
)
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.basic_qos(prefetch_count=int(os.environ.get("PREFETCH", "1")))
channel.basic_consume(queue=MAIN_Q, on_message_callback=on_message)
log.info("started", extra={"fields": {"queue": MAIN_Q}})
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()
# If the broker connection is lost, start_consuming() raises and the process
# exits; Docker's restart policy starts it again (4.2.4).parse, handle_order_confirmed, failed_attempts, and send_to_dlq are unchanged from Lab 3.2.
Runs once as the setup service. Each application gets its own RabbitMQ user with least privilege (4.1.1):
"""Lab 4.2: create RabbitMQ users, permissions, exchanges, and queues.
Runs once at deployment (the `setup` service in docker-compose.yml) with the
admin account. Each application gets its own user with least privilege (4.1.1).
Safe to run again: every step is idempotent.
"""
import base64
import json
import os
import urllib.request
import pika
HOST = os.environ["RABBITMQ_HOST"]
ADMIN = (os.environ["RABBITMQ_ADMIN_USER"], os.environ["RABBITMQ_ADMIN_PASSWORD"])
EXCHANGE = "orders"
SERVICES = ["warehouse", "accounting", "courier", "notification"]
RETRY_DELAY_MS = 10_000
def management_api(method, path, body):
"""Call RabbitMQ's management HTTP API (port 15672) as the admin."""
auth = base64.b64encode(f"{ADMIN[0]}:{ADMIN[1]}".encode()).decode()
req = urllib.request.Request(f"http://{HOST}:15672/api{path}", method=method,
data=json.dumps(body).encode(),
headers={"Authorization": f"Basic {auth}",
"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status
def create_user(user, password, configure, write, read):
management_api("PUT", f"/users/{user}", {"password": password, "tags": ""})
management_api("PUT", f"/permissions/%2F/{user}",
{"configure": configure, "write": write, "read": read})
print(f"user {user}: configure={configure!r} write={write!r} read={read!r}")
# 1. One user per application, allowed only what its job needs.
create_user("store", os.environ["RABBITMQ_STORE_PASSWORD"],
configure="^$", write=f"^{EXCHANGE}$", read="^$")
for service in SERVICES:
q = f"{service}\\.order-confirmed"
create_user(service, os.environ[f"RABBITMQ_{service.upper()}_PASSWORD"],
configure="^$",
write=f"^(amq\\.default|{q}\\.dlq)$", # its DLQ, via the default exchange
read=f"^{q}$") # only its own queue
# 2. The topology from Lab 3.2, declared with the admin account.
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=HOST, credentials=pika.PlainCredentials(*ADMIN)))
channel = connection.channel()
channel.exchange_declare(exchange=EXCHANGE, exchange_type="topic", durable=True)
for service in SERVICES:
main_q, wait_q = f"{service}.order-confirmed", f"{service}.order-confirmed.wait"
channel.queue_declare(queue=main_q, durable=True, arguments={
"x-queue-type": "quorum",
"x-dead-letter-exchange": "", "x-dead-letter-routing-key": wait_q})
channel.queue_bind(queue=main_q, exchange=EXCHANGE, routing_key="order.confirmed")
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})
channel.queue_declare(queue=f"{main_q}.dlq", durable=True,
arguments={"x-queue-type": "quorum"})
print(f"queues for {service} declared")
connection.close()The store's user may only write to the orders exchange; each consumer may only read its own queue and write to the default exchange for its DLQ. None may create or delete anything.
# Lab 4.2: the online store integration, deployed with Docker Compose.
name: store
x-rabbitmq-env: &rabbitmq-env
RABBITMQ_HOST: rabbitmq
RABBITMQ_PORT: "5672"
x-consumer: &consumer
build: ./consumer
restart: unless-stopped
depends_on:
setup:
condition: service_completed_successfully
volumes:
- consumer-data:/data
services:
rabbitmq:
image: rabbitmq:4-management
hostname: rabbitmq # RabbitMQ stores data per host name; keep it fixed
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_ADMIN_USER}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_ADMIN_PASSWORD}
ports:
- "127.0.0.1:15672:15672" # management UI: only from this machine
volumes:
- rabbitmq-data:/var/lib/rabbitmq
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
timeout: 10s
retries: 6
start_period: 30s
restart: unless-stopped
setup: # runs once: users, permissions, queues
build: ./consumer
command: ["python", "setup_topology.py"]
environment:
<<: *rabbitmq-env
SERVICE_NAME: setup
RABBITMQ_ADMIN_USER: ${RABBITMQ_ADMIN_USER}
RABBITMQ_ADMIN_PASSWORD: ${RABBITMQ_ADMIN_PASSWORD}
RABBITMQ_STORE_PASSWORD: ${RABBITMQ_STORE_PASSWORD}
RABBITMQ_WAREHOUSE_PASSWORD: ${RABBITMQ_WAREHOUSE_PASSWORD}
RABBITMQ_ACCOUNTING_PASSWORD: ${RABBITMQ_ACCOUNTING_PASSWORD}
RABBITMQ_COURIER_PASSWORD: ${RABBITMQ_COURIER_PASSWORD}
RABBITMQ_NOTIFICATION_PASSWORD: ${RABBITMQ_NOTIFICATION_PASSWORD}
depends_on:
rabbitmq:
condition: service_healthy
restart: "no"
store:
build: ./store
image: store-api:${APP_VERSION}
environment:
<<: *rabbitmq-env
SERVICE_NAME: store
APP_VERSION: ${APP_VERSION}
RABBITMQ_USER: store
RABBITMQ_PASSWORD: ${RABBITMQ_STORE_PASSWORD}
TOKEN_SIGNING_KEY: ${TOKEN_SIGNING_KEY}
PAYMENT_WEBHOOK_SECRET: ${PAYMENT_WEBHOOK_SECRET}
CLIENTS_JSON: ${CLIENTS_JSON}
ports:
- "8000:8000"
depends_on:
setup:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "-c",
"import urllib.request; urllib.request.urlopen('http://localhost:8000/health/ready', timeout=3)"]
interval: 15s
timeout: 5s
retries: 3
start_period: 10s
restart: unless-stopped
warehouse:
<<: *consumer
environment:
<<: *rabbitmq-env
SERVICE_NAME: warehouse
DATA_DIR: /data
RABBITMQ_USER: warehouse
RABBITMQ_PASSWORD: ${RABBITMQ_WAREHOUSE_PASSWORD}
accounting:
<<: *consumer
environment:
<<: *rabbitmq-env
SERVICE_NAME: accounting
DATA_DIR: /data
RABBITMQ_USER: accounting
RABBITMQ_PASSWORD: ${RABBITMQ_ACCOUNTING_PASSWORD}
courier:
<<: *consumer
environment:
<<: *rabbitmq-env
SERVICE_NAME: courier
DATA_DIR: /data
RABBITMQ_USER: courier
RABBITMQ_PASSWORD: ${RABBITMQ_COURIER_PASSWORD}
SIMULATE_OUTAGE: ${SIMULATE_OUTAGE:-0}
notification:
<<: *consumer
environment:
<<: *rabbitmq-env
SERVICE_NAME: notification
DATA_DIR: /data
RABBITMQ_USER: notification
RABBITMQ_PASSWORD: ${RABBITMQ_NOTIFICATION_PASSWORD}
volumes:
rabbitmq-data:
consumer-data:Copy .env.example to .env, add .env to .gitignore, and fill in random values (python -c "import secrets; print(secrets.token_urlsafe(24))" for each password). Register the storefront and warehouse clients with python tools/register_client.py as in Lab 4.1, put the combined JSON in CLIENTS_JSON='...', and their secrets in STOREFRONT_CLIENT_SECRET and WAREHOUSE_CLIENT_SECRET. Then:
docker compose up -d --build
docker compose ps # wait until store is "healthy"; setup "exited (0)"
docker compose logs setup # the users, permissions, and queues it created
curl -s localhost:8000/health/ready # {"rabbitmq":"ok","status":"ready"}Open http://localhost:15672 and log in as the admin. Under Admin, check the five application users and their permissions; under Queues, check the twelve queues and that each main queue has one consumer.
Use the Lab 4.1 commands (Step 5 of that lab) to get a storefront token and create an order, then send the payment webhook:
python tools/send_webhook.py ORD-XXXXXXXX
docker compose logs --no-log-prefix | python tools/log_report.py ORD-XXXXXXXXYou should see the request, order_confirmed, and one processed line from each of the four consumers, all with the same correlation ID.
Run each experiment with a new order, and after each one trace the order and check the queues (4.1.8):
- Courier outage: SIMULATE_OUTAGE=1 docker compose up -d courier, send an order, watch retry_scheduled then dead_lettered, then docker compose up -d courier (outage off) and replay the DLQ as in Module 3.
- Consumer down: docker compose stop warehouse, send two orders, check the queue depth, then docker compose start warehouse and confirm both are processed once.
- Crash before ack: docker compose kill accounting while orders arrive; restart it and confirm no duplicate sale is recorded.
- Broker restart: docker compose restart rabbitmq. Watch the store's readiness turn to 503 and back, and the consumers restart and reconnect. Confirm queued messages survived.
- Bad data: order a SKU that is not in the catalog; confirm the store rejects it with 422 before anything is published.
Run docker compose logs --no-log-prefix | python tools/log_report.py for the summary: messages per service and level, every failed transaction, and slow requests. Use Module 3's queue_check.py or the management UI to record queue depths during the experiments.
Repeat Lab 4.1's Locust test against the deployed store (--host http://localhost:8000), with and without docker compose up -d --scale courier=3, and record the API results and the maximum courier queue depth in the 4.1.9 report table.
Copy the folder (without .env) to a server or VM that has Docker, for example with git clone; create a new .env there with new secrets; and run docker compose up -d --build. Open only the ports clients need in the server's firewall (port 8000, or 80/443 if you add the Caddy reverse proxy from 4.2.3); do not open 5672 or 15672 to the internet. Use ssh -L 15672:localhost:15672 user@server to reach the management UI securely from your laptop.
the store's code in this lab was tested offline: 20 tests, including publishing, a failed publish returning 503 and succeeding on retry, readiness, and correlation IDs, pass with a stand-in for pika, and the consumer's processing, duplicate, and dead-letter paths were run the same way. The Compose file was validated with docker compose config. The full stack was not run against a live RabbitMQ broker while these notes were written, so run it once before class and adjust versions if needed.
#Final project: Deployed Systems Integration Project
Bring the system you analyzed in Module 1, connected with APIs in Module 2, and connected through messaging in Module 3 to a secured, tested, deployed, monitored, and documented state, then demonstrate and defend it. This is one continuous course project, not a new one.
Required components, and where each was taught. The course outline lists ten components. Use this as your checklist:
| # | Component | What "done" looks like | Sections |
|---|---|---|---|
| 1 | At least two integrated applications | Separately built and run systems with clearly different responsibilities | Module 1; 4.2.3 |
| 2 | An API or message-based connection | At least one REST API and, ideally, one RabbitMQ flow | Modules 2 and 3 |
| 3 | Data exchange and validation | Schemas at every boundary; semantic checks; agreed formats for dates, money, and codes | 4.1.4, 4.1.7 |
| 4 | Authentication and access control | Each system has its own identity; tokens or keys; scopes or roles; least-privilege broker users; signed webhooks if used | 4.1.1 to 4.1.3, 4.1.5 |
| 5 | Error and failure handling | Timeouts, retries with backoff, DLQs, idempotent consumers, health checks, restart policies | Module 3; 4.1.8, 4.2.4 |
| 6 | A deployed working prototype | Running in a shared or cloud environment reachable by the evaluators, started with one command | 4.2.1 to 4.2.3; Lab 4.2 |
| 7 | System and message logs | Structured logs with correlation IDs; a traced journey of one transaction | 4.2.5 |
| 8 | Integration test results | Test cases with expected and actual results, failure experiments, interoperability and performance results | 4.1.6 to 4.1.9 |
| 9 | Technical documentation | Architecture diagram, OpenAPI/AsyncAPI, data dictionary, ADRs, runbooks, README, changelog | 4.2.7, 4.2.8 |
| 10 | Project demonstration and evaluation | Live demonstration, evaluation table with evidence, defense | 4.2.9; below |
Suggested milestones. Adjust the weeks to your class calendar:
| Milestone | Deliverables |
|---|---|
| 1. Security | Caller-permission table, secrets inventory, authentication and validation working, Lab 4.1 tests adapted to your project |
| 2. Testing | Integration and interoperability test cases run, four failure experiments, a performance baseline |
| 3. Deployment | Compose file, deployed environment with its URL, health checks, structured logs, dashboard and alert rules |
| 4. Documentation and evaluation | Documentation set, evaluation table, maintenance plan, rehearsal of the demonstration |
The demonstration (about 20 minutes). A good integration demo shows the system working and failing safely:
- Context (2 min): the systems, the business flow, and the architecture diagram.
- Happy path (4 min): one transaction end to end in the deployed environment, then its journey in the logs by correlation ID.
- Security (3 min): a request without a token (401), with the wrong scope (403), invalid data (422), and a forged webhook or wrong broker credentials.
- Failure (5 min): stop a consumer or simulate a partner outage live; show the queue holding messages, the retries, the DLQ, and recovery with correct data.
- Evidence (4 min): test results, performance numbers, and the evaluation table with what is met and not met.
- Next steps (2 min): technical debt and what production would need.
Typical defense questions. Prepare answers backed by your own system:
- Why did you choose messaging, or an API, for each connection?
- What happens to a transaction if each one of your systems goes down?
- How do you know no transaction was lost or processed twice?
- Who can call each API and queue, and how is that enforced?
- Where are your secrets, and how would you rotate one today?
- What personal data does each system receive, and why does it need it?
- How would you change a field in your main message without breaking consumers?
- What would you monitor first in production, and what would page you at night?
Suggested evaluation rubric. Instructors may adjust the weights. Each criterion is rated on evidence, not on claims:
| Criterion | Weight | Excellent | Developing | Beginning |
|---|---|---|---|---|
| Integration design and data exchange | 15% | Clear contracts; validation at every boundary; interoperability issues handled | Contracts exist but gaps in validation or formats | Data passed without contracts or checks |
| Security and privacy | 20% | Per-system identities, least privilege, TLS where exposed, no secrets in code, data minimization | Authentication present but shared accounts, gaps, or secrets in config files | Little or no access control |
| Reliability and failure handling | 20% | Failure experiments show no loss or duplication; recovery measured | Retries and DLQs present but not tested | Failures lose or duplicate data |
| Testing evidence | 15% | Integration, interoperability, failure, and performance results, with evidence | Some test cases run, little evidence | Untested beyond the demo |
| Deployment and operations | 15% | One-command deployment, health checks, structured logs, monitoring and alerts | Deployed, but manual steps or weak logging | Runs only on a laptop |
| Documentation and evaluation | 10% | Complete, current documents; honest evaluation with evidence; maintenance plan | Partial documents; evaluation without evidence | Little documentation |
| Demonstration and defense | 5% | Clear demo including a live failure; confident, evidence-based answers | Happy path only; partial answers | Demo fails without explanation |
Report what your system actually does. Results that are "not met" with an honest explanation are worth more than claims that cannot be shown. Cite any code, libraries, or AI assistance you used, as your institution requires.
#Lesson 4.2 summary
Key takeaways
- Each environment, from development to production, is a complete copy of the integration with its own configuration, data, credentials, and matching partner endpoints; promote the same tested build (4.2.1).
- Keep everything that varies out of the code, supply it through the environment and secret stores, and validate it at start-up (4.2.2).
- Package systems as container images and run the integration with Docker Compose, using service names, volumes, health checks, and restart policies; put a reverse proxy or gateway in front (4.2.3).
- Set availability targets as SLOs; synchronous chains multiply downtime, while messaging contains it; separate liveness from readiness (4.2.4).
- Write structured logs with one correlation ID carried through every request and message, and never log secrets or personal data (4.2.5).
- Monitor the integration itself (queue depth, consumers, publish versus ack rate, DLQs, end-to-end time) and alert on symptoms that affect customers (4.2.6).
- Change contracts without breaking others: prefer additive changes, version APIs and events, and deprecate on schedule (4.2.7).
- Document for each reader with machine-readable specifications, decision records, runbooks, and a README, kept with the code (4.2.8).
- Evaluate against measurable criteria with evidence, report honestly, and plan all four kinds of maintenance (4.2.9).
Review questions
- A demo in staging sends SMS messages to real customers. Which two practices from 4.2.1 and 4.2.2 would have prevented it?
- Classify each as configuration or code for the courier consumer: the courier API URL, the retry delay, the routing key order.confirmed, the event schema, the number of instances.
- Why should RabbitMQ's AMQP port not be published in the Compose file, and how does the store still reach the broker?
- Three services each have 99.9% availability. What is the availability of a synchronous call through all three? How would asynchronous messaging change the customer's experience when one fails?
- Explain why the store's liveness check should not check RabbitMQ, while its readiness check should.
- Describe how one correlation ID lets you answer "where is my order?" across six systems.
- Every container in the integration is running and healthy, yet orders are not reaching the courier. Which metrics would show the problem?
- Classify as breaking or non-breaking: adding deliveryNotes to order.confirmed; renaming customerId; changing totalAmount from pesos to centavos; adding status RETURNED.
- Name three documents that a new partner needs to integrate with the store's events, and one document your on-call teammate needs.
- Write two measurable evaluation criteria each for reliability and maintainability, with the evidence you would collect.
#Glossary
| Term | Meaning | Section |
|---|---|---|
| Access token | A short-lived credential, often a JWT, that lets a client call an API with certain scopes | 4.1.2 |
| ADR (architecture decision record) | A short note recording an important design decision, its context, and consequences | 4.2.8 |
| Alert fatigue | Ignoring alerts because too many fire, often without need | 4.2.6 |
| API gateway | A front door for APIs that handles HTTPS, authentication, rate limits, and routing | 4.2.3 |
| API key | A long-lived secret string that identifies a client to an API | 4.1.2 |
| AsyncAPI | Standard for describing event-driven interfaces | 4.2.8 |
| Authentication | Proving who is calling | 4.1.1 |
| Authorization | Deciding what an authenticated caller may do | 4.1.1 |
| Availability | Share of time a service works as expected | 4.2.4 |
| BOLA | Broken Object Level Authorization: accessing another user's record by changing an ID | 4.1.1, 4.1.10 |
| Breaking change | A change that forces consumers to change their code | 4.2.7 |
| Chaos engineering | Running controlled failure experiments to build confidence in resilience | 4.1.8 |
| Client credentials grant | OAuth 2.0 flow in which a system gets a token for itself | 4.1.2 |
| Configuration | Everything that varies between deployments, kept out of the code | 4.2.2 |
| Configuration drift | Environments becoming different through untracked manual changes | 4.2.2 |
| Container / image | A running, isolated program / the package it runs from | 4.2.3 |
| Correlation ID | An ID carried by every request and message of one transaction | 4.2.5 |
| Data minimization | Sending and keeping only the personal data a purpose needs | 4.1.10 |
| Deployment environment | A complete, separate set of running systems for one purpose (dev, test, staging, production) | 4.2.1 |
| Error budget | The amount of failure an SLO allows | 4.2.4 |
| Graceful degradation | Losing a feature instead of the whole service when a part fails | 4.1.8, 4.2.4 |
| HMAC signature | A keyed hash proving a message came from someone holding a shared secret and was not changed | 4.1.3 |
| Integration testing | Testing that systems work correctly together | 4.1.6 |
| Interoperability | Ability of systems to exchange information and use it with the same meaning | 4.1.7 |
| JWT | JSON Web Token: signed (not encrypted) claims in three Base64url parts | 4.1.2 |
| Least privilege | Giving each identity only the permissions its job needs | 4.1.1 |
| Liveness / readiness | Is the process alive / can it do its job right now | 4.2.4 |
| Mass assignment | Accepting fields a client should not be able to set | 4.1.4 |
| mTLS | Mutual TLS: both sides prove their identity with certificates | 4.1.3 |
| OAuth 2.0 | Standard framework for issuing access tokens | 4.1.2 |
| Observability | Understanding a system's state from its logs, metrics, and traces | 4.2.6 |
| OpenAPI | Standard for describing HTTP APIs | 4.2.8 |
| Percentile (p95) | The value below which 95% of measurements fall | 4.1.9 |
| Personal information controller / processor | Who decides on processing personal data / who processes it on their behalf (RA 10173) | 4.1.10 |
| Reverse proxy | A server in front of applications that forwards requests to them | 4.2.3 |
| RTO / RPO | Longest acceptable downtime / most acceptable data loss, in time | 4.1.8 |
| Runbook | Step-by-step instructions for handling an alert or task | 4.2.8 |
| Scope | A named permission inside an access token | 4.1.2 |
| Secret management | Storing, distributing, rotating, and auditing secrets | 4.1.5 |
| Semantic Versioning | MAJOR.MINOR.PATCH version numbering | 4.2.7 |
| SLI / SLO / SLA | Service level indicator / objective / agreement | 4.2.4 |
| Single point of failure | A part whose failure stops the whole service | 4.2.4 |
| Structured logging | Logs written as data with named fields, usually JSON | 4.2.5 |
| Technical debt | Shortcuts that must be repaid later | 4.2.9 |
| TLS | Transport Layer Security: encryption and authentication for connections | 4.1.3 |
| Trust boundary | Any point where data enters a system from outside its control | 4.1.4 |
| Twelve-Factor App | A widely used method for building deployable services | 4.2.1, 4.2.2 |
#References
Standards and specifications:
- RFC 6749: The OAuth 2.0 Authorization Framework and RFC 6750: Bearer Token Usage
- RFC 7519: JSON Web Token (JWT) and RFC 9068: JWT Profile for OAuth 2.0 Access Tokens
- RFC 8446: TLS 1.3 and NIST SP 800-52 Rev. 2: Guidelines for TLS Implementations
- RFC 3339: Date and Time on the Internet
- RFC 9745: The Deprecation HTTP Response Header Field and RFC 8594: The Sunset HTTP Header Field
- OpenAPI Specification, AsyncAPI 3.0 Specification, JSON Schema, CloudEvents
- Semantic Versioning 2.0.0 and Keep a Changelog
- ISO/IEC 25010 (software product quality model) and ISO/IEC 14764 (software maintenance)
Security and privacy:
- OWASP API Security Top 10 (2023)
- OWASP Cheat Sheet Series: Input Validation, Secrets Management, Logging, Password Storage, REST Security
- Republic Act 10173, Data Privacy Act of 2012, National Privacy Commission
- NPC Circular 16-03: Personal Data Breach Management and NPC Circular 2023-06: Security of Personal Data
- Stripe: verifying webhook signatures, an example of HMAC-signed webhooks
Deployment, operations, and reliability:
- The Twelve-Factor App
- Google, Site Reliability Engineering, especially "Service Level Objectives" and "Monitoring Distributed Systems"
- Principles of Chaos Engineering
- Docker: Compose file reference and Docker: building best practices
- C4 model for software architecture and Michael Nygard, "Documenting Architecture Decisions"
RabbitMQ documentation:
- TLS support, Authentication, authorization, and access control, Configuration
- Monitoring with Prometheus and Grafana, Quorum queues, Production deployment guidelines
Tools used in the labs:
You've reached the end of the lecture notes
Use the final project checklist and the combined glossary as you prepare your deployed integration.
Combined glossary
All 90 terms from both modules in one A–Z list (45 from Module 3, 47 from Module 4). Terms defined in both modules show both definitions. The original glossaries remain at the end of each module.
No terms match your filter.