← Writing

Event-driven architecture: who does the work after an order is received?

On this page

In an online shop, receiving an order means notifying the customer, showing the order on the operations dashboard, and counting it in statistics. If the order API calls all of these services directly, a slow notification server can delay the order response too. This shop is an illustrative example.

In an event-driven architecture, the order service publishes the fact that it received an order. The notification and statistics services get the same event and do their own work. The order service can acknowledge receipt without waiting for the notification or the statistics update. First, decide what “order received” tells the customer has been completed. Event-driven architecture in the Microsoft Azure Architecture Center

Distinguish order receipt from order confirmation

PlaceOrder is a command asking the service to accept an order. The order service can reject an invalid request. OrderPlaced is an event the service publishes after receiving the order. The notification service sends a receipt notice and the statistics service counts the order. If an operations dashboard later subscribes to the same event, there is no need to add a dashboard call to the order API as long as the event already carries the information the dashboard needs.

For example, if stock still needs to be secured and payment authorized, show Order received · Pending confirmation. Once both conditions are met, confirm the order and publish OrderConfirmed. If stock cannot be secured, record the failed state and handle any follow-up. In particular, if payment was already authorized, that authorization may need to be voided. Event names, order states, and customer-facing messages should convey the same meaning.

The order can be saved while the event is lost

Suppose the process exits just after committing the order to the database, before publishing the event. The customer’s order stays in the database, but the notification and statistics services have no way to know about it. If publication happens first and the database write fails, consumers can end up processing an order that does not exist.

One way to handle this is a transactional outbox. Write the order row and the event row in the same database transaction. A separate relay reads committed events and sends them to the broker. If the relay stops after the order commits, the record to publish is still in the database when it restarts. The AWS transactional outbox pattern

The order and outbox rows commit together. The receipt response and publication to the broker proceed independently. Subscribers handle the published event separately for notification, counting, and dashboard updates.

After the commit, acknowledging receipt and publishing through the relay can proceed independently. Notification, counting, and the dashboard update are separate results of subscriber processing. The diagram shows the successful path.

Run the following one-order example with Python 3. The list stands in for the broker, and the subscriber results are represented by output lines. The demo calls the parts in a fixed order for readability. In the architecture, the relay can work on committed rows independently of the response. The example covers only the successful path, without retries or duplicate handling.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
    CREATE TABLE orders (id TEXT PRIMARY KEY, status TEXT NOT NULL);
    CREATE TABLE outbox (order_id TEXT NOT NULL, event_type TEXT NOT NULL);
""")
broker = []

def place_order(order_id):
    with db:
        db.execute("INSERT INTO orders VALUES (?, ?)", (order_id, "received"))
        db.execute("INSERT INTO outbox VALUES (?, ?)", (order_id, "OrderPlaced"))
    return f"Order received: {order_id}"

def relay():
    for event in db.execute("SELECT order_id, event_type FROM outbox"):
        broker.append(event)

def subscribers(event):
    order_id, event_type = event
    if event_type == "OrderPlaced":
        return [f"Notification: {order_id}", "Order count: +1", f"Dashboard: {order_id}"]

print(place_order("order-1"))
relay()
print(*subscribers(broker[0]), sep="\n")

The expected output for this single run is below.

Order received: order-1
Notification: order-1
Order count: +1
Dashboard: order-1

Apply the business effect once even when an event returns

The broker can receive an event and the relay can stop before recording completion in the outbox. When the relay restarts, it can publish the same eventId again. If the statistics consumer increments the order count every time, one order is counted twice.

The statistics consumer can put a unique constraint on eventId and record processing and update the count in the same database transaction. If the ID has already been processed, it skips the update. An action such as sending email through an external service cannot share that transaction. It needs a separate mechanism, such as an idempotency key supported by the sending service. AWS considerations for duplicate messages

Order matters for some work, too. If the dashboard receives OrderCancelled for an order and then a delayed OrderPlaced, acting on the placement alone could revive the cancelled order. For this current-state projection, include an order version in each event. Even if the order is missing from the projection, record the cancelled state and its version. The delayed placement cannot overwrite that state if its version is older. Consumers that accumulate changes can still need those earlier events.

Decide what must finish before responding

When introducing events, start by writing down what must be true when the order API returns success. In this example, the order receipt and outbox record must already be saved. Notifications and statistics can arrive later without changing what receipt means, so they are good candidates to handle through events.

For a first step, moving just the notification is enough. Stop and restart the relay just after an order is received, then see whether the event is delivered. Check that sending the same event twice does not duplicate the business effect and that you can find the publication record and consumer failures by order ID. Once you have checked all three, use the same criteria to split out other follow-up work.

For how different Kafka consumers read and replay the same records, see the existing hands-on guide. Kafka event streaming with partitions, consumer groups, offsets, and replay

Discussion

View on GitHub ↗