Org Skills

Events and streaming — contracts, Pub/Sub, Event Relay, CDC, subscribers

Supporting material for salesforce-integration. Agents load it on demand; it ships inside the skill folder.

RawSource

Target: Spring '26 (API 66.0). Sources: Platform Events Developer Guide, Pub/Sub API, Event Relay, Change Data Capture.

1. The event contract

A platform event is a public API. Design it like one:

Field Why
Correlation_Id__c (Text, external-system Id or a UUID) Ties the event to the originating record and to logs on both sides
Event_Version__c (Text, 1.0) Consumers branch on it; you add fields, never repurpose them
Source_System__c Lets a consumer ignore its own echo
Occurred_At__c (DateTime) The business time, distinct from CreatedDate and from delivery time
Payload fields Flat, typed, no JSON blobs unless the consumer is genuinely generic. No PII unless it is necessary and the channel is controlled

Publish behaviour is a property of the event definition (Publish After Commit vs Publish Immediately), not of the publisher. EventBus.publish in Apex and a Create Records element in Flow both inherit it. Publish After Commit is the default and the right choice when the event announces a committed change; Publish Immediately is for logging or monitoring events that must survive a rollback.

High-volume platform events are the norm; standard-volume events are rarely justified now.

2. Publishing and consuming in Apex

// Publish — check every result; publishing does not throw on partial failure
List<Order_Event__e> events = new List<Order_Event__e>();
for (Order__c o : approved) {
    events.add(new Order_Event__e(
        Correlation_Id__c = o.ERP_Id__c,
        Event_Version__c  = '1.0',
        Source_System__c  = 'Salesforce',
        Occurred_At__c    = System.now(),
        Status__c         = o.Status__c));
}
for (Database.SaveResult sr : EventBus.publish(events)) {
    if (!sr.isSuccess()) {
        IntegrationLogger.error('Order_Event__e publish', sr.getErrors());
    }
}
// Subscribe — the trigger holds no logic, like every other trigger in the org
trigger OrderEventTrigger on Order_Event__e (after insert) {
    new OrderEventTriggerHandler().run();
}
// Handler — idempotent on EventUuid, retry only transient failures
public with sharing class OrderEventTriggerHandler {
    public void run() {
        List<Order_Event__e> events = (List<Order_Event__e>) Trigger.new;

        Set<String> uuids = new Set<String>();
        for (Order_Event__e e : events) { uuids.add(e.EventUuid); }

        Set<String> seen = new Set<String>();
        for (Processed_Event__c p : [SELECT Event_Uuid__c FROM Processed_Event__c
                                     WHERE Event_Uuid__c IN :uuids WITH USER_MODE]) {
            seen.add(p.Event_Uuid__c);
        }

        List<Order_Event__e> unprocessed = new List<Order_Event__e>();
        for (Order_Event__e e : events) {
            if (!seen.contains(e.EventUuid)) { unprocessed.add(e); }
        }
        if (unprocessed.isEmpty()) { return; }

        try {
            OrderEventService.handle(unprocessed);       // records what it processes
        } catch (CalloutException e) {
            throw new EventBus.RetryableException('ERP unavailable: ' + e.getMessage());
        }
    }
}

A platform-event trigger follows the same rule as any other: no logic in the trigger body, and the handler filters to the records actually in scope rather than working straight off Trigger.new.

  • EventBus.RetryableException asks the platform to redeliver; after the retry budget the subscription is suspended and an admin must resume it in Event Manager — so alert on suspension, do not discover it a week later.
  • EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId) lets a partially-successful batch resume from a known point instead of reprocessing.
  • Anything non-transient is logged and dropped: retrying a validation error forever suspends the subscription.

3. External subscribers

Option Operate When
Pub/Sub API with a managed subscription Salesforce tracks the replay position server-side; the client asks for "what's next" Default for a client you write. Removes replay-Id bookkeeping and its whole class of bugs
Pub/Sub API with client-side replay You persist the last processed replay Id and resume from it When the consumer needs exact control of its position, for example replaying into a rebuild
Event Relay Salesforce forwards platform events and CDC to AWS EventBridge; no subscriber process at all The target is AWS and you want no client to run
lightning/empApi In-browser subscription from an LWC UI that must react to changes by other users or systems

Retention is 72 hours for high-volume events regardless of the option; a consumer that has been down longer needs a replay from the source system, not from the bus. Ordering holds only within a partition, so never encode "B happens after A" in two separate events without a version or sequence field.

4. Change Data Capture

  • Enable per object in Setup → Change Data Capture; the channel carries create, update, delete and undelete with the changed fields and a header (changeType, changeOrigin, transactionKey, commitTimestamp, recordIds).
  • transactionKey groups changes from one transaction — use it when a consumer must see parent and child changes together.
  • changeOrigin identifies the client that made the change, which is how a consumer avoids reacting to its own writes.
  • Entity allocation is limited; CDC is for the handful of objects another system must mirror, not for every object "just in case".
  • CDC is not an audit log: deletes arrive without the old values and the retention window is the same 72 hours.

5. Dead letters and replay

Integration_Error__c
  Correlation_Id__c · Direction__c (Inbound/Outbound) · System__c
  Payload__c (Long Text, no secrets) · Attempt__c · Last_Error__c
  Status__c (New / Retrying / Dead / Replayed)
  • A Queueable Finalizer writes the row after the last failed attempt; a scheduled job replays Status__c = 'Dead' rows on demand, in order, with the same idempotency key.
  • The circuit breaker is a Custom Metadata or Platform Cache flag the client checks before calling out; a scheduled probe closes it again.
  • Dashboards that earn their place: failures per system per day, oldest unreplayed dead letter, suspended event subscriptions, API usage against allocation.