Salesforce provides a robust event-driven architecture that supports real-time, asynchronous intercommunication between various systems. Central to this architecture are Platform Events, which are predefined, secure, and standardized messages to be published and consumed by various Salesforce apps and processes. In this tutorial, we’ll go through a detailed understanding of Salesforce Eventing and Platform Events.
Event Driven Architecture
Event-Driven Architecture (EDA) is a software design pattern where the execution flow is determined by events such as user actions, sensor outputs, or messages from other programs. These events are detected by event listeners. When an event occurs, the listener reacts by triggering a specific action or a sequence of actions.
In the context of Salesforce, an event can be a record change, a platform event, or an external event from an external system.
Platform Events in Salesforce are part of the Salesforce Enterprise Messaging Platform. They are used to deliver secure, scalable, and customizable notification infrastructures. This system allows users to create and listen for custom notifications in near-real-time, leading to an event-driven architecture.
This tutorial will cover the following:
- What are Platform Events?
- How to create Platform Events
- How to publish Platform Events
- How to subscribe to Platform Events
- Example scenario: Creating, publishing, and subscribing to Platform Events
1. What are Platform Events?
Platform Events are based on the publish/subscribe model and are designed to connect Salesforce with external systems. They are a type of Salesforce object (like standard or custom objects) but are intended to carry data from Salesforce to external systems or between Salesforce orgs.
2. How to Create Platform Events
Creating a Platform Event is like creating a custom object in Salesforce. Here are the steps:
- From Setup, enter “Platform Events” in the Quick Find box, then select “Platform Events”.
- Click “New Platform Event”.
- Enter the necessary data:
- Label: Name of the event (e.g., “Inventory Update”)
- Plural Label: Plural form of the label (e.g., “Inventory Updates”)
- Object Name: Unique identifier used by the API and managed packages (e.g., “Inventory_Update”)
- Description: Detailed info about the event (optional but recommended)
- Click “Save”.
- Now, add custom fields if needed by clicking “New Custom Field” and follow the prompts.
3. How to Publish Platform Events
Platform Events can be published using different methods such as Apex, Process Builder, or REST API. Here’s how to publish an event using Apex:
// Instantiate the new Platform Event Inventory_Update__e invUpdate = new Inventory_Update__e(); // Set the custom field values invUpdate.Product_Code__c = 'PRD-1234'; invUpdate.Quantity__c = 50; // Publish the event Database.SaveResult sr = EventBus.publish(invUpdate); // Inspect publishing result if (sr.isSuccess()) { System.debug('Successfully published event.'); } else { for(Database.Error err : sr.getErrors()) { System.debug('Error returned: ' + err.getStatusCode() + ' - ' + err.getMessage()); } }
4. How to Subscribe to Platform Events
Subscriptions to Platform Events can be done using Apex triggers, Lightning components, CometD libraries (for external systems), or Process Builder/Flow. Here’s how to create an Apex trigger to listen for our event:
trigger InventoryUpdateTrigger on Inventory_Update__e (after insert) { for (Inventory_Update__e event : Trigger.New) { System.debug('Received Inventory Update for Product: ' + event.Product_Code__c + ' - New Quantity: ' + event.Quantity__c); } }
5. Example Scenario: Creating, Publishing, and Subscribing to Platform Events
In this example scenario, we’ll create a use case where a third-party warehouse system needs to update Salesforce about changes in product quantities.
Step 1: Creating a Platform Event
First, we need to create a Platform Event “Inventory_Update__e” with two custom fields: “Product_Code__c” (Text) and “Quantity__c” (Number).
- From Setup, enter “Platform Events” in the Quick Find box, then select “Platform Events”.
- Click “New Platform Event”.
- Enter the Label as “Inventory Update”, Plural Label as “Inventory Updates”, and Object Name as “Inventory_Update”.
- Click “Save”.
- Click “New Custom Field”.
- Select “Text” for the Data Type and click “Next”.
- Enter Field Label as “Product Code”, Length as “255”, Field Name as “Product_Code”, and click “Next”.
- Accept the defaults for the remaining steps and click “Save”.
- Click “New Custom Field” again.
- Select “Number” for the Data Type and click “Next”.
- Enter Field Label as “Quantity”, Length as “18”, Decimal Places as “0”, Field Name as “Quantity”, and click “Next”.
- Accept the defaults for the remaining steps and click “Save”.
Step 2: Publishing the Platform Event
The external warehouse system can publish an event to Salesforce whenever there is a change in inventory. This can be done using the REST API or Apex (if it is a Salesforce system). Here is an example using Apex:
// Instantiate the new Platform Event Inventory_Update__e invUpdate = new Inventory_Update__e(); // Set the custom field values invUpdate.Product_Code__c = 'PRD-1234'; invUpdate.Quantity__c = 50; // Publish the event Database.SaveResult sr = EventBus.publish(invUpdate); // Inspect publishing result if (sr.isSuccess()) { System.debug('Successfully published event.'); } else { for(Database.Error err : sr.getErrors()) { System.debug('Error returned: ' + err.getStatusCode() + ' - ' + err.getMessage()); } }
Step 3: Subscribing to the Platform Event
On the Salesforce side, we need to create a trigger to listen for the “Inventory_Update__e” event and then update the inventory accordingly. Here’s how to create such a trigger:
trigger InventoryUpdateTrigger on Inventory_Update__e (after insert) { List<Product2> productsToUpdate = new List<Product2>(); for (Inventory_Update__e event : Trigger.New) { Product2 prod = [SELECT Id, Quantity__c FROM Product2 WHERE ProductCode = :event.Product_Code__c LIMIT 1]; prod.Quantity__c = event.Quantity__c; productsToUpdate.add(prod); } if(!productsToUpdate.isEmpty()){ update productsToUpdate; } }
This trigger listens for the “Inventory_Update__e” event. For each received event, it queries the corresponding product based on the “Product_Code__c”, updates the “Quantity__c” with the new quantity, and then updates the product in Salesforce.
Please remember to replace Product2
and Quantity__c
with your actual Product object API name and its field name, respectively.
This is how you can leverage Platform Events to create an event-driven architecture in Salesforce that integrates with external systems in near-real-time.
Service Oriented Architecture in Salesforce Development
Common Design Patterns in Apex
Factory Method Pattern and Reflection in Apex within Salesforce: An In-Depth Analysis with Examples