Business Events
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
An expense claim is approved, a business partner is changed, a sales order is created: other applications often want to know, but the application where it happened should neither know who they are nor wait for them. A business event is a short message that says "this happened, and here is its key", sent through a messaging service so that every interested application can react in its own time. This page explains the idea in plain words, shows the CloudEvents format in which SAP business events travel, describes how SAP Event Mesh carries them with topics, queues and webhooks, and then builds a small working example in a CAP Node.js application: it emits an event after an approval and consumes it, and it receives an event that looks like one from SAP S/4HANA. The CAP part is written for CAP Node.js 10.2 (@sap/cds 10.2.2) and ran for real in a copy of this site’s expenses lab with file-based messaging, which needs no account and is meant for local tests only. SAP Event Mesh and the real SAP S/4HANA events need an SAP BTP account and an SAP system, so those parts are explained from the documentation and are not run here. For the same idea inside ABAP, where a RAP business object raises the event, read RAP Business Events; this page does not repeat it.
Before you read
-
CAP Concepts: services, events and handlers in outline.
-
CAP Services and Handlers in Node.js: the
before,onandafterhandler phases that the examples build on. -
Consuming SAP APIs from CAP: the synchronous way to reach another system, which events complement.
-
Integration Suite and Business Accelerator Hub: the wider integration picture.
-
RAP Business Events: how an ABAP business object raises an event.
Key terms
-
Business event: a message that states that something significant happened to a business object, such as a created sales order.
-
CloudEvents: a public specification that describes event data in a common format, so that different systems read each other’s events.
-
SAP Event Mesh: the SAP BTP messaging service that carries events between applications.
-
Topic: the address an event is published to; consumers name the topics they care about.
-
Queue: the place where a messaging service keeps events for one consumer until it has taken them.
-
Webhook: a web address of the consumer to which the messaging service pushes each event.
Events instead of calls
A call, such as reading a business partner through OData, is synchronous: the caller asks and waits for the answer. An event is asynchronous: the provider announces and carries on, and there is no answer. Three roles take part.
Source: SAP Event Mesh documentation, whose overview describes applications that "communicate through asynchronous events"; the diagram is this page’s own summary
An event suits "tell whoever cares". It does not suit "give me a result now": that is a request, and it stays an API call or an action. The payload of an event is small on purpose, usually the key of the object, and a consumer that needs more reads the object afterwards through the API.
The CloudEvents format
SAP business events travel in the CloudEvents format. Each event is a small JSON document with a few fixed fields: a specversion, a unique id, a type that names what happened, a source that names who said it, a time, and the business data under data. The CAP documentation shows this example of an SAP S/4HANA event:
{
"type": "sap.s4.beh.salesorder.v1.SalesOrder.Created.v1",
"specversion": "1.0",
"source": "/default/sap.s4.beh/ER9CLNT001",
"id": "0894ef45-7741-1eea-b7be-ce30f48e9a1d",
"time": "2020-08-14T06:21:52Z",
"datacontenttype": "application/json",
"data": {
"SalesOrder":"3016329"
}
}
Reading it: the type is the business object (SalesOrder), the occurrence (Created) and a version, with a prefix that marks it as an SAP S/4HANA business event; the data carries only the key of the order. The page shows the sample as an illustration, so treat the identifiers as an example and take the real event names of a system from its event catalog.
SAP Event Mesh: topics, queues and webhooks
SAP Event Mesh is the messaging service of SAP BTP in the Cloud Foundry environment. The documentation lists its features as publishing business events from SAP and non-SAP sources, consuming them, and decoupled communication for extension and integration scenarios. It also notes that the lite service plan is being discontinued in favor of the default plan.
The CloudEvents REST interface of the service supports CloudEvents specification version 1.0, with the structured mode (JSON only) and the binary mode for publishing. When a CloudEvent is published, the service routes it to a topic built from the event’s source and type. The documentation gives the rule and an example:
topic := <three-segment source w/o leading slash>/ce/<type with dots replaced by slashes>
Source: REST APIs for Events
A consumer does not read topics directly. It owns a queue, which is subscribed to topics and keeps the events until the consumer has taken them, so a consumer that is down for a while misses nothing. The service offers several ways to take events from a queue. For a consumer reachable over HTTPS, the documented way is a webhook subscription: the consumer creates a subscription with a name, the events it wants (each a source and type pair) and its webhookUrl, and the service creates a queue named after the subscription and pushes events to the URL. The documentation shows this request:
POST /sap/ems/v1/events/subscriptions
Host: https://enterprise-messaging-pubsub.cfapps.eu10.hana.ondemand.com
Authorization: Bearer ...
Content-Type: application/json
{
"name": "crm-ext-webhook",
"events": [{
"source": "/default/org.my.crm/1",
"type": "org.my.crm.Customer.Added.v1"
},
{
"source": "/default/org.my.crm/1",
"type": "org.my.crm.Customer.Deleted.v1"
}
],
"webhookUrl": "<URL of my-crm-ext app>"
}
Source: REST APIs for Events; requires an SAP BTP account; not run here
Before the first event, the service checks that the webhook is willing: it sends an OPTIONS request with the header WebHook-Request-Origin, and the webhook must answer with a WebHook-Allowed-Origin header that matches it (or the value *). Webhooks must use HTTPS, and the documented authentication types are basic, OAuth 2.0 client credentials, API key, certificate and none. When publishing, the quality of service is AT_LEAST_ONCE by default, and the time to live defaults to 2592000000 milliseconds. At least once means a consumer can receive the same event twice, so a handler should be safe to run twice.
Events of SAP S/4HANA reach this service through the product’s own configuration. The RAP documentation, summarized on RAP Business Events, says that remote business events are consumed from SAP Event Mesh by subscribing to the respective queues, and that a communication arrangement for inbound and outbound communication must be configured for the product first. SAP also offers a separate product named advanced event mesh; this page covers SAP Event Mesh only.
Emitting and consuming events in CAP
CAP treats messaging like any other service. A model declares an event next to the entity and the action that causes it, the handler emits it, and any application that subscribes to the topic receives it. The lab for this page adds three things to the expenses project, in a copy of the lab: an approve action, an event ClaimApproved, and the setting for file-based messaging.
using { sap.guide.expenses as db } from '../db/schema';
service ExpenseService {
@odata.draft.enabled
entity Claims as projection on db.Claims;
action approve(ID : UUID) returns Boolean;
event ClaimApproved { ID : UUID; amount : Decimal(9,2); }
}
Source: the srv/expense-service.cds of the lab copy; events are described at CAP: Events and Messaging. The lab table is a reduced version of the running example ZEXP_CLAIM: title, status and amount.
{
"cds": {
"requires": {
"messaging": {
"kind": "file-based-messaging",
"file": "../msg-box"
}
}
}
}
Source: the cds section of the package.json of the lab copy, as shown at CAP: Messaging in Node.js, File Based
The documentation says about this kind: "Don’t use this in production, only if you want to test your application locally", and that it allows at most one consuming app per emitted event. The default file is ~/.cds-msg-box; the lab sets a path so that nothing is written outside the scratch folder. In production the same project uses enterprise-messaging for SAP Event Mesh, with webhook.waitingPeriod as one of its options, and if the server uses XSUAA the scope $XSAPPNAME.emcallback must be granted to SAP Event Mesh. The code does not change, which is the point of the messaging service.
import cds from '@sap/cds'
export default class ExpenseService extends cds.ApplicationService {
async init() {
const { Claims } = cds.entities('sap.guide.expenses')
this.on('approve', async req => {
const claim = await SELECT.one.from(Claims).where({ ID: req.data.ID })
if (!claim) return req.reject(404, 'No such claim')
await UPDATE(Claims).set({ status: 'A' }).where({ ID: claim.ID })
await this.emit('ClaimApproved', { ID: claim.ID, amount: claim.amount })
return true
})
const messaging = await cds.connect.to('messaging')
messaging.on('ExpenseService.ClaimApproved', msg => {
console.log('notify: claim', msg.data.ID, 'approved for', msg.data.amount)
})
return super.init()
}
}
Source: the srv/expense-service.js of the lab copy (the validation handler of the lab is left out); emit and messaging.on as in CAP: Messaging in Node.js, Emitting Events
The documentation names two levels. this.emit('ClaimApproved', data) uses the logical event name of the service. The topic that results is, without @topic, the fully qualified event name, here ExpenseService.ClaimApproved, and messaging.on subscribes by that topic; a subscription is created automatically. Messages are sent after the transaction succeeds, and the message is acknowledged after all handlers succeeded: a handler that throws makes the broker deliver the message again. Message handlers run with the privileged user, so a handler that must check permissions does so itself.
Started with cds-serve and called once, the lab printed this (the log shows only the lines that matter):
$ curl -u alice: -H 'Content-Type: application/json' \
-d '{"ID":"11111111-1111-1111-1111-111111111111"}' \
http://localhost:4711/odata/v4/expense/approve
{"@odata.context":"$metadata#Edm.Boolean","value":true}
[cds] - connect to messaging > file-based-messaging
[odata] - POST /odata/v4/expense/approve
notify: claim 11111111-1111-1111-1111-111111111111 approved for 45.50
Source: real output of the lab copy, CAP Node.js 10.2; the first line is the request, the rest are the response and the server log
Consuming an event from another system
The consumer of an SAP S/4HANA event is a CAP application that subscribes to the event’s topic, which is the same type string as in the CloudEvents sample. In the lab, a second small script stands in for the other system: it connects to the same messaging file and emits the topic of the sample. The consumer is two lines of the same handler file.
messaging.on('sap.s4.beh.salesorder.v1.SalesOrder.Created.v1', msg => {
console.log('received SalesOrder.Created for order', msg.data.SalesOrder)
})
Source: added to the init method above in the lab copy; the topic string is the type of the sample at CAP: Messaging in Node.js, CloudEvents Protocol
The stand-in producer and what the running server then printed:
import cds from '@sap/cds'
const messaging = await cds.connect.to('messaging')
await messaging.emit('sap.s4.beh.salesorder.v1.SalesOrder.Created.v1', { SalesOrder: '3016329' })
$ node emit-s4.mjs
emitted
(server log) received SalesOrder.Created for order 3016329
Source: real output of the lab copy; the producer is a stand-in for SAP S/4HANA, not an SAP system. The order number is the one of the documentation sample.
Two details matter for the real thing. The documentation allows a custom topic for an event with the annotation @topic, for example @topic: 'my.custom.topic', which is how an event modeled in a service gets the topic string of an external event. The names publishPrefix and subscribePrefix add a prefix to topics; with format: 'cloudevents' on SAP Event Mesh the defaults become $namespace/ce/ for publishing and //+/ce/ for subscribing, slashes in the event name become dots, and the source header is derived from publishPrefix.
CloudEvents format in CAP
Setting format to cloudevents in the messaging configuration makes CAP fill the CloudEvents header fields itself. Emitting the ClaimApproved event with that option in the lab copy left this line in the message file:
ExpenseService.ClaimApproved {"data":{"ID":"11111111-1111-1111-1111-111111111111","amount":45.5},"headers":{"id":"697bb113-6171-4432-bece-46a32c79d0f2","type":"ExpenseService.ClaimApproved","source":"/default/sap.cap/59675","time":"2026-11-13T14:57:26.900Z","datacontenttype":"application/json","specversion":"1.0"}}
Source: real content of the message file of the lab copy, CAP: Messaging in Node.js, CloudEvents Protocol
The type, source, id and time were added by CAP, and the payload stayed under data. File-based messaging stores this as one line of text, which is its own format; on SAP Event Mesh the same fields form the CloudEvent that the broker routes.
Choosing between event and call
-
Use an event when others should react to something that happened and the sender needs no answer.
-
Use an API call when the caller needs the data or a result now.
-
Combine them: the event carries the key, and the consumer reads the details through the API, as in Consuming SAP APIs from CAP.
-
Design every handler for repeats, because at-least-once delivery can send an event twice.
Summary
-
A business event is a small message that announces something that happened; the provider does not wait and does not know the consumers.
-
SAP business events use the CloudEvents format:
type,source,id,timeand a smalldatapayload, usually the key. -
SAP Event Mesh routes an event to a topic built from
sourceandtype, keeps it in a queue per consumer, and can push it to a webhook after a handshake. -
In CAP Node.js an event is declared in the model, emitted with
emit, and received withmessaging.on(topic, ...);file-based-messagingruns the whole flow locally andenterprise-messagingreplaces it for SAP Event Mesh without code changes. -
The ABAP side of the same idea is described on RAP Business Events.