Sub topic 9
Making repeated messages safe with external IDs
This chapter assumes you know the Salesforce data model, basic Apex, and REST and JSON. It also assumes you have read the chapters on fire-and-forget and batch sync. It covers why integrations deliver the same message more than once, and how external IDs make that harmless.
Why messages arrive twice
Most integration channels guarantee delivery at least once, not exactly once. A sender that gets no acknowledgment will send again, because it cannot tell whether the message was lost or only the reply was lost. Common causes of duplicates:
- A network timeout after Salesforce has already saved the record.
- A subscriber that fails partway through a batch of events and is retried.
- A replay of platform events from an earlier replay ID.
- A Bulk API 2.0 job that you resubmit after an unclear failure.
- An operator who reruns a scheduled sync.
If every message does a plain insert, each repeat creates another record. An operation is idempotent when running it several times leaves the same final state as running it once. The goal is to make every write idempotent.
External IDs as the matching key
An external ID is a custom field marked as an external ID, usually holding the primary key from the other system, such as an ERP customer number. Marking the field Unique as well makes Salesforce reject two records with the same value. Salesforce indexes external ID fields, so lookups by them are fast.
An upsert looks up a record by that key. If a match exists, it updates the record. If none exists, it inserts one. The sender no longer needs to know whether the record is already in Salesforce.
The REST API supports this by addressing the record through the external ID field:
PATCH /services/data/v60.0/sobjects/Account/External_Id__c/ERP-10042
Content-Type: application/json
Authorization: Bearer <access_token>
{
"Name": "Acme Corporation",
"Industry": "Manufacturing"
}The first call creates the Account and returns 201 Created. A repeat of the same call updates the same record and returns 204 No Content. Either way there is one Account for ERP-10042.
Bulk API 2.0 uses the same idea. In the ingest job below, externalIdFieldName tells Salesforce which field to match on for each CSV row:
POST /services/data/v60.0/jobs/ingest
Content-Type: application/json
Authorization: Bearer <access_token>
{
"object": "Account",
"externalIdFieldName": "External_Id__c",
"contentType": "CSV",
"operation": "upsert",
"lineEnding": "LF"
}After creating the job, upload the CSV to the job's batches endpoint and set the job state to UploadComplete. If the job fails midway, you can run the same file again. Rows that already succeeded update to the same values, and failed rows are inserted.
Idempotency for event subscribers
Platform event subscribers also need to tolerate repeats. The publisher can include a stable identifier in the event, such as Order_Number__c in the Order_Shipped__e example from the previous chapter. The subscriber then upserts by that value instead of inserting.
public class OrderShippedHandler {
public static void handle(List<Order_Shipped__e> events) {
List<Shipment__c> shipments = new List<Shipment__c>();
for (Order_Shipped__e e : events) {
shipments.add(new Shipment__c(
Order_Number__c = e.Order_Number__c,
Carrier__c = e.Carrier__c
));
}
Schema.SObjectField key = Shipment__c.Order_Number__c;
Database.upsert(shipments, key, false);
}
}This sketch assumes Shipment__c has a unique external ID field named Order_Number__c. The false argument allows partial success, so one bad row does not roll back the others. Inspect the returned Database.UpsertResult list and log the failures.
Common errors
- No uniqueness on the field. Without the Unique setting, two concurrent upserts can both insert, and a later upsert on that value fails with a duplicate-match error.
- Duplicate keys in one batch. An upsert call that contains the same external ID twice fails for those rows. Deduplicate the list before the call.
- Unstable keys. Using a value that can change, such as an email address, breaks matching. Use the source system's permanent ID.
- Idempotent creates, unsafe side effects. Upserting is safe, but sending an email or charging a card in the same transaction is not. Guard those actions with a status check.
- Stale overwrites. A late retry of an old message can overwrite newer data. Compare a version number or timestamp before updating if order matters.
Exercise
An ERP sends Account changes to Salesforce, and its HTTP client retries on timeout. How do you stop retries from creating duplicate Accounts, and which HTTP method and URL shape do you use?
Show answer
Create a unique external ID field on Account (for example ExternalIdc) that holds the ERP's customer number. Send each change as a PATCH to /services/data/v60.0/sobjects/Account/ExternalId__c/<ERP number>. The first call creates the record and later retries update the same record, so no duplicates appear.