Sub topic 9
Making repeated messages safe with external IDs
This chapter assumes you know the Salesforce data model (objects, fields, records), can read Apex and JSON, and understand HTTP methods and status codes. It also assumes you have seen the request-reply, fire-and-forget, and batch sync patterns from earlier chapters.
Why messages get repeated
Integrations rarely deliver a message exactly once. Networks time out, workers crash, and retry logic resends. A client that does not receive a response cannot tell whether the server never saw the request or processed it and failed to answer. The safe choice is to send it again.
Each pattern has its own way of producing duplicates:
- Request-reply: a callout times out after the remote system already committed the change. The caller retries.
- Fire-and-forget: platform event delivery is at least once from the subscriber's point of view. A subscriber that fails partway through a batch resumes from its last replay position and can see events again.
- Batch sync: a nightly job fails at row 800,000 and an operator reruns it from the start. Rows 1 to 799,999 are sent twice.
A repeated message is only a problem if processing it twice changes the result. That property is called idempotency.
What idempotency means
An operation is idempotent if running it once and running it many times leave the system in the same state. Setting a field to a value is idempotent. Adding 1 to a counter is not. Inserting a record is not, because every insert creates a new row.
An external ID is a custom field on a Salesforce object that stores the identifier a record has in another system, such as an ERP customer number. When you mark the field as External ID (and usually Unique), Salesforce indexes it and lets API calls address the record by that value instead of by the Salesforce record ID.
An upsert is a single operation that updates the record if one matches the key and inserts it if none does. Upsert keyed on an external ID turns a non-idempotent insert into an idempotent write.
Setting up an external ID field
Create a custom field on the object and select External ID. Also select Unique, and choose whether the uniqueness check is case-sensitive. Text, Number, Email, and Auto Number fields can be external IDs.
Some design points matter more than the checkbox:
- Choose a stable key. Use an identifier the source system never reuses or changes. A customer number is better than an email address.
- Enforce uniqueness. Without Unique, two records can share a value. Upsert then fails with a "multiple matches" error, and the data quality problem surfaces at the worst time.
- Mind case sensitivity. If the field is not case-sensitive,
erp-10042andERP-10042match the same record. Decide this up front and normalize the value in the sender. - Use one key per source system. If two systems both write Accounts, give each its own external ID field rather than sharing one.
- Mind the limit on indexed fields. Each object allows a limited number of external ID fields, so do not create one for every attribute.
Upsert through the REST API
The REST API supports upsert by sending a PATCH to a URL that contains the external ID field name and value.
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 response code tells you what happened:
| Result | Status code | Meaning |
|---|---|---|
| Record created | 201 Created | No record matched, so Salesforce inserted one. The body contains the new record ID. |
| Record updated | 204 No Content | A record matched and was updated. The body is empty. |
| Multiple matches | 300 Multiple Choices | More than one record has this external ID. The body lists the matches. |
| Bad request | 400 Bad Request | The payload is invalid, for example it contains the external ID field itself in the body. |
Sending the same request a second time returns 204 and changes nothing further. That is the idempotency you want.
Do not put the external ID field in the request body for a PATCH upsert. The value comes from the URL, and including it in the body causes an error.
Upsert in Apex
Apex offers the same behavior through Database.upsert with an external ID field token.
List<Account> incoming = new List<Account>{
new Account(External_Id__c = 'ERP-10042', Name = 'Acme Corporation', Industry = 'Manufacturing'),
new Account(External_Id__c = 'ERP-10043', Name = 'Globex', Industry = 'Energy')
};
Database.UpsertResult[] results = Database.upsert(incoming, Account.External_Id__c, false);
for (Integer i = 0; i < results.size(); i++) {
Database.UpsertResult r = results[i];
if (!r.isSuccess()) {
for (Database.Error err : r.getErrors()) {
System.debug(LoggingLevel.ERROR,
incoming[i].External_Id__c + ': ' + err.getMessage());
}
} else if (r.isCreated()) {
System.debug('Created ' + r.getId());
} else {
System.debug('Updated ' + r.getId());
}
}The third argument, false, sets allOrNone to false. A bad row then fails on its own and the rest of the batch still saves. Without it, one bad row rolls back the whole call, and a retry repeats the same failure.
One restriction applies: a single upsert call cannot contain two records with the same external ID value. Deduplicate the list first.
Linking related records by external ID
External IDs also help when you load related data. You can set a lookup by referencing the parent's external ID instead of looking up its Salesforce ID first.
Contact c = new Contact(
LastName = 'Rivera',
Email = '[email protected]'
);
c.Account = new Account(External_Id__c = 'ERP-10042');
insert c;Here Salesforce resolves the parent by external ID during the insert. This avoids an extra query and removes a source of mismatch, because the integration only needs to know keys from its own system.
Idempotency in each pattern
Batch sync
Bulk API 2.0 ingest jobs support the upsert operation when you name an external ID field. Rerunning a failed job is then safe.
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, then set the job state to UploadComplete. The CSV must include a column for the external ID field. After processing, read the successful and failed results for the job and handle failed rows separately instead of resubmitting the whole file.
A second rule applies to the file itself. If the CSV has the same external ID twice, the later row wins or errors depending on the job, and the outcome depends on row order. Remove duplicates before upload, and keep the most recent version of each key.
Fire-and-forget
Platform events do not deduplicate for you. If a subscriber receives the same event twice, it must produce the same result both times. Include a business key in the event, such as the order number, and have the subscriber upsert on it.
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
List<Shipment__c> shipments = new List<Shipment__c>();
Map<String, Shipment__c> byKey = new Map<String, Shipment__c>();
for (Order_Shipped__e evt : Trigger.new) {
Shipment__c s = new Shipment__c(
Order_Number__c = evt.Order_Number__c,
Carrier__c = evt.Carrier__c
);
byKey.put(evt.Order_Number__c, s);
}
shipments.addAll(byKey.values());
Database.upsert(shipments, Shipment__c.Order_Number__c, false);
}This example assumes Order_Number__c is an external ID on a custom Shipment__c object. The map removes duplicates inside one trigger batch, since a batch may contain the same key twice. The upsert handles duplicates across batches. If the trigger runs again for a replayed event, the shipment is updated to the same values.
Request-reply
For an outbound callout, the remote system must be the one that is idempotent. Many APIs accept an idempotency key header, a unique value you generate once per logical operation and reuse on each retry. The server stores the result under that key and returns the stored result for repeats.
public with sharing class PaymentClient {
public static HttpResponse charge(String idempotencyKey, String payload) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/charges');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', idempotencyKey);
req.setBody(payload);
req.setTimeout(10000);
return new Http().send(req);
}
}The header name is a common convention, not a standard that every API follows. Check the remote API's documentation. Generate the key before the first attempt and store it, for example on the record that triggered the call, so a retry from a later transaction sends the same value.
Common errors
- Using insert where upsert is needed. A retry creates duplicates. Check that every write path that can be replayed uses a key.
- A non-unique external ID. Upsert returns a multiple-match error. Add the Unique setting and clean existing data first.
- Generating the key at retry time. A new GUID on every attempt defeats idempotency. Create it once and persist it.
- Treating the key as secret or meaningful. It is an identifier, not a credential. Do not encode sensitive data in it.
- Overwriting newer data with older data. A replayed old message can revert a field that a later message already changed. If order matters, include a version or timestamp and skip updates that are older than what is stored.
- Duplicates inside one batch. A single upsert call or CSV with repeated keys can fail or give an order-dependent result. Deduplicate first.
- Non-idempotent side effects. An upsert is safe, but a trigger that sends an email or increments a counter on each update still repeats its effect. Guard those actions with a status check.
Exercises
Exercise
A nightly Bulk API 2.0 job loads 2 million Contacts and fails at 60 percent. An operator wants to rerun the whole file. What must be true for the rerun to be safe, and what should the job use?
Show answer
Each Contact must carry a stable, unique external ID, and the job must use the upsert operation with externalIdFieldName set to that field. Rows already loaded then match and are updated to the same values, and the remaining rows are inserted. With plain insert, the first 60 percent would be duplicated. The file should also be deduplicated by key before upload.
Exercise
A REST API upsert with PATCH to /sobjects/Account/ExternalId_c/ERP-10042 returns 300. What does it mean, and how do you prevent it?
Show answer
Two or more Accounts have ExternalId_c equal to ERP-10042, so Salesforce cannot choose one record. Prevent it by marking the field Unique, deciding on case sensitivity, and cleaning existing duplicates before relying on upsert.
Exercise
A platform event subscriber trigger inserts a Shipment__c for each event. After a subscriber outage and replay, there are duplicate shipments. Describe the fix.
Show answer
Add an external ID field such as OrderNumberc to Shipment_c, include the order number in the event, and change the trigger to upsert on that field. Deduplicate keys inside the trigger batch with a map, use allOrNone false so one bad row does not block others, and guard any side effects so a replay does not repeat them.