Sub topic 11
Custom channels and selecting entities
This chapter assumes you know the earlier channel names (/data/AccountChangeEvent, /data/ChangeEvents), the shape of a change event, and how a client subscribes and stores a replay ID. You should also be able to deploy metadata with Salesforce CLI.
Why a custom channel
An org that enables CDC for many objects ends up with two kinds of channel:
- A per-entity channel such as
/data/AccountChangeEvent. A subscriber sees one object only. - The shared channel
/data/ChangeEvents. A subscriber sees every enabled object.
Many integrations need something in between. A billing system may want changes to Account, Contact, and a custom Invoice__c, but not the other twelve objects the org has enabled. With the standard channels there are two bad options. Open three subscriptions, or subscribe to /data/ChangeEvents and discard most of what arrives.
A custom channel fixes this. It is a named stream that you define, and it carries change events for the entities you select. One subscription then receives exactly the objects one consumer needs.
| Option | What the subscriber receives | Subscriptions needed for 3 objects |
|---|---|---|
| Per-entity channel | One object | 3 |
| `/data/ChangeEvents` | All enabled objects | 1, with client-side filtering |
| Custom channel | The objects you selected | 1 |
The two metadata types
A custom channel is built from two metadata types.
PlatformEventChanneldefines the channel. For change events, setchannelTypetodata.PlatformEventChannelMemberadds one entity to a channel. It names the channel ineventChanneland the change event inselectedEntity.
The channel's API name must end in __chn. The subscription name is /data/ followed by that API name.
Defining a channel in source format
Create the channel first. The file lives in force-app/main/default/platformEventChannels/.
<?xml version="1.0" encoding="UTF-8"?>
<PlatformEventChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<channelType>data</channelType>
<label>Billing Channel</label>
</PlatformEventChannel>Name the file Billing_Channel__chn.platformEventChannel-meta.xml.
Then add one member file per entity, in force-app/main/default/platformEventChannelMembers/. This one selects Account.
<?xml version="1.0" encoding="UTF-8"?>
<PlatformEventChannelMember xmlns="http://soap.sforce.com/2006/04/metadata">
<eventChannel>Billing_Channel__chn</eventChannel>
<selectedEntity>AccountChangeEvent</selectedEntity>
</PlatformEventChannelMember>Name the file Billing_Channel_chn_AccountChangeEvent.platformEventChannelMember-meta.xml. Repeat the file for ContactChangeEvent and Invoice__ChangeEvent, changing only selectedEntity and the file name.
The selectedEntity value is the name of the change event, not the object. Standard objects use <Object>ChangeEvent. Custom objects use <Object>__ChangeEvent, so Invoice__c becomes Invoice__ChangeEvent.
Deploy both folders with Salesforce CLI:
sf project deploy start \
--source-dir force-app/main/default/platformEventChannels \
--source-dir force-app/main/default/platformEventChannelMembersDeploy order matters. A member references its channel, so the channel must exist first. A single deploy that contains both handles this for you. If a member deploy fails with a missing-channel error, check that the eventChannel value matches the channel API name exactly, including __chn.
You can also create channels and members in Setup, under Integrations, in Change Data Capture. The metadata route is better for anything you promote between orgs, because the definitions travel with your source.
Subscribing to a custom channel
The subscriber changes only the channel string. This is the Lightning web component from the subscriber chapter, pointed at the new channel.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class BillingChangeListener extends LightningElement {
subscription = null;
channelName = '/data/Billing_Channel__chn';
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const header = message.data.payload.ChangeEventHeader;
console.log(header.entityName, header.changeType, header.recordIds);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Because the channel mixes objects, the handler can no longer assume one shape. Read ChangeEventHeader.entityName first and branch on it. Fields that exist on Invoice__c will not exist on an Account event. A handler that reads payload.Phone unconditionally will see undefined for every non-Account event.
External clients work the same way. A CometD client subscribes to /data/Billing_Channel__chn. A Pub/Sub API client uses that string as the topic name.
What a custom channel does and does not change
A custom channel is a delivery route. It does not change how events are created. Keep these points straight.
- Event content is unchanged. Each event has the same
ChangeEventHeaderand changed fields as on the per-entity channel. Field-level security and the other access rules from the security chapter still apply. - Apex triggers are not tied to channels. A trigger on
AccountChangeEventfires for Account change events whether or not any channel includes Account. Channel membership only affects what external and Lightning subscribers receive. - Replay IDs belong to a subscription. Store the last replay ID per channel name. Do not reuse an ID saved from
/data/AccountChangeEventwhen you switch to/data/Billing_Channel__chn. After the switch, resume from the ID you saved for the new channel, or start fresh with-1or-2and reconcile. - Gap and overflow events still happen. They can arrive on a custom channel, so the reconciliation logic from the earlier chapter still applies.
- Removing a member stops delivery. Events for that entity stop arriving on the channel. Subscribers receive nothing that says the entity was removed, so a quiet channel may mean a removed member and not a lack of changes.
Allocation and limit effects
Custom channels have their own limits, and they interact with delivery allocations. Check the current numbers in the Platform Events Developer Guide for your edition, because they change between releases. Three design consequences hold regardless of the exact values.
- Channels are a limited resource. The org caps how many custom channels it can define and how many members each can hold. Plan channels around consumers, not around objects.
- Deliveries are counted per subscriber. Each event delivered to a subscriber counts toward the delivery allocation. If two systems subscribe to overlapping channels, the same change is delivered twice and counted twice.
- Narrow channels save allocation. A consumer that subscribes to
/data/ChangeEventsand ignores most events still uses delivery allocation for every event. A custom channel with only the needed objects avoids that cost.
Choosing members and keeping channels narrow
Use these rules when you design channels.
- Create one channel per consumer or per business function, not one big channel for everything. A channel called
Everything__chnreproduces the problem you were solving. - Select only entities the consumer acts on. Each extra member adds events, delivery counts, and handler branches.
- Group objects that the consumer must process in a consistent order. Events are ordered within the bus by commit, so one subscription sees related changes in sequence. Two separate subscriptions give you no ordering guarantee between them.
- Name channels after the consumer, such as
Billing_Channel__chn, so the owner is clear when you read the metadata list.
If a consumer needs only some records of an entity, check whether your org's API version supports filter expressions on channel members. Where it does, the filter is set on the member and reduces events before delivery. Where it does not, the consumer has to filter. This is also one more reason to keep the handler's branching logic cheap.
Common errors
| Symptom | Likely cause |
|---|---|
| Deploy fails with an unknown channel | The member's `eventChannel` does not match the channel API name, or the channel was not in the same deploy |
| Subscribe call returns an error such as an unknown channel | The name is missing the `/data/` prefix or the `__chn` suffix |
| Subscriber gets events for some objects only | A member file is missing, or `selectedEntity` has the wrong change event name |
| Handler throws on some events | It assumes one object's fields on a mixed channel and does not check `entityName` |
| Replay starts at the wrong point after switching channels | The saved replay ID came from a different channel |
Exercise
A subscriber currently listens to /data/AccountChangeEvent and to /data/Invoice_ChangeEvent in two connections. You deploy a custom channel with a PlatformEventChannel named BillingChannel_chn and two members. What value do you put in selectedEntity for the Invoice_c member, what topic string does the subscriber now use, and what must the handler check before reading fields?
Show answer
selectedEntity is Invoice_ChangeEvent. The subscriber uses /data/BillingChannel__chn. The handler must read ChangeEventHeader.entityName first and branch on it, because Account and Invoice events carry different fields.
Exercise
You move a consumer from /data/AccountChangeEvent to a custom channel that includes Account. The consumer stored replay ID 48213 from the old channel. Why is it unsafe to subscribe to the new channel with 48213 without further checks, and what is a safer way to start?
Show answer
Replay IDs are stored per channel subscription, so an ID saved from one channel should not be assumed valid for another. A safer start is to subscribe with -1 (new events only) or -2 (all retained events) and then reconcile any changes made during the switch, for example by querying records modified since the old subscription's last processed event.