Sub topic 6
Deciding what is worth retrying
This chapter covers how to sort callout failures into those worth retrying and those that are not. It assumes you can write a basic Apex callout with Http, HttpRequest, and HttpResponse. It also assumes you know common HTTP status codes and the difference between synchronous and asynchronous Apex. Earlier chapters showed that a callout can fail by throwing an exception or by returning an error response. Here you turn those observations into a decision: retry or give up.
Why classification comes first
A retry is a second attempt at work that already failed once. It costs a callout against your limits, it adds load to a server that may already be struggling, and it can repeat a side effect on the remote system. Retrying a failure that cannot succeed wastes all of that and delays the error report.
Consider two failures from the same endpoint:
- A
POST /ordersreturns 503 because the service is restarting. The same request will probably succeed in a minute. - A
POST /ordersreturns 400 because the payload is missing a required field. The same request will fail every time.
The first is a transient failure, meaning one caused by a temporary condition. The second is a permanent failure, meaning one caused by the request itself or by a state that will not fix itself. Your retry code must tell these apart.
The decision model
Every callout outcome falls into one of three groups.
- Success. A 2xx status code. Stop and process the body.
- Retryable. The request may succeed if sent again unchanged.
- Non-retryable. Sending the same request again will give the same result. Stop, record the failure, and let a person or another process fix the cause.
Classifying status codes
Apex's Http.send does not throw on 4xx or 5xx responses. You must read HttpResponse.getStatusCode() and decide. The table lists the usual cases.
| Status | Meaning | Retry? | Reason |
|---|---|---|---|
| 200-299 | Success | No | Nothing failed. |
| 301, 302 | Redirect | No | Follow or fix the endpoint. Repeating the request does not help. |
| 400 | Bad request | No | The payload or parameters are wrong. |
| 401 | Unauthorized | Usually no | Credentials are missing or expired. See the note on token refresh below. |
| 403 | Forbidden | No | The caller lacks permission. |
| 404 | Not found | Usually no | The resource does not exist. A short retry is only sensible if the resource is created asynchronously. |
| 408 | Request timeout | Yes | The server gave up waiting for the request. |
| 409 | Conflict | Depends | A duplicate or version conflict. Often means the first attempt worked. |
| 422 | Unprocessable | No | The data failed validation. |
| 429 | Too many requests | Yes | Rate limited. Wait before retrying. |
| 500 | Server error | Yes, cautiously | May be a bug that repeats every time. Cap attempts. |
| 502, 503, 504 | Gateway or availability error | Yes | Typical transient conditions. |
The rule behind the table is simple. A 4xx status means the client got something wrong, so repeating the same request fails again. The exceptions are 408 and 429, which describe timing and volume rather than content. A 5xx status means the server failed, which may pass.
A reusable classifier
Instead of scattering status checks through your code, put the decision in one place. An enum keeps the three outcomes explicit.
public with sharing class CalloutOutcome {
public enum Kind { SUCCESS, RETRYABLE, PERMANENT }
public static Kind classify(Integer statusCode) {
if (statusCode >= 200 && statusCode < 300) {
return Kind.SUCCESS;
}
if (statusCode == 408
|| statusCode == 429
|| (statusCode >= 500 && statusCode <= 599)) {
return Kind.RETRYABLE;
}
return Kind.PERMANENT;
}
}A caller then branches on the result:
HttpResponse res = new Http().send(req);
CalloutOutcome.Kind outcome = CalloutOutcome.classify(res.getStatusCode());
if (outcome == CalloutOutcome.Kind.RETRYABLE) {
// schedule another attempt
} else if (outcome == CalloutOutcome.Kind.PERMANENT) {
// log the status and body, do not retry
}Keeping this logic in one class means a change in policy, such as treating 404 as retryable for one integration, happens in one place and is easy to test.
Classifying exceptions
A System.CalloutException is thrown for failures where no usable HTTP response arrived: a read timeout, a failed connection, or a DNS problem. These are usually transient, so they are normally retryable.
Some CalloutException causes are not transient, and retrying them only burns attempts:
Unauthorized endpoint, please check Setup->Security->Remote site settings. The endpoint is not allowed. This is a configuration error.- A missing or invalid named credential.
- Uncommitted work pending. This is a transaction problem covered in the next chapter.
You can separate these by inspecting the message, though matching strings is fragile because the text is not a documented contract. A conservative approach is to treat only messages you recognize as permanent and everything else as retryable, and to keep the attempt cap low so a misclassification is cheap.
public static Boolean isPermanentConfigError(System.CalloutException e) {
String msg = e.getMessage() == null ? '' : e.getMessage().toLowerCase();
return msg.contains('unauthorized endpoint')
|| msg.contains('uncommitted work pending');
}A System.LimitException is different. It is thrown when you exceed a governor limit, such as too many callouts in one transaction, and it cannot be caught. Do not plan to classify it. Prevent it by counting callouts and by moving work to asynchronous jobs.
The ambiguous case: a timeout after the request was sent
A timeout is the hardest failure to classify. When a read timeout fires, your code knows only that no response arrived in time. The server may never have received the request, or it may have processed it fully and the response was lost or slow. From the client side the two look identical.
This matters because retrying a request that already succeeded can create a duplicate order, charge a card twice, or send a second email. Whether a retry is safe depends on the operation, not on the failure.
- Read operations (GET). Repeating has no side effect. Retry freely within your cap.
- Operations that replace state (PUT, DELETE). Repeating normally produces the same final state, so these are usually safe.
- Operations that create (POST). Repeating may create a duplicate unless the remote system can recognize the repeat.
The standard remedy is an idempotency key, a unique value you generate once per logical operation and send with every attempt, so the server can recognize repeats and return the original result. Designing these is the topic of a later chapter. For now, record the rule: a non-idempotent request without a key should not be retried automatically after a timeout. Log it and let the code or a person verify the remote state first.
Special cases worth handling
429 and the Retry-After header
A 429 response often carries a Retry-After header with the number of seconds to wait. When it is present, honor it instead of using your own delay.
public static Integer retryAfterSeconds(HttpResponse res, Integer fallbackSeconds) {
String header = res.getHeader('Retry-After');
if (String.isNotBlank(header) && header.isNumeric()) {
return Integer.valueOf(header);
}
return fallbackSeconds;
}The header may also contain an HTTP date instead of a number. The code above treats that as absent and uses the fallback, which is a safe default.
401 and expired tokens
A 401 normally means retrying the identical request will fail. If the integration uses a token you manage yourself, one retry after refreshing the token is reasonable. With a named credential using an OAuth flow, Salesforce manages the token, so a persistent 401 points to a configuration problem and should be treated as permanent.
409 conflicts
A 409 can mean "the thing you tried to create already exists." If your earlier attempt timed out, this may be the proof that it worked. Decide per integration whether 409 on a repeated create counts as success.
500 versus 503
Both are 5xx, but they differ in how likely a retry is to help. A 503 usually signals temporary unavailability. A 500 often signals a bug triggered by your specific payload and may repeat every time. Treat both as retryable, but keep the attempt cap small so a deterministic 500 does not loop for long.
Putting it together
This method turns one attempt into a decision. It returns what the caller should do next and keeps the status and exception logic in one place.
public with sharing class AttemptEvaluator {
public enum Decision { DONE, RETRY, GIVE_UP }
public static Decision evaluate(HttpRequest req) {
try {
HttpResponse res = new Http().send(req);
CalloutOutcome.Kind kind = CalloutOutcome.classify(res.getStatusCode());
if (kind == CalloutOutcome.Kind.SUCCESS) {
return Decision.DONE;
}
if (kind == CalloutOutcome.Kind.RETRYABLE) {
return Decision.RETRY;
}
System.debug(LoggingLevel.ERROR,
'Permanent failure ' + res.getStatusCode() + ': ' + res.getBody());
return Decision.GIVE_UP;
} catch (System.CalloutException e) {
if (OrderApiClientHelper.isPermanentConfigError(e)) {
return Decision.GIVE_UP;
}
return Decision.RETRY;
}
}
}This example assumes isPermanentConfigError from the earlier snippet lives in a class named OrderApiClientHelper. Adjust the name to wherever you place it. The method also gives up on a RETRY decision only through the caller, which applies the attempt cap discussed in the retry policy chapter.
Common mistakes
- Retrying every non-2xx response. A 400 will not improve. Retrying it wastes callouts and hides a data bug.
- Treating a thrown exception as the only failure.
Http.sendreturns normally for a 500. Code that only has acatchblock silently accepts error responses as success. - Retrying a non-idempotent POST after a timeout. This is the main source of duplicate records.
- Retrying with no cap. A permanent failure misclassified as transient loops until it hits a limit.
- Logging only the status code. Error bodies usually say what is wrong. Log both, and be careful not to log secrets or personal data.
Exercise
A POST to create an invoice returns HTTP 400 with the body {"error":"customerId is required"}. A second POST, for a different invoice, throws a CalloutException with the message "Read timed out". Which one should your code retry automatically, and what must be true before it does?
Show answer
Do not retry the 400. It is a permanent failure caused by the payload, so the same request will fail again. Log the status and body and fix the data. The timeout is a transient failure and can be retried, but only if the create request is safe to repeat. Because the first attempt may have succeeded before the response was lost, the request should carry an idempotency key so the server can recognize a duplicate. Without that, verify the remote state before retrying. The retry also needs an attempt cap.
Exercise
Extend CalloutOutcome.classify so that 409 is treated as SUCCESS for a repeated create. What is the risk of doing this in the shared classifier?
Show answer
Add a branch returning Kind.SUCCESS when statusCode == 409. The risk is that 409 means different things in different integrations. In some it signals a duplicate that proves an earlier attempt worked, and in others it signals a real version conflict where data was not saved. Putting the rule in the shared classifier applies it everywhere. It is safer to make it a per-integration option, for example by passing a flag or by checking the code in the caller that knows the semantics.