Sub topic 13
Reacting to business events
This chapter covers event-driven integration between SAP S/4HANA and a side-by-side extension on SAP BTP. It assumes you have read the previous chapters. You should know what a released API is and how a CAP remote service reaches S/4HANA through a destination. You should also be able to read Node.js code.
Why events
The CAP service from the previous chapter reads Business Partner data on demand. This is a synchronous call. A user opens an app, the extension calls S/4HANA, and the answer comes back in the same request.
Many extension scenarios start from something that happened in S/4HANA, not from a user action. Examples are a business partner being blocked, a sales order being created, or a purchase requisition being released. You could poll the API every few minutes. Polling wastes calls when nothing changed, and it still reacts late when something did.
With event-driven integration, S/4HANA publishes a business event when the change happens. A message broker holds the event until your extension picks it up. The core system does not know who consumes the event, and the extension does not need to ask whether anything changed. This keeps the coupling loose and respects the clean core principle, because the event is a released, documented contract just like an API.
Synchronous calls compared with events
| Aspect | Synchronous API call | Business event |
|---|---|---|
| Trigger | A user or process in the extension | A change in S/4HANA |
| Timing | Immediate answer, caller waits | Delivered later, caller does not wait |
| Coupling | Extension must reach S/4HANA at call time | Extension and S/4HANA are independent |
| Data freshness | Always current | Current as of the event |
| Failure handling | Caller sees the error and retries | Broker retries and holds messages |
| Typical use | Show or edit live data | React to changes, start workflows, sync a copy |
The two styles work together. Events tell you that something changed, and the API tells you what the data looks like now.
The building blocks
Three parts are involved.
- The event source. SAP S/4HANA publishes business events based on its business object model. The event name encodes the object and the operation. An example is
sap.s4.beh.businesspartner.v1.BusinessPartner.Changed.v1. The format follows the CloudEvents specification, a vendor-neutral way to describe events. - The broker. On SAP BTP this is SAP Event Mesh or SAP Advanced Event Mesh, which belongs to SAP Integration Suite. The broker receives events, stores them in queues, and delivers them to subscribers.
- The consumer. This is your side-by-side application. It either listens on a queue or receives events through a webhook.
In SAP S/4HANA Cloud, you connect the system to the broker by creating a communication arrangement for the enterprise event enablement scenario. The arrangement carries the broker credentials and a channel. In the Enterprise Event Enablement app you then choose which topics the system publishes. Check the exact scenario name and app in the documentation for your release, because these details change between versions.
What an event contains
S/4HANA business events are usually thin. The payload carries the key of the changed object, not the full record. For a business partner change, the data section holds the BusinessPartner number and little else.
This is deliberate. It keeps messages small and avoids sending sensitive data through the broker. It also means your consumer follows a common pattern: receive the event, then read the current state through the released API. That is why the previous chapter's remote service is the second half of this chapter's solution.
Consuming events in CAP
CAP has a messaging service that hides the broker details. You declare it in package.json and write handlers with messaging.on.
{
"cds": {
"requires": {
"messaging": {
"kind": "enterprise-messaging-shared",
"format": "cloudevents"
},
"API_BUSINESS_PARTNER": {
"kind": "odata-v2",
"model": "srv/external/API_BUSINESS_PARTNER",
"credentials": {
"destination": "S4HC_BP",
"path": "/sap/opu/odata/sap/API_BUSINESS_PARTNER"
}
}
}
}
}The enterprise-messaging-shared kind binds to an SAP Event Mesh service instance. In production you would use the plain enterprise-messaging kind, which gives each application instance its own queue handling. The cloudevents format tells CAP to read the incoming messages as CloudEvents, so the event payload appears in msg.data. Depending on your broker namespace setup, you may also need to set the topic namespace in the messaging configuration. Check that your queue's subscriptions match the topics S/4HANA publishes.
The extension needs somewhere to keep review tasks. This small model uses the business partner number as the key.
namespace my.partnerreview;
entity ReviewTasks {
key BusinessPartner : String(10);
FullName : String(81);
IsBlocked : Boolean;
receivedAt : Timestamp;
}The handler reacts to the change event and reads the current data from S/4HANA.
const cds = require('@sap/cds')
module.exports = class PartnerReview extends cds.ApplicationService {
async init() {
const bp = await cds.connect.to('API_BUSINESS_PARTNER')
const messaging = await cds.connect.to('messaging')
const { A_BusinessPartner } = bp.entities
const { ReviewTasks } = cds.entities('my.partnerreview')
messaging.on('sap.s4.beh.businesspartner.v1.BusinessPartner.Changed.v1', async msg => {
const { BusinessPartner } = msg.data
const partner = await bp.run(
SELECT.one.from(A_BusinessPartner)
.columns('BusinessPartner', 'BusinessPartnerFullName', 'BusinessPartnerIsBlocked')
.where({ BusinessPartner })
)
if (!partner) return
await UPSERT.into(ReviewTasks).entries({
BusinessPartner: partner.BusinessPartner,
FullName: partner.BusinessPartnerFullName,
IsBlocked: partner.BusinessPartnerIsBlocked,
receivedAt: new Date().toISOString()
})
})
return super.init()
}
}The handler never reads the S/4HANA database directly and never copies the whole partner master. It stores only what the extension needs. If the handler throws an error, CAP does not acknowledge the message, and the broker delivers it again.
Delivery guarantees and the code you must write
Brokers like SAP Event Mesh give you at-least-once delivery. This has direct consequences for your handler.
- Duplicates happen. The broker may deliver an event twice, for example if your app crashed before acknowledging. The handler above uses
UPSERTkeyed on the business partner, so a second delivery produces the same result. AnINSERTwould fail or create a duplicate. - Order is not guaranteed across events. Two changes to the same partner could arrive in reverse order. This is another reason to read the current state from the API instead of trusting the event content. Reading the current state makes the result the same no matter which order the events arrive in.
- Slow or failing handlers block the queue. A message that always fails will be retried again and again. Decide what happens to messages that keep failing. Many teams route them to a dead-letter queue and raise an alert.
- Events can be missed or the extension can be offline. Queues keep messages while the application is down, up to the retention limits of your plan. After a long outage, reconcile by reading the API.
Local development
You do not need a broker to develop the handler. In a local CAP project, a messaging service of kind local-messaging keeps events in process, and you can emit a test event from a script or test with messaging.emit('sap.s4.beh.businesspartner.v1.BusinessPartner.Changed.v1', { BusinessPartner: '1000001' }). The remote call to S/4HANA still needs a real or mocked system. Run the integration against a test tenant before production, with the real broker, queue, and subscriptions.
When to choose events, calls, or both
Use these rules as a starting point.
- Use a synchronous API call when a user waits for the answer and needs current data, such as showing partner details in an app.
- Use an event when the extension must react to a change, start a process, or update its own data, and the reaction need not happen within the original transaction.
- Use both when the event is a signal and the details are in the API, as in this chapter.
- Do not use events when you need the result inside the S/4HANA transaction itself. An event cannot veto or change the transaction that raised it. Such logic belongs in in-app or developer extensibility.
Exercise
A CAP extension receives the same BusinessPartner.Changed event twice because the app restarted before acknowledging it. The handler uses INSERT to store a review task. What goes wrong, and how do you fix it?
Show answer
The second INSERT violates the primary key on BusinessPartner or creates a duplicate row, and the failing handler causes the broker to retry the message repeatedly. At-least-once delivery means duplicates are normal. Make the handler idempotent by using UPSERT keyed on the business partner number, and read the current state from the API so the outcome does not depend on how often or in what order events arrive.
Exercise
Your extension must reject the creation of a sales order in S/4HANA when a custom check fails. Is a business event the right tool?
Show answer
No. An event is published after the change and cannot stop or alter the transaction that raised it. Use in-app or developer extensibility, which run inside the S/4HANA transaction, for this validation.