Sub topic 2
Why combine requests
This chapter explains what problem the Composite resources solve and what you gain and risk by using them. It builds the case for the later chapters, which cover the request format, reference IDs, rollback, and limits.
It assumes you already know HTTP methods, status codes, and JSON bodies. It also assumes you know Salesforce objects, fields, and record IDs, and that you have an OAuth access token and your org's instance URL. You should have used the standard sObject endpoints, such as POST /services/data/v60.0/sobjects/Account.
The cost of one operation per call
The standard REST API takes one operation per HTTP request. Creating an Account is one request. Creating a Contact for that Account is a second request. Reading the Contact back is a third. A client that does this work in order pays three costs.
- Network latency. Each request is a full round trip. The client sends it, the server processes it, and the client reads the response. The latency of your network path is paid every time, even when the server finishes in a few milliseconds.
- API usage. Every REST call counts against your org's API request allocation. Integrations that make thousands of small calls can use up the allocation faster than the data volume would suggest.
- No shared transaction. Each call commits or fails by itself. If the Account is saved and the Contact request fails, the Account stays in the org. Your client has to detect the failure and clean up.
A fourth cost is client complexity. The Contact request needs the Account's ID. Your code must wait for the first response, parse it, and build the second request. Every extra step adds code and a place for errors.
The sequential version
The script below does the three operations as separate calls. It reads the instance URL and token from environment variables and counts the HTTP requests it makes.
import os
import requests
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
api = base + "/services/data/v60.0"
calls = 0
# Call 1: create the Account
resp = requests.post(api + "/sobjects/Account", headers=headers,
json={"Name": "Acme Corp"}, timeout=30)
calls += 1
resp.raise_for_status()
account_id = resp.json()["id"]
# Call 2: create the Contact, which needs the Account ID from call 1
resp = requests.post(api + "/sobjects/Contact", headers=headers,
json={"LastName": "Rivera", "AccountId": account_id},
timeout=30)
calls += 1
resp.raise_for_status()
contact_id = resp.json()["id"]
# Call 3: read the Contact back
resp = requests.get(api + "/sobjects/Contact/" + contact_id, headers=headers,
params={"fields": "Id,LastName,AccountId"}, timeout=30)
calls += 1
resp.raise_for_status()
print(resp.json()["LastName"], "after", calls, "HTTP calls")This code works, but it has three problems.
- It makes three round trips.
- It uses three calls of API allocation.
- If call 2 fails, the Account from call 1 is already saved. Nothing in the code removes it.
The composite version
The Composite resource accepts an ordered list of subrequests in one POST. A subrequest is one operation inside the list, such as a create, an update, or a read. Salesforce runs the subrequests on the server in order and returns all the results in one response. Because the work happens on the server, a later subrequest can use values from an earlier one. The @{newAccount.id} reference below takes the new Account's ID without a trip through your client.
{
"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": { "LastName": "Rivera", "AccountId": "@{newAccount.id}" }
},
{
"method": "GET",
"url": "/services/data/v60.0/sobjects/Contact/@{newContact.id}?fields=Id,LastName,AccountId",
"referenceId": "readContact"
}
]
}Save this as composite.json and send it to the /composite endpoint.
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @composite.jsonThe three operations now cost one round trip and one API call. With allOrNone set to true, they also run as a single unit. If the Contact fails validation, Salesforce rolls back the Account too. The next chapters explain referenceId, allOrNone, and the response format in detail. For now, notice what changed. The client sends one document and gets one response.
The diagrams below compare the two exchanges.
What you gain
Fewer round trips
Total wait time is roughly the number of round trips multiplied by the latency per trip, plus server processing time. The numbers below are illustrative, not measurements. Suppose each round trip costs 120 ms of network time. Three sequential calls add about 360 ms of network time before server work. One composite call adds about 120 ms. The saving grows with the number of steps and with the distance between client and org. It matters most for mobile clients, remote integrations, and any process that runs the same multi-step sequence many times.
Lower API usage
A composite request counts as one call toward your org's API request limits, however many subrequests it holds. A workflow of ten subrequests that used to cost ten calls now costs one. Check your org's current allocation in Salesforce Setup, because limits depend on edition and license.
Server-side dependencies
Without Composite, the client sits in the middle of every dependency. It receives an ID, extracts it, and puts it into the next request. With reference IDs, that logic moves into the request, which removes client code and removes the delay between steps.
Optional transactional behavior
With allOrNone set to true, the subrequests succeed or fail together. This is the only way in the standard REST API to get an "all or nothing" result across different objects in one call. Without it, you would need to write compensating logic. That means deleting the Account yourself after the Contact fails, and handling the case where the delete fails as well.
What you do not gain
Combining requests removes network overhead. It does not remove the work of the operations themselves.
- Each subrequest still runs validation rules, triggers, flows, and duplicate rules. A composite request with 25 subrequests can fire 25 sets of automation.
- Each subrequest is still checked against the running user's object and field permissions.
- The outer HTTP status does not tell you whether the subrequests worked. The call can return
200while a subrequest inside returns400. You must read each result. The Python snippet below shows the pattern, and later chapters cover it in depth. - Composite resources have limits, including a cap on the number of subrequests per call. Large jobs still need to be split up or sent through the Bulk API. The limits chapter covers the exact numbers.
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"},
}
],
}
resp = requests.post(base + "/services/data/v60.0/composite",
headers=headers, json=payload, timeout=30)
resp.raise_for_status()
for sub in resp.json()["compositeResponse"]:
print(sub["referenceId"], sub["httpStatusCode"])Common mistakes
- Treating a
200as success. The outer status says Salesforce processed the envelope. CheckhttpStatusCodefor each entry incompositeResponse. - Combining everything by default. A composite request that mixes unrelated work is harder to debug. One failure can roll back work you wanted to keep when
allOrNoneistrue. - Expecting automation to be cheaper. The saving comes from the network and the API count. Triggers and flows still run for every subrequest.
- Ignoring the order. Subrequests run in the order you list them. A reference to a
referenceIdthat appears later in the list cannot work.
When combining is worth it
Combine requests when one of these is true.
- A step needs a value produced by an earlier step, such as a new record's ID.
- Several writes must stand or fall together.
- You make many small calls in a short time and your API usage or latency is a concern.
Stay with single calls when the operations are unrelated, when each one needs its own error handling and retry, or when a single operation is large enough to need the Bulk API instead.
| Concern | Separate calls | One composite call |
|---|---|---|
| Round trips | One per operation | One |
| API call count | One per operation | One |
| Passing IDs between steps | Client code | Reference in the request |
| Rollback across steps | Manual cleanup | Automatic with `allOrNone: true` |
| Checking the result | One status per call | One status per subrequest, inside the body |
Exercise
Your integration creates an Account, then a Contact for that Account, then an Opportunity for the same Account. It currently makes three separate REST calls and sometimes leaves an Account with no Contact when the second call fails. Name two benefits of moving to one composite request, and one thing it will not change.
Show answer
The first benefit is fewer round trips and fewer API calls: the three operations cost one of each instead of three. The second benefit is rollback control. With allOrNone set to true, a failed Contact creation rolls back the Account, so no orphan is left. The Account ID is passed to the later subrequests by reference, so the client no longer parses it. It will not change the automation cost: validation rules, triggers, and flows still run once for each subrequest.
Exercise
A composite request returns HTTP 200. Your code reports "all records saved". Why is this unsafe, and what should the code check instead?
Show answer
The 200 only means Salesforce accepted and processed the composite envelope. Individual subrequests can still fail, for example with a 400 on a validation error. The code should loop over each entry in compositeResponse and check its httpStatusCode and body, using referenceId to identify which subrequest each result belongs to.