Sub topic 6
Deciding what is worth retrying
This chapter assumes you can write a basic Apex callout with Http, HttpRequest, and HttpResponse. It also assumes you know common HTTP status codes and understand that callouts can fail in two ways: a thrown exception or an error response. Here you will learn which of those failures are worth sending again.
Why classification comes first
A retry is a second attempt at work that already failed once. If the failure was temporary, the second attempt may succeed. If the failure was permanent, it fails again and wastes callouts, queue slots, and time.
Each transaction has a limit on callouts, and asynchronous jobs share org-wide limits. Retrying a request that can never succeed uses those limits for nothing. It can also hide a bug, because a bad payload keeps failing quietly in the background.
So before you write any retry code, sort each failure into one of two groups:
- Transient: the same request might work if you wait and try again.
- Permanent: the same request will fail every time until something changes.
Transient failures
A transient failure points to a problem on the network or the remote server, not to your request.
| Signal | Meaning | Retry? |
|---|---|---|
| `CalloutException` (timeout, connection failure) | The request may not have reached the server, or the reply never came back | Yes |
| 408 Request Timeout | The server gave up waiting for the request | Yes |
| 429 Too Many Requests | You are being rate limited | Yes, after a delay |
| 500 Internal Server Error | The server failed unexpectedly | Usually yes |
| 502, 503, 504 | A gateway or the service is unavailable or slow | Yes |
For 429 and 503, the server may send a Retry-After header that says how long to wait. Read it when it is present and use it as the minimum delay.
Permanent failures
A permanent failure means the server understood the request and rejected it. Sending the same request again gets the same answer.
| Status | Meaning | What to do |
|---|---|---|
| 400 Bad Request | The payload or parameters are invalid | Fix the data, log the error |
| 401 Unauthorized | Credentials are missing or expired | Fix authentication |
| 403 Forbidden | The caller lacks permission | Fix permissions |
| 404 Not Found | The resource or path does not exist | Check the endpoint and IDs |
| 409 Conflict | The request conflicts with current state | Resolve the conflict first |
| 422 Unprocessable Entity | The data is well formed but fails validation | Fix the data |
Two cases need extra care. A 401 caused by an expired token can be worth one retry after a token refresh. With a Named Credential, Salesforce normally manages the token, so a repeated 401 usually means a configuration problem. A 404 can also be temporary if the record you are looking for has not replicated yet, but treat that as a special case you know about, not a default rule.
Turning the rules into code
The helper from the previous chapters can be written as one method that returns a classification. Using an enum keeps the decision in one place, so every caller treats failures the same way.
public with sharing class CalloutClassifier {
public enum Outcome { SUCCESS, RETRYABLE, PERMANENT }
public static Outcome classify(Integer statusCode) {
if (statusCode >= 200 && statusCode < 300) {
return Outcome.SUCCESS;
}
if (statusCode == 408 || statusCode == 429
|| (statusCode >= 500 && statusCode <= 599)) {
return Outcome.RETRYABLE;
}
return Outcome.PERMANENT;
}
}Anything not listed as retryable falls through to PERMANENT. This is the safer default, because an unknown code does not trigger endless retries. Exceptions are handled separately. A System.CalloutException is treated as retryable, and the code that catches it decides that.
Common mistakes
- Retrying every non-200 response. This repeats 400 and 404 errors that cannot recover.
- Treating all 5xx codes as equal. A 501 Not Implemented will not fix itself. If the API documents specific codes as permanent, add them to your rules.
- Ignoring the HTTP method. A retry after a timeout on a
POSTmay create a duplicate, because the first request might have succeeded. The next chapters on idempotency cover how to make this safe. - Hardcoding the rules in many places. Keep the classification in one class so a change applies everywhere.
Exercise
Exercise
An Apex callout returns status 422 with a body saying that a required field is missing. Should your code retry it? What should it do instead?
Show answer
No. A 422 is a permanent failure, because the same payload will be rejected every time. Log the status code and response body, record the failed request for review, and fix the data or the mapping that omitted the field.
Exercise
Using CalloutClassifier, what does classify(503) return, and what does classify(404) return?
Show answer
classify(503) returns Outcome.RETRYABLE because 503 is in the 500 to 599 range. classify(404) returns Outcome.PERMANENT because it is not a success code and is not in the retryable list.