Sub topic 10
Handling failures, retries, and replay
This chapter assumes you know the three patterns from earlier chapters (request-reply, fire-and-forget, batch sync), basic Apex, HTTP status codes, and why external IDs make repeated writes safe. Here you will learn how each pattern fails, which failures are worth retrying, and how to recover missed work.
Why failure handling differs by pattern
Each pattern fails in a different place, so each needs a different recovery tool.
| Pattern | Where it fails | Who notices | Typical recovery |
|---|---|---|---|
| Request-reply | Timeout, 4xx or 5xx response | The caller, immediately | Retry or surface an error to the user |
| Fire-and-forget | Publish rejected, or a subscriber fails later | The publisher sees only the publish result | Subscriber retry and event replay |
| Batch sync | Individual rows fail inside a job | Whoever reads the job results | Resubmit only the failed rows |
Classify the failure first
A retry helps only when the problem is temporary. Retrying a permanent failure wastes limits and delays the real fix.
- Transient: timeouts, HTTP 429 (rate limited), 502, 503, 504, and row-lock errors such as
UNABLE_TO_LOCK_ROW. Retry these. - Permanent: HTTP 400, 401, 403, 404, validation rule failures, and missing required fields. Fix the data or configuration. Do not retry unchanged.
HTTP 408 and 409 sit in between. Treat 409 as a conflict you must resolve, not a transient error.
Request-reply: retry with care
An Apex callout runs inside a transaction, and Apex cannot pause between attempts. Sleeping in a loop burns CPU time and holds the user's request. For a short retry, loop a small number of times. For a delayed retry, hand the work to Queueable Apex.
public with sharing class InvoiceRetryClient {
private static final Set<Integer> RETRYABLE = new Set<Integer>{ 429, 502, 503, 504 };
public static String fetchWithRetry(String invoiceId) {
Integer maxAttempts = 3;
for (Integer attempt = 1; attempt <= maxAttempts; attempt++) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/' + EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('GET');
req.setTimeout(10000);
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
return res.getBody();
}
if (!RETRYABLE.contains(res.getStatusCode())) {
throw new CalloutException('Permanent failure: ' + res.getStatusCode());
}
} catch (System.CalloutException e) {
if (attempt == maxAttempts) {
throw e;
}
}
}
throw new CalloutException('Gave up after ' + maxAttempts + ' attempts');
}
}This retries immediately, which is acceptable for a brief glitch. If the server asks you to slow down (429), an immediate retry makes things worse. Move that work to a Queueable job that re-enqueues itself with a counter, and stop after a fixed maximum.
Only retry requests that are safe to repeat. A GET is safe. A POST that creates an invoice can create two. Make the call idempotent first, for example by sending an idempotency key header that the external system honors.
Fire-and-forget: two failure points
A platform event publish can fail, and a subscriber can fail after a successful publish. Check Database.SaveResult when you publish, as shown in the earlier chapter. That covers the first point.
For the second point, an Apex trigger subscriber can ask Salesforce to redeliver the batch by throwing EventBus.RetryableException. Salesforce retries the trigger, up to 9 times, with a delay between attempts. After that, the trigger stops and the event is not redelivered to it automatically.
trigger OrderShippedSubscriber on Order_Shipped__e (after insert) {
for (Order_Shipped__e evt : Trigger.new) {
try {
ShipmentService.process(evt.Order_Number__c);
} catch (System.CalloutException e) {
throw new EventBus.RetryableException('Temporary failure: ' + e.getMessage());
}
EventBus.TriggerContext.currentContext().setResumeCheckpoint(evt.ReplayId);
}
}The setResumeCheckpoint call records the last event you finished. When the trigger retries, it resumes after that event instead of reprocessing the whole batch. Retries mean the same event can arrive more than once, so the subscriber must be idempotent.
Replay
Salesforce keeps published platform events on the event bus for 72 hours. Each event has a ReplayId. An external subscriber, such as one using the Pub/Sub API, can reconnect and ask for events from a stored ReplayId, or from the earliest retained event. This is how a subscriber recovers after downtime.
Store the last processed ReplayId durably, after you finish processing, not before. If you save it first and then crash, you skip an event. If you save it after, a crash causes a repeat, which idempotency handles.
Batch sync: read the job results
A Bulk API 2.0 job can finish in state JobComplete while some rows failed. The state tells you the job ran, not that every row succeeded. After completion, fetch the result sets:
successfulResultslists rows that were saved.failedResultslists rows that failed, with an error message.unprocessedrecordslists rows that never ran, for example because the job was aborted.
GET /services/data/v60.0/jobs/ingest/750xx0000000001AAA/failedResults
Authorization: Bearer <access_token>Build a new CSV from the failed rows that had transient errors, and submit it as a new upsert job. Because the job upserts by external ID, resubmitting rows that already succeeded does not create duplicates.
Dead-letter handling
Some messages never succeed. After the retry limit, do not drop them silently. Save the payload, the error, and the attempt count in a custom object, often called an error log. Someone can then correct the data and reprocess it. Without this, a failure is invisible until a user reports missing data.
Common errors
- Retrying a non-idempotent POST and creating duplicates.
- Retrying 400 and 404 responses that will never succeed.
- Treating
JobCompleteas "all rows saved". - Saving the ReplayId before processing finishes.
- Retrying forever with no limit and no error log.
Exercise
A subscriber trigger processes 200 platform events and fails on event 150 with a temporary callout error. How do you avoid reprocessing events 1 to 149 on the retry, and what must be true of the subscriber logic?
Show answer
Call EventBus.TriggerContext.currentContext().setResumeCheckpoint() with the ReplayId of each event after it finishes, then throw EventBus.RetryableException on the failure. Salesforce resumes after the last checkpoint. The subscriber logic must still be idempotent, because the failing event and any event processed after the last checkpoint can be delivered more than once.
Exercise
A Bulk API 2.0 upsert job shows state JobComplete, yet users report missing accounts. What do you check, and how do you fix it safely?
Show answer
Fetch the failedResults (and unprocessedrecords) for the job. Rows can fail while the job still completes. Correct or filter out permanent errors, then resubmit the failed rows as a new upsert job keyed on the external ID. Rows that already succeeded are not duplicated.