Sf integration
Salesforce integration architecture with 120-point scoring. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use sf-connected-apps), Apex-only logic (use sf-apex), or data import/export (use sf-data).
By- name:
- sf-integration
- description:
- Salesforce integration architecture with 120-point scoring. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use sf-connected-apps), Apex-only logic (use sf-apex), or data import/export (use sf-data).
sf-integration: Salesforce Integration Patterns Expert
Use this skill when the user needs integration architecture and runtime plumbing: Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, CDC, and event-driven integration design.
When This Skill Owns the Task
Use sf-integration when the work involves:
.namedCredential-meta.xmlor External Credential metadata- outbound REST/SOAP callouts
- External Service registration from OpenAPI specs
- Platform Events, CDC, and event-driven architecture
- choosing sync vs async integration patterns
Delegate elsewhere when the user is:
- configuring the OAuth app itself → sf-connected-apps
- writing Apex-only business logic → sf-apex
- deploying metadata → sf-deploy
- importing/exporting data → sf-data
Required Context to Gather First
Ask for or infer:
- integration style: outbound callout, inbound event, External Service, CDC, platform event
- auth method
- sync vs async requirement
- system endpoint / spec details
- rate limits, retry expectations, and failure tolerance
- whether this is net-new design or repair of an existing integration
Recommended Workflow
1. Choose the integration pattern
| Need | Default pattern |
|---|---|
| authenticated outbound API call | Named Credential / External Credential + Apex or Flow |
| spec-driven API client | External Service |
| trigger-originated callout | async callout pattern |
| decoupled event publishing | Platform Events |
| change-stream consumption | CDC |
2. Choose the auth model
Prefer secure runtime-managed auth:
- Named Credentials / External Credentials
- OAuth or JWT via the right credential model
- no hardcoded secrets in code
3. Generate from the right templates
Use the provided assets under:
assets/named-credentials/assets/external-credentials/assets/external-services/assets/callouts/assets/platform-events/assets/cdc/assets/soap/
4. Validate operational safety
Check:
- timeout and retry handling
- async strategy for trigger-originated work
- logging / observability
- event retention and subscriber implications
5. Hand off deployment or implementation details
Use:
- sf-deploy for deployment
- sf-apex for deeper service / retry code
- sf-flow for declarative HTTP callout orchestration
High-Signal Rules
- never hardcode credentials
- do not do synchronous callouts from triggers
- define timeout behavior explicitly
- plan retries for transient failures
- use middleware / event-driven patterns when outbound volume is high
- prefer External Credentials architecture for new development when supported
Common anti-patterns:
- sync trigger callouts
- no retry or dead-letter strategy
- no request/response logging
- mixing auth setup responsibilities with runtime integration design
Output Format
When finishing, report in this order:
- Integration pattern chosen
- Auth model chosen
- Files created or updated
- Operational safeguards
- Deployment / testing next step
Suggested shape:
Integration: <summary>
Pattern: <named credential / external service / event / cdc / callout>
Files: <paths>
Safety: <timeouts, retries, async, logging>
Next step: <deploy, register, test, or implement>
Cross-Skill Integration
| Need | Delegate to | Reason |
|---|---|---|
| OAuth app setup | sf-connected-apps | consumer key / cert / app config |
| advanced callout service code | sf-apex | Apex implementation |
| declarative HTTP callout / Flow wrapper | sf-flow | Flow orchestration |
| deploy integration metadata | sf-deploy | validation and rollout |
| use integration from Agentforce | sf-ai-agentscript | agent action composition |
Reference Map
Start here
- references/named-credentials-guide.md
- references/external-services-guide.md
- references/callout-patterns.md
- references/security-best-practices.md
Event-driven / platform patterns
- references/event-patterns.md
- references/platform-events-guide.md
- references/cdc-guide.md
- references/event-driven-architecture-guide.md
- references/messaging-api-v2.md
CLI / automation / scoring
- references/cli-reference.md
- references/named-credentials-automation.md
- references/scoring-rubric.md
- assets/
Score Guide
| Score | Meaning |
|---|---|
| 108+ | strong production-ready integration design |
| 90–107 | good design with some hardening left |
| 72–89 | workable but needs architectural review |
| < 72 | unsafe / incomplete for deployment |
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Callout Patterns Reference
This document provides detailed implementation patterns for REST and SOAP callouts in Salesforce integrations.
Parent Document: sf-integration/SKILL.md Related: event-patterns.md
Table of Contents
REST Callout Patterns
Synchronous REST Callout
Use Case: Need immediate response, NOT triggered from DML
Template: assets/callouts/rest-sync-callout.cls
When to Use:
- User-initiated actions requiring immediate feedback
- API calls from Lightning Web Components
- Scheduled batch jobs needing sequential processing
- Any non-trigger context where response is needed
When NOT to Use:
- Triggered from DML operations (triggers, Process Builder, flows)
- Long-running operations (>10 seconds expected)
- High-volume batch operations
Implementation
public with sharing class {{ServiceName}}Callout {
private static final String NAMED_CREDENTIAL = 'callout:{{NamedCredentialName}}';
public static HttpResponse makeRequest(String method, String endpoint, String body) {
HttpRequest req = new HttpRequest();
req.setEndpoint(NAMED_CREDENTIAL + endpoint);
req.setMethod(method);
req.setHeader('Content-Type', 'application/json');
req.setTimeout(120000); // 120 seconds max
if (String.isNotBlank(body)) {
req.setBody(body);
}
Http http = new Http();
return http.send(req);
}
public static Map<String, Object> get(String endpoint) {
HttpResponse res = makeRequest('GET', endpoint, null);
return handleResponse(res);
}
public static Map<String, Object> post(String endpoint, Map<String, Object> payload) {
HttpResponse res = makeRequest('POST', endpoint, JSON.serialize(payload));
return handleResponse(res);
}
public static Map<String, Object> put(String endpoint, Map<String, Object> payload) {
HttpResponse res = makeRequest('PUT', endpoint, JSON.serialize(payload));
return handleResponse(res);
}
public static Map<String, Object> patch(String endpoint, Map<String, Object> payload) {
HttpResponse res = makeRequest('PATCH', endpoint, JSON.serialize(payload));
return handleResponse(res);
}
public static void deleteRequest(String endpoint) {
makeRequest('DELETE', endpoint, null);
}
private static Map<String, Object> handleResponse(HttpResponse res) {
Integer statusCode = res.getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
return (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
} else if (statusCode >= 400 && statusCode < 500) {
throw new CalloutException('Client Error: ' + statusCode + ' - ' + res.getBody());
} else if (statusCode >= 500) {
throw new CalloutException('Server Error: ' + statusCode + ' - ' + res.getBody());
}
return null;
}
}
Key Features
- Named Credential Integration: Uses
callout:syntax for secure authentication - Timeout Management: 120-second max timeout (governor limit)
- HTTP Method Support: GET, POST, PUT, PATCH, DELETE
- Status Code Handling: Differentiates between client (4xx) and server (5xx) errors
- JSON Serialization: Automatic JSON handling for request/response bodies
Usage Example
// GET request
try {
Map<String, Object> data = StripeCallout.get('/v1/customers/cus_123');
String email = (String) data.get('email');
} catch (CalloutException e) {
// Handle error
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
}
// POST request
Map<String, Object> payload = new Map<String, Object>{
'email' => 'customer@example.com',
'name' => 'John Doe'
};
Map<String, Object> response = StripeCallout.post('/v1/customers', payload);
Asynchronous REST Callout (Queueable)
Use Case: Callouts triggered from DML (triggers, Process Builder)
Template: assets/callouts/rest-queueable-callout.cls
When to Use:
- Callouts from triggers (REQUIRED - sync callouts fail in triggers)
- Fire-and-forget operations (no immediate response needed)
- Bulk operations processing multiple records
- Long-running API calls (>10 seconds)
Governor Limit Considerations:
- Max 50 queueable jobs per transaction
- Queueable can chain to another queueable (max depth varies by org)
- Callout timeout: 120 seconds
Implementation
public with sharing class {{ServiceName}}QueueableCallout implements Queueable, Database.AllowsCallouts {
private List<Id> recordIds;
private String operation;
public {{ServiceName}}QueueableCallout(List<Id> recordIds, String operation) {
this.recordIds = recordIds;
this.operation = operation;
}
public void execute(QueueableContext context) {
if (recordIds == null || recordIds.isEmpty()) {
return;
}
try {
// Query records
List<{{ObjectName}}> records = [
SELECT Id, Name, {{FieldsToSend}}
FROM {{ObjectName}}
WHERE Id IN :recordIds
WITH USER_MODE
];
// Make callout for each record (consider batching)
for ({{ObjectName}} record : records) {
makeCallout(record);
}
} catch (CalloutException e) {
// Log callout errors
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
// Consider: Create error log record, retry logic, notification
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'Error: ' + e.getMessage());
}
}
private void makeCallout({{ObjectName}} record) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:{{NamedCredentialName}}/{{Endpoint}}');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(120000);
Map<String, Object> payload = new Map<String, Object>{
'id' => record.Id,
'name' => record.Name
// Add more fields
};
req.setBody(JSON.serialize(payload));
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
// Success - update record status if needed
} else {
// Handle error
throw new CalloutException('API Error: ' + res.getStatusCode());
}
}
}
Trigger Integration
trigger OpportunityTrigger on Opportunity (after insert, after update) {
List<Id> opportunityIds = new List<Id>();
for (Opportunity opp : Trigger.new) {
// Only sync closed-won opportunities
if (opp.StageName == 'Closed Won') {
opportunityIds.add(opp.Id);
}
}
if (!opportunityIds.isEmpty()) {
// Enqueue async callout
System.enqueueJob(new SalesforceQueueableCallout(opportunityIds, 'SYNC'));
}
}
Bulkification Pattern
For high-volume scenarios, batch multiple callouts:
private void makeCallouts(List<{{ObjectName}}> records) {
// Batch up to 10 records per callout
Integer BATCH_SIZE = 10;
List<Map<String, Object>> batch = new List<Map<String, Object>>();
for (Integer i = 0; i < records.size(); i++) {
batch.add(buildPayload(records[i]));
if (batch.size() == BATCH_SIZE || i == records.size() - 1) {
// Make single callout with batch
sendBatch(batch);
batch.clear();
}
}
}
private void sendBatch(List<Map<String, Object>> batch) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:{{NamedCredentialName}}/batch');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(120000);
req.setBody(JSON.serialize(new Map<String, Object>{'records' => batch}));
Http http = new Http();
HttpResponse res = http.send(req);
// Handle response
}
Retry Handler with Exponential Backoff
Use Case: Handle transient failures with intelligent retry logic
Template: assets/callouts/callout-retry-handler.cls
Retry Strategy:
- Max Retries: 3 attempts
- Backoff: Exponential (1s, 2s, 4s)
- Retry on: 5xx server errors, network timeouts
- Don't Retry: 4xx client errors (bad request, auth failure)
Implementation
public with sharing class CalloutRetryHandler {
private static final Integer MAX_RETRIES = 3;
private static final Integer BASE_DELAY_MS = 1000; // 1 second
public static HttpResponse executeWithRetry(HttpRequest request) {
Integer retryCount = 0;
HttpResponse response;
while (retryCount < MAX_RETRIES) {
try {
Http http = new Http();
response = http.send(request);
// Success or client error (4xx) - don't retry
if (response.getStatusCode() < 500) {
return response;
}
// Server error (5xx) - retry with backoff
retryCount++;
if (retryCount < MAX_RETRIES) {
// Exponential backoff: 1s, 2s, 4s
Integer delayMs = BASE_DELAY_MS * (Integer) Math.pow(2, retryCount - 1);
// Note: Apex doesn't have sleep(), so we schedule retry via Queueable
throw new RetryableException('Server error, retry ' + retryCount);
}
} catch (CalloutException e) {
retryCount++;
if (retryCount >= MAX_RETRIES) {
throw e;
}
}
}
return response;
}
public class RetryableException extends Exception {}
}
Queueable Retry Pattern
Since Apex doesn't support Thread.sleep(), implement retry delays using Queueable chaining:
public with sharing class CalloutWithRetryQueueable implements Queueable, Database.AllowsCallouts {
private HttpRequest request;
private Integer retryCount;
private static final Integer MAX_RETRIES = 3;
public CalloutWithRetryQueueable(HttpRequest req) {
this(req, 0);
}
private CalloutWithRetryQueueable(HttpRequest req, Integer retries) {
this.request = req;
this.retryCount = retries;
}
public void execute(QueueableContext context) {
try {
Http http = new Http();
HttpResponse res = http.send(request);
if (res.getStatusCode() >= 500 && retryCount < MAX_RETRIES) {
// Server error - retry
System.debug(LoggingLevel.WARN, 'Retry ' + (retryCount + 1) + ' for ' + request.getEndpoint());
System.enqueueJob(new CalloutWithRetryQueueable(request, retryCount + 1));
} else if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
// Success
handleSuccess(res);
} else {
// Client error - don't retry
handleError(res);
}
} catch (CalloutException e) {
if (retryCount < MAX_RETRIES) {
System.enqueueJob(new CalloutWithRetryQueueable(request, retryCount + 1));
} else {
throw e;
}
}
}
private void handleSuccess(HttpResponse res) {
// Process successful response
System.debug('Callout succeeded: ' + res.getBody());
}
private void handleError(HttpResponse res) {
// Log error
System.debug(LoggingLevel.ERROR, 'Callout error: ' + res.getStatusCode() + ' - ' + res.getBody());
}
}
Idempotency Considerations
When implementing retries, ensure API operations are idempotent:
// BAD: Non-idempotent (creates new record on each retry)
POST /api/orders { "item": "Widget", "quantity": 1 }
// GOOD: Idempotent (uses idempotency key)
POST /api/orders
Headers: Idempotency-Key: {{recordId}}-{{timestamp}}
{ "item": "Widget", "quantity": 1 }
SOAP Callout Patterns
WSDL2Apex Process
SOAP integrations in Salesforce use WSDL2Apex to auto-generate Apex classes from WSDL files.
Step-by-Step Process
Step 1: Generate Apex from WSDL
- Navigate to Setup → Apex Classes → Generate from WSDL
- Upload WSDL file or provide URL
- Salesforce parses WSDL and generates:
- Stub class (contains service endpoint and operations)
- Request/Response classes (for each operation)
- Type classes (for complex data types)
Step 2: Configure Named Credential
Create a Named Credential for the SOAP endpoint:
<?xml version="1.0" encoding="UTF-8"?>
<NamedCredential xmlns="http://soap.sforce.com/2006/04/metadata">
<label>{{ServiceName}} SOAP</label>
<endpoint>https://api.example.com/soap/v1</endpoint>
<principalType>NamedUser</principalType>
<protocol>Password</protocol>
<username>{{Username}}</username>
<password>{{Password}}</password>
</NamedCredential>
Step 3: Use Generated Classes
Generated classes follow this naming pattern:
- Stub Class:
{{WsdlNamespace}}.{{ServiceName}} - Port Type:
{{WsdlNamespace}}.{{PortTypeName}} - Operations: Methods on the port type class
SOAP Service Implementation
Template: assets/soap/soap-callout-service.cls
Basic SOAP Callout
public with sharing class {{ServiceName}}SoapService {
public static {{ResponseType}} callService({{RequestType}} request) {
try {
// Generated stub class
{{WsdlGeneratedClass}}.{{PortType}} stub = new {{WsdlGeneratedClass}}.{{PortType}}();
// Set endpoint (use Named Credential if possible)
stub.endpoint_x = 'callout:{{NamedCredentialName}}';
// Set timeout
stub.timeout_x = 120000;
// Make the call
return stub.{{OperationName}}(request);
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'SOAP Callout Error: ' + e.getMessage());
throw new CalloutException('SOAP service error: ' + e.getMessage());
}
}
}
Example: Weather Service SOAP Callout
WSDL: http://www.webservicex.net/globalweather.asmx?WSDL
Generated Classes:
GlobalWeatherSoapGetWeatherRequestGetWeatherResponse
Service Implementation:
public with sharing class WeatherService {
public static String getWeather(String city, String country) {
try {
// Initialize SOAP stub
GlobalWeatherSoap.GlobalWeatherSoap stub =
new GlobalWeatherSoap.GlobalWeatherSoap();
// Configure endpoint and timeout
stub.endpoint_x = 'callout:GlobalWeather_NC';
stub.timeout_x = 120000;
// Build request
GlobalWeatherSoap.GetWeatherRequest req =
new GlobalWeatherSoap.GetWeatherRequest();
req.CityName = city;
req.CountryName = country;
// Make callout
GlobalWeatherSoap.GetWeatherResponse res = stub.GetWeather(req);
return res.GetWeatherResult;
} catch (System.CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Weather API callout failed: ' + e.getMessage());
return null;
}
}
}
SOAP Headers and Authentication
For SOAP services requiring custom headers (e.g., WS-Security):
public with sharing class SecureSoapService {
public static void callServiceWithAuth(String username, String password) {
// Generated stub
MyService.MyServiceSoap stub = new MyService.MyServiceSoap();
// Set endpoint
stub.endpoint_x = 'callout:MyService_NC';
stub.timeout_x = 120000;
// Set SOAP headers for authentication
stub.inputHttpHeaders_x = new Map<String, String>{
'SOAPAction' => 'http://tempuri.org/IMyService/MyOperation',
'Authorization' => 'Basic ' + EncodingUtil.base64Encode(
Blob.valueOf(username + ':' + password)
)
};
// Make request
MyService.MyRequest req = new MyService.MyRequest();
MyService.MyResponse res = stub.MyOperation(req);
}
}
SOAP Fault Handling
public with sharing class RobustSoapService {
public static Object callWithFaultHandling() {
try {
MyService.MyServiceSoap stub = new MyService.MyServiceSoap();
stub.endpoint_x = 'callout:MyService_NC';
stub.timeout_x = 120000;
MyService.MyRequest req = new MyService.MyRequest();
return stub.MyOperation(req);
} catch (System.CalloutException e) {
// Parse SOAP fault
String errorMessage = e.getMessage();
if (errorMessage.contains('faultcode')) {
// SOAP Fault occurred
System.debug(LoggingLevel.ERROR, 'SOAP Fault: ' + errorMessage);
// Extract fault details using XML parsing if needed
} else {
// Network/HTTP error
System.debug(LoggingLevel.ERROR, 'Callout error: ' + errorMessage);
}
throw e;
}
}
}
Async SOAP Callout (Queueable)
For SOAP callouts triggered from DML:
public with sharing class SoapQueueableCallout implements Queueable, Database.AllowsCallouts {
private List<Id> recordIds;
public SoapQueueableCallout(List<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(QueueableContext context) {
try {
// Query records
List<Account> accounts = [
SELECT Id, Name, BillingCity, BillingCountry
FROM Account
WHERE Id IN :recordIds
WITH USER_MODE
];
// Initialize SOAP stub
GlobalWeatherSoap.GlobalWeatherSoap stub =
new GlobalWeatherSoap.GlobalWeatherSoap();
stub.endpoint_x = 'callout:GlobalWeather_NC';
stub.timeout_x = 120000;
// Process each record
for (Account acc : accounts) {
GlobalWeatherSoap.GetWeatherRequest req =
new GlobalWeatherSoap.GetWeatherRequest();
req.CityName = acc.BillingCity;
req.CountryName = acc.BillingCountry;
GlobalWeatherSoap.GetWeatherResponse res = stub.GetWeather(req);
// Update account with weather data
acc.Weather_Data__c = res.GetWeatherResult;
}
// Update records
update as user accounts;
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'SOAP Queueable error: ' + e.getMessage());
}
}
}
Best Practices
Callout Governor Limits
| Limit | Value | Notes |
|---|---|---|
| Max callouts per transaction | 100 | Batch multiple requests if possible |
| Max timeout per callout | 120 seconds | Set explicitly with setTimeout() |
| Max total timeout per transaction | 120 seconds | All callouts combined |
| Max heap size | 6 MB (sync) / 12 MB (async) | Large responses consume heap |
Security Checklist
- Use Named Credentials for authentication (NEVER hardcode credentials)
- Minimize OAuth scopes to least privilege
- Use Certificate-based auth for high-security integrations
- Validate SSL certificates (don't disable SSL verification)
- Sanitize user input before including in callout payloads
- Log callout errors without exposing sensitive data
Error Handling Patterns
try {
HttpResponse res = makeCallout();
handleResponse(res);
} catch (System.CalloutException e) {
// Network error, timeout, SSL error
logError('Callout failed', e);
} catch (JSONException e) {
// Malformed JSON response
logError('JSON parsing failed', e);
} catch (Exception e) {
// Unexpected error
logError('Unexpected error', e);
}
Testing Callouts
Use Test.setMock() to mock HTTP responses:
@isTest
private class MyCalloutTest {
@isTest
static void testSuccessfulCallout() {
// Set mock response
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
Test.startTest();
Map<String, Object> result = MyService.get('/customers/123');
Test.stopTest();
System.assertEquals('customer@example.com', result.get('email'));
}
// Mock class
private class MockHttpResponseGenerator implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"email":"customer@example.com"}');
res.setStatusCode(200);
return res;
}
}
}
Related Resources
- Event Patterns - Platform Events and Change Data Capture
- Main Skill Documentation - sf-integration overview
- Named Credentials Templates - Authentication templates
- Callout Templates - Ready-to-use callout patterns
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Change Data Capture (CDC) Guide
Overview
Change Data Capture publishes change events for Salesforce records, enabling near real-time data synchronization with external systems.
How CDC Works
┌─────────────────────────────────────────────────────────────────┐
│ CHANGE DATA CAPTURE FLOW │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. Record Created/Updated/Deleted in Salesforce │
│ ↓ │
│ 2. Salesforce generates Change Event │
│ ↓ │
│ 3. Event published to {{Object}}ChangeEvent channel │
│ ↓ │
│ 4. Apex Trigger or External Subscriber receives event │
│ ↓ │
│ 5. Process event (sync, audit, notify) │
│ │
└─────────────────────────────────────────────────────────────────┘
CDC vs Platform Events
| Feature | CDC | Platform Events |
|---|---|---|
| Trigger | Automatic on DML | Manual publish |
| Schema | Predefined (object fields) | Custom defined |
| Use Case | Data sync/replication | Custom messaging |
| Control | Limited | Full control |
Enabling CDC
Via Setup
- Go to Setup → Integrations → Change Data Capture
- Select objects to enable
- Save
Supported Objects
- Most Standard objects (Account, Contact, Opportunity, etc.)
- Custom objects
- Some system objects (User, Group, etc.)
Event Channel Names
| Object Type | Channel Name |
|---|---|
| Standard | AccountChangeEvent, ContactChangeEvent |
| Custom | My_Object__ChangeEvent (append ChangeEvent) |
Change Event Structure
ChangeEventHeader
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
// Available methods
header.getChangeType(); // CREATE, UPDATE, DELETE, UNDELETE
header.getChangedFields(); // List of changed field API names
header.getRecordIds(); // Affected record IDs
header.getEntityName(); // Object API name
header.getCommitNumber(); // Transaction sequence
header.getCommitTimestamp(); // When change occurred
header.getTransactionKey(); // Unique transaction ID
Change Types
| Type | Description | Event Contains |
|---|---|---|
| CREATE | New record | All field values |
| UPDATE | Record modified | Changed field values only |
| DELETE | Record deleted | Record IDs only |
| UNDELETE | Restored from bin | All field values |
| GAP_* | Events missed | Affected record IDs |
| GAP_OVERFLOW | Too many changes | Entity name |
Field Values
- Changed fields: Contain new values
- Unchanged fields: Null
- Use
getChangedFields()to know what changed
Subscribing to CDC
Apex Trigger
trigger AccountCDC on AccountChangeEvent (after insert) {
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
String changeType = header.getChangeType();
List<String> changedFields = header.getChangedFields();
List<String> recordIds = header.getRecordIds();
switch on changeType {
when 'CREATE' {
// Handle new records
}
when 'UPDATE' {
// Handle updates
}
when 'DELETE' {
// Handle deletions
}
}
}
// Set checkpoint
EventBus.TriggerContext.currentContext().setResumeCheckpoint(
Trigger.new[Trigger.new.size()-1].ReplayId
);
}
External (CometD)
Channel: /data/AccountChangeEvent
Handling Specific Changes
Filter by Changed Fields
// Only process if important fields changed
Set<String> importantFields = new Set<String>{'Status__c', 'Amount__c'};
List<String> changedFields = header.getChangedFields();
Boolean relevant = false;
for (String field : changedFields) {
if (importantFields.contains(field)) {
relevant = true;
break;
}
}
if (!relevant) return;
Get New Values
// Access field values from event (UPDATE: only changed fields have values)
if (changedFields.contains('Status__c')) {
String newStatus = event.Status__c;
// Process status change
}
Gap Events
Gap events indicate missed events:
Types
| Event | Meaning | Action |
|---|---|---|
| GAP_CREATE | Missed creates | Query and sync records |
| GAP_UPDATE | Missed updates | Query current state |
| GAP_DELETE | Missed deletes | Reconcile with source |
| GAP_UNDELETE | Missed restores | Query and sync |
| GAP_OVERFLOW | Too many changes | Full sync required |
Handling Gaps
when 'GAP_CREATE', 'GAP_UPDATE', 'GAP_DELETE', 'GAP_UNDELETE' {
// Query current state and sync
List<Account> records = [
SELECT Id, Name, Status__c
FROM Account
WHERE Id IN :header.getRecordIds()
];
syncToExternalSystem(records);
}
when 'GAP_OVERFLOW' {
// Trigger full sync batch job
Database.executeBatch(new FullSyncBatch());
}
Replay and Durability
Retention
CDC events retained for 3 days (72 hours).
Replay ID
Each event has unique ReplayId for tracking:
String replayId = event.ReplayId;
Resume Checkpoint
Critical for durability:
// Always set checkpoint at end of trigger
EventBus.TriggerContext.currentContext().setResumeCheckpoint(lastReplayId);
If trigger fails after checkpoint, processing resumes from that point.
External Sync Pattern
public class AccountCDCHandler {
public static void syncToExternal(AccountChangeEvent event) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
Map<String, Object> payload = new Map<String, Object>{
'recordIds' => header.getRecordIds(),
'operation' => header.getChangeType(),
'timestamp' => header.getCommitTimestamp(),
'changedFields' => header.getChangedFields()
};
// Add field values for CREATE/UPDATE
if (header.getChangeType() != 'DELETE') {
payload.put('name', event.Name);
payload.put('accountNumber', event.AccountNumber);
// Add relevant fields
}
// Queue async callout
System.enqueueJob(new ExternalSyncJob(payload));
}
}
Best Practices
DO
- Set resume checkpoint in every trigger
- Filter by relevant fields to reduce noise
- Handle all change types including GAPs
- Process idempotently (events may replay)
- Use async for external callouts
- Log changes for debugging
DON'T
- Don't throw exceptions - catch and log
- Don't ignore GAP events - they indicate data loss
- Don't assume single record - batch DML creates multi-record events
- Don't block on external calls - use Queueable
Monitoring
Event Delivery
Check for failures in:
- Setup → Platform Events → Monitor
- Debug logs for triggers
Common Issues
| Issue | Cause | Solution |
|---|---|---|
| Missing events | No CDC enabled | Enable in Setup |
| Duplicate processing | No idempotency | Check transactionKey |
| GAP events | Processing too slow | Optimize trigger, scale out |
| Timeout | Heavy processing | Move to async |
Limits
| Limit | Value |
|---|---|
| Objects per org | 100 |
| Events per 15 minutes | Varies by edition |
| Event retention | 3 days (72 hours) |
| Replay window | 3 days |
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->CLI Commands & Helper Scripts
Named Credentials
# List Named Credentials
sf org list metadata --metadata-type NamedCredential --target-org {{alias}}
# Deploy Named Credential
sf project deploy start --metadata NamedCredential:{{Name}} --target-org {{alias}}
# Retrieve Named Credential
sf project retrieve start --metadata NamedCredential:{{Name}} --target-org {{alias}}
External Services
# List External Service Registrations
sf org list metadata --metadata-type ExternalServiceRegistration --target-org {{alias}}
# Deploy External Service
sf project deploy start --metadata ExternalServiceRegistration:{{Name}} --target-org {{alias}}
Platform Events
# List Platform Events
sf org list metadata --metadata-type CustomObject --target-org {{alias}} | grep "__e"
# Deploy Platform Event
sf project deploy start --metadata CustomObject:{{EventName}}__e --target-org {{alias}}
API Requests (Beta)
# REST API request
sf api request rest /services/data/v66.0/sobjects/Account/describe --target-org {{alias}}
# REST with POST body
sf api request rest /services/data/v66.0/sobjects/Account --method POST \
--body '{"Name":"Test Account"}' --target-org {{alias}}
# GraphQL query
sf api request graphql --body '{"query":"{ uiapi { query { Account { edges { node { Name { value } } } } } } }"}' --target-org {{alias}}
[Beta] These commands simplify API exploration. For production, use Named Credentials and Apex callouts.
Helper Scripts
sf-integration includes automation scripts to configure credentials without manual UI steps.
Available Scripts
| Script | Purpose | Usage |
|---|---|---|
configure-named-credential.sh |
Set API keys via ConnectApi (Enhanced NC) | ./scripts/configure-named-credential.sh <org-alias> |
set-api-credential.sh |
Store keys in Custom Settings (legacy) | ./scripts/set-api-credential.sh <name> - <org-alias> |
Auto-Run Behavior
| File Pattern | Suggested Action |
|---|---|
*.namedCredential-meta.xml |
Run configure-named-credential.sh |
*.externalCredential-meta.xml |
Run configure-named-credential.sh |
*.cspTrustedSite-meta.xml |
Deploy endpoint security |
Example Workflow
# 1. Deploy metadata first
sf project deploy start --metadata ExternalCredential:WeatherAPI \
--metadata NamedCredential:WeatherAPI \
--target-org MyOrg
# 2. Run automation script
./scripts/configure-named-credential.sh MyOrg
# Enter API key when prompted (secure, hidden input)
Prerequisites
- Salesforce CLI v2+:
sfcommand available - Authenticated org:
sf org login web -a <alias> - Deployed metadata: External Credential and Named Credential deployed
See references/named-credentials-automation.md for complete guide.
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Event-Driven Architecture Guide
Source: Salesforce Architect Decision Guides — Event-Driven Architecture, Async Processing Related: event-patterns.md | callout-patterns.md
Overview
Event-Driven Architecture (EDA) decouples producers from consumers, enabling scalable, resilient integrations. Salesforce supports multiple event mechanisms — choosing the right one depends on volume, latency, and consumer location.
5 Core EDA Patterns
Pattern Comparison Matrix
| Pattern | Description | Salesforce Implementation | Best For |
|---|---|---|---|
| Pub/Sub | Publisher emits, multiple subscribers consume | Platform Events + Pub/Sub API | Multi-consumer notifications, cross-system sync |
| Fanout | One event → multiple independent consumers | Platform Events + multiple subscribers | Parallel processing, diverse downstream systems |
| Passed Messages | Event carries data payload for consumer processing | Platform Events with rich fields | External systems needing full context in message |
| Streaming | Continuous data feed for real-time consumers | CDC + Pub/Sub API | Data replication, real-time dashboards |
| Queueing | Ordered, guaranteed-delivery message processing | Platform Events (High-Volume) with checkpoints | Sequential processing, backpressure handling |
When to Use Each
Pub/Sub: Default choice for most event-driven integrations. Works for both internal (Apex triggers) and external (Pub/Sub API) consumers.
Fanout: When a single business event (e.g., "Order Placed") needs to notify billing, shipping, analytics, and notifications simultaneously.
Passed Messages: When the consumer needs all context in the event itself (no callback to Salesforce). Keep payloads lean — 1 MB limit.
Streaming: For data replication to warehouses or lakes. CDC + Pub/Sub API replaces legacy Streaming API.
Queueing: When processing order matters and you need backpressure handling. Use High-Volume Platform Events with resume checkpoints.
Pub/Sub API (Recommended External Subscription)
The Pub/Sub API is the recommended mechanism for external consumers subscribing to Platform Events and CDC events. It replaces the legacy Streaming API (CometD).
Key Characteristics
| Feature | Pub/Sub API | Legacy Streaming API (Deprecated) |
|---|---|---|
| Protocol | gRPC | CometD (long-polling) |
| Authentication | OAuth 2.0 | Session-based |
| Event Types | Platform Events, CDC, Custom Channels | PushTopic, Generic Events, Platform Events |
| Performance | High throughput, binary protocol | Limited by long-polling overhead |
| Status | Current — use for all new development | Deprecated — no new investments |
Subscription Modes
- Subscribe: Stream events from a given replay ID forward
- PublishStream: Bi-directional — publish events via gRPC (no Apex needed)
- ManagedSubscribe: Salesforce manages replay state (simplest for external consumers)
External Consumer Architecture
Salesforce Org
└── Platform Event / CDC Event
└── Pub/Sub API (gRPC endpoint)
└── External Consumer (Java, Python, Node.js, Go)
├── Process event
├── Commit replay ID
└── Handle failures with retry
LWC Subscription (Internal)
For Lightning Web Components subscribing to Platform Events, use empApi:
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
const channelName = '/event/Order_Status__e';
let subscription = {};
connectedCallback() {
subscribe(channelName, -1, (response) => {
console.log('Event received:', JSON.stringify(response));
this.handleEvent(response.data.payload);
}).then((sub) => {
subscription = sub;
});
onError((error) => {
console.error('empApi error:', JSON.stringify(error));
});
}
disconnectedCallback() {
unsubscribe(subscription);
}
Event Relays to AWS EventBridge
Salesforce Event Relays forward Platform Events to AWS EventBridge, enabling cloud-native event processing.
Architecture
Salesforce Platform Event
└── Event Relay Definition (Metadata)
└── AWS EventBridge Partner Event Source
├── AWS Lambda
├── AWS SQS
├── AWS Step Functions
└── Any EventBridge target
When to Use
- AWS-native architecture needing Salesforce events
- Complex event processing requiring AWS services (Step Functions, SQS, SNS)
- Fan-out to multiple AWS consumers from a single Salesforce event
- Event archival in AWS S3 or data lakes
Limitations
- One-way only (Salesforce → AWS)
- Adds latency (~seconds) compared to direct Pub/Sub API
- Requires AWS account configuration and IAM setup
- Platform Event limits still apply on the Salesforce side
Apache Kafka on Heroku
For organizations needing long-retention, high-throughput event streaming beyond Platform Event limits.
Comparison with Platform Events
| Feature | Platform Events | Kafka on Heroku |
|---|---|---|
| Retention | 24h (HV) / 72h (SV) | 1-6 weeks (configurable) |
| Throughput | Millions/day (HV) | Millions/second |
| Consumer groups | Limited | Unlimited |
| Replay | ReplayId-based | Offset-based, topic-level |
| Cost | Included / Platform Event add-on | Heroku Kafka add-on |
When to Choose Kafka
- Retention > 72 hours required
- Need multiple independent consumer groups
- Event throughput exceeds Platform Event limits
- Existing Kafka ecosystem in organization
- Need topic partitioning for ordered processing
Integration Pattern
Salesforce → Platform Event → Apex/Flow subscriber → Heroku Kafka producer
└── Consumer Group A (analytics)
└── Consumer Group B (data lake)
└── Consumer Group C (external CRM)
When NOT to Use Events
Events are not always the right choice. Prefer synchronous patterns when:
| Scenario | Why Not Events | Better Alternative |
|---|---|---|
| Need synchronous response | Events are async — no return value | REST callout with Named Credential |
| Infrequent data changes | Event infrastructure overhead not justified | Scheduled batch sync |
| Target system lacks event support | Consumer can't subscribe to events | Outbound Messages or REST callout |
| Simple record sync | Over-engineering for basic needs | Salesforce Connect / External Objects |
| Data volume < 100 records/day | Platform Event overhead unnecessary | Scheduled Flow with REST callout |
High-Volume Outbound Pattern
For scenarios requiring high-volume data push to external systems:
Do NOT use async Apex directly for high-volume outbound. Apex async limits (250K daily Queueable, 250K daily @future) are shared across all org operations. Consuming them for outbound sync starves other automation.
Recommended Pattern: Middleware + Platform Events
Salesforce Record Change
└── After-Save Flow / Trigger
└── Publish Platform Event (lightweight payload)
└── External Middleware (MuleSoft, Pub/Sub API consumer)
├── Enrich data (callback to Salesforce REST API if needed)
├── Transform to target format
├── Deliver to target system with retry logic
└── Report status back via Platform Event or REST callback
Benefits
- No Apex async limit consumption — events don't count against daily limits
- Middleware handles retries — exponential backoff, dead letter queues
- Scalable — middleware scales independently of Salesforce
- Observable — middleware provides logging, monitoring, alerting
Monitoring Event-Driven Systems
AsyncApexJob Monitoring
Query job status for async Apex that processes events:
List<AsyncApexJob> jobs = [
SELECT Id, JobType, Status, NumberOfErrors, MethodName, CreatedDate
FROM AsyncApexJob
WHERE CreatedDate = TODAY
AND Status IN ('Failed', 'Aborted')
ORDER BY CreatedDate DESC
LIMIT 50
];
Polling limit: AsyncApexJob queries are subject to SOQL limits. Max polling frequency: every 5 minutes.
Platform Event Metrics
- Setup → Platform Events → Usage: View publish/subscribe counts
- EventBusSubscriber: Query for subscriber status and position
- Proactive Monitoring: Set up Flow or Apex to alert on failed event processing
// Check subscriber lag
List<EventBusSubscriber> subs = [
SELECT Name, Position, Retries, LastError, Status
FROM EventBusSubscriber
WHERE Topic = 'Order_Status__e'
];
Key Metrics to Monitor
| Metric | Source | Alert Threshold |
|---|---|---|
| Failed events | EventBusSubscriber.Retries |
> 3 consecutive retries |
| Subscriber lag | EventBusSubscriber.Position vs latest ReplayId |
Lag > 1000 events |
| Async job failures | AsyncApexJob.NumberOfErrors |
Any failure |
| Event publish errors | Database.SaveResult in publisher |
Any failure |
| Daily event usage | Setup → Company Information → Platform Event Usage | > 80% of allocation |
Summary: EDA Decision Tree
Need real-time data sync?
├── YES → Is consumer external?
│ ├── YES → Pub/Sub API + Platform Events (or CDC for record changes)
│ └── NO → Platform Event trigger subscriber (or empApi for LWC)
└── NO → Is volume high (>10K records/day)?
├── YES → Middleware + Platform Events (high-volume outbound pattern)
└── NO → Scheduled batch sync (simplest, most maintainable)
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Event-Driven Integration Patterns
This document provides detailed implementation patterns for Platform Events and Change Data Capture (CDC) in Salesforce integrations.
Parent Document: sf-integration/SKILL.md Related: callout-patterns.md
Table of Contents
Platform Events
Platform Events enable asynchronous, event-driven communication between applications. They provide a publish-subscribe model where publishers fire events and subscribers listen for them.
Platform Event Definition
Use Case: Asynchronous, event-driven communication
Template: assets/platform-events/platform-event-definition.object-meta.xml
Standard Volume Event
Best for moderate event volumes (~2,000 events/hour):
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<deploymentStatus>Deployed</deploymentStatus>
<eventType>StandardVolume</eventType>
<label>{{EventLabel}}</label>
<pluralLabel>{{EventPluralLabel}}</pluralLabel>
<publishBehavior>PublishAfterCommit</publishBehavior>
<fields>
<fullName>{{FieldName}}__c</fullName>
<label>{{FieldLabel}}</label>
<type>Text</type>
<length>255</length>
</fields>
<fields>
<fullName>RecordId__c</fullName>
<label>Record ID</label>
<type>Text</type>
<length>18</length>
<description>Salesforce record ID related to this event</description>
</fields>
<fields>
<fullName>Timestamp__c</fullName>
<label>Timestamp</label>
<type>DateTime</type>
<description>When the event was triggered</description>
</fields>
</CustomObject>
High-Volume Event
Best for millions of events per day:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<deploymentStatus>Deployed</deploymentStatus>
<eventType>HighVolume</eventType>
<label>{{EventLabel}}</label>
<pluralLabel>{{EventPluralLabel}}</pluralLabel>
<publishBehavior>PublishAfterCommit</publishBehavior>
<fields>
<fullName>{{FieldName}}__c</fullName>
<label>{{FieldLabel}}</label>
<type>Text</type>
<length>255</length>
</fields>
</CustomObject>
Key Configuration Options
| Option | Values | Description |
|---|---|---|
| eventType | StandardVolume, HighVolume |
Event throughput capacity |
| publishBehavior | PublishAfterCommit, PublishImmediately |
When events are published |
| deploymentStatus | Deployed, InDevelopment |
Deployment status |
PublishBehavior Details:
PublishAfterCommit: Event published only if transaction commits (recommended)PublishImmediately: Event published immediately, even if transaction rolls back
Event Publisher
Template: assets/platform-events/event-publisher.cls
Bulk Event Publisher
public with sharing class {{EventName}}Publisher {
public static void publishEvents(List<{{EventName}}__e> events) {
if (events == null || events.isEmpty()) {
return;
}
List<Database.SaveResult> results = EventBus.publish(events);
for (Integer i = 0; i < results.size(); i++) {
Database.SaveResult sr = results[i];
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug(LoggingLevel.ERROR,
'Event publish error: ' + err.getStatusCode() + ' - ' + err.getMessage());
}
}
}
}
public static void publishSingleEvent(Map<String, Object> eventData) {
{{EventName}}__e event = new {{EventName}}__e();
// Map fields from eventData
event.{{FieldName}}__c = (String) eventData.get('{{fieldKey}}');
event.RecordId__c = (String) eventData.get('recordId');
event.Timestamp__c = DateTime.now();
Database.SaveResult sr = EventBus.publish(event);
if (!sr.isSuccess()) {
throw new EventPublishException('Failed to publish event: ' + sr.getErrors());
}
}
public class EventPublishException extends Exception {}
}
Usage Examples
Single Event:
Map<String, Object> eventData = new Map<String, Object>{
'recordId' => '001xx000003DXXXAAA',
'status' => 'Completed',
'amount' => 1000.00
};
OrderStatusPublisher.publishSingleEvent(eventData);
Bulk Events:
List<Order_Status__e> events = new List<Order_Status__e>();
for (Order order : orders) {
Order_Status__e event = new Order_Status__e();
event.RecordId__c = order.Id;
event.Status__c = order.Status;
event.Timestamp__c = DateTime.now();
events.add(event);
}
OrderStatusPublisher.publishEvents(events);
Best Practices for Publishing
- Batch Events: Publish up to 2,000 events per transaction (governor limit)
- Error Handling: Always check
Database.SaveResultfor failures - Transaction Context: Use
PublishAfterCommitto ensure events only fire on successful transactions - Field Population: Populate all required fields before publishing
- Logging: Log failed event publishes for debugging
Event Subscriber Trigger
Template: assets/platform-events/event-subscriber-trigger.trigger
Standard Volume Subscriber
trigger {{EventName}}Subscriber on {{EventName}}__e (after insert) {
// Get replay ID for resumption
String lastReplayId = '';
for ({{EventName}}__e event : Trigger.new) {
// Store replay ID for potential resume
lastReplayId = event.ReplayId;
try {
// Process event
{{EventName}}Handler.processEvent(event);
} catch (Exception e) {
// Log error but don't throw - allow other events to process
System.debug(LoggingLevel.ERROR,
'Event processing error: ' + e.getMessage() +
' ReplayId: ' + event.ReplayId);
}
}
}
High-Volume Subscriber (with Resume Checkpoint)
trigger {{EventName}}Subscriber on {{EventName}}__e (after insert) {
String lastReplayId = '';
for ({{EventName}}__e event : Trigger.new) {
lastReplayId = event.ReplayId;
try {
{{EventName}}Handler.processEvent(event);
} catch (Exception e) {
System.debug(LoggingLevel.ERROR,
'Event processing error: ' + e.getMessage() +
' ReplayId: ' + event.ReplayId);
}
}
// Set resume checkpoint for high-volume events
// Allows resuming from this point if subscriber fails
EventBus.TriggerContext.currentContext().setResumeCheckpoint(lastReplayId);
}
Event Handler Class
public with sharing class {{EventName}}Handler {
public static void processEvent({{EventName}}__e event) {
// Extract event data
String recordId = event.RecordId__c;
String status = event.Status__c;
DateTime timestamp = event.Timestamp__c;
System.debug('Processing event - RecordId: ' + recordId +
', Status: ' + status +
', ReplayId: ' + event.ReplayId);
// Business logic
updateRelatedRecords(recordId, status);
syncToExternalSystem(recordId, status);
}
private static void updateRelatedRecords(String recordId, String status) {
// Update related records based on event
List<Task> tasks = [
SELECT Id, Status
FROM Task
WHERE WhatId = :recordId
WITH USER_MODE
];
for (Task t : tasks) {
t.Status = status;
}
update as user tasks;
}
private static void syncToExternalSystem(String recordId, String status) {
// Queue async callout
Map<String, Object> payload = new Map<String, Object>{
'recordId' => recordId,
'status' => status
};
System.enqueueJob(new ExternalSyncQueueable(payload));
}
}
<a id="high-volume-vs-standard-volume-events"></a>
High-Volume vs Standard-Volume Events
| Feature | Standard-Volume | High-Volume |
|---|---|---|
| Throughput | ~2,000 events/hour | Millions/day |
| Delivery | Exactly-once | At-least-once (may deliver duplicates) |
| Retention | 3 days (72 hours) | 24 hours |
| Replay | ReplayId from last 3 days | ReplayId from last 24 hours |
| Use Case | Low-volume integrations, workflows | IoT, real-time analytics, high-traffic |
| Cost | Included in platform | Additional licensing |
When to Use High-Volume Events
- IoT Data: Sensor data, device telemetry
- Real-Time Analytics: Clickstream, user behavior tracking
- High-Traffic Systems: E-commerce order processing, stock updates
- Event Sourcing: Append-only event logs
When to Use Standard-Volume Events
- Business Workflows: Order status updates, approval processes
- Integration Events: Sync to external CRM, ERP systems
- Notifications: Email triggers, Slack notifications
- Audit Trails: Record-level change notifications
Change Data Capture (CDC)
Change Data Capture publishes change events whenever records are created, updated, deleted, or undeleted in Salesforce. CDC events are published automatically—no custom code needed.
CDC Enablement
Enable via Setup UI
- Navigate to Setup → Integrations → Change Data Capture
- Select objects to enable (Standard or Custom)
- Save
Enable via Metadata API
File: force-app/main/default/changeDataCaptures/AccountChangeEvent.cdc-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<ChangeDataCapture xmlns="http://soap.sforce.com/2006/04/metadata">
<entityName>Account</entityName>
<isEnabled>true</isEnabled>
</ChangeDataCapture>
Channel Naming Convention
CDC channels follow the pattern: {{ObjectAPIName}}ChangeEvent
Examples:
AccountChangeEvent(Standard object)Order__ChangeEvent(Custom object)OpportunityChangeEventContact_Request__ChangeEvent
CDC Subscriber Trigger
Template: assets/cdc/cdc-subscriber-trigger.trigger
Basic CDC Subscriber
trigger {{ObjectName}}CDCSubscriber on {{ObjectName}}ChangeEvent (after insert) {
for ({{ObjectName}}ChangeEvent event : Trigger.new) {
// Get change event header
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
String changeType = header.getChangeType();
List<String> changedFields = header.getChangedFields();
String recordId = header.getRecordIds()[0]; // First record ID
System.debug('CDC Event - Type: ' + changeType +
', RecordId: ' + recordId +
', Changed Fields: ' + changedFields);
// Route based on change type
switch on changeType {
when 'CREATE' {
// Handle new record
{{ObjectName}}CDCHandler.handleCreate(event);
}
when 'UPDATE' {
// Handle update
{{ObjectName}}CDCHandler.handleUpdate(event, changedFields);
}
when 'DELETE' {
// Handle delete
{{ObjectName}}CDCHandler.handleDelete(recordId);
}
when 'UNDELETE' {
// Handle undelete
{{ObjectName}}CDCHandler.handleUndelete(event);
}
}
}
}
ChangeEventHeader Fields
| Field | Type | Description |
|---|---|---|
getChangeType() |
String | CREATE, UPDATE, DELETE, UNDELETE |
getRecordIds() |
List<String> | Record IDs affected (usually 1, up to 5 for related changes) |
getChangedFields() |
List<String> | Field API names that changed (UPDATE only) |
getCommitTimestamp() |
Long | Transaction commit timestamp |
getCommitUser() |
String | User ID who made the change |
getCommitNumber() |
Long | Monotonically increasing commit number |
getEntityName() |
String | Object API name |
CDC Handler Service
Template: assets/cdc/cdc-handler.cls
public with sharing class {{ObjectName}}CDCHandler {
public static void handleCreate({{ObjectName}}ChangeEvent event) {
// Sync to external system on create
Map<String, Object> payload = buildPayload(event);
System.enqueueJob(new ExternalSystemSyncQueueable(payload, 'CREATE'));
}
public static void handleUpdate({{ObjectName}}ChangeEvent event, List<String> changedFields) {
// Only sync if relevant fields changed
Set<String> fieldsToWatch = new Set<String>{'Name', 'Status__c', 'Amount__c'};
Boolean relevantChange = false;
for (String field : changedFields) {
if (fieldsToWatch.contains(field)) {
relevantChange = true;
break;
}
}
if (relevantChange) {
Map<String, Object> payload = buildPayload(event);
payload.put('changedFields', changedFields);
System.enqueueJob(new ExternalSystemSyncQueueable(payload, 'UPDATE'));
}
}
public static void handleDelete(String recordId) {
Map<String, Object> payload = new Map<String, Object>{'recordId' => recordId};
System.enqueueJob(new ExternalSystemSyncQueueable(payload, 'DELETE'));
}
public static void handleUndelete({{ObjectName}}ChangeEvent event) {
handleCreate(event); // Treat undelete like create
}
private static Map<String, Object> buildPayload({{ObjectName}}ChangeEvent event) {
return new Map<String, Object>{
'recordId' => event.ChangeEventHeader.getRecordIds()[0],
'commitTimestamp' => event.ChangeEventHeader.getCommitTimestamp(),
'commitUser' => event.ChangeEventHeader.getCommitUser(),
// Add event field values
'name' => event.Name,
'status' => event.Status__c
// Add more fields
};
}
}
<a id="field-specific-change-detection"></a>
Field-Specific Change Detection
Filtering by Changed Fields
public static void handleUpdate(AccountChangeEvent event, List<String> changedFields) {
// Only process if billing address changed
Set<String> billingFields = new Set<String>{
'BillingStreet',
'BillingCity',
'BillingState',
'BillingPostalCode',
'BillingCountry'
};
Boolean billingChanged = false;
for (String field : changedFields) {
if (billingFields.contains(field)) {
billingChanged = true;
break;
}
}
if (billingChanged) {
updateShippingPartner(event);
}
}
Multi-Field Change Logic
public static void handleUpdate(OpportunityChangeEvent event, List<String> changedFields) {
Set<String> changedFieldSet = new Set<String>(changedFields);
// Check if stage AND amount both changed
if (changedFieldSet.contains('StageName') && changedFieldSet.contains('Amount')) {
// Alert sales ops about significant deal change
sendAlert('Deal stage and amount changed', event);
}
// Check if close date moved backward
if (changedFieldSet.contains('CloseDate')) {
checkCloseDateRegression(event);
}
}
CDC vs Platform Events: When to Use Which
| Use Case | Platform Events | Change Data Capture |
|---|---|---|
| Custom business events | Preferred | Not applicable |
| Record change notifications | Requires custom trigger | Automatic (no code) |
| External system sync | Both work | CDC (lower maintenance) |
| Custom event fields | Fully customizable | Limited to object fields |
| Event filtering | Filter in publisher code | Filter in subscriber code |
| Performance overhead | Manual event creation | Automatic (minimal overhead) |
Decision Matrix
┌───────────────────────────────────────────────────────────────────────┐
│ WHEN TO USE PLATFORM EVENTS vs CHANGE DATA CAPTURE │
├───────────────────────────────────────────────────────────────────────┤
│ Use PLATFORM EVENTS when: │
│ • Custom business event (not tied to record changes) │
│ • Event needs custom fields not on object │
│ • Need to batch/aggregate data before publishing │
│ • Publishing from external system to Salesforce │
│ • Complex event logic (multi-object aggregation) │
│ │
│ Use CHANGE DATA CAPTURE when: │
│ • Syncing record changes to external system │
│ • Audit trail of all record modifications │
│ • Real-time replication to data warehouse │
│ • Event sourcing from Salesforce objects │
│ • Zero-code event publishing required │
└───────────────────────────────────────────────────────────────────────┘
Advanced Patterns
Combining CDC with Callouts
public with sharing class AccountCDCHandler {
public static void handleUpdate(AccountChangeEvent event, List<String> changedFields) {
// Extract data
String recordId = event.ChangeEventHeader.getRecordIds()[0];
String accountName = event.Name;
// Queue async callout to external CRM
Map<String, Object> payload = new Map<String, Object>{
'salesforceId' => recordId,
'name' => accountName,
'changedFields' => changedFields,
'timestamp' => event.ChangeEventHeader.getCommitTimestamp()
};
System.enqueueJob(new CRMSyncQueueable(payload));
}
}
Event Replay with Stored ReplayId
public with sharing class EventReplayService {
@future(callout=true)
public static void replayFromLastCheckpoint(String eventChannel) {
// Get last stored replay ID
Event_Checkpoint__c checkpoint = [
SELECT ReplayId__c
FROM Event_Checkpoint__c
WHERE Channel__c = :eventChannel
LIMIT 1
];
if (checkpoint != null) {
// Use stored replay ID to resume from last successful event
// Note: Replay is typically done via API/streaming API, not Apex
System.debug('Last replay ID: ' + checkpoint.ReplayId__c);
}
}
public static void storeCheckpoint(String channel, String replayId) {
Event_Checkpoint__c checkpoint = new Event_Checkpoint__c(
Channel__c = channel,
ReplayId__c = replayId,
Last_Updated__c = DateTime.now()
);
upsert checkpoint Channel__c;
}
}
Error Handling with Dead Letter Queue
trigger OrderEventSubscriber on Order_Status__e (after insert) {
for (Order_Status__e event : Trigger.new) {
try {
OrderEventHandler.processEvent(event);
} catch (Exception e) {
// Log to dead letter queue for manual review
Event_Error_Log__c errorLog = new Event_Error_Log__c(
Event_Type__c = 'Order_Status__e',
Replay_Id__c = event.ReplayId,
Error_Message__c = e.getMessage(),
Event_Payload__c = JSON.serialize(event),
Occurred_At__c = DateTime.now()
);
insert as user errorLog;
}
}
}
Best Practices
Platform Events
- Batch Publishing: Publish events in batches (up to 2,000 per transaction)
- Idempotent Subscribers: Design subscribers to handle duplicate events (especially for high-volume)
- ReplayId Tracking: Store ReplayIds for resume capability
- Error Isolation: Catch exceptions in subscriber loops to process remaining events
- Resume Checkpoints: Use
setResumeCheckpoint()for high-volume events
Change Data Capture
- Field Filtering: Only process relevant field changes to reduce processing overhead
- Async Processing: Use Queueable/Future for callouts or long-running operations
- ChangeType Routing: Use switch statements for different change types
- RecordIds Array: Handle multiple RecordIds (CDC can batch related changes)
- Commit Metadata: Use
getCommitTimestamp()andgetCommitUser()for audit trails
Governor Limits
| Limit | Value | Notes |
|---|---|---|
| Platform Events published/transaction | 2,000 | Both Standard and High-Volume |
| Platform Event delivery | Asynchronous | Delivered to subscribers after commit |
| CDC events/hour (per object) | 250,000 | Auto-throttled if exceeded |
| Event message size | 1 MB | Total size of all fields |
| Event retention (Standard) | 3 days | ReplayId available for 72 hours |
| Event retention (High-Volume) | 24 hours | ReplayId available for 24 hours |
Testing Event-Driven Integrations
Platform Event Test
@isTest
private class OrderEventTest {
@isTest
static void testEventPublish() {
Test.startTest();
Order_Status__e event = new Order_Status__e(
RecordId__c = '006xx000000XXXAAA',
Status__c = 'Completed'
);
Database.SaveResult sr = EventBus.publish(event);
Test.stopTest();
System.assert(sr.isSuccess(), 'Event should publish successfully');
}
@isTest
static void testEventSubscriber() {
// Subscriber triggers execute synchronously in tests
Test.startTest();
Order_Status__e event = new Order_Status__e(
RecordId__c = '006xx000000XXXAAA',
Status__c = 'Completed'
);
EventBus.publish(event);
Test.stopTest();
// Verify subscriber logic executed
// (check that handler updated related records)
}
}
CDC Test
@isTest
private class AccountCDCTest {
@isTest
static void testAccountUpdate() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.startTest();
acc.BillingCity = 'San Francisco';
update acc;
Test.stopTest();
// CDC events don't fire in test context
// Must test handler methods directly
AccountChangeEvent mockEvent = new AccountChangeEvent();
// Note: Can't instantiate ChangeEvent in Apex
// Test handler logic with mock data instead
}
}
Pub/Sub API (Recommended for External Consumers)
The Pub/Sub API is the recommended mechanism for external systems subscribing to Platform Events and CDC events. It replaces the legacy Streaming API (CometD).
Why Pub/Sub API
| Feature | Pub/Sub API | Legacy Streaming API |
|---|---|---|
| Protocol | gRPC (binary, high performance) | CometD (long-polling, HTTP overhead) |
| Authentication | OAuth 2.0 | Session-based |
| Event Types | Platform Events, CDC, Custom Channels | PushTopic, Generic Events |
| Status | Current | Deprecated — no new investments |
Subscription Modes
- Subscribe: Stream events from a given replay ID forward
- PublishStream: Bi-directional — publish events via gRPC
- ManagedSubscribe: Salesforce manages replay state (simplest)
LWC Internal Subscription
For Lightning Web Components, use the empApi module:
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
connectedCallback() {
subscribe('/event/Order_Status__e', -1, (response) => {
this.handleEvent(response.data.payload);
}).then((sub) => { this.subscription = sub; });
}
disconnectedCallback() {
unsubscribe(this.subscription);
}
Note:
empApiuses CometD internally but is the supported LWC API. For external consumers, always use the gRPC-based Pub/Sub API.
Platform Event Anti-Patterns
1. Publishing from Trigger on Same Event Object → Infinite Loop
// ❌ WRONG: Trigger on Order_Status__e publishes Order_Status__e
trigger OrderStatusSubscriber on Order_Status__e (after insert) {
for (Order_Status__e event : Trigger.new) {
// This creates an infinite loop!
EventBus.publish(new Order_Status__e(Status__c = 'Processed'));
}
}
Fix: Never publish the same event type from its own subscriber trigger. Use a different event type or update a record instead.
2. PublishImmediately When Data Integrity Matters
// ❌ WRONG: Event fires even if the transaction rolls back
Order_Status__e event = new Order_Status__e();
event.Status__c = 'Completed';
// publishBehavior = PublishImmediately in event definition
EventBus.publish(event);
// If subsequent DML fails, the event was already published
// External system thinks order is "Completed" but it's not
Fix: Use PublishAfterCommit (the default) when the event represents a state change that depends on the transaction succeeding.
3. Using Platform Events for Synchronous-Style Flow Orchestration
// ❌ WRONG: Using events to simulate synchronous request/response
Flow A → Publish "Request" Event → Subscriber triggers Flow B → Publish "Response" Event → ???
Fix: Platform Events are asynchronous and unordered. For synchronous orchestration, use Subflows, @InvocableMethod, or direct Apex calls. Events are for decoupled, fire-and-forget communication.
4. Oversized Event Payloads
1 MB message size limit. Balance payload size — smaller = faster delivery, larger = fewer API calls. Include record IDs and essential context; let consumers query Salesforce for full records if needed.
Related Resources
- Callout Patterns - REST and SOAP callout implementations
- Event-Driven Architecture Guide - EDA patterns, Pub/Sub API deep dive, monitoring
- Main Skill Documentation - sf-integration overview
- Platform Event Templates - Event definitions and triggers
- CDC Templates - Change Data Capture triggers
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->External Services Guide
Overview
External Services in Salesforce automatically generate Apex classes from OpenAPI (Swagger) specifications, enabling type-safe REST API integrations without writing HTTP code.
How It Works
┌─────────────────────────────────────────────────────────────────┐
│ EXTERNAL SERVICE FLOW │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. OpenAPI Spec (JSON/YAML) │
│ ↓ │
│ 2. External Service Registration (Metadata) │
│ ↓ │
│ 3. Auto-generated Apex Classes │
│ ↓ │
│ 4. Type-safe API calls from Apex │
│ │
└─────────────────────────────────────────────────────────────────┘
Prerequisites
- Named Credential configured for authentication
- OpenAPI Specification (2.0 or 3.0) for the API
- API Version 48.0+ (Winter '20)
Creating External Service
Via Setup UI
- Go to Setup → External Services
- Click New External Service
- Provide name and description
- Select Named Credential
- Upload or paste OpenAPI spec
- Review operations
- Save
Via Metadata API
<?xml version="1.0" encoding="UTF-8"?>
<ExternalServiceRegistration xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Stripe API</label>
<description>Stripe payment processing API</description>
<namedCredential>Stripe_API</namedCredential>
<schemaType>OpenApi3</schemaType>
<schema>
{
"openapi": "3.0.0",
"info": { "title": "Stripe API", "version": "1.0" },
"paths": { ... }
}
</schema>
<status>Complete</status>
</ExternalServiceRegistration>
Generated Classes
For an External Service named "StripeAPI":
| Class | Purpose |
|---|---|
ExternalService.StripeAPI |
Main service class with operation methods |
ExternalService.StripeAPI_createCustomer_Request |
Request wrapper |
ExternalService.StripeAPI_createCustomer_Response |
Response wrapper |
ExternalService.StripeAPI_Customer |
DTO matching schema |
Usage Patterns
Basic GET Request
// Instantiate service
ExternalService.StripeAPI stripe = new ExternalService.StripeAPI();
// Call GET operation
ExternalService.StripeAPI_getCustomer_Response response =
stripe.getCustomer('cus_ABC123');
// Access response data
String email = response.email;
POST with Request Body
// Create request object
ExternalService.StripeAPI_createCustomer_Request request =
new ExternalService.StripeAPI_createCustomer_Request();
request.email = 'customer@example.com';
request.name = 'John Doe';
// Make call
ExternalService.StripeAPI_createCustomer_Response response =
stripe.createCustomer(request);
// Get created resource ID
String customerId = response.id;
Handling Nested Objects
// Access nested data
ExternalService.StripeAPI_Address address = response.address;
String city = address.city;
String postalCode = address.postalCode;
Error Handling
try {
ExternalService.StripeAPI stripe = new ExternalService.StripeAPI();
response = stripe.getCustomer('invalid_id');
} catch (ExternalService.ExternalServiceException e) {
// API returned error response
System.debug('Status Code: ' + e.getStatusCode());
System.debug('Error Body: ' + e.getBody());
System.debug('Error Message: ' + e.getMessage());
} catch (CalloutException e) {
// Network/connection error
System.debug('Connection failed: ' + e.getMessage());
}
Async Calls (Queueable)
Use Queueable for calls from triggers:
public class StripeCustomerSync implements Queueable, Database.AllowsCallouts {
private Account account;
public StripeCustomerSync(Account account) {
this.account = account;
}
public void execute(QueueableContext context) {
ExternalService.StripeAPI stripe = new ExternalService.StripeAPI();
ExternalService.StripeAPI_createCustomer_Request req =
new ExternalService.StripeAPI_createCustomer_Request();
req.email = account.Email__c;
req.name = account.Name;
try {
ExternalService.StripeAPI_createCustomer_Response resp =
stripe.createCustomer(req);
account.Stripe_Customer_Id__c = resp.id;
update account;
} catch (Exception e) {
System.debug('Sync failed: ' + e.getMessage());
}
}
}
OpenAPI Schema Tips
Supported Features
- GET, POST, PUT, PATCH, DELETE methods
- Path and query parameters
- Request and response bodies
- JSON schema types (string, number, boolean, object, array)
- References ($ref)
- Basic authentication headers
Limitations
- No file uploads (multipart/form-data limited)
- No WebSockets (HTTP only)
- No streaming responses
- Some complex schemas may not parse
- Maximum schema size limited
Schema Best Practices
{
"openapi": "3.0.0",
"info": {
"title": "My API",
"version": "1.0.0"
},
"paths": {
"/customers/{id}": {
"get": {
"operationId": "getCustomer",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": { "type": "string" }
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/Customer" }
}
}
}
}
}
}
},
"components": {
"schemas": {
"Customer": {
"type": "object",
"properties": {
"id": { "type": "string" },
"email": { "type": "string" }
}
}
}
}
}
Updating External Service
When API changes:
- Get updated OpenAPI spec
- Go to Setup → External Services
- Edit service
- Upload new schema
- Review changes to operations
- Save and validate
- Update calling code if signatures changed
Testing
@isTest
private class StripeIntegrationTest {
@isTest
static void testCreateCustomer() {
// Set mock
Test.setMock(HttpCalloutMock.class, new StripeMock());
Test.startTest();
ExternalService.StripeAPI stripe = new ExternalService.StripeAPI();
ExternalService.StripeAPI_createCustomer_Request req =
new ExternalService.StripeAPI_createCustomer_Request();
req.email = 'test@example.com';
ExternalService.StripeAPI_createCustomer_Response resp =
stripe.createCustomer(req);
Test.stopTest();
System.assertEquals('cus_test123', resp.id);
}
private class StripeMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest request) {
HttpResponse response = new HttpResponse();
response.setStatusCode(201);
response.setBody('{"id": "cus_test123", "email": "test@example.com"}');
return response;
}
}
}
Use with Agentforce
External Services are ideal for Agent Actions:
- Create External Service from API spec
- Create Flow that calls External Service
- Reference Flow in Agent Script action
actions:
lookup_customer:
description: "Looks up customer in payment system"
inputs:
customer_email: string
outputs:
customer_id: string
target: "flow://Lookup_Stripe_Customer"
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Messaging API v2 Guide (MIAW)
This guide covers building custom clients for Messaging for In-App and Web (MIAW), enabling Agentforce and Service Cloud conversations outside of Salesforce.
Overview
┌─────────────────────────────────────────────────────────────────────────┐
│ MIAW CUSTOM CLIENT ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Custom │ REST API v2 │ Salesforce │ │
│ │ Client │◀────────────────────────────▶│ MIAW / Agent │ │
│ │ (React/Vue) │ /iamessage/api/v2/* │ Service Cloud │ │
│ └──────────────┘ └──────────────────────┘ │
│ │
│ Endpoints: │
│ • POST /authorization JWT token exchange │
│ • POST /conversation Start conversation │
│ • POST /conversation/{id}/message Send message │
│ • GET /conversation/{id}/messages Poll for messages (or SSE) │
│ • POST /conversation/{id}/end End conversation │
│ │
│ Use Cases: │
│ • Custom chat widgets on external websites │
│ • Mobile app integrations │
│ • Kiosk / in-store experiences │
│ • Third-party platform integrations │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Prerequisites
Salesforce Setup
- Messaging for In-App and Web license
- Embedded Service Deployment created
- Agentforce or Omni-Channel routing configured
- Connected App for JWT authentication
Embedded Service Deployment
Setup → Embedded Service Deployments → New Deployment
├─ Type: Messaging for In-App and Web
├─ Channel: Web
└─ API Name: Your_Deployment_API_Name
Get the Deployment ID and Organization ID from the deployment settings.
Authentication
JWT Token Exchange
MIAW uses JWT bearer tokens for API authentication.
// Server-side token generation (Node.js example)
import jwt from 'jsonwebtoken';
import fetch from 'node-fetch';
async function getAccessToken(orgId, deploymentId, privateKey) {
// CRITICAL: OrgId must be 15-character format for JWT
const orgId15 = orgId.substring(0, 15);
const payload = {
iss: 'YOUR_CONNECTED_APP_CLIENT_ID',
sub: `${orgId15}`, // 15-char org ID
aud: 'https://login.salesforce.com',
exp: Math.floor(Date.now() / 1000) + 300, // 5 min expiry
iat: Math.floor(Date.now() / 1000)
};
const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' });
// Exchange JWT for access token
const response = await fetch(
'https://login.salesforce.com/services/oauth2/token',
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token
})
}
);
const data = await response.json();
return data.access_token;
}
Authorization Endpoint
Exchange access token for MIAW-specific authorization:
async function getMessagingAuth(accessToken, orgDomain, deploymentId) {
const response = await fetch(
`https://${orgDomain}/iamessage/api/v2/authorization`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
orgId: 'YOUR_ORG_ID',
esDeveloperName: deploymentId,
capabilitiesVersion: '1',
platform: 'Web'
})
}
);
return await response.json();
// Returns: { accessToken, context, ... }
}
Conversation Lifecycle
Start Conversation
async function startConversation(messagingAuth, customerName) {
const { accessToken, context } = messagingAuth;
const response = await fetch(
`https://${context.url}/iamessage/api/v2/conversation`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
esDeveloperName: context.esDeveloperName,
routingAttributes: {
// Optional: Pre-chat fields
customerName: customerName
},
// Optional: Context for agent
contextParameters: {
recordId: '001xx000003ABC',
caseReason: 'Technical Support'
}
})
}
);
const data = await response.json();
return data.conversationId;
}
Send Message
async function sendMessage(messagingAuth, conversationId, text) {
const { accessToken, context } = messagingAuth;
const response = await fetch(
`https://${context.url}/iamessage/api/v2/conversation/${conversationId}/message`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: {
messageType: 'StaticContentMessage',
staticContent: {
formatType: 'Text',
text: text
}
}
})
}
);
return await response.json();
}
Receive Messages
Option 1: Server-Sent Events (SSE)
SSE provides real-time streaming but may not work on serverless platforms.
function subscribeToMessages(messagingAuth, conversationId, onMessage) {
const { accessToken, context } = messagingAuth;
const eventSource = new EventSource(
`https://${context.url}/iamessage/api/v2/conversation/${conversationId}/messages?stream=true`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);
eventSource.onmessage = (event) => {
const message = JSON.parse(event.data);
onMessage(message);
};
eventSource.onerror = (error) => {
console.error('SSE error:', error);
// Fallback to polling
};
return eventSource;
}
Option 2: Polling (Serverless Compatible)
For Vercel, AWS Lambda, or other serverless environments:
class MessagePoller {
constructor(messagingAuth, conversationId, onMessage) {
this.messagingAuth = messagingAuth;
this.conversationId = conversationId;
this.onMessage = onMessage;
this.lastMessageId = null;
this.seenMessageIds = new Set();
this.intervalId = null;
}
start(intervalMs = 2000) {
this.intervalId = setInterval(() => this.poll(), intervalMs);
this.poll(); // Immediate first poll
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
async poll() {
const { accessToken, context } = this.messagingAuth;
try {
const url = new URL(
`https://${context.url}/iamessage/api/v2/conversation/${this.conversationId}/messages`
);
if (this.lastMessageId) {
url.searchParams.set('after', this.lastMessageId);
}
const response = await fetch(url, {
headers: { 'Authorization': `Bearer ${accessToken}` }
});
const data = await response.json();
for (const message of data.messages || []) {
// CRITICAL: Deduplicate messages
if (!this.seenMessageIds.has(message.id)) {
this.seenMessageIds.add(message.id);
this.lastMessageId = message.id;
this.onMessage(message);
}
}
} catch (error) {
console.error('Poll error:', error);
}
}
}
End Conversation
async function endConversation(messagingAuth, conversationId) {
const { accessToken, context } = messagingAuth;
await fetch(
`https://${context.url}/iamessage/api/v2/conversation/${conversationId}/end`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
}
);
}
Message Types
Incoming Message Structure
{
"id": "msg_abc123",
"conversationId": "conv_xyz789",
"messageType": "StaticContentMessage",
"sender": {
"role": "Agent", // or "EndUser", "Chatbot"
"displayName": "Service Agent"
},
"staticContent": {
"formatType": "Text",
"text": "Hello! How can I help you today?"
},
"timestamp": "2026-01-15T10:30:00.000Z"
}
Rich Message Types
| Type | Use Case |
|---|---|
StaticContentMessage |
Plain text |
RichLinkMessage |
Clickable cards with images |
ListPickerMessage |
Selection lists |
QuickReplyMessage |
Suggested responses |
AttachmentMessage |
File attachments |
Handling Rich Messages
function renderMessage(message) {
switch (message.messageType) {
case 'StaticContentMessage':
return renderText(message.staticContent.text);
case 'QuickReplyMessage':
return renderQuickReplies(message.quickReplies);
case 'ListPickerMessage':
return renderListPicker(message.listPicker);
case 'RichLinkMessage':
return renderRichLink(message.richLink);
default:
console.warn('Unknown message type:', message.messageType);
return null;
}
}
function renderQuickReplies(quickReplies) {
return quickReplies.replies.map(reply => ({
label: reply.title,
value: reply.itemId,
onClick: () => sendQuickReplySelection(reply.itemId)
}));
}
React Integration Example
// ChatWidget.jsx
import { useState, useEffect, useRef } from 'react';
export function ChatWidget({ orgDomain, deploymentId }) {
const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState('');
const [conversationId, setConversationId] = useState(null);
const [isConnecting, setIsConnecting] = useState(false);
const pollerRef = useRef(null);
const authRef = useRef(null);
// Initialize conversation
const startChat = async () => {
setIsConnecting(true);
try {
// Get auth from your backend
const authResponse = await fetch('/api/messaging/auth', {
method: 'POST',
body: JSON.stringify({ deploymentId })
});
authRef.current = await authResponse.json();
// Start conversation
const convId = await startConversation(authRef.current, 'Web User');
setConversationId(convId);
// Start polling for messages
pollerRef.current = new MessagePoller(
authRef.current,
convId,
handleNewMessage
);
pollerRef.current.start();
} catch (error) {
console.error('Failed to start chat:', error);
} finally {
setIsConnecting(false);
}
};
const handleNewMessage = (message) => {
setMessages(prev => [...prev, message]);
};
const handleSend = async () => {
if (!inputText.trim() || !conversationId) return;
// Optimistic update
const localMessage = {
id: `local_${Date.now()}`,
sender: { role: 'EndUser' },
staticContent: { text: inputText },
timestamp: new Date().toISOString()
};
setMessages(prev => [...prev, localMessage]);
setInputText('');
// Send to server
await sendMessage(authRef.current, conversationId, inputText);
};
// Cleanup
useEffect(() => {
return () => {
if (pollerRef.current) {
pollerRef.current.stop();
}
};
}, []);
return (
<div className="chat-widget">
{!conversationId ? (
<button onClick={startChat} disabled={isConnecting}>
{isConnecting ? 'Connecting...' : 'Start Chat'}
</button>
) : (
<>
<div className="messages">
{messages.map(msg => (
<MessageBubble key={msg.id} message={msg} />
))}
</div>
<input
value={inputText}
onChange={(e) => setInputText(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
placeholder="Type a message..."
/>
<button onClick={handleSend}>Send</button>
</>
)}
</div>
);
}
Common Gotchas
1. OrgId Format
// ❌ WRONG: Using 18-character OrgId in JWT
const orgId = '00D5g000004ABCDEFGH'; // 18 chars
// ✅ CORRECT: Use 15-character format for JWT
const orgId15 = orgId.substring(0, 15); // '00D5g000004ABCD'
2. Message Deduplication
Polling can return the same messages multiple times:
// ❌ WRONG: No deduplication
messages.forEach(msg => onMessage(msg));
// ✅ CORRECT: Track seen message IDs
if (!this.seenMessageIds.has(message.id)) {
this.seenMessageIds.add(message.id);
onMessage(message);
}
3. SSE on Serverless
SSE connections won't work on serverless platforms:
// ❌ WRONG: SSE on Vercel/Netlify Functions
const eventSource = new EventSource(url); // Connection dies immediately
// ✅ CORRECT: Use polling fallback
const poller = new MessagePoller(auth, convId, onMessage);
poller.start(2000);
4. Token Refresh
Access tokens expire; implement refresh logic:
class MessagingClient {
constructor() {
this.auth = null;
this.tokenExpiry = null;
}
async ensureValidToken() {
const now = Date.now();
const buffer = 60000; // 1 minute buffer
if (!this.auth || now >= this.tokenExpiry - buffer) {
this.auth = await this.refreshAuth();
this.tokenExpiry = now + (this.auth.expiresIn * 1000);
}
return this.auth;
}
async sendMessage(conversationId, text) {
const auth = await this.ensureValidToken();
// ... send with valid token
}
}
Security Best Practices
| Practice | Implementation |
|---|---|
| Never expose private keys | Keep JWT signing server-side only |
| Use short-lived tokens | 5-15 minute expiry for JWTs |
| Validate conversation ownership | Server tracks user → conversation mapping |
| Rate limit messages | Prevent spam/abuse |
| Sanitize message content | XSS prevention on display |
Deployment Platforms
Vercel
// api/messaging/auth.js
export default async function handler(req, res) {
// Server-side auth - never expose keys to client
const auth = await getMessagingAuth(
process.env.SF_ACCESS_TOKEN,
process.env.SF_ORG_DOMAIN,
req.body.deploymentId
);
res.json(auth);
}
AWS Lambda
// handler.js
exports.startConversation = async (event) => {
const { deploymentId, customerName } = JSON.parse(event.body);
const auth = await getMessagingAuth(/* ... */);
const conversationId = await startConversation(auth, customerName);
return {
statusCode: 200,
body: JSON.stringify({ conversationId })
};
};
Cross-Skill References
| Topic | Resource |
|---|---|
| Connected Apps setup | sf-connected-apps skill |
| Named Credentials | named-credentials-guide.md |
| Agentforce agents | sf-ai-agentforce skill |
| Platform Events | platform-events-guide.md |
| REST callout patterns | rest-callout-patterns.md |
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Named Credentials Automation Guide
This guide explains how to automate Named Credential configuration using the sf-integration helper scripts.
Key Insight: Enhanced Named Credentials (API 60+) can be configured programmatically using
ConnectApi.NamedCredentials- no UI required!
Overview
Enhanced Named Credentials = External Credential + Named Credential + Endpoint Security
External Credential (stores the API key securely)
↓
Named Credential (references the External Credential)
↓
Your HTTP Callout (uses callout:NamedCredentialName)
Why Enhanced Named Credentials?
| Benefit | Description |
|---|---|
| Security | AES-256 encryption by Salesforce platform |
| Flexibility | Supports Custom, Basic, OAuth, JWT protocols |
| Portability | Easier to manage across multiple orgs |
| Automation | Configurable via ConnectApi (no UI required) |
| Compliance | Passes PCI-DSS, SOC 2 audits |
Deployment Order
CRITICAL: Deploy components in this exact order:
# 1. Deploy External Credential (defines the credential structure)
sf project deploy start \
--source-dir force-app/main/default/externalCredentials/YourAPI.externalCredential-meta.xml \
--target-org YourOrg
# 2. Deploy Named Credential (references the External Credential)
sf project deploy start \
--source-dir force-app/main/default/namedCredentials/YourAPI.namedCredential-meta.xml \
--target-org YourOrg
# 3. Deploy endpoint security (allows outbound HTTP calls)
sf project deploy start \
--source-dir force-app/main/default/cspTrustedSites/YourAPI.cspTrustedSite-meta.xml \
--target-org YourOrg
# 4. Set the API key using our automation script
./scripts/configure-named-credential.sh YourOrg
Automation Scripts
configure-named-credential.sh
Purpose: Sets API keys for Enhanced Named Credentials using ConnectApi
Usage:
./scripts/configure-named-credential.sh <org-alias>
What it does:
- Validates org connection via
sf org display - Checks External Credential exists via SOQL
- Prompts for API key securely (input hidden)
- Generates Apex using
ConnectApi.NamedCredentials.createCredential() - Handles create vs. patch automatically
Under the hood:
ConnectApi.CredentialInput creds = new ConnectApi.CredentialInput();
creds.externalCredential = 'YourExternalCredential';
creds.principalName = 'yourPrincipalName';
creds.authenticationProtocol = ConnectApi.CredentialAuthenticationProtocol.Custom;
Map<String, ConnectApi.CredentialValueInput> params = new Map<String, ConnectApi.CredentialValueInput>();
ConnectApi.CredentialValueInput apiKey = new ConnectApi.CredentialValueInput();
apiKey.encrypted = true;
apiKey.value = 'YOUR_API_KEY';
params.put('apiKey', apiKey);
creds.credentials = params;
ConnectApi.NamedCredentials.createCredential(creds);
set-api-credential.sh
Purpose: Stores API keys in Custom Settings (legacy/dev approach)
Usage:
# Secure input (recommended)
./scripts/set-api-credential.sh <setting-name> - <org-alias>
# Direct input
./scripts/set-api-credential.sh <setting-name> <api-key> <org-alias>
When to use:
- Dev/test environments
- CI/CD pipelines (no Apex execution)
- Simple API key auth via query parameters
Not recommended for production - use Enhanced Named Credentials instead.
Complete Example: Weather API
Step 1: Create Metadata
External Credential:
<?xml version="1.0" encoding="UTF-8"?>
<ExternalCredential xmlns="http://soap.sforce.com/2006/04/metadata">
<authenticationProtocol>Custom</authenticationProtocol>
<externalCredentialParameters>
<parameterGroup>weatherAPIKey</parameterGroup>
<parameterName>weatherAPIKey</parameterName>
<parameterType>NamedPrincipal</parameterType>
<sequenceNumber>1</sequenceNumber>
</externalCredentialParameters>
<label>Weather API</label>
</ExternalCredential>
Named Credential:
<?xml version="1.0" encoding="UTF-8"?>
<NamedCredential xmlns="http://soap.sforce.com/2006/04/metadata">
<allowMergeFieldsInBody>false</allowMergeFieldsInBody>
<allowMergeFieldsInHeader>true</allowMergeFieldsInHeader>
<calloutStatus>Enabled</calloutStatus>
<label>Weather API</label>
<namedCredentialParameters>
<parameterName>Url</parameterName>
<parameterType>Url</parameterType>
<parameterValue>https://api.weather.com</parameterValue>
</namedCredentialParameters>
<namedCredentialParameters>
<externalCredential>WeatherAPI</externalCredential>
<parameterName>ExternalCredential</parameterName>
<parameterType>Authentication</parameterType>
</namedCredentialParameters>
<namedCredentialType>SecuredEndpoint</namedCredentialType>
</NamedCredential>
Step 2: Deploy and Configure
# Deploy all metadata
sf project deploy start --metadata ExternalCredential:WeatherAPI \
--metadata NamedCredential:WeatherAPI \
--metadata CspTrustedSite:WeatherAPI \
--target-org MyOrg
# Configure API key
./scripts/configure-named-credential.sh MyOrg
Step 3: Use in Apex
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:WeatherAPI/forecast?city=London');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
System.debug(res.getBody());
The API key is automatically included - no manual credential handling!
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
| "External Credential not found" | Not deployed or wrong name | Deploy first, check spelling |
| "Named Credential not found" | Not deployed | Deploy after External Credential |
| "No existing credentials to update" | Using patch instead of create | Script handles automatically |
| "Unable to connect" | Missing endpoint security | Deploy CSP Trusted Site |
Related Documentation
- named-credentials-guide.md - Template reference
- external-services-guide.md - OpenAPI integration
- security-best-practices.md - Security patterns
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Named Credentials Guide
Overview
Named Credentials provide secure storage of authentication credentials and endpoint URLs for external system integrations. They eliminate the need to hardcode credentials in Apex code.
Architecture Evolution
Legacy Named Credentials (Pre-API 61)
- Single principal per credential
- Authentication configured directly on Named Credential
- Simpler setup but less flexible
External Credentials (API 61+)
- Separate External Credential and Named Credential
- Named Principal and Per-User Principal support
- Permission Set-based access control
- More secure and flexible
┌─────────────────────────────────────────────────────────────────┐
│ CREDENTIAL ARCHITECTURE (API 61+) │
├─────────────────────────────────────────────────────────────────┤
│ │
│ External Credential │
│ ├── Authentication Protocol (OAuth, JWT, Custom) │
│ ├── OAuth/JWT Parameters │
│ └── Principals │
│ ├── Named Principal (shared service account) │
│ └── Per-User Principal (individual auth) │
│ │
│ Named Credential │
│ ├── Endpoint URL │
│ └── References External Credential │
│ │
│ Permission Set │
│ └── External Credential Principal Access │
│ │
└─────────────────────────────────────────────────────────────────┘
Authentication Types
1. OAuth 2.0 Client Credentials
Use Case: Server-to-server integration without user context
// Apex usage - Named Credential handles auth automatically
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyOAuthCredential/api/resource');
req.setMethod('GET');
// Authorization header added automatically
Setup:
- Create Auth Provider (optional, for complex OAuth)
- Create Named Credential with OAuth protocol
- Enter Client ID and Client Secret via UI
2. OAuth 2.0 JWT Bearer
Use Case: Certificate-based server-to-server auth
Prerequisites:
- Certificate in Setup → Certificate and Key Management
- Connected App configured for JWT Bearer
- External system configured to trust certificate
Flow:
- Salesforce creates JWT with claims (iss, sub, aud, exp)
- JWT signed with certificate private key
- JWT exchanged for access token
- Access token used for API calls
3. Certificate-Based (Mutual TLS)
Use Case: High-security integrations requiring client certificate
Setup:
- Obtain client certificate from CA or external system
- Import to Setup → Certificate and Key Management
- Configure Named Credential with certificate
- External system must trust Salesforce's certificate
4. Basic Auth / API Key
Use Case: Simple APIs, internal systems
Pattern for API Key:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyCredential/api/resource');
req.setHeader('X-API-Key', '{!$Credential.Password}');
Best Practices
DO
- Use Named Credentials for ALL external callouts
- Rotate credentials regularly using Named Credential update
- Use External Credentials (API 61+) for new development
- Limit OAuth scopes to minimum required
- Use Per-User Principal when user context matters
- Test credentials before deployment
DON'T
- Never hardcode credentials in Apex
- Never commit credentials to source control
- Don't share service account credentials across environments
- Don't use overly broad OAuth scopes
Common Patterns
Pattern 1: Service Integration
public class ExternalServiceCallout {
public static HttpResponse callService(String endpoint, String body) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:ServiceCredential' + endpoint);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(body);
return new Http().send(req);
}
}
Pattern 2: Multiple Environments
Named Credentials:
├── MyAPI_Dev → https://api-dev.example.com
├── MyAPI_UAT → https://api-uat.example.com
└── MyAPI_Prod → https://api.example.com
Use Custom Metadata or Custom Settings to select credential by environment.
Pattern 3: Per-User OAuth (API 61+)
For APIs requiring user-specific authentication:
- Create External Credential with Per-User Principal
- Create Named Credential referencing External Credential
- Users authenticate individually via OAuth flow
- Each user's callouts use their own token
Troubleshooting
| Error | Cause | Solution |
|---|---|---|
Named credential not found |
Credential doesn't exist or wrong name | Verify credential name in Setup |
Authentication failed |
Invalid credentials | Update credentials via Setup UI |
Insufficient privileges |
User lacks permission | Assign Permission Set with External Credential Principal Access |
Connection refused |
Network/firewall issue | Check Remote Site Settings, firewall rules |
Certificate error |
SSL/TLS issue | Verify certificate chain, expiration |
Migration: Legacy to External Credentials
- Create External Credential with same auth parameters
- Create new Named Credential referencing External Credential
- Create Permission Set with External Credential Principal Access
- Assign Permission Set to integration users
- Update Apex code to use new Named Credential
- Test thoroughly before decommissioning legacy credential
- Delete legacy Named Credential after validation
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Platform Events Guide
Overview
Platform Events enable event-driven architecture in Salesforce. They provide a scalable, asynchronous messaging system for real-time integrations.
Event Types
Standard Volume
- Up to ~2,000 events per hour
- Included in all Salesforce editions
- Standard delivery guarantees
High Volume
- Millions of events per day
- At-least-once delivery
- 24-hour retention for replay
- May require additional entitlement
When to Use Platform Events
| Scenario | Platform Events | Other Options |
|---|---|---|
| Real-time notifications | ✅ Best choice | - |
| Decoupled integrations | ✅ Best choice | - |
| High-volume streaming | ✅ High Volume | Change Data Capture |
| Simple record sync | Consider | Change Data Capture |
| External system notifications | ✅ Best choice | - |
| Internal process triggers | ✅ Good choice | Process Builder, Flow |
Creating Platform Events
Via Metadata (Recommended)
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<deploymentStatus>Deployed</deploymentStatus>
<eventType>HighVolume</eventType>
<label>Order Update Event</label>
<pluralLabel>Order Update Events</pluralLabel>
<publishBehavior>PublishAfterCommit</publishBehavior>
<fields>
<fullName>Order_Id__c</fullName>
<label>Order ID</label>
<type>Text</type>
<length>18</length>
</fields>
<fields>
<fullName>Status__c</fullName>
<label>Status</label>
<type>Text</type>
<length>50</length>
</fields>
</CustomObject>
File Location
force-app/main/default/objects/Order_Update_Event__e/Order_Update_Event__e.object-meta.xml
Publishing Events
From Apex
// Single event
Order_Update_Event__e event = new Order_Update_Event__e();
event.Order_Id__c = orderId;
event.Status__c = 'Shipped';
Database.SaveResult result = EventBus.publish(event);
if (result.isSuccess()) {
System.debug('Event published: ' + result.getId());
}
// Multiple events
List<Order_Update_Event__e> events = new List<Order_Update_Event__e>();
// ... populate events
List<Database.SaveResult> results = EventBus.publish(events);
From Flow
- Create Record element
- Select Platform Event object
- Map field values
From Process Builder
- Add Immediate Action
- Select "Create a Record"
- Choose Platform Event
Subscribing to Events
Apex Trigger
trigger OrderUpdateSubscriber on Order_Update_Event__e (after insert) {
for (Order_Update_Event__e event : Trigger.new) {
System.debug('Order ' + event.Order_Id__c + ' is now ' + event.Status__c);
// Process event
}
// Set checkpoint for durability
EventBus.TriggerContext.currentContext().setResumeCheckpoint(
Trigger.new[Trigger.new.size() - 1].ReplayId
);
}
Flow (Record-Triggered)
- Create Platform Event-Triggered Flow
- Select Platform Event object
- Build logic with event data
External (CometD)
External systems can subscribe using CometD streaming:
/event/Order_Update_Event__e
Publish Behavior
PublishAfterCommit (Default)
- Event published after transaction commits
- If transaction rolls back, event NOT published
- Recommended for most cases
PublishImmediately
- Event published immediately
- Event still published even if transaction rolls back
- Use when external system must be notified regardless of outcome
Durability & Replay
Replay ID
Each event has a unique ReplayId for tracking and replay:
String replayId = event.ReplayId;
Resume Checkpoint
Set checkpoint to ensure durability:
// In trigger
EventBus.TriggerContext.currentContext().setResumeCheckpoint(lastReplayId);
If trigger fails after checkpoint, processing resumes from that point.
Retention
- High Volume events: 24 hours
- Standard Volume: 24 hours
Best Practices
Publishing
- Batch events when publishing multiple
- Check SaveResults for publish failures
- Use meaningful correlation IDs for tracking
- Include timestamp for ordering
- Keep payloads small - use IDs, not full records
Subscribing
- Always set resume checkpoint in triggers
- Don't throw exceptions - catch and log errors
- Process idempotently - events may replay
- Keep processing lightweight - queue heavy work
- Handle duplicates using correlation ID
Design
- Event granularity - not too fine, not too coarse
- Include enough context but not entire records
- Version your events if schema evolves
- Document event contracts for consumers
Error Handling
Publish Errors
List<Database.SaveResult> results = EventBus.publish(events);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug('Publish failed: ' + err.getMessage());
}
}
}
Subscriber Errors
trigger MySubscriber on My_Event__e (after insert) {
for (My_Event__e event : Trigger.new) {
try {
processEvent(event);
} catch (Exception e) {
// Log error, don't throw
System.debug('Error processing ' + event.ReplayId + ': ' + e.getMessage());
// Create error log record
}
}
// Still set checkpoint even if some failed
EventBus.TriggerContext.currentContext().setResumeCheckpoint(lastReplayId);
}
Monitoring
Setup → Platform Events
- View event definitions
- Check usage metrics
- Monitor delivery status
Event Delivery Failures
Check for:
- Unhandled exceptions in triggers
- Apex CPU timeout
- Governor limit errors
Event Publishing
Query EventBusSubscriber for subscription health:
SELECT Id, Position, ExternalId, Name, Status, Tip
FROM EventBusSubscriber
WHERE Topic = 'Order_Update_Event__e'
Limits
| Limit | Standard Volume | High Volume |
|---|---|---|
| Events per hour | ~2,000 | Millions |
| Retention | 24 hours | 24 hours |
| Max event size | 1 MB | 1 MB |
| Fields per event | 100 | 100 |
External Integration
Subscribe from External System
Use CometD client to connect to Streaming API:
Endpoint: /cometd/62.0
Channel: /event/Order_Update_Event__e
Publish from External System
Use REST API:
POST /services/data/v66.0/sobjects/Order_Update_Event__e
Content-Type: application/json
{
"Order_Id__c": "001xx000003NGSFAA4",
"Status__c": "Shipped"
}
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->REST Callout Patterns
Overview
This guide covers patterns for making HTTP callouts from Salesforce Apex to external REST APIs.
Synchronous vs Asynchronous
When to Use Synchronous
- User needs immediate response
- Called from Visualforce, LWC, or Aura
- NOT triggered by DML operations
- Response required before next action
When to Use Asynchronous
- Called from triggers (REQUIRED)
- Fire-and-forget operations
- Background processing
- Long-running operations
┌─────────────────────────────────────────────────────────────────┐
│ CALLOUT CONTEXT DECISION │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Is this called from a trigger or after DML? │
│ ├── YES → Use Queueable with Database.AllowsCallouts │
│ └── NO → Synchronous OK │
│ │
│ Does user need immediate response? │
│ ├── YES → Synchronous (if allowed) │
│ └── NO → Consider async for better UX │
│ │
└─────────────────────────────────────────────────────────────────┘
Basic Request Pattern
public class RestCallout {
public static HttpResponse makeRequest(String method, String endpoint, String body) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyCredential' + endpoint);
req.setMethod(method);
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept', 'application/json');
req.setTimeout(120000); // 120 seconds max
if (String.isNotBlank(body)) {
req.setBody(body);
}
return new Http().send(req);
}
}
HTTP Methods
| Method | Use Case | Body |
|---|---|---|
| GET | Retrieve resource | No |
| POST | Create resource | Yes |
| PUT | Full update | Yes |
| PATCH | Partial update | Yes |
| DELETE | Remove resource | Usually No |
Response Handling
Status Code Categories
Integer statusCode = response.getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
// Success (2xx)
} else if (statusCode >= 400 && statusCode < 500) {
// Client error (4xx) - don't retry
} else if (statusCode >= 500) {
// Server error (5xx) - may retry
}
Common Status Codes
| Code | Meaning | Action |
|---|---|---|
| 200 | OK | Process response |
| 201 | Created | Resource created |
| 204 | No Content | Success, no body |
| 400 | Bad Request | Fix request |
| 401 | Unauthorized | Check credentials |
| 403 | Forbidden | Check permissions |
| 404 | Not Found | Resource doesn't exist |
| 429 | Too Many Requests | Rate limited, retry later |
| 500 | Server Error | Retry with backoff |
| 503 | Service Unavailable | Retry later |
Error Handling Pattern
public class ApiClient {
public static Map<String, Object> callApi(String endpoint) {
try {
HttpResponse res = makeRequest('GET', endpoint, null);
if (res.getStatusCode() == 200) {
return (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
}
// Handle specific errors
if (res.getStatusCode() == 404) {
throw new NotFoundException('Resource not found: ' + endpoint);
}
if (res.getStatusCode() == 429) {
String retryAfter = res.getHeader('Retry-After');
throw new RateLimitedException('Rate limited. Retry after: ' + retryAfter);
}
throw new ApiException('API Error: ' + res.getStatusCode() + ' - ' + res.getBody());
} catch (CalloutException e) {
// Network error, timeout, SSL error
throw new ApiException('Connection failed: ' + e.getMessage(), e);
}
}
public class ApiException extends Exception {}
public class NotFoundException extends Exception {}
public class RateLimitedException extends Exception {}
}
Retry Pattern
public class RetryableCallout {
private static final Integer MAX_RETRIES = 3;
private static final Set<Integer> RETRYABLE_CODES = new Set<Integer>{
408, 429, 500, 502, 503, 504
};
public static HttpResponse callWithRetry(HttpRequest request) {
Integer attempts = 0;
while (attempts < MAX_RETRIES) {
HttpResponse res = new Http().send(request);
if (!RETRYABLE_CODES.contains(res.getStatusCode())) {
return res;
}
attempts++;
System.debug('Retry ' + attempts + ' for ' + res.getStatusCode());
}
throw new CalloutException('Max retries exceeded');
}
}
Queueable Pattern (Async)
public class AsyncCallout implements Queueable, Database.AllowsCallouts {
private Id recordId;
public AsyncCallout(Id recordId) {
this.recordId = recordId;
}
public void execute(QueueableContext context) {
// Query record
Account acc = [SELECT Id, Name FROM Account WHERE Id = :recordId];
// Make callout
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyAPI/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(new Map<String, Object>{
'name' => acc.Name,
'sfId' => acc.Id
}));
HttpResponse res = new Http().send(req);
// Update record with result
if (res.getStatusCode() == 201) {
acc.External_Id__c = extractId(res.getBody());
update acc;
}
}
private String extractId(String body) {
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(body);
return (String) result.get('id');
}
}
// Usage from trigger:
// System.enqueueJob(new AsyncCallout(accountId));
Pagination Pattern
public class PaginatedApiClient {
public static List<Map<String, Object>> getAllRecords(String endpoint) {
List<Map<String, Object>> allRecords = new List<Map<String, Object>>();
String nextPageUrl = endpoint;
while (String.isNotBlank(nextPageUrl)) {
HttpResponse res = makeRequest('GET', nextPageUrl, null);
Map<String, Object> response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
// Add records from this page
List<Object> records = (List<Object>) response.get('data');
for (Object rec : records) {
allRecords.add((Map<String, Object>) rec);
}
// Get next page URL
nextPageUrl = (String) response.get('nextPage');
}
return allRecords;
}
}
Governor Limits
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Maximum timeout | 120,000 ms (120 seconds) |
| Maximum request size | 6 MB |
| Maximum response size | 6 MB |
| Concurrent long-running requests | 10 |
Testing Callouts
@isTest
private class ApiClientTest {
@isTest
static void testSuccessfulCallout() {
// Set mock
Test.setMock(HttpCalloutMock.class, new MockSuccess());
Test.startTest();
Map<String, Object> result = ApiClient.callApi('/endpoint');
Test.stopTest();
System.assertEquals('value', result.get('key'));
}
private class MockSuccess implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"key": "value"}');
return res;
}
}
}
Best Practices
- Always use Named Credentials - Never hardcode endpoints or credentials
- Set appropriate timeouts - Default may be too short for slow APIs
- Handle all error cases - Don't assume success
- Log requests and responses - Essential for debugging
- Use async for trigger contexts - Queueable with AllowsCallouts
- Implement retry logic - For transient failures
- Monitor governor limits - Especially callout count
- Parse errors gracefully - APIs return errors in various formats
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Scoring System (120 Points)
Category Breakdown
| Category | Points | Evaluation Criteria |
|---|---|---|
| Security | 30 | Named Credentials used (no hardcoded secrets), OAuth scopes minimized, certificate auth where applicable |
| Error Handling | 25 | Retry logic present, timeout handling (120s max), specific exception types, logging implemented |
| Bulkification | 20 | Batch callouts considered, CDC bulk handling, event batching for Platform Events |
| Architecture | 20 | Async patterns for DML-triggered callouts, proper service layer separation, single responsibility |
| Best Practices | 15 | Governor limit awareness, proper HTTP methods, idempotency for retries |
| Documentation | 10 | Clear intent documented, endpoint versioning noted, API contract documented |
Scoring Thresholds
| Rating | Score Range | Description |
|---|---|---|
| Excellent | 108-120 | Production-ready, follows all best practices |
| Very Good | 90-107 | Minor improvements suggested |
| Good | 72-89 | Acceptable with noted improvements |
| Needs Work | 54-71 | Address issues before deployment |
| Block | <54 | CRITICAL issues, do not deploy |
Scoring Output Format
📊 INTEGRATION SCORE: XX/120 ⭐⭐⭐⭐ Rating
════════════════════════════════════════════════════
🔐 Security XX/30 ████████░░ XX%
├─ Named Credentials used: ✅
├─ No hardcoded secrets: ✅
└─ OAuth scopes minimal: ✅
⚠️ Error Handling XX/25 ████████░░ XX%
├─ Retry logic: ✅
├─ Timeout handling: ✅
└─ Logging: ✅
📦 Bulkification XX/20 ████████░░ XX%
├─ Batch callouts: ✅
└─ Event batching: ✅
🏗️ Architecture XX/20 ████████░░ XX%
├─ Async patterns: ✅
└─ Service separation: ✅
✅ Best Practices XX/15 ████████░░ XX%
├─ Governor limits: ✅
└─ Idempotency: ✅
📝 Documentation XX/10 ████████░░ XX%
├─ Clear intent: ✅
└─ API versioning: ✅
════════════════════════════════════════════════════
Open this reference as its own page
<!-- Parent: sf-integration/SKILL.md -->Integration Security Best Practices
Overview
Security is critical for integrations. This guide covers best practices for securing Salesforce integrations with external systems.
Credential Management
DO: Use Named Credentials
// ✅ CORRECT - Named Credential handles auth
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MySecureAPI/resource');
DON'T: Hardcode Credentials
// ❌ WRONG - Never hardcode credentials
req.setHeader('Authorization', 'Bearer sk_live_abc123...');
req.setEndpoint('https://api.example.com');
Credential Storage Rules
| Item | Storage Location | Never Store In |
|---|---|---|
| API Keys | Named Credential | Apex code, Custom Settings |
| Client Secrets | Named Credential / External Credential | Source control |
| Certificates | Certificate & Key Management | Static Resources |
| Passwords | Named Credential | Custom Metadata |
OAuth Best Practices
Scope Minimization
Request only necessary scopes:
✅ read:orders write:orders
❌ admin:* read:* write:*
Token Handling
- Never log access tokens
- Don't expose tokens in error messages
- Use short-lived tokens when possible
- Implement token refresh handling
PKCE for Public Clients
For mobile or SPA clients:
Use Authorization Code with PKCE, not Implicit flow
Network Security
Remote Site Settings
- Only allow necessary domains
- Don't use wildcard domains
- Review and audit regularly
Certificate Validation
- Use trusted CA certificates
- Don't disable SSL/TLS verification
- Monitor certificate expiration
IP Restrictions
For Connected Apps:
- Configure IP relaxation carefully
- Use "Enforce IP restrictions" when possible
Input Validation
Validate External Data
// Validate before processing
public static void processExternalData(String externalId) {
// Validate format
if (!Pattern.matches('[A-Za-z0-9]{10,20}', externalId)) {
throw new ValidationException('Invalid external ID format');
}
// Sanitize for SOQL
String safeId = String.escapeSingleQuotes(externalId);
}
Output Encoding
// Encode data sent to external systems
String encodedData = EncodingUtil.urlEncode(userData, 'UTF-8');
Error Handling Security
Don't Expose Internal Details
// ❌ WRONG - Exposes internal structure
throw new CalloutException('Failed: ' + response.getBody());
// ✅ CORRECT - User-friendly, log details separately
System.debug(LoggingLevel.ERROR, 'API Error: ' + response.getBody());
throw new CalloutException('Unable to complete request. Contact support.');
Log Securely
// ❌ WRONG - Logs sensitive data
System.debug('Request: ' + JSON.serialize(request)); // May contain PII
// ✅ CORRECT - Redact sensitive fields
System.debug('Request to: ' + endpoint + ', Status: ' + statusCode);
API Security Patterns
Rate Limiting Awareness
if (response.getStatusCode() == 429) {
String retryAfter = response.getHeader('Retry-After');
// Implement backoff, don't hammer the API
}
Idempotency Keys
For POST requests that shouldn't duplicate:
req.setHeader('Idempotency-Key', generateUniqueKey());
Request Signing
For APIs requiring signature:
String signature = generateHmacSignature(payload, secretKey);
req.setHeader('X-Signature', signature);
User Context Security
Per-User vs Named Principal
| Scenario | Use |
|---|---|
| User-specific data access | Per-User Principal |
| Background/batch jobs | Named Principal |
| Service integrations | Named Principal |
| User-initiated with audit | Per-User Principal |
Audit Logging
public static void logIntegrationActivity(String operation, Id userId, String externalSystem) {
Integration_Log__c log = new Integration_Log__c(
Operation__c = operation,
User__c = userId,
External_System__c = externalSystem,
Timestamp__c = Datetime.now()
);
insert log;
}
Platform Event Security
Sensitive Data in Events
- Don't include PII in event payloads when avoidable
- Use record IDs and query for details
- Consider encryption for sensitive fields
Event Consumer Validation
trigger SecureEventHandler on My_Event__e (after insert) {
for (My_Event__e event : Trigger.new) {
// Validate event source/origin if possible
if (!isValidEventSource(event)) {
System.debug(LoggingLevel.WARN, 'Suspicious event: ' + event.ReplayId);
continue;
}
processEvent(event);
}
}
Security Checklist
Before Deployment
- Named Credentials used for all external calls
- No hardcoded credentials in code
- OAuth scopes minimized
- Remote Site Settings restricted
- Error messages don't expose internals
- Sensitive data not logged
- Input validation implemented
- Rate limiting handled
- Certificate expiration monitored
Regular Review
- Audit Named Credential usage
- Review integration user permissions
- Check for unused credentials
- Monitor integration error logs
- Validate certificate validity
- Review OAuth app authorizations
Compliance Considerations
GDPR / Data Privacy
- Minimize data transferred
- Document data flows
- Implement data deletion for integrated records
- Encrypt PII in transit and at rest
SOC 2 / Security Audits
- Maintain integration documentation
- Log all external access
- Implement change management
- Regular security assessments
HIPAA (Healthcare)
- Business Associate Agreements
- Encryption requirements
- Access logging
- Minimum necessary standard
More in this playbook
Cross crm opportunity sync
Coordinate opportunities and customer records across multiple CRMs while preserving attribution, visibility, commissions, and governance.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierInstall zapier
Install and connect Zapier, routing to the right surface (MCP, SDK, or CLI) for what the person needs. Use when someone says "install Zapier", "add Zapier", "connect Zapier", or "set up Zapier", or when they want an AI client (Claude, ChatGPT, Cursor) to use their apps, want to call Zapier from code, or want Zapier in the terminal.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierMcp sheet cache bridge
Keep Zapier Tables or another MCP-connected record store as the source of truth while Google Sheets-based tools read an event-driven cache tab.

