Business Events

Publish business events reliably with MySQL transactions and the transactional outbox pattern, and prevent repeated order updates with idempotent consumers.

🎯 Introduction

Earlier lessons covered asynchronous communication, and the RabbitMQ course introduced publication, consumption, and acknowledgments. But once payments writes a successful payment to MySQL, is orders guaranteed to receive and correctly process the event? No: publication may never happen, and an already processed message may arrive again.

This article addresses two questions in our order system: how payments publishes events reliably, and how orders avoids processing the same event twice. We use the transactional outbox pattern and idempotent consumers, respectively.


🧱 Clarifying Each Service's Responsibilities

Payments saves payment outcomes and publishes PaymentSucceeded; orders receives it and updates its own status. RabbitMQ delivers the event, rather than modifying the order database itself.

courseComponents.mermaid.loading

This reviews the business relationship. The vulnerable steps are publication and consumption, which we address separately below.

Here is an example event:

{
    "eventId": "evt-9001",
    "type": "PaymentSucceeded",
    "version": 1,
    "data": {
        "orderId": "o-100",
        "paymentId": "p-200"
    }
}

orderId identifies the order, paymentId identifies the payment record, and eventId uniquely identifies this event. One order can have many different events, but resending an event must preserve its original eventId rather than generate a new one. This enables duplicate detection later.


⚡ Preventing Duplicate Order Updates

Suppose orders marks o-100 paid but crashes before acknowledging the RabbitMQ message. Redelivery brings evt-9001 to orders again.

The desired behavior is: the first processing updates the order; subsequent deliveries of the same event do not repeat the business operation. This is consumer idempotency.

1. Identify processed events with a database primary key

Create this table in the order service's own database:

CREATE TABLE processed_events (
    event_id VARCHAR(80) PRIMARY KEY,
    processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

The primary key allows each event_id to be inserted successfully only once. Assume the order table contains id = 'o-100' with status pending_payment.

On first processing, record the event and update the order in one local transaction:

START TRANSACTION;

INSERT INTO processed_events (event_id)
VALUES ('evt-9001');

UPDATE orders
SET status = 'paid'
WHERE id = 'o-100' AND status = 'pending_payment';

-- Commit only after confirming that UPDATE affected exactly 1 row
COMMIT;

This SQL illustrates transaction boundaries, not a complete program where checks are optional. If the order is missing, the payment does not match it, or its state disallows the update, roll back and handle the outcome under business rules. Do not execute COMMIT unconditionally.

Both writes must succeed together. An event must not be recorded as processed while its order remains unchanged.

2. Handle repeated delivery

Processing evt-9001 again causes a primary-key conflict in processed_events. After confirming duplicate delivery of the same event, the consumer rolls back the current transaction, skips the order update, and acknowledges the duplicate normally.

courseComponents.mermaid.loading

Do not simply run SELECT to check for prior processing before updating: two consumers can both observe no record. A unique constraint combined with a transaction handles that race reliably.

Only a primary-key conflict confirmed to involve the same event qualifies as a duplicate. A disconnected database does not mean processing already succeeded. Different eventId values can also incorrectly represent one payment, so real business logic must validate paymentId and order status too.

⚠️ The Payment Commits but the Event Is Never Published

Idempotent consumption handles events received repeatedly. It cannot handle events never received.

Saving payment success before sending a message leaves this gap:

courseComponents.mermaid.loading

This is the dual-write problem: payments must update MySQL and publish to RabbitMQ, two separate systems that cannot commit together in one MySQL transaction.

RabbitMQ publisher confirms do not eliminate a crash between database commitment and publication. Reversing the order also fails: the event might publish while the database transaction never commits.


🛠 Transactional Outbox: Persist the Event First

The transactional outbox pattern avoids assuming that a database update and a RabbitMQ publication will both succeed consecutively. Instead, payments saves the payment outcome and the event awaiting publication in its own database using one local transaction.

1. Create the outbox table

In the payment service database, create:

CREATE TABLE outbox_events (
    id VARCHAR(80) PRIMARY KEY,
    event_type VARCHAR(80) NOT NULL,
    payload JSON NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    published_at TIMESTAMP NULL DEFAULT NULL
);

payload stores the complete event. A NULL published_at means successful publication has not been confirmed, allowing a background publisher to find it.

2. Commit the payment and event together

Assume p-200 initially has status pending. This SQL illustrates two writes in one transaction:

START TRANSACTION;

UPDATE payment_attempts
SET status = 'success'
WHERE id = 'p-200' AND status = 'pending';

-- The application must first verify that UPDATE affected 1 row;
-- if it affected 0 rows, handle the payment state and roll back; do not insert a success event.
INSERT INTO outbox_events (id, event_type, payload)
VALUES (
    'evt-9001',
    'PaymentSucceeded',
    JSON_OBJECT(
        'eventId', 'evt-9001',
        'type', 'PaymentSucceeded',
        'version', 1,
        'data', JSON_OBJECT(
            'orderId', 'o-100',
            'paymentId', 'p-200'
        )
    )
);

COMMIT;

The SQL client does not execute checks written in comments. Real Node.js code must inspect the affected row count and insert the event only when payment transitions from pending to successful, while handling transaction errors. Duplicate payment callbacks should reuse the completed outcome instead of inventing another success event.

A crash now leaves two possibilities:

  • Before commitment: both the payment update and pending event roll back.
  • After commitment: both remain in the database. Even if publication is delayed, process exit does not erase the event.

3. Publish events in the background

Another background process or scheduled job finds unpublished outbox records and sends them to RabbitMQ:

courseComponents.mermaid.loading

The confirm comes from the RabbitMQ broker for publication. It does not mean orders has updated its database.

If the publisher crashes after delivery but before updating published_at, it republishes the event after recovery. Retries must therefore preserve the original eventId, allowing orders to recognize duplicates as described above.

Failure pointOutbox outcome
Payment transaction rolls backPayment state and pending event roll back together
Database commits, then payments crashesPending record remains available for later publication
RabbitMQ temporarily unavailableKeep the pending record and retry after recovery
Crash after publication but before marking completionPublication may repeat; consumer idempotency handles it
The outbox is a reliable publication design, not a special RabbitMQ message type. Production systems must also coordinate competing publishers, handle events that remain unpublishable, and monitor backlog. Here we focus on transactions and retries.

Each side now has a clear responsibility: payments uses an outbox to reduce missed events; orders uses idempotency to prevent repeated business effects. This does not automatically make every cross-service operation succeed. Next, we will coordinate and compensate local transactions across orders, inventory, and payments.


❓ Knowledge Check

Q1: Why use an outbox if RabbitMQ already has persistence and publisher confirms?

Those mechanisms primarily cover publication to RabbitMQ and storage there. The outbox addresses an earlier risk: the database commits before the application successfully publishes the message.

Q2: Does an outbox guarantee exactly one consumption?

No. Publication can repeat if its completion was not recorded. Delivery can repeat if consumer acknowledgment fails. Consumers must be idempotent.

Q3: Can duplicate handling ignore every database error?

No. Skip business processing only when the same eventId is confirmed as successfully processed. Connection errors, validation failures, and other problems need separate handling.


🧪 Exercise

Design an InventoryReserved event indicating that stock has been reserved:

  1. Supply eventId, type, version, and data, including order and reservation IDs.
  2. Explain why updating inventory reservations and saving the outbox event require one local transaction.
  3. If delivery happens twice, design the sequence for orders to record processed_events and update state.
  4. Explain what happens after a publisher exits between sending successfully and marking publication, and how to avoid repeated business effects.

Acceptance criteria: Distinguish reliable publication on the payment or inventory side from idempotent consumption on the order side. Explain where database commitment, publisher confirms, and message acknowledgments occur.


🎉 Congratulations on completing this article! You now understand how to reduce missing business events and prevent duplicate events from repeating business operations.