Table of Contents
Salesforce Platform Events are a powerful tool for real-time data integration and event-driven architecture within the Salesforce platform. They are crucial in enhancing Salesforce capabilities for automation, communication, and integration. In this blog, we will explore the steps to create a Salesforce Platform Event, the various types of events, use cases, and their limitations.
Do you know that in Salesforce, it is possible to connect business processes with external applications with platform events that help in exchanging real-time data?
These events are both scalable and secure ways of holding the data. Publishers can publish messages that subscribers receive in real-time. If you want to modify data published, it is necessary to define platform event fields.
Let’s dive into the world of Salesforce Platform Events!
What are Salesforce Platform Events?
Before we delve into creating Platform Events, it’s essential to grasp their significance. A Salesforce Platform Event is a message that represents an event or a trigger in Salesforce. These events can be used to communicate information within the Salesforce platform or with external systems, enabling seamless data integration and automation.
Streaming API uses push technology for publishing events and providing a mechanism to subscribe to these events for receiving the data in near real-time. Platform events are simply one of such streaming APIs in Salesforce. The mechanism it follows is called fire-and-forget integration.
Types of Salesforce Platform Events
1. Standard platform event
These events are predefined and provided by Salesforce only. Some noteworthy examples of these events are:
- AssetTokenEvent: Monitors OAuth 2.0 authentications activity
- BatchApexErrorEvent: Reports error encountered in batch apex jobs
2. High-Volume platform event
These are custom platform events that are used for publishing and processing millions of events effectively and scaling your event-based applications.
So, platform events have two types: standard and high-volume. Next, let’s take a look at the various aspects of platform events, such as limits, use cases, and examples.
Steps to Create a Salesforce Platform Events
Publishing and Subscribing of platform events are more flexible. You can publish event messages from a Force.com application or an external application using Salesforce APIs or Apex.
It is also possible to subscribe from Salesforce or an external application or use polling with cometD as well. Next, let’s explore the ways we can create platform events in Salesforce:
1. Defining Platform Event
It is the first step in the process of creating a platform event in Salesforce. It is similar to a custom object and can be done by going to set up > developer > Platform events > create a new platform event, as shown in the figure below:
To add a field to the event on the notification platform event page, click on new in Custom Fields & Relationships > Select test as the field data type > Click next > Set the values to (Field label: Message, Length: 255, Field name: Message, Description: The notification message, Required: Check the box next to “Always require a value in this field in order to save a record”) > Save.
2. Publish Platform Events
Publish using Apex
A trigger processes platform event notifications sequentially in the order they’re received. It also runs its process asynchronously and transactions that publish the event. Salesforce holds its special class to publish the platform events called EventBus, which has a method called publish method.
After the event is published, it can be consumed from the channel. The code for publishing the event using Apex is as follows:
trigger PlatformEventPublish on Account (after insert , after update )
{
If(trigger.isAfter && trigger.isUpdate){
List<Employee_On_boarding__e> publishEvents = new List<Employee_On_boarding__e>();
for(Account a : Trigger.new){
Employee_On_boarding__e eve = new Employee_On_boarding__e();
eve.Name__c = a.Name ;
eve.Phone__c = a.Phone ;
eve.Salary__c = a.AnnualRevenue ;
publishEvents.add(eve);}
if(publishEvents.size()>0)
{
EventBus.publish(publishEvents);
}
}
}
Publish using Process Builder
You can use Process Builder to publish event messages from a Salesforce application as part of an automated process. These declarative tools in Salesforce help in publishing event messages in Salesforce.
Publish using Flow
Flow is used to publish an event message from a Salesforce application as a part of a few-person interaction, an automatic process, Apex, or workflow action.
Create flow using platform event producer:
Create flow using Platform Event Consumer:
Run/Debug Flow: Via platform event producer and send the post in chatter.
Final result
Publish Events using API
This way of publishing events is similar to inserting objects. You can easily use any Salesforce API for creating platform events such as REST, SOAP, or Bulk.
The result returned by API contains information about success or errors encountered in publishing. If the success field is true, then the publish request is queued within Salesforce, and the event message is published asynchronously.
3. Subscribing for Platform Events
You can subscribe for the platform event from the platform events object trigger that is created in step 1. Here is a sample trigger on how you can handle subscribed events quite easily.
In this example, we are creating a new account from platform events, but you can implement your business logic to update the data.
Using Trigger
trigger OnBoardingTrigger on Employee_On_boarding__e (after insert) {
List<Account> acc = new List<Account>();
for(Employee_On_boarding__e oBording :trigger.new){
acc.add(new Account(Name =oBording.Name__c , Phone =oBording.Phone__c , AnnualRevenue = oBording.Salary__c));
}
if(acc.size() >0){
insert acc ;
}
}
Suppose there is a Visualforce page that consumes the platform events that you published. This page is built on CometD, which is a set of libraries for writing web applications that perform messaging over the web.
Wherever you need to write applications where clients need to react to server-side events, CometD is a good option. You can easily consume the platform events by using this URL /event/Employee_on_boarding_e. The complete code for the process is as follows:
<apex:page standardStylesheets="false" showHeader="false" sidebar="false">
<div id="content">
</div>
<apex:includeScript value="{!$Resource.cometd}"/>
<apex:includeScript value="{!$Resource.jquery}"/>
<apex:includeScript value="{!$Resource.json2}"/>
<apex:includeScript value="{!$Resource.jquery_cometd}"/>
<script type="text/javascript">
(function($){
$(document).ready(function() {
$.cometd.configure({
url: window.location.protocol+'//'+window.location.hostname+ (null != window.location.port ? (':'+window.location.port) : '') +'/cometd/40.0/',
requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
});
$.cometd.handshake();
$.cometd.addListener('/meta/handshake', function(message) { $.cometd.subscribe('/event/Employee_On_boarding__e', function(message) {
var div = document.getElementById('content');
div.innerHTML = div.innerHTML + '<p>Notification </p><br/>' +
'Streaming Message ' + JSON.stringify(message) + '</p><br>';
});
})
});
})(jQuery)
</script>
</apex:page>
Salesforce Platform Event Limits
Understanding the limits of Platform Events is crucial to planning your implementation. Salesforce imposes limits on the number of events you can publish, the number of subscribers, and the event retention period.
Keep these limits in mind as you design your event-based solutions. Here is a table for you to grasp the allocation limit for platform events:
Description | Performance and Unlimited Editions | Enterprise Edition | Developer Edition | Professional Edition (with API Add-On) |
Maximum platform event definitions possible for an organization | 100 | 50 | 5 | 5 |
Maximum number of concurrent CometD clients (subscribers) across all channels and for all event types | 2,000 | 1,000 | 20 | 20 |
Maximum number of Process Builder processes and flows that can subscribed to a platform event | 4,000 | 4,000 | 4,000 | 5 |
Maximum number of active Process Builder processes and flows that can subscribe to a platform event | 2,000 | 2,000 | 2,000 | 5 |
Maximum number of custom channels that can be created (This allocation is separate from the one for custom change data capture channels.) | 100 | 100 | 100 | 100 |
Maximum number of distinct platform events that can be added to a channel as part of channel members (If the same platform event is added to multiple channels, it’s counted once toward the allocation) | 50 | 50 | 5 | 5 |
Note: These values of allocation apply for both standard-volume and high-volume events.
In case your organisation has no add-on licenses, default allocations apply for event publishing and delivery that can’t be exceeded.
Salesforce Platform Event Use Cases
Salesforce Platform Events have a wide range of use cases across industries and business processes. Some common use cases include:
- Keep records and dashboards up to date in real-time as data changes occur.
- Integrate Salesforce with external systems, such as ERP or marketing automation platforms.
- Trigger workflows, processes, and approvals based on events, streamlining business processes.
- External product application notifies Salesforce of merchandise returns.
- A status change in Salesforce notifies external order fulfilment applications of a product shipment order.
Platform Event Example in Salesforce
One example of a platform event in Salesforce is order management. When the order management application creates an order in a pending state and publishes an order-created event, customer service receives the event and attempts to process an order.
Further, it publishes and orders update events. The order update service receives the event from the changes in the state of the order to either approve, cancel, or fulfil. It is an example of a platform event in Salesforce.
Salesforce Integration Patterns
In case you implement Salesforce, it is required to integrate it with other applications quite frequently. Although each integration scenario is unique in itself, there are common requirements and issues that the Salesforce developer manages and resolves.
When planning to create a Platform Event, it’s vital to consider your integration pattern. Platform Events are particularly useful for the “Publish-Subscribe” integration pattern, where systems can publish events, and other systems subscribe to them for real-time updates.
Salesforce Broadcasting
Salesforce Platform Events act as a broadcasting system, allowing various components within Salesforce and external systems to listen for and react to events in real time. This broadcasting capability enhances collaboration, automation, and data consistency across your organization.
It would help if you were clear about terminologies used in platform events before going forward with creating one. Thus, in the next part, we will provide some important terminologies necessary for learning and creating platform events in Salesforce.
Terminologies in Platform Events
1. Event
An event is defined as a change in the state that is meaningful in a business process. A meaningful example of this is the placement of an order, as its fulfilment needs notification for processing the order.
2. Event Notifier
A message containing data about the event is called an event notification
3. Event Producer
Publisher of an event message over a channel
4. Channel
A channel is considered a conduit for an event that transmits a message. Event consumers subscribe to the channel to receive messages.
5. Event Consumer
A consumer is a subscriber to a channel that receives messages through the channel.
In case you overlook platform events, it makes it similar to streaming API. Here are some points that differentiate between platform events and streaming API:
- Platform events are special forms of entities that are similar to custom objects to some extent.
- You can publish and consume platform events by using Apex or a SOAP or REST API.
- Platform events integrate easily with the Salesforce platform via Apex triggers. Triggers are the event consumers on Salesforce that listen to event messages.
- Platform events may be published using declarative tools (Process Builder).
- Platform events can also be subscribed to using Apex or decoratively process builder and flow.
- Unlike custom objects, you can’t update or delete event records. You also can’t view event records in the user interface given by Salesforce. Platform events also don’t have any page layouts. When you delete a platform event definition, it’s deleted permanently.
Advantages and Limitations of Platform Events
There are certain reasons for using platform events in Salesforce. Some of the most crucial ones are as follows:
- Salesforce clients can run their organizations quickly, specifically for event-driven architecture.
- Businesses would be able to create a 360-degree client experience.
- It will help in prevailing event-driven work processes, thus enlarging necessary information.
- Businesses would catch up while following up on many great streaming events.
Similar to any other Salesforce functionality, platform events have their limitations as follows:
- It only works for specific field types: Checkbox, Date, Time, Number, Text, TextArea (Long).
- Salesforce enforces limits on the number of Platform Events you can publish and consume within a given 24-hour window.
- Platform Events have a limited data retention period. By default, events are retained for 24 hours, which means subscribers must consume the events within that time frame.
- Platform Events do not guarantee the order in which subscribers process events.
- Platform Events follow a publish-subscribe model, but there’s no guarantee that events will be delivered to subscribers in real-time.
- Salesforce does not provide a built-in mechanism for replaying missed events. If a subscriber goes offline or experiences issues, it may miss events.
- Each Platform Event has a maximum payload size, and large payloads may need to be handled differently.
Conclusion
Salesforce Platform Events is a pivotal feature for enabling real-time integration, automation, and communication within the Salesforce platform. By understanding the event types, limits, and use cases and by following the steps to create and use Platform Events, you can unlock the full potential of this powerful tool in your Salesforce environment.
Whether you’re looking to streamline processes, enhance data integration, or achieve real-time updates, Platform Events are the key to success in the world of event-driven architecture. Start harnessing their power today!