# Event mesh and event-driven architecture: brokers, topics, queues and delivery guarantees

> Choose between SAP's event brokers, design topics, queues and dead message queues that survive outages, and review an event design before go-live.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/event-mesh-and-event-driven-architecture/
- Updated: 2026-11-29
- Reading time: Foundational 8 min, Deep 38 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

An **event** is a short message that says "something happened": sales order `1000011` changed, a business partner was created, an operation was confirmed on the shop floor. The system where it happened **publishes** the event. Other systems that care **subscribe** to it. Between them sits an **event broker**, which keeps a copy for every subscriber until that subscriber says it has the event.

That is all **event-driven architecture** means: systems announce changes instead of being asked about them, and the broker makes sure each announcement reaches everyone who needs it, even when a receiver is offline for the night.

SAP offers three ways to run the broker, and SAP's architecture guidance draws the lines between them. This topic helps you choose one, and then design the parts that decide whether the events are trustworthy: what each event is called, which queue holds it for whom, how long it waits, and where it goes when it can't be delivered.

It uses Calder Pumpworks, the fictional pump maker used across this course, whose CRM, AI agent and shop-floor system all need to hear about changes in its S/4HANA system `CP10`. The decision for a leader: **no event goes live without a named owner for its queue and for the queue where its failures land.**

### Why it matters to the business

Events are cheap to send and expensive to get wrong. Four things go wrong at Calder when the design is weak:

- **A changed date never reaches the CRM.** The CRM's queue lets events expire after four hours, and the CRM's maintenance window lasts eight. The account manager quotes Brennock Water Utility the old delivery date.
- **The right events arrive in the wrong order.** Sales order `1000011` changes three times in ten minutes. A receiver that crashes halfway processes the second change last, and the CRM shows a date that was already replaced.
- **Failures disappear.** A shop-floor confirmation fails five times and is moved to a "dead message queue" that nobody created, so the broker discards it. Production costs for that order are never posted.
- **The broker fills up.** Someone attached the test certificate PDF to every confirmation event. A twelve-hour outage of the receiver fills the queue's storage in under four hours.

Each of these is a design choice made months before go-live, and each is cheap to catch in a design review. SAP's own design guidance lists "zero loss of messages" as the first requirement for event-driven applications ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/ee6233)). That only holds if the queues are designed for the outages that will happen.

### How SAP does it

As of November 2026, SAP's architecture guidance describes its event strategy in two connected parts ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/196eba), last updated October 2025):

- **SAP Cloud Application Event Hub** carries business events between SAP's own cloud applications. You don't manage queues or topics: an administrator connects systems and switches subscriptions on. SAP's tutorial says it "distributes business events across SAP cloud applications" and requires a customer or partner license ([SAP Developers](https://developers.sap.com/tutorials/eh-basic-concepts.html)).
- **The SAP Integration Suite family** carries events between SAP and everything else, with two brokers you manage yourself:
  - the **Event Mesh capability** of Integration Suite, which SAP positions for starter or small-volume scenarios and a "start small and expand" strategy;
  - **SAP Integration Suite, advanced event mesh**, a distributed mesh of brokers for enterprise-wide use with higher demands on scale and resilience ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/59c1f6)).

SAP's comparison puts numbers on the difference: the Event Mesh capability handles messages of 1 MB and 10 GB of storage on shared infrastructure; advanced event mesh handles messages of 30 MB and more and 800 GB of storage and more, in sizes you choose, and adds event replay and dynamic routing between brokers ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/ee6233)). Advanced event mesh runs on AWS, Microsoft Azure and Google Cloud data centers, which SAP's product page lists by region ([sap.com](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html)).

S/4HANA publishes standard business events, listed on the SAP Business Accelerator Hub. Custom events are built with the ABAP RESTful application programming model (RAP). For older S/4HANA releases and ECC, SAP points to SAP Application Interface Framework ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/196eba)), and its product page sells an ERP event add-on for ECC or S/4HANA, an ASAPIO connector priced per connection ([sap.com](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html)).

### Which broker: a decision guide

| Question | If the answer is... | Lean towards |
| --- | --- | --- |
| Are both ends SAP cloud applications SAP already connects? | Yes | SAP Cloud Application Event Hub |
| Is it a first, small event scenario, with small messages and modest storage? | Yes | Event Mesh capability of Integration Suite |
| Do non-SAP systems, several regions, high volume or large messages matter? | Yes | Advanced event mesh |
| Must a consumer be able to receive old events again after a bad load? | Yes | Advanced event mesh (replay; ask SAP, see the deep layer) |
| Does the event start in ECC? | Yes | AIF or the ERP event add-on, or wait for the migration |

The choices are not exclusive. SAP's guidance has Event Hub for SAP-to-SAP flows alongside an Integration Suite broker for the rest. What you should avoid is three teams each buying a broker for one project.

**At Calder**, the target integration architecture already proposed advanced event mesh ([integration platform and clean core](https://erpfde.com/topics/integration-platform-and-clean-core/)). This topic tests that choice against Calder's real needs, then designs the queues.

| Calder consumer | Hears about | Must it see every event? | Delivery |
| --- | --- | --- | --- |
| CRM, through Cloud Integration | Sales order and business partner changes | Yes | Guaranteed, on its own queue |
| Order exceptions agent `AGT_ORDER_EXC` | A credit block was set (a custom event) | Yes | Guaranteed, on its own queue |
| Cloud Integration posting into S/4HANA | Operation confirmed on the Rockford shop floor | Yes, in order per production order | Guaranteed, partitioned queue |
| Order dashboard in the office | Sales order changes | No, it refreshes anyway | Direct |

> **Note** **For functional consultants.** Events change your test cases. For each process that sends or receives events, test four cases beyond the happy path: the receiver is offline for its longest maintenance window, the same event arrives twice, two changes to one document arrive out of order, and an event fails until it lands in the dead message queue. Each dead message queue needs an owner from the business side who knows what a failed event means for the process, and a documented way to send it again.

### Questions to ask

- Which broker do we have today, under which contract, and who else in the company already uses one?
- For each consumer: what is its longest planned outage, and how long does its queue keep events?
- Which events must be processed in order, and how does the design keep that order when a consumer crashes?
- Where does an event go after it fails, who looks there every day, and how do they resend it?
- Do our events carry only keys, or business data? Who approved the data that travels in them?
- If the CRM has to be rebuilt from scratch, can we send it the last week's events again?
- Which events start in ECC, and what happens to them at the migration?

### Common misconceptions

- **"The broker guarantees each event arrives exactly once."** It guarantees an acknowledged event isn't lost. After a crash it delivers again, so a consumer can see the same event twice and must recognize it.
- **"More consumers on one queue is always faster."** On an ordinary shared queue, more consumers means events can overtake each other. Order needs an exclusive or a partitioned queue.
- **"Events should carry all the data, so receivers don't call back."** Big events fill brokers, carry data to everyone who subscribes and arrive in the wrong order with stale values. SAP's standard events mostly carry the key only.
- **"Failed events go to the dead-letter queue automatically."** Only if someone created it. Otherwise the broker can discard them.
- **"Event Hub, Event Mesh and advanced event mesh are three names for one thing."** They are three offerings with different scope, management and limits.

### Key terms

- **Event:** a message saying a business object changed state.
- **Event broker:** the service that receives published events and keeps them for subscribers.
- **Topic:** the label an event is published under, with levels such as system, object, action and version.
- **Queue:** storage on the broker that keeps events for one consumer until it acknowledges them.
- **Guaranteed delivery:** the broker keeps the event until the consumer confirms it; the opposite is direct delivery, which can lose events.
- **Notification event:** an event that carries only the key of the changed object; the receiver reads the details.
- **Data event:** an event that carries the changed data itself.
- **Dead message queue (DMQ):** the queue where events go after they fail or expire, for a person to check.
- **Event mesh:** several brokers linked so that events published on one reach subscribers on another.

### Check yourself

1. Calder's CRM and its AI agent both need to hear about sales order changes from S/4HANA, and the CRM is not an SAP product. Which offering fits SAP's own positioning?
   - A. SAP Cloud Application Event Hub, because it carries all SAP business events
   - B. An Integration Suite broker, since the CRM sits outside SAP
   - C. A direct subscription from the CRM to S/4HANA, because a broker adds a hop
   - D. Event Hub for the CRM and a separate broker bought by the agent team

   Answer: B. SAP's guidance places Event Hub between SAP cloud applications and the Integration Suite brokers between SAP and non-SAP systems. A CRM outside SAP calls for the Event Mesh capability or advanced event mesh, and one broker shared by both consumers beats one per project.

2. The CRM's queue lets events expire after four hours. The CRM's maintenance window lasts eight hours. What happens?
   - A. Nothing, because guaranteed delivery keeps every event until it is read
   - B. The broker pauses S/4HANA until the CRM is back online
   - C. Events published early in the window expire before the CRM returns
   - D. The CRM receives the events twice to make up for the delay

   Answer: C. A queue keeps events until they are acknowledged or their time to live runs out. If the time to live is shorter than the outage, the oldest events expire and the CRM never sees them, which is how an old delivery date reaches a customer.

3. A partner proposes three consumers on one shared queue to speed up the CRM feed, whose events carry the new delivery date. What is the risk?
   - A. The broker refuses to deliver to more than one consumer
   - B. A crash can let an older change be applied last
   - C. Each consumer receives every event, tripling the CRM's load
   - D. Three consumers make the queue's storage three times larger

   Answer: B. On a shared queue, events are handed out in turn, and a crashed consumer's event is redelivered to another one later. If events carry data, the older value can be written last. An exclusive or partitioned queue, or notifications plus a fresh read, keeps the result right.

4. Which question best tests whether a vendor's event design is ready for go-live?
   - A. How many events per second can the broker handle at its largest size?
   - B. Which cloud provider hosts the broker in our region?
   - C. Where does a failed event go, and who checks it every day?
   - D. Does the design use the newest CloudEvents version?

   Answer: C. Failed events are where money leaks: a confirmation that never posts or an order change that never arrives. A named owner for each dead message queue, with a daily check and a way to resend, is what turns "zero loss" from a slogan into a process.

5. Why does SAP's standard sales order event mostly carry only the order number?
   - A. Because the broker can't carry messages larger than a few bytes
   - B. Because SAP charges per field included in an event
   - C. Because the CloudEvents standard forbids business data in events
   - D. Because each receiver then reads the latest order

   Answer: D. A notification event says what changed, and the receiver reads the latest state. That keeps events small and makes the result right even when events arrive late or out of order. Data events are allowed and have their uses, but they need more care with order and with what data travels.

6. Calder may need to rebuild its CRM's data from last week's events after a bad load. What should the architect check before promising that?
   - A. That the Event Mesh capability is switched on in Integration Suite
   - B. That replay is in the advanced event mesh contract and set up
   - C. That the CRM's queue is exclusive rather than partitioned
   - D. That the events are published as data events instead of notifications

   Answer: B. SAP's comparison lists event replay for advanced event mesh, not for the Event Mesh capability. SAP's documentation calls replay a controlled availability feature you ask SAP for, so it has to be confirmed and set up before anyone relies on it.

## Deep layer

### Mental model

Think of the broker as a post office with one **mailbox per consumer**, not one mailbox per sender.

S/4HANA publishes each event once, under a **topic**: an address with levels such as `default/sap.s4/S4P/ce/sap/s4/beh/salesorder/v1/SalesOrder/Changed/v1`. Each consumer owns a **queue** that subscribes to the topics it cares about. When an event arrives, the broker drops a copy into every queue whose subscriptions match. Each queue then has its own life: its consumer can be offline, slow, crashed or fast, and no other consumer notices.

Almost every design decision is a property of one mailbox:

- **What lands in it**: the topic subscriptions.
- **Who empties it, and in what order**: exclusive, shared or partitioned access.
- **How long letters wait**: the time to live, set against the consumer's longest outage.
- **How many times the post office tries**: the maximum redelivery count.
- **Where undeliverable letters go**: the dead message queue, which needs its own owner.
- **How big it is**: the quota, set against the backlog of the longest outage.

And one decision is about the letters themselves: **what goes inside an event**. A notification carries a key and makes the receiver look up the rest; a data event carries the content and makes the receiver trust it. Get the mailboxes and the letters right, and the broker product matters less than vendors suggest.

### How it works

```mermaid
flowchart LR
  S4[S/4HANA CP10<br/>system S4P] -->|publish once| B[(Event broker<br/>calder-aem-prod)]
  MES[Rockford MES] -->|publish| B
  B --> Q1[q/crm/salesorder]
  B --> Q2[q/agent/order-exc]
  B --> Q3[q/s4/mes-confirm<br/>4 partitions]
  B -.direct.-> D[Dashboard]
  Q1 --> CI1[Cloud Integration<br/>to the CRM]
  Q2 --> AG[AGT_ORDER_EXC]
  Q3 --> CI2[Cloud Integration<br/>into S4P]
  Q1 -.fails.-> DMQ1[(q/crm/salesorder/dmq)]
  Q3 -.fails.-> DMQ3[(q/s4/mes-confirm/dmq)]
```

#### Topics and subscriptions

SAP's tutorial shows the levels of an S/4HANA event topic in advanced event mesh: system information (`default/sap.s4/S4D`), `ce` for CloudEvent, `sap/s4` for the source, the business object (`beh/businesspartner/v1/BusinessPartner`), the action (`Created`) and the message version (`v1`) ([SAP Developers](https://developers.sap.com/tutorials/pubsub-view-events.html)). A subscription can use `*` for exactly one level and `>` at the end for everything below. So `.../BusinessPartner/*/v1` receives every action at version 1, while `default/sap.s4/S4D/>` receives everything that system publishes.

Two design rules follow. First, **the system level names the stage**: a production queue that subscribes to `S4Q`, the quality system, receives test events in production and nothing from production. Second, **a subscription should name the business object**. A queue subscribed to `>` near the top receives every event the system publishes, fills with events its consumer ignores, and gives a consumer data it has no business seeing.

#### Events: notifications and data

SAP's architecture guidance says business events are either **notification events** or **data events**, and asks designs to categorize each one ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/59c1f6)). Its sample business partner event is a notification:

```json
{
  "type": "sap.s4.beh.businesspartner.v1.BusinessPartner.Changed.v1",
  "specversion": "1.0",
  "source": "/default/sap.s4.beh/244572008",
  "id": "194780e0-b5db-1ede-b58a-4550178dff9e",
  "datacontenttype": "application/json",
  "data": { "BusinessPartner": "1000187" }
}
```

The envelope follows CloudEvents (`type`, `source`, `id`, `specversion`); the [event-driven agents topic](https://erpfde.com/topics/event-driven-agents-with-sap-events/) explains why `source` plus `id` is the duplicate key. The `data` holds only the key, so the receiver calls an API for the rest.

| | Notification event | Data event |
| --- | --- | --- |
| Size | A key, around a kilobyte | Grows with the data |
| Receiver's work | Reads the current state by API | Uses what the event says |
| Out-of-order arrival | Harmless: the read returns the latest state | Dangerous: an older value can be written last |
| Who sees the data | Only those allowed to call the API | Everyone subscribed to the topic |
| Use when | The receiver can reach the source's API | The receiver can't call back, or the event is the record |

Calder's shop-floor confirmations are data events on purpose: the MES is the record of what was confirmed, and S/4HANA can't read it back. Everything S/4HANA publishes stays a notification.

#### Delivery: direct or guaranteed

In advanced event mesh, **direct** messages are not kept for a client that isn't connected, can be discarded under congestion and are not acknowledged. **Guaranteed** messages "can't be lost once they are acknowledged by the event broker" and stay on a durable endpoint, such as a queue, until a consumer acknowledges them ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Get-Started/message-delivery-modes.htm)). Direct delivery is fine for a dashboard that refreshes anyway. Anything that must not miss an event needs a queue.

#### Queue access: exclusive, shared, partitioned

SAP's queue documentation describes three ways to consume one queue ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Messaging/Guaranteed-Msg/Queues.htm)):

| Access type | Consumers | Order | Use for |
| --- | --- | --- | --- |
| Exclusive | One active; others wait as standby | Delivered in the order received | Low volume where order matters |
| Non-exclusive, not partitioned | Several, in turn ("competing consumers") | Lost after a failure: a crashed consumer's message goes to another, marked redelivered | Notifications, or work where order doesn't matter |
| Non-exclusive, partitioned | One per partition at most | Kept within a partition, not between partitions | Volume and order per business object |

On a **partitioned** queue, the publisher sets a partition key, and the broker sends each message to the partition given by the key's hash modulo the partition count. Every event for production order `1100019` lands in the same partition, so they stay in order, while other orders spread across the other partitions. The number of active consumers is limited to the number of partitions; when consumers come and go, the broker rebalances partitions between them, and consumers must handle that handoff. SAP's page warns to change the partition count only after draining the queue.

#### When delivery fails

A message leaves a queue's storage in three unhappy ways: its time to live (TTL) runs out, it exceeds the queue's maximum redelivery count, or the consumer rejects it ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Messaging/Guaranteed-Msg/Queues.htm)). What happens next depends on the **dead message queue** (DMQ):

- The default DMQ name is `#DEAD_MSG_QUEUE`, and an administrator must create DMQs. If a queue's DMQ doesn't exist, the broker discards the message.
- From broker version 10.25.10, all removed messages go to the DMQ by default; in earlier versions only messages the publisher flagged as eligible did. Check your broker's version and setting.
- DMQs can't be chained, a DMQ can have its own maximum TTL, and messages can be copied from a DMQ back to the original queue.
- SAP recommends a separate DMQ per endpoint. One shared DMQ mixes CRM failures with shop-floor failures and has no single owner.

#### Replay and the mesh

**Message replay** lets a broker send stored messages again to new or existing clients, "hours or sometimes even days" later. As of November 2026, SAP's documentation calls it a controlled availability feature: you contact SAP to get a replay log. The log stores persistent messages up to a size you set and drops the oldest when full; it works for non-partitioned queues and topic endpoints, and replays from the beginning, from a date, or from a message ID ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Cloud/Broker-Manager/configuring-message-replay.htm)).

**Dynamic Message Routing** links event broker services into a mesh, within a site or between sites, and shares subscriptions across them, so an event published in one region reaches a subscriber in another with its quality of service preserved ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Features/DMR/DMR-Overview.htm)). Calder doesn't need it yet; a group with plants on several continents might.

### Build it yourself: review Calder's event design

You'll run a small script that holds two versions of Calder's event design, the partner's first draft and the reviewed design, as JSON files. It reviews each against twelve rules, compares the two SAP brokers' published limits with Calder's needs, and simulates what the queues do when a consumer crashes or goes offline. No account is needed.

```mermaid
flowchart LR
  A[event_design.py --init] --> B[design_draft.json<br/>design_reviewed.json]
  B --> C[review: 12 rules]
  B --> D[--broker: limits]
  B --> E[--simulate: crash and outage]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). This walkthrough doesn't repeat their steps. The setup topic's event lab showed a broker's behavior; this script reviews a design before any broker exists.

> **Note** New words. **JSON** is a text format for structured data, here the design files. A **rule** is a check the script runs, with a result of `OK`, `WARN` or `FAIL`. An **exit code** is a number a program returns when it finishes; `2` here means at least one rule failed, which a pipeline can use to stop a release.

#### What you need

- Python 3.10 or newer and your `orchestrate-course` folder with its `.venv`, from the setup topics.
- No account, no key, no cost. Built-in modules only; nothing to add to `requirements.txt`.
- About 30 minutes.

#### Step 1: Open your course folder and turn on the virtual environment

Windows (PowerShell):

```powershell
cd $HOME\orchestrate-course
.\.venv\Scripts\Activate.ps1
```

macOS or Linux:

```bash
cd ~/orchestrate-course
source .venv/bin/activate
```

Your prompt now starts with `(.venv)`.

#### Step 2: Save the script

1. Make sure the folder `unit26` exists (the setup topic created it). If not, create it: `mkdir unit26`.
2. Create the file `unit26/event_design.py` in your editor and paste the code below. Save it.

```python
"""Review Calder's event design and simulate what its queues do.

Course lab for the Unit 26 topic "Event mesh and event-driven architecture".
Built-in modules only, no randomness. All names, numbers and rules are
course values for the fictional Calder Pumpworks, not SAP defaults.

  python unit26/event_design.py --init              write both designs
  python unit26/event_design.py                     review the reviewed design
  python unit26/event_design.py --design draft      review the partner's draft
  python unit26/event_design.py --broker            check both brokers' published limits
  python unit26/event_design.py --simulate          ordering and outage simulation
"""
import argparse
import json
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent / "events"
AS_OF = "2026-11-29"

# Published figures from SAP's "Design Considerations for EDA Applications"
# page (SAP Architecture Center, last updated 2025-10-18), read 2026-11-29.
BROKERS = {
    "event-mesh-capability": {"max_message_mb": 1, "storage_gb": 10,
                              "replay": False, "dynamic_routing": False},
    "advanced-event-mesh": {"max_message_mb": 30, "storage_gb": 800,
                            "replay": True, "dynamic_routing": True},
}

# Course rules. Numbers are Calder's choices, not SAP's.
MAX_EVENT_KB = 64          # Q02: files travel by reference, not inside events
TTL_FACTOR = 2             # Q08: TTL at least twice the longest planned outage
REDELIVERY_RANGE = (1, 10) # Q09
QUOTA_HEADROOM = 0.5       # Q12: outage backlog at most half the queue quota

S4 = "default/sap.s4/{sid}/ce/sap/s4/beh"


def events():
    return [
        {"id": "EV01", "type": "sap.s4.beh.salesorder.v1.SalesOrder.Changed.v1",
         "kind": "standard", "shape": "notification", "key": "SalesOrder",
         "size_kb": 1, "source": "S4P", "owner": "00100296"},
        {"id": "EV02", "type": "sap.s4.beh.salesorder.v1.SalesOrder.Created.v1",
         "kind": "standard", "shape": "notification", "key": "SalesOrder",
         "size_kb": 1, "source": "S4P", "owner": "00100296"},
        {"id": "EV03", "type": "sap.s4.beh.businesspartner.v1.BusinessPartner.Changed.v1",
         "kind": "standard", "shape": "notification", "key": "BusinessPartner",
         "size_kb": 1, "source": "S4P", "owner": "00100250"},
        {"id": "EV04", "type": "com.calder.cp10.v1.CreditBlock.Set.v1",
         "kind": "custom (RAP)", "shape": "notification", "key": "SalesOrder",
         "size_kb": 1, "source": "S4P", "owner": "00100304"},
        {"id": "EV05", "type": "com.calder.mes.v1.Operation.Confirmed.v1",
         "kind": "custom (MES)", "shape": "data", "key": "ProductionOrder",
         "size_kb": 3, "source": "MES-RK", "owner": "00100314"},
    ]


def reviewed():
    so = S4.format(sid="S4P") + "/salesorder/v1/SalesOrder/*/v1"
    bp = S4.format(sid="S4P") + "/businesspartner/v1/BusinessPartner/*/v1"
    return {
        "name": "Calder event design, reviewed", "as_of": AS_OF, "stage": "production",
        "system": "S4P", "broker": "advanced-event-mesh",
        "broker_service": "calder-aem-prod", "needs_replay": True, "events": events(),
        "queues": [
            {"name": "q/crm/salesorder", "consumer": "CRM via Cloud Integration (I03)",
             "events": ["EV01", "EV02"], "subscriptions": [so],
             "delivery": "guaranteed", "access": "non-exclusive", "partitions": 0,
             "partition_key": None, "consumers": 2, "needs_order": False,
             "max_redelivery": 3, "dmq": "q/crm/salesorder/dmq", "ttl_hours": 48,
             "planned_outage_hours": 8, "events_per_hour": 120, "quota_mb": 2000,
             "owner": "00100292"},
            {"name": "q/crm/bp", "consumer": "CRM via Cloud Integration (I03)",
             "events": ["EV03"], "subscriptions": [bp],
             "delivery": "guaranteed", "access": "exclusive", "partitions": 0,
             "partition_key": None, "consumers": 1, "needs_order": False,
             "max_redelivery": 3, "dmq": "q/crm/bp/dmq", "ttl_hours": 48,
             "planned_outage_hours": 8, "events_per_hour": 10, "quota_mb": 500,
             "owner": "00100292"},
            {"name": "q/agent/order-exc", "consumer": "AGT_ORDER_EXC (I09)",
             "events": ["EV04"],
             "subscriptions": ["default/sap.s4/S4P/ce/com/calder/cp10/CreditBlock/Set/v1"],
             "delivery": "guaranteed", "access": "non-exclusive", "partitions": 0,
             "partition_key": None, "consumers": 2, "needs_order": False,
             "max_redelivery": 3, "dmq": "q/agent/order-exc/dmq", "ttl_hours": 24,
             "planned_outage_hours": 2, "events_per_hour": 6, "quota_mb": 500,
             "owner": "00100296"},
            {"name": "q/s4/mes-confirm", "consumer": "Cloud Integration to S4P (I02 back)",
             "events": ["EV05"],
             "subscriptions": ["calder/mes/RK/ce/com/calder/mes/Operation/Confirmed/v1"],
             "delivery": "guaranteed", "access": "partitioned", "partitions": 4,
             "partition_key": "ProductionOrder", "consumers": 4, "needs_order": True,
             "max_redelivery": 5, "dmq": "q/s4/mes-confirm/dmq", "ttl_hours": 72,
             "planned_outage_hours": 12, "events_per_hour": 90, "quota_mb": 2000,
             "owner": "00100314"},
            {"name": "DASH", "consumer": "Order dashboard (display only)",
             "events": ["EV01", "EV02"], "subscriptions": [so],
             "delivery": "direct", "may_miss": True, "owner": "00100288"},
        ],
        "dmqs": [{"name": n, "owner": o} for n, o in [
            ("q/crm/salesorder/dmq", "00100292"), ("q/crm/bp/dmq", "00100292"),
            ("q/agent/order-exc/dmq", "00100296"), ("q/s4/mes-confirm/dmq", "00100314")]],
    }


def draft():
    d = reviewed()
    d["name"] = "Calder event design, partner's draft"
    d["broker"] = "event-mesh-capability"
    d["broker_service"] = "calder-em"
    ev = {e["id"]: e for e in d["events"]}
    ev["EV01"].update(type="com.calder.cp10.SalesOrderFull.Changed", kind="custom (RAP)",
                      shape="data", size_kb=180)
    ev["EV05"].update(size_kb=1600)            # the test certificate PDF inside
    q = {x["name"]: x for x in d["queues"]}
    q["q/crm/salesorder"].update(subscriptions=["default/sap.s4/S4Q/>"], consumers=3,
                                 needs_order=True, ttl_hours=4, dmq="#DEAD_MSG_QUEUE")
    q["q/crm/bp"].update(dmq="#DEAD_MSG_QUEUE")
    q["q/agent/order-exc"].update(delivery="direct", owner="", dmq=None)
    q["q/s4/mes-confirm"].update(partition_key=None, consumers=6, max_redelivery=0,
                                 quota_mb=500)
    d["dmqs"] = [{"name": "#DEAD_MSG_QUEUE", "owner": ""}]
    return d


def load(name):
    path = HERE / f"design_{name}.json"
    if not path.exists():
        sys.exit(f"{path} not found. Run: python unit26/event_design.py --init")
    return json.loads(path.read_text(encoding="utf-8"))


def backlog_mb(q, size_kb):
    return q["events_per_hour"] * q["planned_outage_hours"] * size_kb / 1024


def review(d):
    ev = {e["id"]: e for e in d["events"]}
    dmqs = {x["name"]: x for x in d.get("dmqs", [])}
    rows = []

    def add(rule, obj, status, text):
        rows.append((rule, obj, status, text))

    for e in d["events"]:
        ok = re.search(r"\.v\d+$", e["type"]) is not None
        add("Q01", e["id"], "OK" if ok else "FAIL",
            "type ends with a version" if ok else f"{e['type']} has no version")
        limit = BROKERS[d["broker"]]["max_message_mb"] * 1024
        if e["size_kb"] > limit:
            add("Q02", e["id"], "FAIL",
                f"{e['size_kb']} KB is above the broker's {limit} KB message limit")
        elif e["size_kb"] > MAX_EVENT_KB:
            add("Q02", e["id"], "FAIL", f"{e['size_kb']} KB; send a reference, not the file "
                f"(course limit {MAX_EVENT_KB} KB)")
        else:
            add("Q02", e["id"], "OK", f"{e['size_kb']} KB")

    used_dmqs = {}
    for q in d["queues"]:
        n = q["name"]
        for s in q["subscriptions"]:
            if s.startswith("default/sap.s4/"):
                sid = s.split("/")[2]
                add("Q03", n, "OK" if sid == d["system"] else "FAIL",
                    f"system level {sid}" + ("" if sid == d["system"]
                                             else f", design is for {d['system']}"))
            parts = s.split("/")
            wide = ">" in parts and parts.index(">") < 8
            add("Q04", n, "FAIL" if wide else "OK",
                "subscription stops above the business object" if wide
                else "subscription names the business object")
        if q["delivery"] == "direct":
            add("Q05", n, "OK" if q.get("may_miss") else "FAIL",
                "direct, display only" if q.get("may_miss")
                else "direct delivery for a consumer that must not miss events")
            if not q.get("owner"):
                add("Q10", n, "FAIL", "no owner")
            else:
                add("Q10", n, "OK", f"owner {q['owner']}")
            continue
        add("Q05", n, "OK", "guaranteed delivery on a durable queue")
        shapes = {ev[i]["shape"] for i in q["events"]}
        if q["needs_order"] and "data" in shapes:
            if q["access"] == "exclusive" or (q["access"] == "partitioned" and q["partition_key"]):
                add("Q06", n, "OK", f"order kept ({q['access']}"
                    + (f" by {q['partition_key']})" if q["partition_key"] else ")"))
            else:
                why = "no partition key" if q["access"] == "partitioned" else \
                      f"{q['consumers']} competing consumers"
                add("Q06", n, "FAIL", f"data events need order; {why}")
        else:
            add("Q06", n, "OK", "order not needed: notifications read current state"
                if "notification" in shapes else "order not needed")
        dmq = q.get("dmq")
        if not dmq:
            add("Q07", n, "FAIL", "no dead message queue: failed events are discarded")
        elif dmq not in dmqs:
            add("Q07", n, "FAIL", f"{dmq} is not in the design")
        elif dmq == "#DEAD_MSG_QUEUE":
            add("Q07", n, "WARN", "the broker's default dead message queue, shared by every queue")
        elif dmq in used_dmqs:
            add("Q07", n, "WARN", f"{dmq} shared with {used_dmqs[dmq]}")
        else:
            add("Q07", n, "OK", dmq)
        used_dmqs.setdefault(dmq, n)
        need = q["planned_outage_hours"] * TTL_FACTOR
        add("Q08", n, "OK" if q["ttl_hours"] >= need else "FAIL",
            f"TTL {q['ttl_hours']} h, outage {q['planned_outage_hours']} h"
            + ("" if q["ttl_hours"] >= need else f", needs {need} h"))
        lo, hi = REDELIVERY_RANGE
        okr = lo <= q["max_redelivery"] <= hi
        add("Q09", n, "OK" if okr else "FAIL", f"max redelivery {q['max_redelivery']}"
            + ("" if okr else f", allowed {lo} to {hi}"))
        add("Q10", n, "OK" if q.get("owner") else "FAIL",
            f"owner {q['owner']}" if q.get("owner") else "no owner")
        if q["access"] == "partitioned":
            okp = q["consumers"] <= q["partitions"]
            add("Q11", n, "OK" if okp else "WARN",
                f"{q['consumers']} consumers, {q['partitions']} partitions"
                + ("" if okp else f": {q['consumers'] - q['partitions']} stay idle"))
        size = max(ev[i]["size_kb"] for i in q["events"])
        mb = backlog_mb(q, size)
        okq = mb <= q["quota_mb"] * QUOTA_HEADROOM
        add("Q12", n, "OK" if okq else "FAIL",
            f"outage backlog {mb:,.1f} MB of {q['quota_mb']:,} MB quota")
    for x in d.get("dmqs", []):
        add("Q10", x["name"], "OK" if x["owner"] else "FAIL",
            f"owner {x['owner']}" if x["owner"] else "no owner for the dead message queue")
    return rows


def print_review(d):
    rows = review(d)
    print(f"{d['name']} (as of {d['as_of']}, broker {d['broker']})\n")
    print(f"{'Rule':<5} {'Object':<22} {'Status':<6} Detail")
    for r, o, s, t in rows:
        print(f"{r:<5} {o:<22} {s:<6} {t}")
    c = {k: sum(1 for x in rows if x[2] == k) for k in ("OK", "WARN", "FAIL")}
    print(f"\n{len(rows)} checks: {c['OK']} OK, {c['WARN']} WARN, {c['FAIL']} FAIL")
    return 2 if c["FAIL"] else 0


def broker_check(d):
    ev = {e["id"]: e for e in d["events"]}
    biggest_kb = max(e["size_kb"] for e in d["events"])
    spool_mb = sum(backlog_mb(q, max(ev[i]["size_kb"] for i in q["events"]))
                   for q in d["queues"] if q["delivery"] == "guaranteed")
    need = {"max_message_mb": biggest_kb / 1024, "storage_gb": spool_mb / 1024,
            "replay": d["needs_replay"], "dynamic_routing": False}
    print(f"Calder's needs ({d['name']}): largest event {biggest_kb} KB, "
          f"outage backlog {spool_mb:,.1f} MB, replay wanted: {need['replay']}\n")
    print(f"{'Broker':<24} {'Message':<9} {'Storage':<9} {'Replay':<8} Verdict")
    for name, b in BROKERS.items():
        gaps = []
        if need["max_message_mb"] > b["max_message_mb"]:
            gaps.append("message size")
        if need["storage_gb"] > b["storage_gb"]:
            gaps.append("storage")
        if need["replay"] and not b["replay"]:
            gaps.append("replay")
        verdict = "FITS" if not gaps else "GAP: " + ", ".join(gaps)
        plus = "+" if b["dynamic_routing"] else ""   # SAP states "30MB+", "800GB+"
        print(f"{name:<24} {str(b['max_message_mb']) + plus + ' MB':<9} "
              f"{str(b['storage_gb']) + plus + ' GB':<9} {'yes' if b['replay'] else 'no':<8} {verdict}")
    print("\nFigures as SAP's Architecture Center states them (last updated 2025-10-18);"
          "\nreplay in advanced event mesh is a controlled availability feature: ask SAP.")


def simulate(d):
    print("1. Order 1000011 changes three times; a consumer crashes holding version 2\n")
    dates = {1: "2026-11-13", 2: "2026-11-30", 3: "2026-11-19"}
    # (version, minute it is processed). Versions are published at minutes
    # 0, 5 and 10; the crashed consumer's version 2 is redelivered at minute 11.
    cases = [
        ("data events, non-exclusive", "data", [(1, 0), (3, 10), (2, 11)]),
        ("notifications + read, non-exclusive", "notification", [(1, 0), (3, 10), (2, 11)]),
        ("data events, partitioned by SalesOrder", "data", [(1, 0), (2, 11), (3, 11)]),
    ]
    published = {1: 0, 2: 5, 3: 10}
    print(f"{'Design':<40} {'Processed':<10} {'CRM shows':<11} Right?")
    for label, shape, steps in cases:
        shown = None
        for v, minute in steps:
            if shape == "data":
                shown = dates[v]          # the payload says what to write
            else:                         # read the order as it is now
                shown = dates[max(k for k, t in published.items() if t <= minute)]
        right = "yes" if shown == dates[3] else "NO"
        order = "-".join(f"v{v}" for v, _ in steps)
        print(f"{label:<40} {order:<10} {shown:<11} {right}")
    print("\n2. Each queue's longest planned outage\n")
    ev = {e["id"]: e for e in d["events"]}
    print(f"{'Queue':<20} {'Outage':<7} {'Events':<7} {'Backlog':<11} {'Quota':<9} "
          f"{'TTL':<6} Outcome")
    for q in d["queues"]:
        if q["delivery"] != "guaranteed":
            outcome = ("direct: missed while offline (allowed, display only)"
                       if q.get("may_miss") else
                       "direct: every event published while offline is lost")
            print(f"{q['name']:<20} {outcome}")
            continue
        n = q["events_per_hour"] * q["planned_outage_hours"]
        size = max(ev[i]["size_kb"] for i in q["events"])
        mb = backlog_mb(q, size)
        if mb > q["quota_mb"]:
            out = f"quota full after {q['quota_mb'] / (q['events_per_hour'] * size / 1024):.1f} h"
        elif q["ttl_hours"] < q["planned_outage_hours"]:
            exp = q["events_per_hour"] * (q["planned_outage_hours"] - q["ttl_hours"])
            out = f"{exp} expire to {q['dmq'] or 'nowhere (discarded)'}"
        else:
            out = "all delivered after the outage"
        print(f"{q['name']:<20} {str(q['planned_outage_hours']) + ' h':<7} {n:<7} "
              f"{mb:>7,.1f} MB {str(q['quota_mb']) + ' MB':<9} {str(q['ttl_hours']) + ' h':<6} {out}")
    print("\nSynthetic course values: rates, outages and quotas are Calder's, not measured.")


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--init", action="store_true", help="write both design files")
    p.add_argument("--design", choices=["reviewed", "draft"], default="reviewed")
    p.add_argument("--broker", action="store_true", help="compare the two brokers")
    p.add_argument("--simulate", action="store_true", help="ordering and outage simulation")
    a = p.parse_args()
    if a.init:
        HERE.mkdir(parents=True, exist_ok=True)
        for name, fn in (("reviewed", reviewed), ("draft", draft)):
            (HERE / f"design_{name}.json").write_text(json.dumps(fn(), indent=2), encoding="utf-8")
            print(f"wrote {HERE / f'design_{name}.json'}")
        return 0
    d = load(a.design)
    if a.broker:
        broker_check(d)
        return 0
    if a.simulate:
        simulate(d)
        return 0
    return print_review(d)


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 3: Write the two designs

1. Run:

   ```bash
   python unit26/event_design.py --init
   ```

2. You should see two lines (your folder path will differ):

   ```text
   wrote .../orchestrate-course/unit26/events/design_reviewed.json
   wrote .../orchestrate-course/unit26/events/design_draft.json
   ```

3. Open `unit26/events/design_draft.json` and skim it. Each queue lists its subscriptions, access type, TTL, redelivery limit, DMQ and owner, plus the consumer's longest planned outage and its event rate. These are course values for Calder, not measurements.

#### Step 4: Review the partner's draft

1. Run:

   ```bash
   python unit26/event_design.py --design draft
   ```

2. The last line should read:

   ```text
   46 checks: 29 OK, 3 WARN, 14 FAIL
   ```

3. Look at the failures. These are the ones that matter most:

   ```text
   Q01   EV01                   FAIL   com.calder.cp10.SalesOrderFull.Changed has no version
   Q02   EV05                   FAIL   1600 KB is above the broker's 1024 KB message limit
   Q03   q/crm/salesorder       FAIL   system level S4Q, design is for S4P
   Q04   q/crm/salesorder       FAIL   subscription stops above the business object
   Q06   q/crm/salesorder       FAIL   data events need order; 3 competing consumers
   Q08   q/crm/salesorder       FAIL   TTL 4 h, outage 8 h, needs 16 h
   Q05   q/agent/order-exc      FAIL   direct delivery for a consumer that must not miss events
   Q06   q/s4/mes-confirm       FAIL   data events need order; no partition key
   Q07   q/s4/mes-confirm       FAIL   q/s4/mes-confirm/dmq is not in the design
   Q12   q/s4/mes-confirm       FAIL   outage backlog 1,687.5 MB of 500 MB quota
   ```

   The draft replaced SAP's sales order notification with a custom "full order" data event of 180 KB, subscribed the production CRM queue to everything the quality system publishes, put the agent on direct delivery, and left the shop-floor queue pointing at a DMQ nobody created. The `Q07` WARN lines say every queue shares the broker's default DMQ.

4. Check the exit code. In PowerShell run `echo $LASTEXITCODE`; on macOS or Linux run `echo $?`. It prints `2`.

#### Step 5: Review the reviewed design

1. Run:

   ```bash
   python unit26/event_design.py
   ```

2. The last line should read `54 checks: 54 OK, 0 WARN, 0 FAIL`, and the exit code is `0`.

3. Compare a few lines with the draft:

   ```text
   Q06   q/crm/salesorder       OK     order not needed: notifications read current state
   Q06   q/s4/mes-confirm       OK     order kept (partitioned by ProductionOrder)
   Q08   q/crm/salesorder       OK     TTL 48 h, outage 8 h
   Q11   q/s4/mes-confirm       OK     4 consumers, 4 partitions
   ```

   The CRM queue keeps two competing consumers because it receives notifications and reads the order; the shop-floor queue, whose events are data, is partitioned by production order.

#### Step 6: Check both brokers against Calder's needs

1. Run:

   ```bash
   python unit26/event_design.py --broker
   ```

2. You should see:

   ```text
   Calder's needs (Calder event design, reviewed): largest event 3 KB, outage backlog 4.2 MB, replay wanted: True

   Broker                   Message   Storage   Replay   Verdict
   event-mesh-capability    1 MB      10 GB     no       GAP: replay
   advanced-event-mesh      30+ MB    800+ GB   yes      FITS
   ```

3. Run it on the draft too: `python unit26/event_design.py --broker --design draft`. The capability now also shows `GAP: message size`, because of the 1,600 KB event. That gap is a design error, not a reason to buy a bigger broker.

> **Note** These verdicts use the limits SAP's Architecture Center publishes and Calder's synthetic volumes. They show the method; they are not a sizing for a real system. Replay is a controlled availability feature in advanced event mesh, so "FITS" still means "confirm with SAP".

#### Step 7: Simulate a crash and the outages

1. Run:

   ```bash
   python unit26/event_design.py --simulate --design draft
   ```

2. The first table shows sales order `1000011`, changed three times (versions 1 to 3, confirmed dates 13, 30 and 19 November), with a consumer crashing while it holds version 2:

   ```text
   Design                                   Processed  CRM shows   Right?
   data events, non-exclusive               v1-v3-v2   2026-11-30  NO
   notifications + read, non-exclusive      v1-v3-v2   2026-11-19  yes
   data events, partitioned by SalesOrder   v1-v2-v3   2026-11-19  yes
   ```

3. The second table runs each queue through its longest planned outage:

   ```text
   Queue                Outage  Events  Backlog     Quota     TTL    Outcome
   q/crm/salesorder     8 h     960       168.8 MB 2000 MB   4 h    480 expire to #DEAD_MSG_QUEUE
   q/crm/bp             8 h     80          0.1 MB 500 MB    48 h   all delivered after the outage
   q/agent/order-exc    direct: every event published while offline is lost
   q/s4/mes-confirm     12 h    1080    1,687.5 MB 500 MB    72 h   quota full after 3.6 h
   DASH                 direct: missed while offline (allowed, display only)
   ```

4. Run `python unit26/event_design.py --simulate` for the reviewed design: every guaranteed queue ends with `all delivered after the outage`.

> **Note** All rates, outages, quotas and sizes are synthetic Calder course values. The simulation shows how the rules interact; it doesn't model a real broker's timing.

#### Step 8: Save your work in Git

```bash
git add unit26/event_design.py unit26/events
git commit -m "Unit 26: event design review and queue simulation"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `BROKERS` | The message size, storage, replay and routing figures SAP's comparison states for each broker |
| `events()` | Calder's five events: three SAP standard notifications, a custom credit block event built with RAP, and the MES's data event |
| `reviewed()` and `draft()` | The two designs; the draft is the reviewed one with the partner's choices put back |
| `review()` | Runs rules `Q01` to `Q12` per event, per queue and per DMQ |
| `broker_check()` | Compares the largest event, the total outage backlog and the replay need with each broker |
| `simulate()` | Replays the three-change crash case and each queue's longest outage |
| `main()` | Reads the options and returns exit code 2 when a rule fails |

The rules, in short: `Q01` event types end with a version; `Q02` events stay under 64 KB and the broker's limit; `Q03` the topic's system level matches the stage; `Q04` subscriptions name the business object; `Q05` only display-only consumers use direct delivery; `Q06` ordered data events use an exclusive or keyed partitioned queue; `Q07` each queue has its own existing DMQ; `Q08` TTL is at least twice the longest planned outage; `Q09` maximum redelivery is between 1 and 10; `Q10` every queue and DMQ has an owner; `Q11` a partitioned queue has no more consumers than partitions; `Q12` the outage backlog fits in half the quota. `Q11` follows SAP's queue documentation; the numbers in `Q02`, `Q08`, `Q09` and `Q12` are Calder's course rules.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't installed or isn't on the path | Follow [Set up your computer](https://erpfde.com/topics/set-up-your-computer/); on macOS or Linux try `python3` |
| `design_reviewed.json not found` | You skipped Step 3 or ran from another folder | Run from `orchestrate-course`: `python unit26/event_design.py --init` |
| `json.decoder.JSONDecodeError` | A design file was edited and has a missing comma or quote | Fix the line the error names, or run `--init` again to start over |
| `KeyError: 'EV06'` | A queue names an event that isn't in `events` | Add the event to the file, or fix the ID in the queue |
| Counts differ from the text | The design files were edited | Run `--init` to restore both files |
| `ModuleNotFoundError` | You copied an import that isn't in the script | The script needs built-in modules only; paste it again |

No network or key is involved, so proxy and key problems can't occur here.

### The SAP way

#### Getting events out of S/4HANA and ECC

S/4HANA's standard events are listed on the SAP Business Accelerator Hub; check each event and its payload for your edition and release before designing around it. For custom or derived events, SAP's guidance points to RAP; for older S/4HANA releases and ECC from NetWeaver 7.31, to SAP Application Interface Framework ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/196eba)). The connection setup inside S/4HANA, a channel created from the broker's service key, is shown step by step in the [event-driven agents topic](https://erpfde.com/topics/event-driven-agents-with-sap-events/). Calder's custom credit block event is a course name for an event built with RAP.

#### The Event Mesh capability

SAP's training describes the Event Mesh capability as having the same functionality as the standalone SAP Event Mesh service, with a different implementation and usage. Applications connect as **message clients**, created from the *SAP Integration Suite, Event Mesh* service with the `message-client` plan, and SAP's example connects over AMQP 1.0 on WebSocket. A queue's settings in that training include access type, queue size, message size, maximum unacknowledged messages, maximum redelivery count, dead message queue and maximum time to live ([SAP Learning](https://learning.sap.com/courses/sap-cloud-platform-integration-service-overview/understanding-event-mesh-emis)). The same rules from this topic apply; the limits are lower.

#### Advanced event mesh

SAP's documentation describes advanced event mesh as an event streaming, event management and monitoring platform, run as SaaS or deployed in your own private cloud or Kubernetes. Its Cloud Console offers **Mission Control** for event broker services, **Event Portal** to "design, create, discover, share, secure and manage" events, and **Insights** dashboards ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Cloud/What-Is-PubSub-Cloud.htm)). Event Portal is where Calder's event catalog, the `events` list in the lab, would live in production, with owners and versions.

#### Licensing notes

As read on 2026-11-29, SAP's product page lists advanced event mesh plan sizes from 100 to 100K, a spooling add-on in blocks of 500 GB, and the ERP event add-on per connection, with yearly pricing and contracts of 3 to 60 months ([sap.com](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html)). Earlier topics found Integration Suite editions that include an advanced event mesh tenant on some country pages ([integration platform and clean core](https://erpfde.com/topics/integration-platform-and-clean-core/)). Your contract decides what you have; ask before you design around replay or a size.

### Build vs. SAP

| Need | Build or open source | SAP | Choose SAP when |
| --- | --- | --- | --- |
| A broker | Run your own open-source broker on BTP or a hyperscaler | Event Mesh capability or advanced event mesh | You want S/4HANA's channel to connect directly and SAP to operate the broker |
| SAP-to-SAP cloud events | Point every SAP application at your broker | SAP Cloud Application Event Hub | Both ends are SAP cloud applications Event Hub connects |
| Events from ECC | Custom ABAP that posts to a broker | AIF, or the ERP event add-on | You want supported content and fewer custom programs before the migration |
| Event catalog | A spreadsheet or Git repository of event definitions | Event Portal in advanced event mesh | Many teams publish and consume, and need approvals and discovery |
| Ordered, scaled consumers | Your own partitioning in the consumer | Partitioned queues | Order per business object matters at volume |
| The design review | This lab's rules in a pipeline | No SAP checker for these course rules | Never: the rules are yours to own |

### Architecture view

**Where it sits.** One advanced event mesh broker service, `calder-aem-prod`, serves production, with a separate non-production service for `S4Q`. S/4HANA `CP10` (`S4P`) publishes to it through its channel; the Rockford MES publishes shop-floor confirmations. Cloud Integration consumes for the CRM and for postings back into S/4HANA; `AGT_ORDER_EXC` consumes directly. The diagram under *How it works* shows the pieces. Augsburg's ECC `CP20` publishes no events: its interfaces stay on IDocs until the July 2027 rollout into `CP10`.

**Non-functional requirements.**

| Requirement | Calder's target | What breaks if missed |
| --- | --- | --- |
| Loss | No acknowledged event lost; every failure in a DMQ with an owner | Missing CRM dates, unposted confirmations |
| Outage tolerance | TTL at least twice each consumer's longest planned outage | Events expire during maintenance |
| Order | Per production order for MES confirmations | Final confirmation posted before a partial one |
| Volume | Outage backlog under half of each queue's quota | Queue full, new events refused or lost |
| Event size | Under 64 KB; files by reference | Broker limits hit, data spread to every subscriber |
| Latency | Seconds, not guaranteed; nothing waits on an event synchronously | A process that blocks on the broker fails with it |

**Integration and identity.** Each consumer authenticates to the broker with its own client credentials and may read only its own queues; the CRM flow can't read the agent's queue. Events carry keys, so the data access happens on the API read, with the consumer's own S/4HANA identity: the CRM flow's technical user and, for the agent, the permissions from [agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/). The released APIs behind those reads are the ones the [order-to-cash topic](https://erpfde.com/topics/order-to-cash-end-to-end/) lists.

**The decision to record** (short ADR form from the [design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context.** ADR-001 proposed advanced event mesh. Calder's needs are small events (3 KB at most), a backlog of a few megabytes in the worst planned outage, ordered shop-floor confirmations and a wish to rebuild the CRM from recent events.
- **Options.** A: the Event Mesh capability now, move later. B: advanced event mesh with SAP's standard notifications, a queue and DMQ per consumer, partitioned queues where order matters. C: advanced event mesh with data events carrying full orders, so the CRM needs no API reads.
- **Decision.** B. The capability fits Calder's sizes, but not the replay requirement, and a later move means redoing every consumer's connection.
- **Consequences.** Each consumer reads S/4HANA after each notification, one API call per event. Replay must be confirmed with SAP before the CRM rebuild procedure depends on it. Four DMQs need named owners and a daily check. If replay isn't available, option A becomes cheaper and should be reconsidered.

**What a design review will ask.**

1. What happens to each queue during its consumer's longest planned outage, in events and megabytes?
2. Which events must stay in order, and what keeps them in order when a consumer crashes?
3. Where does a failed event go, who checks it, and how is it resent?
4. Which data travels inside events, and who approved every subscriber seeing it?
5. How do we know a production queue never subscribes to a test system?

### Production concerns

- **Security and authorizations.** One client identity per consumer, allowed only its own queues and topics. Keep personal and bank data out of event payloads; the API read applies S/4HANA's authorizations, the broker doesn't. Treat text inside events, such as a customer note, as data and never as instructions to an agent.
- **Evaluation.** Run the design review in the pipeline before any change to topics or queues, and keep the crash and outage cases as tests. Add a case for every incident.
- **Cost.** Plan sizes and the spooling add-on are priced in blocks, so size from the outage backlog, not from average volume. Large events cost twice: broker storage and every consumer's network.
- **Operations.** SAP Cloud ALM's health monitoring for the Event Mesh capability reports message consumers, active connections, broker state, number of queues and message spool usage ([SAP Support](https://support.sap.com/en/alm/sap-cloud-alm/operations/expert-portal/health-monitoring/health-monitoring-setup-configuration/health-monitoring-isem.html)). Alert on DMQ depth and on queues that grow without being read; the [observability topic](https://erpfde.com/topics/btp-observability/) covers alert routing.
- **Clean core.** Publish from S/4HANA only standard events or RAP events, and read through released APIs, as the [clean core topic](https://erpfde.com/topics/integration-platform-and-clean-core/) explains.
- **Resilience.** A single broker service in one region is a dependency of every consumer. The [resilience topic](https://erpfde.com/topics/btp-resilience-and-multi-region/) covers what to accept and what to pay for.

### Where AI fits

As of November 2026, AI changes events in two ways and the broker in none.

- **An agent is one more consumer.** `AGT_ORDER_EXC` gets its own queue, its own DMQ and its own owner, and must skip duplicates and reread state like any consumer. The [event-driven agents topic](https://erpfde.com/topics/event-driven-agents-with-sap-events/) builds one.
- **Events carry text an agent may read.** A customer note copied into an event is written by an outsider. The agent treats it as data; the event design keeps such fields out where it can.

AI can also draft event definitions and queue settings. Drafts go through the same review as human designs: the lab's rules don't care who wrote the JSON.

### Pitfalls

- **One queue for several consumers.** One slow consumer then holds back the others, and nobody owns the backlog.
- **TTL set by habit.** Four hours looks generous until the CRM's eight-hour maintenance window.
- **A DMQ named but never created.** The broker discards what it can't deliver there.
- **One shared DMQ.** Failures from every process in one place, with no owner who understands them all.
- **Changing the partition count on a full queue.** Drain first, as SAP's documentation says.
- **More consumers than partitions.** The extra consumers sit idle and look like spare capacity that isn't there.
- **Data events by default.** They grow, spread data and break on order. Use them only when the receiver can't call back.
- **Wide subscriptions.** `>` near the top of the topic pulls every event into the queue.
- **Assuming replay.** It is a controlled availability feature; confirm it before you plan a rebuild around it.

### Exercise: add the supplier portal

Calder's supplier portal wants to hear about business partner changes so it can ask suppliers to confirm new bank details. Its owner is the master data specialist `00100250`, and its longest planned outage is 24 hours (a Sunday maintenance window).

1. Open `unit26/events/design_reviewed.json`.
2. In `queues`, add this entry after the `q/crm/bp` block, minding the comma before it:

   ```json
   {"name": "q/portal/bp", "consumer": "Supplier portal", "events": ["EV03"],
    "subscriptions": ["default/sap.s4/S4P/ce/sap/s4/beh/businesspartner/v1/BusinessPartner/*/v1"],
    "delivery": "guaranteed", "access": "exclusive", "partitions": 0,
    "partition_key": null, "consumers": 1, "needs_order": false,
    "max_redelivery": 3, "dmq": "q/portal/bp/dmq", "ttl_hours": 24,
    "planned_outage_hours": 24, "events_per_hour": 10, "quota_mb": 500,
    "owner": "00100250"}
   ```

3. In `dmqs`, add `{"name": "q/portal/bp/dmq", "owner": "00100250"}`.
4. Run `python unit26/event_design.py`. You get `64 checks: 63 OK, 0 WARN, 1 FAIL`: `Q08 ... TTL 24 h, outage 24 h, needs 48 h`.
5. Change `ttl_hours` to `48` for the portal queue and run it again.
6. In `unit26/notes.md`, write two sentences: why the portal gets a notification and reads bank details through an API instead of receiving them in the event, and who checks `q/portal/bp/dmq`.

**Done when** the review prints `64 checks: 64 OK, 0 WARN, 0 FAIL`, `--simulate` shows `q/portal/bp` with `all delivered after the outage`, and your two sentences are in `notes.md`. [B2B and EDI with Trading Partner Management](https://erpfde.com/topics/b2b-and-edi-integration/) adds the partner-facing side of the same supplier data.

### Going further

For readers who want the mechanics beneath the design rules.

- **Partition rebalancing and handoff.** SAP's [queue documentation](https://help.pubsub.em.services.cloud.sap/Messaging/Guaranteed-Msg/Queues.htm) links pages on rebalancing and on partition handoff. They explain what a consumer sees while a partition moves to another flow, which matters if a consumer keeps state per production order in memory.
- **Replay versus DMQ.** A DMQ holds what failed; a replay log holds what succeeded, for a while. [Configuring Message Replay](https://help.pubsub.em.services.cloud.sap/Cloud/Broker-Manager/configuring-message-replay.htm) shows that replay starts only after live messages are removed from the endpoint, which shapes a rebuild procedure.
- **Meshes across sites.** [Dynamic Message Routing](https://help.pubsub.em.services.cloud.sap/Features/DMR/DMR-Overview.htm) describes horizontal scaling within a site and multi-site scaling through gateway nodes. Read it before designing a broker per region.
- **SAP's whole EDA guidance.** The [design considerations page](https://architecture.learning.sap.com/docs/ref-arch/ee6233) lists the full set of requirements, event catalogs and mediation with Cloud Integration.

### Check yourself

1. A production queue for the CRM subscribes to `default/sap.s4/S4Q/>`. Which two problems does the review flag?
   - A. The wildcard `>` is not allowed in advanced event mesh subscriptions
   - B. It listens to the quality system and to every object it publishes
   - C. It listens to production, but only to the `Created` action of each object
   - D. It needs an exclusive queue because the subscription uses a wildcard

   Answer: B. The third level of an S/4HANA topic is the system, so `S4Q` means test events in production and no production events. A `>` straight after the system level matches everything below, so the queue fills with objects the CRM ignores. The fix names the system `S4P` and the business object.

2. On a non-exclusive, non-partitioned queue, consumer B crashes while holding version 2 of an order change. What does SAP's documentation say happens to that message?
   - A. It is discarded because B never acknowledged it
   - B. It stays locked until B reconnects, keeping the order intact
   - C. It goes to another consumer as redelivered, so order is lost
   - D. It moves straight to the dead message queue after the first failure

   Answer: C. On a competing-consumer queue the unacknowledged message is redelivered to another consumer with the redelivered flag set, so it can be processed after version 3. That is harmless for notifications, which reread the order, and wrong for data events.

3. How does a partitioned queue keep events for production order `1100019` in order while still using four consumers?
   - A. It sends every event to all four consumers and keeps the first acknowledgment
   - B. The key's hash picks one partition, and each partition has one consumer
   - C. It sorts events by their CloudEvents `time` before delivering them
   - D. It waits until all four consumers acknowledge before delivering the next event

   Answer: B. The publisher sets the partition key, here the production order, and the broker maps it to a partition by hash modulo the partition count. Order holds within a partition and each partition is served by a single flow, so different orders run in parallel.

4. The shop-floor queue's design names `q/s4/mes-confirm/dmq`, but nobody created that queue. A confirmation fails five times. What happens?
   - A. The broker creates the DMQ on first use and parks the message there
   - B. The message returns to the end of the queue and is retried forever
   - C. The broker sends it to `#DEAD_MSG_QUEUE` instead, which always exists
   - D. The broker discards it, and the confirmation is never posted

   Answer: D. SAP's documentation says administrators must create DMQs, and if an endpoint's DMQ doesn't exist the message is discarded. That is why the lab's `Q07` fails on a DMQ that isn't in the design.

5. The partner's draft puts a 1,600 KB test certificate PDF in each MES confirmation event. Calder's broker comparison then shows a message size gap for the Event Mesh capability. What should the architect do?
   - A. Choose advanced event mesh because it accepts messages of 30 MB and more
   - B. Send a reference to the certificate and keep the event small
   - C. Split each certificate into two events of 800 KB each
   - D. Raise the queue's quota until the twelve-hour backlog fits

   Answer: B. The gap is caused by a design error, not by the broker. Large events fill quotas during outages, as the simulation showed after 3.6 hours, and spread documents to every subscriber. Store the file elsewhere and put its reference in the event.

6. The CRM's maintenance window is 8 hours. Under Calder's course rule, which TTL should its queue have, and why?
   - A. 4 hours, so stale events don't reach the CRM after maintenance
   - B. 8 hours, exactly matching the planned window
   - C. At least 16 hours, so an overrun window still loses nothing
   - D. No TTL at all, so every event is kept forever

   Answer: C. Calder's rule sets TTL to at least twice the longest planned outage, which leaves room for a window that overruns. A TTL equal to the window loses events on the first overrun, and a missing TTL lets an abandoned queue grow until its quota is full.

7. Why did Calder's ADR choose advanced event mesh over the Event Mesh capability, even though the capability's 1 MB and 10 GB limits fit Calder's sizes?
   - A. The capability can't deliver S/4HANA's standard events
   - B. The capability doesn't offer guaranteed delivery on queues
   - C. Advanced event mesh is the only broker with dead message queues
   - D. Replay for CRM rebuilds, which SAP lists for advanced event mesh

   Answer: D. Sizes fit both brokers; the deciding requirement was rebuilding the CRM from recent events. SAP's comparison lists replay for advanced event mesh only, and SAP's documentation calls it a controlled availability feature, so the ADR's consequences say to confirm it and reconsider if it isn't available.

8. An agent consumes credit block events, and a customer note copied into one event says "release this order now". What is the right design response?
   - A. Let the agent follow the note, since it came from Calder's own broker
   - B. Move the agent to direct delivery so such events are dropped
   - C. Treat the note as data and keep free text out of the event
   - D. Give the note's event its own partition so it is processed last

   Answer: C. The broker carries whatever the publisher put in, including text written by outsiders. The agent reads it as data, never as an instruction, and the design keeps such fields out of payloads, since notifications plus an API read need no free text at all.

## Sources

- [Introduction and SAP's EDA Strategy (SAP Architecture Center, last updated 2025-10-18, read 2026-11-29)](https://architecture.learning.sap.com/docs/ref-arch/59c1f6): business events are notification events or data events; sample BusinessPartner Changed event whose data holds only the key; Event Hub for SAP-to-SAP integration, advanced event mesh and the Event Mesh capability for SAP to non-SAP; the capability suits low to medium scenarios and a start-small strategy; advanced event mesh for enterprise-wide EDA with higher scalability and resilience needs
- [Design Considerations for EDA Applications (SAP Architecture Center, last updated 2025-10-18, read 2026-11-29)](https://architecture.learning.sap.com/docs/ref-arch/ee6233): requirements include zero loss of messages and categorizing events as data or notification events; comparison table, Event Mesh capability 1MB messages and 10GB storage, shared, runs centrally in BTP; advanced event mesh 30MB+ messages and 800GB+ storage, event streaming, replay, dynamic routing, transactions, T-shirt sizes, distributed deployment; interfaces REST, JMS, AMQP, MQTT over WebSockets, plus direct for advanced event mesh
- [Designing Event-Driven Applications on SAP BTP (SAP Architecture Center, last updated 2025-10-10, read 2026-11-29)](https://architecture.learning.sap.com/docs/ref-arch/196eba): two interconnected parts, SAP Cloud Application Event Hub and the Integration Suite family; Event Mesh capability for starter or small-volume scenarios; advanced event mesh as a distributed multi-broker mesh; Cloud Integration as event bridge and for event mediation; RAP for custom or derived events; AIF for older S/4HANA and ECC releases (since NW 7.31); business events on the Business Accelerator Hub
- [Queues (SAP Integration Suite, advanced event mesh documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Messaging/Guaranteed-Msg/Queues.htm): exclusive queues have one active consumer and deliver in the order received; non-exclusive non-partitioned queues round-robin and lose order after a failure; partitioned queues hash a publisher-set key, keep order within a partition, limit active consumers to the number of partitions and rebalance; messages leave the spool on TTL expiry, after exceeding max redelivery, or on rejection; default DMQ
- [Message Delivery Modes (SAP Integration Suite, advanced event mesh documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Get-Started/message-delivery-modes.htm): direct messaging not retained for disconnected clients, can be discarded under congestion, not acknowledged; guaranteed messages can't be lost once the broker acknowledges them and stay on durable endpoints until consumed and acknowledged
- [Configuring Message Replay (SAP Integration Suite, advanced event mesh documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Cloud/Broker-Manager/configuring-message-replay.htm): controlled availability feature, contact SAP; replay log stores persistent messages and replaces the oldest when full; non-partitioned queues and topic endpoints only; replay from beginning, from a date or from a replication group message ID; topic filter on the log
- [Dynamic Message Routing (SAP Integration Suite, advanced event mesh documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Features/DMR/DMR-Overview.htm): the technology underneath an event mesh; links event broker services within a site and between sites; subscriptions shared across clusters; quality of service of the publisher preserved
- [What Is SAP Integration Suite, Advanced Event Mesh? (documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Cloud/What-Is-PubSub-Cloud.htm): event streaming, event management and monitoring platform as SaaS; Cloud Console with Mission Control, Event Portal and Insights; fully managed or in your own private cloud or Kubernetes
- [View Events in SAP Integration Suite, advanced event mesh (SAP Developers tutorial, read 2026-11-29)](https://developers.sap.com/tutorials/pubsub-view-events.html): S/4HANA topic levels system, ce, sap/s4, business object, action, version; * matches one level, > at the last level matches one or more; direct is the Try Me! default
- [SAP Integration Suite, advanced event mesh (sap.com product page, read 2026-11-29)](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html): managed service, a mesh of brokers across regions; plan sizes 100 to 100K in the add-on list; spooling add-on in 500 GB blocks; ERP event add-on (ASAPIO connector) for ECC or S/4HANA per connection; data centers on AWS, Azure and Google Cloud
