Why is idempotency a critical architectural requirement when designing reliable inbound and outbound API integrations?
Answer
Basics: In a distributed integration you cannot know whether a timed-out request was processed. The client must retry, so the server must tolerate repeats. Without idempotency, a retried "create payment" produces two payments. HTTP GET, PUT and DELETE are idempotent by definition; POST and PATCH are not, unless you design them to be.
How it works:
- The caller generates a stable unique key per business operation (an order number or an
Idempotency-KeyUUID header). - Salesforce stores it in an External ID field (marked unique) on the record, or in a log object of processed messages.
- Writes use upsert by that External ID:
Database.upsert(recs, Order__c.Ext_Id__c, false)or RESTPATCH /sobjects/Order__c/Ext_Id__c/123. - A repeated request updates the same record instead of inserting another.
- For side effects (emails, payments) check a processed-keys table first and skip if it exists.
Advanced / deep dive: Upsert is atomic per record but two concurrent upserts for a not-yet-existing key can collide, one failing with DUPLICATE_VALUE; handle by retrying once, which then finds the record. Mark External ID fields unique so Salesforce enforces it (and choose the case-sensitivity setting deliberately). For outbound calls, send an idempotency key header if the target supports it. Events (Platform Events, Outbound Messages) can be delivered more than once and out of order, so use replay IDs, event UUIDs or version numbers: apply an update only if its version or timestamp is newer. Idempotent consumers also make retry and replay recovery safe after outages. Avoid relying on field-value comparison alone for deduplication; keys are more reliable.
Code / config example: