Sub topic 9
Retries, idempotency, and error handling across systems
This chapter assumes you know basic Salesforce objects and records, REST APIs and JSON, and what a two-system integration is. It covers what goes wrong when a call between systems fails, and why middleware often handles that better than hand-written Apex.
Why failures are different across systems
Inside one database, a transaction either commits or rolls back. Across two systems there is no shared transaction. A request can time out after the other system has already processed it. The caller then cannot tell whether the work happened.
Failures fall into two groups:
- Transient: timeouts, HTTP 429 (rate limited), 503 (unavailable). A retry may succeed.
- Permanent: HTTP 400 (bad data), 404 (missing record), 401 (bad credentials). A retry will fail the same way.
Retrying a permanent failure wastes calls. Giving up on a transient failure loses data. Good error handling tells the two apart.
Retries and backoff
A retry resends a failed request. Resending immediately often makes an outage worse, so use exponential backoff: wait longer after each attempt, for example 1 s, 2 s, 4 s, then stop. Adding a small random delay (jitter) keeps many clients from retrying at the same moment.
Apex has no sleep, and a callout cannot wait inside a transaction. A native retry therefore needs a queued job. This example re-enqueues itself with a retry counter.
public class OrderSyncJob implements Queueable, Database.AllowsCallouts {
private String orderId;
private Integer attempt;
public OrderSyncJob(String orderId, Integer attempt) {
this.orderId = orderId;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:ERP_Credential/orders/' + orderId);
req.setMethod('GET');
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
if (code == 429 || code >= 500) {
if (attempt < 3) {
System.enqueueJob(new OrderSyncJob(orderId, attempt + 1));
} else {
System.debug('Giving up on order ' + orderId);
}
}
}
}This works, but you must build the delay, the retry counter, and the failure record yourself. Middleware usually offers retry policies as configuration.
Idempotency
An operation is idempotent if running it twice has the same effect as running it once. Retries make this essential. If a POST /orders call times out and you retry, you may create two orders.
Common techniques:
- Upsert on an external ID. Salesforce can upsert on a field marked External ID, so a replay updates the same record instead of inserting a duplicate.
- Idempotency keys. The caller sends a unique key with each request. The receiver stores it and returns the first result for any repeated key.
- Natural keys and state checks. Check whether the order is already
Shippedbefore applying the change.
Where failed messages go
A failure you cannot fix by retrying needs a place to wait for a human or a later fix. A dead-letter queue (DLQ) holds messages that exhausted their retries. Someone can inspect, correct, and replay them.
Native versus middleware
| Need | Native Salesforce | Middleware such as MuleSoft |
|---|---|---|
| Backoff retries | Custom Queueable code | Configured retry policy |
| Dead-letter handling | Custom error object | Built-in queues |
| Replay of failed messages | Build it yourself | Usually supported |
| Cross-system visibility | Debug logs, custom logging | Central monitoring and alerts |
For one simple integration with an upsert and a small error log, native tools are enough. When many integrations need consistent retry, replay, and alerting, middleware pays off.
Common mistakes
- Retrying every error, including 400 responses.
- Retrying without idempotency, which creates duplicates.
- Swallowing exceptions so failures are never recorded.
- Retrying with no limit, which can exhaust API limits.
Exercise
An Apex callout that creates an order in an ERP times out. You add a retry. What must be true of the ERP call to make the retry safe, and name one way to achieve it?
Show answer
The call must be idempotent, because the first request may have succeeded before the timeout. One way is to send a unique idempotency key with each request so the ERP returns the original result for a repeated key. Upserting on an external ID is another.
Exercise
Your integration receives HTTP 400 with a validation message. Should it retry with backoff? Where should the message go?
Show answer
No. A 400 is a permanent failure, and retrying it will fail the same way. Send it to a dead-letter queue or error log, alert someone, and replay it after the data is corrected.