Sub topic 4
Concurrent long-running requests
What this limit controls
The daily API request limit counts how many calls you make in 24 hours. The concurrent request limit counts how many calls are running at the same moment. The two limits are independent. An org can be far below its daily total and still reject calls because too many slow requests overlap.
Salesforce applies this limit only to long-running requests. A request counts toward the limit while it runs, and only if it has been running for 20 seconds or longer. Fast requests never count. A burst of 200 calls that each finish in 300 ms does not touch this limit, however many of them overlap.
This chapter assumes you know the other two categories from earlier in the tutorial. It also assumes you can read a JSON error body and write a basic retry loop.
The numbers
Salesforce documents the ceiling by org type. The values below are the ones published at the time of writing, so check the current "API Request Limits and Allocations" page before you rely on them.
| Org type | Concurrent long-running API requests |
|---|---|
| Developer Edition and trial orgs | 5 |
| Production orgs | 25 |
| Sandboxes | 25 |
The limit is per org, not per user, per connected app, or per integration. Every integration, user session, and tool that targets the same org shares one pool. A nightly export from your data warehouse and an interactive Data Loader session compete for the same slots.
Because Developer Edition orgs allow only 5, code that works in a developer org can fail in production when it misbehaves differently. The reverse also happens. A load test in a Developer Edition org may hit the ceiling at a fifth of the concurrency that production would tolerate.
What counts as long-running
A request becomes long-running once its elapsed time reaches 20 seconds. Salesforce does not know in advance that a request will be slow. A request is counted from the moment it crosses the threshold until it finishes.
Typical causes of slow API requests are:
- SOQL queries with non-selective filters on large objects, so the query scans many rows.
- Queries that return large result pages with many fields or relationship subqueries.
- Record saves that fire heavy triggers, flows, or sharing recalculations.
- Callouts from Apex to a slow external system, made inside a synchronous operation your API call triggered.
- Row-lock waits when many requests update the same parent record or hit the same lookup.
The last cause is the one that surprises people. A request that is fast when it runs alone can wait on a record lock held by another request. Waiting makes it long-running. Then more requests queue behind it, and the number of slow requests grows quickly.
Apex has a related limit of its own. Salesforce limits the number of synchronous Apex executions that run longer than 5 seconds at one time, with a documented ceiling of 10 per org. It is a separate pool from the API limit above, and it is measured per Apex execution rather than per API call. An API call that triggers slow Apex can touch both.
How the failure looks
When the org is already at its ceiling and your request crosses the 20-second mark, Salesforce rejects it. The HTTP status is 403, and the body is a JSON array:
[
{
"message": "ConcurrentPerOrgLongTxn Limit exceeded.",
"errorCode": "REQUEST_LIMIT_EXCEEDED"
}
]The errorCode is the same value you get when the daily limit runs out. The message is the part that tells them apart. A daily-limit failure reads TotalRequests Limit exceeded., and a concurrency failure names ConcurrentPerOrgLongTxn. Your retry logic must read the message, because the correct response is different for each:
- Daily limit exhausted: retrying in seconds will not help. The count recovers gradually as old requests leave the 24-hour window. Stop, alert, and wait.
- Concurrency limit hit: the condition is temporary. Slots free up as other slow requests finish, so a short delay and a retry usually works.
Mermaid diagrams must follow the stated fence format, so the diagram is given below.
Seeing it coming
The REST Limits resource, covered in a later chapter, reports the daily request counters and several report-related concurrency counters. For the long-running API request limit, the exact field set varies by release. Request /services/data/v60.0/limits from your own org and inspect the keys, rather than assuming a counter exists.
What you can rely on is indirect evidence:
- Error counts in your own logs. Count the
ConcurrentPerOrgLongTxnmessages your clients receive. A rising count is your leading indicator. - Request duration. Record the elapsed time of each call on the client. Calls approaching 20 seconds are the ones that occupy slots.
- Event Monitoring. Event log files, such as the REST API and Apex execution events, include run-time fields. Salesforce also provides a log event type for concurrent long-running Apex errors. These let you find which user, connected app, or query produced the slow requests. A later chapter covers
EventLogFilequeries.
Controlling your own concurrency
You cannot raise the org ceiling from the client side, but you can make sure that your own integration never uses more than its share. Three practices matter.
- Cap parallel workers. Pick a fixed pool size. Do not let an unbounded loop launch one thread per record. For a Developer Edition org, keep your whole integration well below 5 workers. For production, leave room for other tools and humans, so use a fraction of 25, not all of it.
- Retry only concurrency errors, with jittered backoff. Wait 1 s, 2 s, 4 s, and so on, and add random jitter so many workers do not all retry at the same instant.
- Shorten the slow requests. Add selective filters, request fewer fields, reduce page size, and avoid parallel updates to children of the same parent.
The Python example below combines the first two practices. It runs SOQL queries through a fixed worker pool and retries only on concurrency errors.
import os
import random
import time
from concurrent.futures import ThreadPoolExecutor
import requests
INSTANCE_URL = os.environ["INSTANCE_URL"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
API_VERSION = "v60.0"
MAX_WORKERS = 5 # stay well under the org ceiling
MAX_ATTEMPTS = 5
BASE_DELAY = 1.0 # seconds
class DailyLimitError(Exception):
"""The daily request allocation is exhausted; retrying will not help."""
def limit_message(resp):
"""Return the REQUEST_LIMIT_EXCEEDED message, or None for other responses."""
if resp.status_code != 403:
return None
try:
body = resp.json()
except ValueError:
return None
if not isinstance(body, list):
return None
for item in body:
if item.get("errorCode") == "REQUEST_LIMIT_EXCEEDED":
return item.get("message", "")
return None
def run_query(soql):
url = f"{INSTANCE_URL}/services/data/{API_VERSION}/query"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
for attempt in range(1, MAX_ATTEMPTS + 1):
resp = requests.get(url, headers=headers, params={"q": soql}, timeout=120)
message = limit_message(resp)
if message is None:
resp.raise_for_status()
return resp.json()["records"]
if "ConcurrentPerOrgLongTxn" not in message:
raise DailyLimitError(message)
if attempt == MAX_ATTEMPTS:
raise RuntimeError(f"Still over the concurrency limit after {attempt} tries")
delay = BASE_DELAY * (2 ** (attempt - 1)) + random.uniform(0, 1)
print(f"Concurrency limit hit, retrying in {delay:.1f}s (attempt {attempt})")
time.sleep(delay)
if __name__ == "__main__":
queries = [
"SELECT Id, Name FROM Account WHERE CreatedDate = LAST_N_DAYS:1",
"SELECT Id, Name FROM Contact WHERE CreatedDate = LAST_N_DAYS:1",
"SELECT Id, Name FROM Opportunity WHERE CreatedDate = LAST_N_DAYS:1",
]
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
for soql, records in zip(queries, pool.map(run_query, queries)):
print(f"{len(records)} rows for: {soql}")The timeout=120 is deliberate. A request that your client abandons may continue to run on the server, so a short client timeout followed by an immediate retry can add a second slow request while the first one still holds a slot. Set the timeout above the longest legitimate request, and prefer fixing the slow query.
Common mistakes
- Treating every
REQUEST_LIMIT_EXCEEDEDas the same error. Retrying a daily-limit failure in a tight loop wastes calls and delays recovery. Always branch on the message. - Retrying without backoff. Immediate retries add more slow requests while the org is already saturated, which prolongs the problem.
- Sizing the pool from a Developer Edition test. Concurrency behavior in a 5-slot org does not predict production, and the reverse is also true.
- Ignoring other consumers. Your integration may be careful while a report export, a Data Loader session, or a second integration fills the pool. Look at org-wide evidence, not only your own client.
- Parallelizing updates to the same parent record. This creates lock waits. Sort or group records so one worker handles all the children of a parent.
- Assuming a bigger batch is faster. Large batches are fewer calls, but each one runs longer and is more likely to cross 20 seconds. Tune the batch size by measuring elapsed time.
Choosing a response strategy
| Situation | Better response |
|---|---|
| Occasional concurrency errors, calls usually finish quickly | Jittered backoff and retry |
| Frequent errors from one integration | Lower its worker count, shorten its queries |
| Frequent errors with many different clients | Find the slow requests in Event Monitoring, then fix them at the source |
| Long-running exports or loads | Move to an asynchronous API, such as the Bulk API, so you do not hold a synchronous request open |
Exercise
Your integration runs 30 parallel workers against a production org. Calls start failing with HTTP 403 and the message "ConcurrentPerOrgLongTxn Limit exceeded." The daily API usage is only 20% consumed. Name two changes you would make and explain why raising the retry count alone is not enough.
Show answer
First, reduce the worker pool well below the org ceiling (25 in production), leaving room for other users and integrations. Second, shorten the slow requests, for example by making query filters selective, requesting fewer fields, or grouping updates by parent record to avoid lock waits. Raising the retry count alone only repeats calls into an already saturated pool, and with 30 workers retrying together it can keep the pool full. Add jittered exponential backoff to the retries, and retry only when the message names ConcurrentPerOrgLongTxn. Daily-limit errors should stop the job instead.
Exercise
A request returns HTTP 403 with errorCode REQUESTLIMITEXCEEDED and the message "TotalRequests Limit exceeded." Should your client retry after a few seconds? Why or why not?
Show answer
No. This message indicates that the daily API request allocation is exhausted, not that the concurrency pool is momentarily full. The allocation recovers gradually as old requests leave the rolling 24-hour window, so a retry after a few seconds will fail again and use more calls. The client should stop, raise an alert, and resume later.