Sub topic 7
Handling partial failure and halted subrequests
This chapter assumes you can send a composite request, chain subrequests with @{referenceId.field}, and set allOrNone. It also assumes you can read HTTP status codes. Here you will learn how to interpret a response in which some subrequests worked and others did not, and how to write client code that does not misreport the result.
The outer status code does not tell you the outcome
A composite call is one HTTP request that carries many operations. When Salesforce can parse the request and process it, the outer HTTP response is usually 200 OK, even if some or all subrequests failed. The real outcome of each operation is inside compositeResponse.
The outer call can fail in two ways:
- Request-level failure. The call is rejected before any subrequest runs. Examples are an expired token (
401), malformed JSON, or an invalid structure (400). Nothing was executed. - Subrequest-level failure. The call is accepted and processed. One or more entries in
compositeResponsecarry a non-2xxhttpStatusCode.
Code that only checks the outer status will report success for a transaction that was rolled back. Always inspect every entry.
The three outcomes for a subrequest
Each entry in compositeResponse has a referenceId, an httpStatusCode, a body, and httpHeaders. Entries come back in the same order as the subrequests you sent. Every entry falls into one of three groups:
| Outcome | Typical status | What it means |
|---|---|---|
| Succeeded | `200`, `201`, `204` | The operation ran and its result is usable by later subrequests. |
| Failed | `400`, `404`, and others | This subrequest hit a real error, such as a validation rule failure or a missing record. |
| Halted | `400` with `PROCESSING_HALTED` | The subrequest did not fail by itself. It was stopped or undone because of another failure. |
The third group is the one people misread. A halted subrequest is not the cause of the problem. Look for the entry with a different error code, because that entry is the root cause.
What allOrNone changes
The allOrNone flag decides what happens to the other subrequests when one fails.
allOrNone set to true
Salesforce treats the whole composite request as one transaction. When any subrequest fails:
- The failing subrequest returns its own error in
body. - All changes made by earlier subrequests in the same call are rolled back.
- Every other subrequest returns a
400entry whose error code isPROCESSING_HALTED. This includes subrequests that had already succeeded before the rollback, and subrequests that never ran.
So after a rollback, a request with ten subrequests shows one real error and nine halted entries. Nothing was saved.
allOrNone set to false
Each subrequest commits on its own. A failure does not undo earlier successes, and Salesforce keeps going with the later subrequests that can still run. You can end up with a partially applied result: some records saved, others not.
A later subrequest that uses @{referenceId.field} to refer to a failed subrequest cannot get its value, so it fails too. Check its errorCode and message instead of assuming one specific code. Subrequests that do not depend on the failure still run normally.
The next diagram shows the decision path Salesforce follows after one subrequest fails.
A request that fails halfway
The following request creates an Account and then a Contact. The Contact has no LastName, which is a required field, so it fails. The third subrequest reads the Contact back.
{
"allOrNone": true,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "newAccount",
"body": { "Name": "Acme Corp" }
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "newContact",
"body": { "FirstName": "Sam", "AccountId": "@{newAccount.id}" }
},
{
"method": "GET",
"url": "/services/data/v60.0/sobjects/Contact/@{newContact.id}?fields=Id,AccountId",
"referenceId": "readContact"
}
]
}The response has this shape. IDs and message text are shortened here, and httpHeaders is omitted.
{
"compositeResponse": [
{
"body": [
{
"errorCode": "PROCESSING_HALTED",
"message": "The transaction was rolled back since another operation in the same transaction failed."
}
],
"httpStatusCode": 400,
"referenceId": "newAccount"
},
{
"body": [
{
"errorCode": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [LastName]",
"fields": ["LastName"]
}
],
"httpStatusCode": 400,
"referenceId": "newContact"
},
{
"body": [
{
"errorCode": "PROCESSING_HALTED",
"message": "The transaction was rolled back since another operation in the same transaction failed."
}
],
"httpStatusCode": 400,
"referenceId": "readContact"
}
]
}The Account was created and then rolled back, which is why it shows PROCESSING_HALTED even though its own operation was valid. The only real error is the one on newContact. The body of an error entry is an array of objects, not a single object, so index into it when you read the message.
If you send the same request with allOrNone set to false, the Account is saved and the response reports it as 201. The Contact fails with REQUIRED_FIELD_MISSING. The readContact subrequest fails because it depends on newContact, which has no ID. You are left with an Account and no Contact.
Parsing the response in code
A reliable client does three things. It checks the outer call, separates the real failures from the halted entries, and reports a single clear result. This script does all three.
import os
import requests
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
payload = {
"allOrNone": True,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "newAccount",
"body": {"Name": "Acme Corp"},
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "newContact",
"body": {"FirstName": "Sam", "AccountId": "@{newAccount.id}"},
},
],
}
resp = requests.post(
base + "/services/data/v60.0/composite",
headers=headers,
json=payload,
timeout=30,
)
resp.raise_for_status() # catches request-level failures only
results = resp.json()["compositeResponse"]
failures = []
halted = []
for sub in results:
status = sub["httpStatusCode"]
if 200 <= status < 300:
continue
errors = sub["body"] if isinstance(sub["body"], list) else []
codes = [e.get("errorCode") for e in errors]
if "PROCESSING_HALTED" in codes:
halted.append(sub["referenceId"])
else:
failures.append((sub["referenceId"], status, errors))
if not failures and not halted:
print("All subrequests succeeded")
else:
print("Halted (not the cause):", halted)
for ref, status, errors in failures:
for e in errors:
print("Root cause:", ref, status, e.get("errorCode"), e.get("message"))Note that raise_for_status() does not detect a rolled-back transaction, because the outer status is still 200. The loop is what finds the failure.
What to do when you see a failure
The right response depends on the allOrNone setting.
- With
allOrNonetrue: the org is unchanged, so you can fix the root-cause entry and send the whole request again. There is nothing to clean up. This is the main reason to prefer it when the operations belong together. - With
allOrNonefalse: some records exist already. If you resend the full request, you create duplicates of the ones that succeeded. Resend only the failed subrequests, or make the operations safe to repeat.
To make repeats safe, use an upsert on an external ID field. A PATCH to /services/data/v60.0/sobjects/Account/External_Id__c/ABC-100 creates the record if it is missing and updates it if it exists. Running it twice gives the same final state. The field name External_Id__c is an example, so use an external ID field that exists in your org.
Common mistakes
- Treating
200as success. The outer status says the call was processed, nothing more. - Reporting the first non-2xx entry as the error. With
allOrNonetrue, the first entry may be a halted one. Search for the entry whose error code is notPROCESSING_HALTED. - Assuming an entry's
bodyis an object. Error bodies are arrays, while success bodies for creates are objects such as{"id": "...", "success": true, "errors": []}. - Matching entries by position without checking. Match by
referenceIdinstead, which stays correct if you reorder subrequests later. - Retrying blindly after partial success. Check which records were created before you resend.
Exercises
Exercise
A composite request with allOrNone set to true has four subrequests: createAccount, createContact, createCase, and readCase. The createCase subrequest fails a validation rule. What does the response show for each of the four entries, and is anything saved in the org?
Show answer
The createCase entry shows its own validation error with a 400 status. The other three entries (createAccount, createContact, readCase) each show a 400 status with the PROCESSING_HALTED error code, including the first two, which had run before the failure. Nothing is saved, because the whole transaction is rolled back. The outer HTTP status is still 200.
Exercise
You run the same four-subrequest request with allOrNone set to false, and createContact fails. The subrequest createCase references @{createContact.id}, while createAccount and a fifth subrequest, createTask, do not reference any other result. Which subrequests succeed, which fail, and what is the safest way to retry?
Show answer
createAccount and createTask succeed and stay committed, because they are independent of the failure. createContact fails with its own error. createCase fails because the ID it references does not exist, so its entry carries an error, and you should read its errorCode and message to confirm. To retry, fix the cause and resend only createContact and createCase, using the stored Account ID if needed. Resending the whole request would create a second Account and Task unless the operations are upserts on an external ID.