Sub topic 2
Defining a platform event and its fields
A platform event definition is the schema of a message. It names the event, lists its fields, and sets how it is published. Publishers, subscribers, and the event bus all depend on that definition. This chapter covers what a definition contains, how to create one in Setup and as metadata, and which mistakes cause the most trouble.
This chapter assumes you know how custom objects and custom fields work in Salesforce. It also assumes you can read basic Apex and have seen how the event bus connects publishers and subscribers. Publishing and subscribing code appear in later chapters. Here the code only shows how the definition is used.
What a platform event definition is
A platform event looks like a custom object, but it behaves differently. The differences matter for design.
| Aspect | Custom object | Platform event |
|---|---|---|
| API name suffix | `__c` | `__e` |
| Stored as | Database rows you can query and update | Messages on the event bus for a limited time |
| Update or delete after creation | Allowed | Not allowed |
| Tab, page layout, list view | Available | Not available |
| Triggers | before and after, insert, update, delete | `after insert` only |
| Field suffix | `__c` | `__c` |
The key difference is that an event is an immutable message. You never update an event, and you never delete one after publishing it. Publishing is an insert into the event bus, and delivery to subscribers follows from that insert.
The event's API name also forms its channel name. An event named Order_Shipped__e is delivered on the channel /event/Order_Shipped__e. Subscribers such as Lightning Web Components and external clients use that channel string, so renaming an event later breaks them.
Create the event in Setup
Follow these steps to create the event in the Salesforce UI:
- Open Setup and search for Platform Events.
- Click New Platform Event.
- Enter the Label (Order Shipped), Plural Label (Order Shipped Events), and Object Name (
Order_Shipped). Salesforce adds__efor you. - Choose a Publish Behavior. The default is Publish After Commit. The next chapter covers this setting, so keep the default for now.
- Select Deploy status. An event in In Development status is only partly available. Deploy it before other users or integrations rely on it.
- Save, then add custom fields in the Custom Fields & Relationships section.
New platform events are high-volume events. Older standard-volume events may still exist in some orgs, and this tutorial covers only the high-volume kind.
Event fields
Every event gets standard fields from Salesforce. You add the custom fields that carry your business data.
| Standard field | Purpose |
|---|---|
| `ReplayId` | Position of the event in the stream. Subscribers use it to resume. |
| `EventUuid` | Unique identifier for the event. Useful for correlating logs and detecting duplicates. |
| `CreatedDate` | When the event was published. |
| `CreatedById` | The user who published it. |
Salesforce fills in these fields. You do not set them when you publish. ReplayId is covered in a later chapter on replay and retention.
Custom fields support a limited set of types.
| Field type | Notes |
|---|---|
| Text | Up to 255 characters. You choose the length. |
| Text Area (Long) | For larger payloads such as JSON strings. |
| Number | You set precision and scale. |
| Checkbox | True or false. |
| Date | A date without a time. |
| Date/Time | A timestamp. |
Lookup and master-detail relationships are not available. A platform event has no real link to a record, so carry the record's ID as a Text field. For example, Order_Id__c can hold the 18-character ID. Subscribers can then query the record if they need more data.
You can mark a field Required and give it a Default Value. A required field with no value makes the publish fail. Publishing then returns a failed SaveResult and does not throw an exception. Unique and external ID options are not useful here, because events are not stored as queryable rows.
The definition as metadata
You can keep the definition in source control and deploy it with the Metadata API or the Salesforce CLI. The event itself is a CustomObject file with the suffix .object-meta.xml.
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<deploymentStatus>Deployed</deploymentStatus>
<eventType>HighVolume</eventType>
<label>Order Shipped</label>
<pluralLabel>Order Shipped Events</pluralLabel>
<publishBehavior>PublishAfterCommit</publishBehavior>
</CustomObject>Each field gets its own file under the event's fields folder. This one is Order_Number__c.field-meta.xml.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Order_Number__c</fullName>
<externalId>false</externalId>
<label>Order Number</label>
<length>20</length>
<required>true</required>
<type>Text</type>
</CustomField>Define Status__c the same way, as a Text field with a length of 20. The examples in later chapters use both fields.
Permissions
Access to a platform event is a permission on the event object, set in a profile or permission set.
- Create lets a user or integration publish events.
- Read lets a user or integration subscribe to events.
Apex triggers on platform events run as the Automated Process user, not as the publishing user. That user does not need your permission setup, but your trigger code must not depend on the publisher's identity. Use CreatedById on the event if you need to know who published it.
An external system that publishes through the REST API needs Create access for the user it authenticates as. A Lightning component that subscribes needs Read access for the signed-in user. A missing permission produces a subscription or publish error, not an empty result, so check it first when something fails.
Using the definition in code
After you deploy the event, Apex can use Order_Shipped__e as a type. You build an instance with the field values and pass it to EventBus.publish, which later chapters cover in detail.
Order_Shipped__e evt = new Order_Shipped__e(
Order_Number__c = '00012345',
Status__c = 'Shipped'
);
Database.SaveResult sr = EventBus.publish(evt);
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug('Publish failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}If you deploy the event with Order_Number__c required and leave that field out, sr.isSuccess() returns false. The error list then names the missing field. Always check the result rather than assuming the publish worked.
Design guidelines for fields
A good event is small, self-describing, and stable. These rules help:
- Name the event after something that happened. Use past tense, such as
Order_Shipped__e, notShip_Order__e. An event reports a fact and does not command a subscriber. - Send identifiers and the facts that changed. Put the record ID and the few values subscribers need. Do not copy the whole record.
- Plan for several subscribers. A trigger, a flow, and an external system may all read the same event. Fields should make sense to all of them.
- Prefer adding fields over changing them. Subscribers depend on field names and types, so additive changes break fewer consumers.
- Use one event with a type field for closely related facts. A
Status__cvalue avoids creating a separate event for each status. Create separate events when subscribers differ or when the payloads differ a lot.
Common errors
- Using the event like an object. Code that tries to
updateordeletean event record fails. Publish a new event instead. - Forgetting to deploy. An event left in In Development status can behave inconsistently across publishers and subscribers. Deploy it.
- Renaming after subscribers exist. The API name is the channel. Changing it breaks every LWC and external client that uses the old channel string.
- Expecting a lookup field. Store the related record's ID as text.
- Ignoring
SaveResult. Required-field and permission problems show up there. They do not throw. - Putting sensitive data in events. Events are visible to every subscriber that has Read access. Limit the payload to what those subscribers should see.
Exercise
You define OrderShippede with a required Text field OrderNumber_c. A developer publishes an event with only Status_c set. What happens, and where do they see it? Also, why should they store a related Order record's ID as a Text field rather than a lookup?
Show answer
The publish fails because the required field is missing. EventBus.publish does not throw. It returns a Database.SaveResult whose isSuccess() is false, and getErrors() describes the missing field. Platform events do not support lookup or master-detail relationships, so the Order's 18-character ID is stored as Text, such as OrderId_c. Subscribers can query the Order with that ID when they need more data.