Sub topic 5
Reducing round trips with Composite and Batch resources
This chapter assumes you can already authenticate with OAuth 2.0, call the REST API with an access token, and read SOQL. Here you will learn how to pack several REST operations into one HTTP request, and where each packing method stops helping.
Why round trips matter
Every REST call has a cost beyond the work Salesforce does on the record. Each call adds network latency and TLS overhead. Each call also counts against your org's 24-hour API request allocation, which later chapters cover in detail.
Suppose an integration creates an Account, then a Contact under it, then an Opportunity. Done naively, that is three sequential calls. The Contact call must wait for the Account Id. If each call takes 200 ms, you wait about 600 ms and spend three API requests.
Salesforce provides several REST resources that bundle work into one request:
| Resource | Path | What it does | Dependencies between steps |
|---|---|---|---|
| Composite | `/composite` | Up to 25 subrequests in one call | Yes, through reference IDs |
| Batch | `/composite/batch` | Up to 25 independent subrequests | No |
| Composite Graph | `/composite/graph` | Several independent graphs of subrequests | Yes, within each graph |
| sObject Collections | `/composite/sobjects` | Up to 200 records of create, update, or delete | No |
Check the current limits in the REST API Developer Guide for your API version. The numbers above are the documented values at the time of writing.
Composite: chained subrequests
The Composite resource accepts a compositeRequest array. Salesforce runs the subrequests in order, as one API call. Each subrequest has a method, a url, a referenceId, and optionally a body.
The referenceId is a label you choose. Later subrequests can read the earlier response through the syntax @{referenceId.field}. This removes the need to return to the client between steps.
This example creates an Account and a Contact that points to it. It is a body for POST /services/data/v60.0/composite.
{
"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": "Smith", "AccountId": "@{newAccount.id}" }
}
]
}Send it with curl. Save the JSON above as composite.json first.
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/composite" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @composite.jsonThe response contains a compositeResponse array. Each entry has the referenceId, an httpStatusCode, an httpHeaders object, and a body. The outer HTTP status is usually 200 even when a subrequest failed, so you must read each inner status.
The allOrNone flag
allOrNone controls what happens when a subrequest fails.
true: Salesforce rolls back every change from the call. Subrequests that ran before the failure are undone, and the remaining ones are not run. Each rolled-back subrequest reportsPROCESSING_HALTED.false(the default): Salesforce keeps the successful changes. A failed subrequest does not stop the later ones, unless a later one depends on it through a reference.
Use true when the records only make sense together, such as an Account and its required Contact. Use false when each subrequest stands alone and you prefer partial progress.
Reference rules and common mistakes
- A reference ID must be unique within the request.
- You can only refer to an earlier subrequest. Forward references fail.
- References work in URLs and in bodies. For example, a GET subrequest can use
@{newAccount.id}in its path. - If the referenced subrequest failed, the dependent one fails too. In
allOrNone: falsemode, you will see the dependent error in its own entry. - Reference JSON paths can reach into arrays, such as
@{queryResult.records[0].Id}.
Limits specific to Composite
- A request holds at most 25 subrequests.
- Only 5 of those can be query operations or sObject Collections calls.
- The whole request counts as one API call for the 24-hour allocation. Each subrequest still counts toward other limits, such as governor limits on triggers that fire.
- The subrequests run inside one transaction context only when
allOrNoneistrue. Triggers and flows still run per record, so complex automation can hit CPU or SOQL limits.
Batch: independent subrequests
The Batch resource at /composite/batch also takes up to 25 subrequests. It differs from Composite in three ways:
- Subrequests cannot reference each other.
- Each subrequest is its own transaction. There is no rollback across them.
- It supports a wider range of resources, including Limits and Chatter.
Batch is a good fit for dashboards or sync jobs that need several unrelated reads, such as an Account, a user's Limits, and a report summary, all in one call. Here is a request body.
{
"haltOnError": false,
"batchRequests": [
{ "method": "GET", "url": "v60.0/sobjects/Account/001000000000001AAA" },
{ "method": "GET", "url": "v60.0/limits" },
{ "method": "PATCH", "url": "v60.0/sobjects/Contact/003000000000001AAA",
"richInput": { "Title": "Director" } }
]
}Notice two details. URLs omit the /services/data/ prefix, and bodies go in richInput instead of body. The haltOnError flag stops processing after the first error when set to true.
sObject Collections: many records of one kind
When you need to create, update, or delete many records of the same object, sObject Collections is simpler. You send up to 200 records in one call.
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/composite/sobjects" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"allOrNone": false,
"records": [
{ "attributes": { "type": "Contact" }, "LastName": "Alpha" },
{ "attributes": { "type": "Contact" }, "LastName": "Beta" }
]
}'Every record needs an attributes.type value. The response is an array with one result per record, in the same order as the input, each with success, id, and errors. Always check each entry, because with allOrNone: false the call can return HTTP 200 while some records failed.
Composite Graph
Composite Graph handles larger workflows. You send several graphs, each with its own graphId and its own compositeRequest. Within a graph, subrequests can use references like regular Composite. Graphs are independent of one another, and a failure rolls back only its own graph. A request can hold up to 500 subrequests in total across graphs, though you should confirm the current cap in the documentation.
Use Graph when you need more than 25 dependent steps, or when you want several independent groups to succeed or fail on their own.
Choosing between the four resources
| Need | Best fit |
|---|---|
| Create a parent and children with dependent Ids | Composite |
| Run unrelated reads or small writes together | Batch |
| Insert, update, or delete up to 200 records of one object | sObject Collections |
| Large multi-step workflow with independent groups | Composite Graph |
| Thousands or millions of records | Bulk API 2.0, covered in a later chapter |
Error handling and practical advice
- Always inspect the inner status of each subrequest. Do not trust the outer HTTP 200.
- Log the
referenceIdwith each failure so you can tell which step broke. - Keep payload size in mind. Very large bodies still hit request size limits.
- Make retries safe. If the call times out, you do not know which subrequests ran. Use an External ID with upsert so a retry updates the same record instead of duplicating it.
- Do not assume ordering across Batch subrequests as a dependency. Use Composite if order matters.
Summary of trade-offs
- Composite saves round trips and gives you atomic behavior, but the 25-subrequest cap limits it.
- Batch is simple and flexible, but it has no dependencies and no shared transaction.
- sObject Collections is the shortest path for same-object bulk-ish work up to 200 records.
- Once volume passes a few thousand records, the Bulk API 2.0 becomes the better choice.
Exercise
You must create an Account, then two Contacts that link to it, and either all three records are saved or none is. Which resource and settings do you use, and how does a Contact refer to the Account?
Show answer
Use the Composite resource (POST /services/data/v60.0/composite) with allOrNone set to true. Give the Account subrequest a referenceId such as newAccount, then set AccountId to "@{newAccount.id}" in each Contact body. This uses 3 subrequests in one API call, and a failure in any of them rolls back all three.
Exercise
A Batch call returns HTTP 200, but one record was never updated. Where do you look, and why is the outer status misleading?
Show answer
Look at the per-subrequest results in the response, specifically the statusCode and result entries for the failed item. The outer 200 only says Salesforce processed the batch envelope. Each subrequest is its own transaction, so one can fail while the others succeed.