ERPClimb logoERPClimb
Events and messaging
SAP Cloud Application Programming Modelintermediate 5 min read

Events and messaging — SAP Guided Tutorial

Free sample lesson · open to everyone

Key takeaway

Emitting and consuming events in CAP, connecting to SAP Event Mesh or file-based messaging for local tests, using the transactional outbox so events are published only after commit, and writing idempotent consumers for at-least-once delivery.

In this lessonShow sections

Visual overview

Events and messaging — learning sheetFlow: Declare event in CDS → emit inside transaction → Outbox: publish after commit → Consumer: idempotent handler. Key ideas: DECLARING AND EMITTING; MESSAGING CONFIGURATION; TRANSACTIONAL OUTBOX; IDEMPOTENT CONSUMERS. Watch out: Messaging is at-least-once: consumers will see duplicates and must be idempotent.ERPClimb.com / CAP / LESSON 9/12 / LEARNING SHEETEvents and messaging1 · HOW IT FLOWS1Declare event inCDS2emit insidetransaction3Outboxpublish after commit4Consumeridempotent handler2 · KEY IDEAS EXPLAINEDDeclaring And EmittingEvents are part of the service contract, just likeentities and actions.Emit after the business change is made, inside thehandler, so payload reflects committed data.Messaging Configuration`"messaging": {"[development]": { "kind":"file-based-messaging" }…Topics are derived from namespace and event nameunless overridden with @topic.Transactional OutboxWithout an outbox, a message sent before commitcan announce an order that was rolled back.With the persistent outbox, messages are writtento an outbox table in the same transaction anddispatched afterwards with retries.Idempotent ConsumersStore processed message IDs (or a business key +version) and ignore repeats.Make updates upserts or conditional updates, notblind inserts.3 · REMEMBER · WATCH OUTRememberDeclare events in the service: `event OrderCreated : { orderID : UUID;total : Decimal; }`.Emit with `await this.emit('OrderCreated', { orderID, total })`;subscribe with `srv.on('OrderCreated', msg => ...)`.Connect a messaging service in cds.requires — file-based for localtests, SAP Event Mesh in the cloud.!Watch outMessaging is at-least-once:consumers will see duplicates andmust be idempotent.4 · IN A REAL PROJECTA shipping system received OrderCreated events for orders that failed validation afterwards, and occasionallyprocessed one order twice after a broker reconnect. Enabling the transactional outbox removed the phantomevents, and a processed-message table keyed by order ID made the consumer idempotent.Original ERPClimb learning sheet • Verify against your SAP release and edition

The situation: a real project scenario

A shipping system received OrderCreated events for orders that failed validation afterwards, and occasionally processed one order twice after a broker reconnect. Enabling the transactional outbox removed the phantom events, and a processed-message table keyed by order ID made the consumer idempotent.

Explanation

Once an app needs to tell other systems what happened — or react to events from systems like S/4HANA — CAP treats events as part of the service contract, declared right alongside entities and actions: event OrderCreated : { orderID : UUID; total : Decimal(15,2); }.

You emit an event from inside a handler with await this.emit('OrderCreated', { orderID: order.ID, total: order.total }), and another service subscribes with srv.on('OrderCreated', msg => ...).

The right place to emit is after the business change has actually been made, so the payload reflects data that was genuinely committed, and payloads are best kept small and stable — keys plus the essential fields, with consumers reading further detail through the API if they need it.

Which broker is behind this is a matter of configuration: cds.requires.messaging can point to file-based messaging for local tests and to SAP Event Mesh in the cloud, with topics derived from the namespace and event name unless you override them with @topic. Subscribing to S/4HANA's own business events works through the same srv.on API once their AsyncAPI definitions are imported.

The detail that matters most here is what happens if you emit without the persistent outbox. Without it, a message published before the transaction commits can announce something — an order, say — that the same transaction then rolls back, leaving consumers acting on an event for something that never actually happened.

With the persistent outbox enabled, the outgoing message is written to an outbox table in the very same transaction as the business data, and only dispatched, with retries, after that transaction commits. This is what gives you atomicity between the database change and the event being published, rather than two separate things that can get out of sync.

Because messaging in CAP (and in most brokers generally) is at-least-once delivery, consumers will occasionally see the same message more than once, and need to be built to tolerate that: storing processed message IDs or a business key plus version and ignoring repeats, and using upserts or conditional updates rather than blind inserts so a duplicate doesn't double an effect.

A message that can never succeed, no matter how many times it's retried, should go to a dead-letter path after a limited number of attempts, with an alert, rather than retrying forever.

To test this in practice: declare OrderCreated and emit it from the CREATE handler using file-based messaging; make the CREATE fail after the emit and check whether the message still appears; enable the persistent outbox and repeat the same failing test; then deliver the same message twice to a consumer and prove it only produces one business effect. You should end up able to show that a rolled-back transaction publishes nothing at all, and that a duplicated message still produces exactly one effect downstream.

Code example

ABAP Code
service OrdersService {  entity Orders as projection on my.Orders;  event OrderCreated : { orderID : UUID; total : Decimal(15,2); }}// handlerthis.after('CREATE', 'Orders', async (order) => {  await this.emit('OrderCreated', { orderID: order.ID, total: order.total });});// package.json: "requires": { "outbox": true, "messaging": { ... } }

Watch out

Common mistakes

  • Publishing events before the transaction commits.
  • Assuming exactly-once delivery and creating duplicates in consumers.
  • Putting full documents with personal data into event payloads.
  • Infinite retries of a message that can never succeed.

Do this

Best practices

  • Use the persistent outbox for every event that announces a business fact.
  • Design consumers to be idempotent from day one.
  • Version event payloads and keep them minimal.

In the interview

Interview angle

Event questions test reliability thinking. Cover declaring and emitting events, the broker setup, why the outbox is needed for atomicity, and how idempotent consumers deal with at-least-once delivery and poison messages.

Practice this lesson

Original educational case studies for SAP consultants, not official SAP certification exam questions. Verify product edition and implementation details against the current SAP documentation.

Quick check

0 of 4 questions attempted

Question 1 of 4

Why use CAP's persistent (transactional) outbox for events?

Practise this in an interview

Answer in your own words and get instant feedback, the way an interviewer would judge it.

1How do you guarantee that an event is only published if the database change was committed?

2Design an idempotent consumer for a 'PaymentReceived' event.

Was this lesson helpful?

Keep exploring

Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.