Sub topic 3
The Salesforce integration toolbox
This chapter assumes you know the Salesforce data model (objects, fields, records), basic Apex and triggers, REST and JSON, and HTTP methods and status codes. The previous chapters covered integration styles and the synchronous and asynchronous trade-offs. This chapter surveys the five Salesforce features you will use to build the three patterns. Later chapters cover each pattern in detail.
Two questions that sort every surface
Each feature in the toolbox answers two questions. The answers tell you when to use it.
- Who starts the conversation? Either Salesforce reaches out to another system (outbound), or another system reaches into Salesforce (inbound).
- Does the caller wait? The caller either blocks for a response (synchronous) or hands off a message and moves on (asynchronous).
The table places the five surfaces on those two axes.
| Surface | Direction | Timing | Typical pattern | Data shape |
|---|---|---|---|---|
| REST API | Inbound | Synchronous | Request-reply | One record or a small set per call, JSON |
| Apex callouts | Outbound | Synchronous (can be moved to async code) | Request-reply | One HTTP request and response |
| Platform events | Both | Asynchronous | Fire-and-forget | Small custom messages |
| Change Data Capture | Outbound | Asynchronous | Fire-and-forget | Change notifications for record changes |
| Bulk API 2.0 | Inbound (and query export) | Asynchronous job | Batch sync | Thousands to millions of records, CSV |
The "typical pattern" column is a default, not a rule. Platform events can carry a reply message in the other direction. The REST API can load data in bulk, though badly. Chapter 11 covers choosing between them.
REST API: inbound, synchronous
The REST API is the general entry point for external systems. It exposes standard operations over HTTPS with JSON bodies.
- sObject resources create, read, update, and delete one record:
/services/data/v60.0/sobjects/Account/<id>. - Query runs SOQL:
/services/data/v60.0/query?q=.... Large results come back in pages, and each page includes anextRecordsUrlto follow. - Composite resources bundle several operations into one HTTP request, which saves round trips and API calls.
- Upsert by external ID uses
PATCHon/sobjects/Account/External_Id__c/<value>. It creates the record if no match exists and updates it otherwise. Chapter 9 builds on this. - Apex REST lets you publish your own endpoint with
@RestResourcewhen the standard shape is a poor fit for the caller.
A query for one account by external ID looks like this:
GET /services/data/v60.0/query?q=SELECT+Id,Name+FROM+Account+WHERE+External_Id__c+%3D+'ERP-10042'
Accept: application/json
Authorization: Bearer <access_token>The caller gets the answer in the same HTTP exchange. That makes the REST API a natural request-reply surface, and it is also why it is a poor choice for large data loads. Every call consumes API allowance and takes a round trip.
Edge cases to know
- API request limits are org-wide. Salesforce caps total API calls per rolling 24 hours, based on edition and licenses. One chatty integration can starve the others.
- Each record write still runs your automation. Triggers, flows, and validation rules fire as they would from the UI. A slow trigger slows the API call.
- A composite request is not always one transaction. Some composite forms let you choose whether a failure rolls back the other sub-requests. Check the option you use.
Apex callouts: outbound, synchronous
An Apex callout is an HTTP request your Apex code sends to an external service, using Http, HttpRequest, and HttpResponse. You use it when Salesforce needs data or an action from another system, such as a credit check or a shipping quote.
Endpoints should be addressed through a Named Credential, as in callout:Billing_API/invoices/42. The next chapter covers authentication in detail. For now, note that the endpoint host and the secret live in setup configuration, not in code.
Constraints that surprise people:
- No callout after uncommitted DML. If a transaction has inserted or updated records and not yet committed, Apex throws a
CalloutException("You have uncommitted work pending") when you try a callout. Do the callout first, or move it to separate asynchronous code. - Triggers cannot call out directly. A trigger runs inside the save transaction, so the callout must run in asynchronous Apex. Use a
Queueableclass that implementsDatabase.AllowsCallouts, or an@future(callout=true)method. - Per-transaction limits apply. A single transaction is limited in callouts (100) and in total callout time (120 seconds). Chapter 8 returns to these numbers.
- The caller blocks. The user or process that triggered the code waits for the external service. Set a short, explicit timeout with
setTimeout.
A trigger that hands off to a queueable looks like this:
public with sharing class InvoiceStatusJob implements Queueable, Database.AllowsCallouts {
private final String invoiceId;
public InvoiceStatusJob(String invoiceId) {
this.invoiceId = invoiceId;
}
public void execute(QueueableContext ctx) {
String status = InvoiceClient.fetchInvoiceStatus(invoiceId);
System.debug('Invoice ' + invoiceId + ' is ' + status);
}
}This reuses the InvoiceClient class from the request-reply chapter. Calling System.enqueueJob(new InvoiceStatusJob('INV-1')) from a trigger moves the wait out of the save transaction. Note that the pattern has changed at that point. The user no longer waits, and the answer arrives later. It is request-reply on the wire but asynchronous from the user's view.
Platform events: asynchronous messages
A platform event is a message with a schema you define. You create a custom event object with a name ending in __e, and add custom fields. Events are published to the event bus, and any number of subscribers receive them.
- Publishers: Apex (
EventBus.publish), Flow, the REST API (insert an event record), and external clients. - Subscribers: Apex triggers on the event object, Flow, and external clients that connect through the Pub/Sub API (gRPC) or the older CometD streaming.
- Delivery is decoupled.
EventBus.publishreturns aDatabase.SaveResultthat tells you Salesforce accepted the event. It does not tell you any subscriber processed it. - Replay. Each event carries a replay ID. A subscriber that disconnects can reconnect and ask for events after a given ID, within the retention window. For standard-volume platform events, retention is 72 hours.
- Publish behavior. An event can be set to publish immediately or after the publishing transaction commits. "After commit" avoids announcing a change that later rolls back. "Immediately" delivers the event even if the transaction fails.
An Apex trigger subscribes to an event like any trigger, but it only supports after insert:
trigger OrderShippedSubscriber on Order_Shipped__e (after insert) {
for (Order_Shipped__e evt : Trigger.new) {
System.debug('Order ' + evt.Order_Number__c + ' shipped with ' + evt.Carrier__c);
}
}Event triggers run in their own transaction, as a separate system user. They do not share a transaction with the publisher, so a failure in the subscriber never rolls back the publisher's work.
Change Data Capture: events about record changes
Change Data Capture (CDC) publishes a change event whenever a record changes in an object you have enabled. You do not write a publisher. The platform emits the events for creates, updates, deletes, and undeletes.
- Channels.
/data/ChangeEventscarries all enabled objects./data/AccountChangeEventcarries one object. - Event content. The event has a
ChangeEventHeaderwith the change type, the record IDs, the entity name, and the changed field names. Update events contain only the changed field values, so a subscriber that needs the full record must query for it. - Gap events and overflow. When Salesforce cannot generate the full change data, it can send a gap event instead. A subscriber should treat that as a signal to re-fetch the record.
- Retention. CDC events are kept for three days for replay.
A subscriber trigger reads the header:
trigger AccountChangeSubscriber on AccountChangeEvent (after insert) {
for (AccountChangeEvent evt : Trigger.new) {
EventBus.ChangeEventHeader header = evt.ChangeEventHeader;
if (header.getChangeType() == 'UPDATE') {
System.debug('Records ' + header.getRecordIds()
+ ' changed fields ' + header.getChangedFields());
}
}
}Choose CDC when the question is "tell me when this data changes." Choose a custom platform event when the question is "tell me this business thing happened." A shipped order is a business event, and a changed Status__c field is a data change. Business events keep their meaning if you later change the underlying fields. CDC events do not.
Bulk API 2.0: asynchronous jobs for volume
Bulk API 2.0 moves large datasets. You do not send records one call at a time. You create a job, upload CSV data to it, close the upload, and let Salesforce process it in the background.
POST /services/data/v60.0/jobs/ingestcreates the job with an object, an operation (insert,update,upsert,delete, orhardDelete), and for upserts anexternalIdFieldName.PUTthe CSV to the job's batches endpoint.PATCHthe job with{"state": "UploadComplete"}to start processing.- Poll the job until it reaches
JobCompleteorFailed. - Download the
successfulResults,failedResults, andunprocessedRecordsfiles.
Salesforce splits the data into internal batches for you, which is a main difference from the original Bulk API. Query jobs (/jobs/query) work the same way in reverse, for large exports.
Behaviors that matter in design:
- Partial success is normal. A job can finish with some rows failed. Always read the failed-results file. A
JobCompletestate does not mean every record loaded. - There is no replay of a single row. You correct the failed rows and submit them in a new job.
- Limits are per 24 hours. Salesforce caps the number of records and batches processed per day. Check the current limits for your org before you size a nightly load.
- Locking. Parallel processing can cause row lock errors when many rows touch the same parent. Sort the CSV by parent ID to reduce them.
Pub/Sub API and other surfaces
Two other surfaces appear in real designs and are worth a mention. The Pub/Sub API is the current way for external systems to subscribe to platform events and CDC. It uses gRPC and lets the subscriber control how many events it receives. Outbound Messages and flow-based HTTP callouts also exist. Use those when a declarative tool is enough, and move to Apex when you need retries, custom parsing, or testable logic.
Common mistakes
- Using REST for a nightly million-row load. It burns API calls and runs slowly. Use Bulk API 2.0.
- Calling out from a trigger. It fails or blocks saves. Hand off to a queueable.
- Treating
EventBus.publishsuccess as delivery. It only means the platform accepted the event. - Subscribing to CDC when you need a business event. Consumers then depend on your field names.
- Ignoring the failed-results file after a Bulk API 2.0 job.
Exercise
A trigger on Opportunity must tell an external ERP system that a deal was won, and the user saving the record must not wait for the ERP. The ERP also wants only the fields that changed. Which Salesforce surface fits best, and why is a direct Apex callout from the trigger a poor choice?
Show answer
Use Change Data Capture on Opportunity, or a custom platform event if the ERP should receive a business message such as "Opportunity won" instead of raw field changes. Both are asynchronous, so the user does not wait, and CDC already includes the changed field names. A direct callout from a trigger is not allowed in the save transaction, and it would make the user wait for the ERP. A queueable callout would avoid the blocking but gives no built-in replay, so you would have to build your own retry logic.
Exercise
A Bulk API 2.0 upsert job shows state JobComplete. Does that confirm that every record was saved? What do you check next?
Show answer
No. A job can complete with some rows failed. Download the failedResults file, and also the unprocessedRecords file, correct the rows, and submit them in a new job.