Sub topic 8
Subrequest limits and constraints
This chapter covers the documented size limits of each Composite resource and the structural rules that cause a request to be rejected. It assumes you can already build a composite request with reference IDs, read a compositeResponse, and set allOrNone. You should also have an OAuth access token and instance URL. Limits change between API releases, so treat the numbers here as the values documented for the v60.0 era and confirm them in the current Salesforce REST API Developer Guide before you depend on them.
Why limits shape your design
A composite call is cheap in API usage. The whole HTTP request counts as one call against your org's API request limit, however many subrequests it holds. That makes it tempting to pack in as much as possible. The limits below stop you. The skill is to split work into valid requests, not to find ways around the caps.
Limits of the main Composite resource
The /composite endpoint has these constraints:
- A request holds at most 25 subrequests.
- Within those 25, at most 5 can be query subrequests (SOQL
queryorqueryAll) or sObject Collections subrequests. - Every
referenceIdmust be unique within the request. - A subrequest can only reference results from subrequests that appear earlier in the array.
- Each subrequest
urlmust be a relative path that starts with/services/data/and includes an API version.
The cap on queries and collections exists because those operations can touch many records. Twenty of your 25 slots can be single-record operations, such as creating, updating, or reading one record by ID. Only five can be the heavier kinds.
| Resource | Endpoint | Main limits |
|---|---|---|
| Composite | `/composite` | 25 subrequests, 5 of them queries or collections |
| Composite Batch | `/composite/batch` | 25 subrequests, no references between them |
| sObject Tree | `/composite/tree/{SObject}` | 200 records total, up to 5 record types, up to 5 levels deep |
| sObject Collections | `/composite/sobjects` | 200 records per create, update, upsert, or delete; up to 2,000 per retrieve |
| Composite Graph | `/composite/graph` | Up to 500 subrequests in total, split across graphs |
The Graph limit is the one most likely to have changed. Check it before you design a large graph.
Rules that are easy to break
Unique reference IDs
Two subrequests with the same referenceId make the request invalid. This usually happens when you generate subrequests in a loop and use a fixed name. Build the ID from the loop index instead.
Forward references
A reference like @{newAccount.id} only works if newAccount appears earlier in the compositeRequest array. The server does not reorder subrequests for you. If you put the Contact before the Account, the Contact fails because the reference cannot be resolved.
Dependent subrequests inherit failure
If a subrequest that others depend on fails, the dependent ones cannot resolve their references and fail too. With allOrNone set to false, you will see one real error followed by several errors about unresolved references. Fix the first error in the list. The later ones are usually side effects.
Relative URLs and versions
Composite subrequest URLs begin with /services/data/v60.0/.... Composite Batch URLs are different. They omit the leading path and start with the version, as in v60.0/sobjects/Account. Mixing the two styles is a common source of "not found" errors.
Body keys
Composite subrequests send data in body. Composite Batch subrequests send data in richInput. Sending body to the batch endpoint means your data is not read.
Limits that still apply inside the call
Combining requests does not turn off server-side logic. Each create or update subrequest still runs validation rules, triggers, flows, and duplicate rules, as it would for a single call. With allOrNone set to true, the subrequests share one transaction, so heavy automation across many subrequests adds up. A request that looks small can fail on a limit like DML statements or CPU time because automation on each record adds work. If you see a limit error that none of your subrequests would cause on its own, reduce the number of subrequests in that call.
Rolling back also costs something. When a late subrequest fails under allOrNone: true, every earlier subrequest is undone, and you pay for the work again when you retry.
Checking limits before you send
You can catch most limit problems on the client. The script below validates a composite payload against the documented subrequest rules, then splits a large list of Accounts into valid requests of at most 25 subrequests each.
import os
import re
import requests
MAX_SUBREQUESTS = 25
MAX_LIMITED = 5
API = "v60.0"
LIMITED = re.compile(r"/(query|queryAll)$|/composite/sobjects$")
def validate_composite(payload):
"""Return a list of problems found in a composite payload."""
problems = []
subs = payload["compositeRequest"]
if len(subs) > MAX_SUBREQUESTS:
problems.append(f"{len(subs)} subrequests, maximum is {MAX_SUBREQUESTS}")
seen = set()
limited = 0
for sub in subs:
ref = sub["referenceId"]
if ref in seen:
problems.append(f"duplicate referenceId: {ref}")
seen.add(ref)
path = sub["url"].split("?")[0]
if LIMITED.search(path):
limited += 1
if limited > MAX_LIMITED:
problems.append(f"{limited} query/collections subrequests, maximum is {MAX_LIMITED}")
return problems
def chunk_account_creates(names, size=MAX_SUBREQUESTS):
"""Yield composite payloads that each create up to `size` Accounts."""
for start in range(0, len(names), size):
group = names[start:start + size]
yield {
"allOrNone": False,
"compositeRequest": [
{
"method": "POST",
"url": f"/services/data/{API}/sobjects/Account",
"referenceId": f"acct{start + i}",
"body": {"Name": name},
}
for i, name in enumerate(group)
],
}
def send(payload):
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
resp = requests.post(
f"{base}/services/data/{API}/composite",
headers=headers,
json=payload,
timeout=30,
)
resp.raise_for_status()
return resp.json()["compositeResponse"]
if __name__ == "__main__":
names = [f"Chunked Account {n}" for n in range(60)]
for payload in chunk_account_creates(names):
problems = validate_composite(payload)
count = len(payload["compositeRequest"])
print(count, "subrequests;", problems or "valid")
if not problems and "INSTANCE_URL" in os.environ:
for sub in send(payload):
if sub["httpStatusCode"] >= 400:
print(sub["referenceId"], sub["httpStatusCode"])For 60 names, the script prints three payloads of 25, 25, and 10 subrequests. Each chunk is its own request, so a reference ID in one chunk cannot point to a result in another. Keep any chain of dependent subrequests inside a single chunk.
Here allOrNone is false because the Accounts are independent. With true, one bad name would roll back the other 24 in its chunk.
Deciding how to split work
The next diagram shows the questions to ask when a job is larger than one request allows.
Failure when you exceed a limit
Exceeding a structural limit is different from a subrequest failing. If you send 26 subrequests, or break a rule such as duplicate reference IDs, the server rejects the request as a whole and returns an error. No subrequest runs. If you send valid structure and one subrequest fails on a field validation, you get a normal compositeResponse with that subrequest's error and an outer HTTP 200.
Your client code should tell these cases apart:
- Check the outer HTTP status. A 400-level error with an error array means the request itself was invalid.
- If the outer status is 200, loop over
compositeResponseand check eachhttpStatusCode.
The script above does this with raise_for_status() followed by the per-subrequest loop.
Practical limits advice
- Leave headroom. Build to 20 or 23 subrequests rather than 25 if the request is generated dynamically, so one extra lookup does not break it.
- Count queries and collections as you build. Moving a lookup into your own cache is often cheaper than spending one of the five slots.
- Pick
allOrNoneby chunk, not globally. Usetruefor a chain that must stay consistent, andfalsefor independent records. - Prefer the specialized resource when it matches. For 150 independent Accounts, one Collections call is simpler than six Composite chunks.
- Log the
referenceIdwith every error. It is the only handle that ties a failure to the record you meant to write.
Exercise
You need to create 30 Accounts, each followed by one Contact that references its Account's ID. You also need 2 queries at the end. Can this fit in one composite request, and what would you do?
Show answer
No. That is 60 create subrequests plus 2 queries, well over the 25-subrequest cap. Split it into chunks that keep each Account and its Contact together, for example 12 pairs (24 subrequests) per request, and run the queries in a separate request or the last chunk if there is room. Because each Contact references its own Account, no chain crosses chunks. You could also use sObject Tree, which allows up to 200 records in one call with parent-child nesting, if the records fit its type and depth limits.
Exercise
A composite request has 8 subrequests, and 6 of them are SOQL queries. The server rejects it. Which rule was broken and how do you fix it?
Show answer
At most 5 of the subrequests can be queries or sObject Collections operations, and this request has 6. Move one query into a second composite request, or replace two queries with a single query that returns both result sets, such as a relationship query.