Sub topic 10
Handling failures, retries, and replay
This chapter assumes you have read the earlier chapters on request-reply, fire-and-forget, and batch sync. It also assumes you know how external IDs make an upsert safe to repeat. You should be comfortable with Apex triggers, Queueable jobs, and HTTP status codes.
Every integration fails sooner or later. Networks drop, partner systems return 503, records lock, and a bad row slips into a CSV. Your job is to decide what happens next. The answer depends on the pattern, because each pattern reports failure in a different way and each offers a different way to recover.
How each pattern reports failure
| Pattern | How you learn about failure | Main recovery tool |
|---|---|---|
| Request-reply | Immediately, as an HTTP status code or a `CalloutException` | Retry from an asynchronous job with backoff |
| Fire-and-forget | The publisher learns only that Salesforce accepted the event. Subscriber failures appear later, if at all | Subscriber-side retry, checkpoints, and replay by replay ID |
| Batch sync | After the job finishes, in the failed and unprocessed result sets | Resubmit only the failed rows to an idempotent upsert |
A retry is only safe when repeating the operation causes no harm. That is why idempotency comes first in this part of the plan. Without an external ID or an idempotent HTTP method, a retry can create duplicates.
Classify the error before you retry
Retrying a permanent error wastes limits and hides the real problem. Sort every failure into one of two groups.
- Transient: the same request may succeed later. Examples are timeouts,
429 Too Many Requests,502,503,504, andUNABLE_TO_LOCK_ROW. - Permanent: the same request will always fail. Examples are
400for a malformed payload,401or403for bad credentials,404for a missing resource, and a validation rule failure.
Authentication errors need special care. A 401 often means an expired token. Named Credentials refresh tokens for you, so a repeated 401 usually points to a configuration problem. Alert a person instead of retrying.
Put the classification in one place so every integration shares it.
public with sharing class RetryPolicy {
public static final Integer MAX_ATTEMPTS = 5;
public static Boolean isRetryable(Integer statusCode) {
return statusCode == 408 || statusCode == 429
|| statusCode == 500 || statusCode == 502
|| statusCode == 503 || statusCode == 504;
}
// Exponential backoff: 1, 2, 4, 8, then capped at 10 minutes.
public static Integer delayMinutes(Integer attempt) {
Integer delay = (Integer) Math.pow(2, attempt - 1);
return Math.min(10, delay);
}
}The cap of 10 minutes matches the maximum delay that System.enqueueJob accepts.
Retrying request-reply calls
Apex cannot sleep, and a trigger should not loop on a callout. The usual approach is to make the first attempt, and on a transient failure enqueue a Queueable job with a delay. The job implements Database.AllowsCallouts, so it can call out again. Each retry carries its attempt count.
public with sharing class InvoiceSyncJob implements Queueable, Database.AllowsCallouts {
private final String invoiceId;
private final String payload;
private final Integer attempt;
public InvoiceSyncJob(String invoiceId, String payload, Integer attempt) {
this.invoiceId = invoiceId;
this.payload = payload;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/'
+ EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('PUT'); // PUT is idempotent, so a repeat is safe
req.setHeader('Content-Type', 'application/json');
req.setBody(payload);
req.setTimeout(10000);
try {
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
if (code >= 200 && code < 300) {
return;
}
handleFailure(code, 'HTTP ' + code + ': ' + res.getBody());
} catch (CalloutException e) {
// Timeouts and connection errors land here.
handleFailure(0, e.getMessage());
}
}
private void handleFailure(Integer code, String message) {
Boolean transientFailure = code == 0 || RetryPolicy.isRetryable(code);
if (transientFailure && attempt < RetryPolicy.MAX_ATTEMPTS) {
System.enqueueJob(
new InvoiceSyncJob(invoiceId, payload, attempt + 1),
RetryPolicy.delayMinutes(attempt)
);
} else {
insert new Integration_Error__c(
Record_Key__c = invoiceId,
Attempts__c = attempt,
Last_Error__c = message.left(255),
Status__c = 'Needs Review'
);
}
}
}Integration_Error__c is an example custom object that you define in your org. The next sections explain why it exists.
Three details matter here.
- Exhaustion: after the last attempt, the job writes a record that a person or a scheduled process can review. It never fails silently.
- Timeouts are ambiguous: a timeout does not tell you whether the partner processed the request. The
PUTto a fixed URL is what makes the retry safe. - Respect
Retry-After: if the partner sends this header on a429or503, use its value in place of your computed delay when it is within the 10-minute cap.
Retrying fire-and-forget subscribers
When you publish a platform event, a successful EventBus.publish only means Salesforce accepted it. The publisher is no longer involved. Failure handling moves to the subscriber.
An Apex trigger subscriber can ask the platform to run it again by throwing EventBus.RetryableException. It can also record how far it got with a checkpoint, so a retry resumes from the first unprocessed event instead of repeating the whole batch.
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
EventBus.TriggerContext ctx = EventBus.TriggerContext.currentContext();
for (Order_Shipped__e evt : Trigger.new) {
Shipment__c shipment = new Shipment__c(
Order_Number__c = evt.Order_Number__c,
Carrier__c = evt.Carrier__c
);
// Upsert by external ID, so a replayed event does not duplicate.
Database.UpsertResult result =
Database.upsert(shipment, Shipment__c.Order_Number__c, false);
if (!result.isSuccess()) {
Boolean lockError = false;
for (Database.Error err : result.getErrors()) {
if (err.getStatusCode() == StatusCode.UNABLE_TO_LOCK_ROW) {
lockError = true;
}
}
if (lockError && ctx.retries < 4) {
throw new EventBus.RetryableException(
'Row locked for order ' + evt.Order_Number__c);
}
insert new Integration_Error__c(
Record_Key__c = evt.Order_Number__c,
Attempts__c = ctx.retries + 1,
Last_Error__c = result.getErrors()[0].getMessage().left(255),
Status__c = 'Needs Review'
);
}
// Everything up to this event is now handled.
ctx.setResumeCheckpoint(evt.ReplayId);
}
}Note the order of work. The trigger throws the retry exception before it writes the error log, because an exception rolls back the transaction, including the log insert. The checkpoint is the one thing that survives the retry.
The platform caps retries. After the trigger has been retried the maximum number of times, the platform stops retrying and the trigger can move to a suspended state. A suspended trigger needs a person to resume it in Setup. Unhandled errors that you did not catch also count as failures, so catch what you can and log it.
Replay IDs and retention
Every platform event and Change Data Capture event gets a replay ID. It increases over time but is not guaranteed to be contiguous. The event bus keeps events for 72 hours. External subscribers, such as those using the Pub/Sub API or CometD, choose where to start when they connect.
-1receives only new events published after the subscription starts.-2receives all retained events, then new ones.- A specific replay ID receives events after that ID.
A well-behaved external subscriber stores the replay ID of the last event it fully processed, and does so only after processing succeeds. After a crash or an outage it reconnects with that stored ID. If the outage lasts longer than 72 hours, the missed events are gone, so you need a fallback. For Change Data Capture, that fallback is usually a batch reconciliation.
A related trap is the publish behavior setting on the event definition. With Publish After Commit, an event is dropped if the publishing transaction rolls back. With Publish Immediately, the event goes out even if the transaction later fails. Choose deliberately. If a downstream system would act on an event for data that never saved, use Publish After Commit.
Recovering from partial batch failures
Bulk API 2.0 accepts a job and then processes rows independently. One bad row does not fail the others. When the job reaches a final state, it exposes three result sets.
| Endpoint | Contents |
|---|---|
| `successfulResults` | Rows that were saved, with `sf__Id` and `sf__Created` |
| `failedResults` | Rows that were rejected, with `sf__Id` and `sf__Error` added to the original columns |
| `unprocessedrecords` | Rows never attempted, for example because the job was aborted |
Download the failed rows like this.
GET /services/data/v60.0/jobs/ingest/750xx000000abcdAAA/failedResults/
Accept: text/csv
Authorization: Bearer <access_token>Handle the two sets differently.
- Unprocessed rows were never tried. Resubmit them unchanged in a new job.
- Failed rows carry an error. Read
sf__Errorfirst. A lock error or a timeout is transient, so resubmit those rows. A validation error or a missing required field is permanent. Fix the data or send the row to the error log.
Because the job upserts by external ID, resubmitting an already saved row simply updates it again. This is the same idempotency property that makes event replay safe. You can resubmit the whole file without duplicates, but sending only the failed rows saves API calls and keeps the error trail clear.
Also check the job's own state. A job can end as Failed (the whole job could not run), Aborted, or JobComplete with some failed rows. Treat JobComplete with a non-zero failed count as a partial failure, not a success.
Keep an error log and a dead letter queue
A message that cannot be delivered after all retries should land somewhere visible. This place is often called a dead letter queue. In Salesforce it is usually a custom object such as Integration_Error__c. Useful fields are:
- A key identifying the business record (an order number or invoice ID).
- The integration name and operation.
- The attempt count and the last error message.
- A status, such as
Needs Review,Retrying, orResolved. - The original payload, if it is small enough and contains no sensitive data.
With this log, support staff can fix the data and trigger a reprocess. A scheduled job can also sweep records with status Needs Review after the root cause is fixed. Keep the reprocess path idempotent too.
Common mistakes
- Retrying inside a loop: a synchronous retry loop in a trigger burns your callout limit and holds a user's transaction open. Retry from a Queueable job.
- Callouts after DML: an Apex transaction that has made uncommitted changes cannot make a callout. Do the callout first, or move it into its own asynchronous job.
- Retrying everything: a permanent
400retried five times produces five identical failures and no fix. - No jitter: if many jobs fail together and all back off by the same amount, they all retry together. Add a small random offset where you control the delay, such as in a middleware layer.
- Unbounded retries: always cap attempts and always end in the error log.
- Trusting the publish result: a successful publish says nothing about subscribers.
Exercise
A nightly Bulk API 2.0 upsert job finishes in the JobComplete state, but the failedResults file contains 40 rows. Twelve show an sf_Error of UNABLETOLOCKROW, and 28 show a required-field-missing error. What do you do with each group, and why is it safe to resubmit?
Show answer
Resubmit the 12 lock-error rows in a new upsert job, because that failure is transient and a later attempt will probably succeed. Do not resubmit the 28 required-field rows as they are, because they will fail again. Fix the data or write them to the error log for review. Resubmitting is safe because the job upserts by external ID. A row that already saved is updated again rather than duplicated.
Exercise
An external subscriber reads platform events through the Pub/Sub API and was down for 20 hours. It stored the replay ID of the last event it fully processed. How does it catch up, and what must be true of its processing logic? What changes if it was down for four days?
Show answer
It reconnects and subscribes starting from the stored replay ID, so it receives every retained event after that point. Its processing must be idempotent, because replay is at-least-once and an event may arrive twice. After four days the 72-hour retention window has passed, so some events are no longer available. The subscriber needs a fallback, such as a batch reconciliation against Salesforce data.