Sub topic 3
Designing a Retry Policy
Assume you know basic Apex classes, HTTP status codes, callouts, and governor limits. A retry policy defines which failures to repeat, how often to repeat them, and when to stop.
Retry only failures that may succeed later:
- Timeouts and connection failures.
408 Request Timeout.429 Too Many Requests.5xxserver errors.
Do not retry most 4xx responses. A 400 request is invalid, and a 401 request needs new credentials. Repeating either request does not fix the cause.
| Failure | Retry? | Reason |
|---|---|---|
| Timeout | Yes | The server may still be available |
| `429` | Yes | Rate limiting may be temporary |
| `404` | No | The resource or URL is probably wrong |
| `500` | Yes | The server may recover |
Use exponential backoff. Each attempt waits longer than the previous one. Add jitter, which is a small random delay, so many jobs do not retry at the same time. For POST requests, send an idempotency key. The key lets the service recognize a repeated request and avoid creating duplicate records.
public class RetryableCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
private final String body;
private final Integer attempt;
private final String idempotencyKey;
public RetryableCallout(String body, Integer attempt, String key) {
this.body = body;
this.attempt = attempt;
this.idempotencyKey = key;
}
public void execute(QueueableContext context) {
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Orders_API/orders');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setHeader('Idempotency-Key', idempotencyKey);
request.setBody(body);
request.setTimeout(30000);
try {
HttpResponse response = new Http().send(request);
Integer code = response.getStatusCode();
if (code >= 200 && code < 300) return;
if (code != 408 && code != 429 && (code < 500 || code > 599)) {
System.debug(LoggingLevel.ERROR, 'Permanent failure: ' + code);
return;
}
} catch (System.CalloutException error) {
System.debug(LoggingLevel.WARN, error.getMessage());
}
if (attempt < MAX_ATTEMPTS) {
Integer backoff = Math.min(10, (Integer)Math.pow(2, attempt - 1));
System.enqueueJob(
new RetryableCallout(body, attempt + 1, idempotencyKey),
backoff
);
} else {
System.debug(LoggingLevel.ERROR, 'Retries exhausted');
}
}
}When Retries Run Out
Persist a failure record containing the endpoint, request identifier, status or exception, response body, attempt count, and next action. A support process can review and replay that record after correcting the underlying problem.
Testing Timeouts and Errors
HttpCalloutMock replaces the real service in a test. Create one mock that throws CalloutException and another that returns a 503 response. Assert that the job retries, while a 400 response does not.
Exercise
Should a 401 response normally be retried?
Show answer
No. Refresh or correct authentication first, then send a new request.