Sub topic 9
Retries, Idempotency, and Error Handling Across Systems
This chapter assumes you know Salesforce objects and records, REST and JSON, and what an integration between two systems is. It covers what happens when a call between systems fails, and why that failure shapes the choice between native tools and middleware.
Why failures are the normal case
Two systems talk over a network. Any call can time out, return a 5xx error, or succeed on the remote side while the response is lost on the way back. A design that only works when every call succeeds will lose or duplicate data in production.
Three questions drive the design of every integration:
- What happens when a call fails? (error handling)
- Is it safe to try again? (retries and idempotency)
- Who finds out, and how is the data fixed? (monitoring and recovery)
Middleware is often justified by how it answers these questions at scale, not by how it moves data on a good day.
Classifying errors
Retrying everything is a mistake. First decide whether an error is worth retrying.
| Error type | Examples | Retry? |
|---|---|---|
| Transient | Timeout, HTTP 503, HTTP 429, connection reset | Yes, with backoff |
| Permanent (data) | HTTP 400, validation failure, missing required field | No. Fix the data or route to a dead-letter store |
| Permanent (auth/config) | HTTP 401, 403, expired credential | No. Alert an owner, fix the configuration, then replay |
| Business | Duplicate order, closed account | No. Handle by business rule |
A permanent error retried forever wastes limits and hides the real problem. A transient error never retried drops data.
Retries with backoff
A retry policy has three parts: how many attempts, how long to wait between them, and what to do when attempts run out.
Waiting a fixed time can overload a recovering system. Exponential backoff doubles the wait after each failure (for example 1 s, 2 s, 4 s, 8 s). Adding jitter, a small random amount, stops many clients from retrying at the same instant.
Here is a retry pattern in Apex using Queueable Apex. Each attempt is a separate transaction, so a callout failure does not roll back unrelated work.
public class OrderSyncJob implements Queueable, Database.AllowsCallouts {
private Id orderId;
private Integer attempt;
private static final Integer MAX_ATTEMPTS = 4;
public OrderSyncJob(Id orderId, Integer attempt) {
this.orderId = orderId;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:ERP_Credential/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', String.valueOf(orderId));
req.setBody(JSON.serialize(new Map<String, Object>{ 'orderId' => orderId }));
Integer status;
try {
HttpResponse res = new Http().send(req);
status = res.getStatusCode();
} catch (CalloutException e) {
status = 599; // treat network failure as transient
}
Boolean transientError = status == 429 || status >= 500;
if (status >= 200 && status < 300) {
return;
}
if (transientError && attempt < MAX_ATTEMPTS) {
System.enqueueJob(new OrderSyncJob(orderId, attempt + 1));
} else {
System.debug(LoggingLevel.ERROR,
'Order sync failed for ' + orderId + ' with status ' + status);
// Record the failure for review, for example in a custom error object.
}
}
}This code has a limit worth noticing. Apex cannot pause for a set time between attempts, so the retry runs as soon as the queue picks it up. There is no real exponential backoff. Real delays need Scheduled Apex, a platform event with replay, or an external layer. This is a common gap that middleware fills out of the box.
Idempotency
An operation is idempotent if doing it twice has the same result as doing it once. Setting a status to "Shipped" is idempotent. Creating an order, or adding 100 to a balance, is not.
Retries create duplicates unless the receiver is idempotent. The classic case: Salesforce sends a create request, the remote system saves the order, and the response times out. Salesforce sees a failure and retries. Now there are two orders.
There are three common ways to make writes safe:
- Idempotency key. The sender generates a unique key per logical operation and sends it in a header or field. The receiver stores keys and returns the original result for a repeat. The Apex above sends the record Id for this purpose.
- Upsert on an external ID. Salesforce supports upsert by an External ID field, so the same record arriving twice updates instead of duplicating.
- Natural keys and conditional updates. Use a business identifier, or check a version or timestamp before writing.
The next example shows the upsert approach through the REST API. The request name and path use a field called External_Id__c on Account.
curl -X PATCH \
"https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/External_Id__c/CUST-1001" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Ltd", "BillingCity": "Leeds"}'Sending this once or five times leaves one Account. A 201 means it was created. A 204 means it already existed and was updated.
Delivery guarantees
Messaging systems offer different guarantees.
| Guarantee | Meaning | Consequence |
|---|---|---|
| At most once | Sent once, never retried | Messages can be lost |
| At least once | Retried until acknowledged | Duplicates are possible |
| Exactly once | Each message processed once | Hard to achieve end to end |
Most practical integrations use at-least-once delivery combined with idempotent receivers. This gives the effect of exactly-once without needing a perfect transport.
Platform Events are a useful example. Subscribers can replay events from a replay ID within the retention window, so a subscriber that was down can catch up. The cost is that a subscriber may see an event more than once, so it must tolerate duplicates.
Handling errors in Salesforce native tools
Each native option reports failure differently.
- Apex callouts: you handle exceptions and status codes yourself, as in the code above. Nothing retries automatically.
- Flow: a fault path catches errors from actions. You can send an email or create an error record. Complex retry logic in Flow becomes hard to read and test.
- Platform Event triggers: a trigger can throw
EventBus.RetryableExceptionto ask the platform to redeliver the batch, and the platform limits how many times it retries. - Bulk API: results list success and failure per record, so you must read the result files and reprocess failed rows.
The pattern in all four is the same. The platform gives you the signal, and you build the policy: logging, retry, alerting, and replay.
What middleware adds
A middleware platform such as MuleSoft turns much of that policy into configuration. Typical capabilities:
- Retry and backoff at the connector or flow level, with configurable attempts and delays.
- Dead-letter queues. Messages that fail after all retries go to a queue where an operator can inspect and replay them.
- Scoped error handlers. In Mule, error handlers catch errors by type and decide to retry, continue, or route elsewhere.
- Idempotent filters. A flow can drop a message whose key it has already seen.
- Compensation. If step three of a multi-system process fails, the flow runs steps that undo steps one and two.
- Central visibility. One place to see failed messages across all integrations.
The following diagram shows a flow with these parts.
Multi-step processes and partial failure
A single call is simple. A process that touches Salesforce, an ERP, and a billing system is harder, because there is no shared transaction across them. If billing fails after the ERP succeeded, the systems disagree.
Options, from simplest to most involved:
- Make each step idempotent and retry the whole process. Works when every step is safe to repeat.
- Store process state and resume from the failed step.
- Compensating actions that undo completed steps, such as cancelling the ERP order.
- Reconciliation jobs that periodically compare systems and repair differences.
Salesforce Flow and Apex can do options 1 and 4 with effort. Options 2 and 3 across several systems are where orchestration in middleware earns its cost.
Using this in the decision
Ask these questions about a candidate integration:
- Is the target idempotent, or can you make it so?
- How bad is a lost or duplicated message? A missed marketing sync differs from a double-charged payment.
- How many systems does one business process touch?
- Who gets alerted at 3 a.m., and what can they do about it?
If one system is called, failures are transient and rare, the target accepts upserts, and a missed record can be fixed the next day, native tools with a small retry job are enough. If the process spans several systems, needs replayable failure queues, or has real financial consequences, the built-in policy and visibility of middleware lower risk and long-term effort.
Exercise
Salesforce sends a "create invoice" request to a billing system. The billing system saves the invoice, but the response times out, so Salesforce retries. Two invoices now exist. Name two ways to prevent the duplicate and say what each requires of the billing system.
Show answer
One way is an idempotency key. Salesforce sends a unique key per logical invoice (for example the Salesforce record Id), and the billing system must store keys and return the original result for a repeated key. The other way is an upsert on an external ID. Salesforce sends the invoice with a stable external identifier, and the billing system must support create-or-update by that identifier, so a second request updates the same invoice instead of creating another.
Exercise
A request returns HTTP 400 because a required field is missing. Should the integration retry it with backoff? What should happen instead?
Show answer
No. A 400 is a permanent data error, and retrying will fail the same way and waste limits. The message should go to an error record or dead-letter queue, an owner should be alerted, and the message should be replayed after the data is corrected.