Sub topic 7
Reading usage from the REST Limits resource
This chapter assumes you can send authenticated HTTP requests to the Salesforce REST API, that you have an access token and instance URL from an OAuth flow, and that you can read short Python and shell scripts. You should already know the difference between daily API request limits, concurrent request limits, and Apex governor limits from earlier chapters.
The REST Limits resource is the most direct way to ask an org how much of each limit it has used. One GET request returns a JSON document with a maximum and a remaining value for dozens of limits. It is the foundation for dashboards, health checks, and the alerts built later in this tutorial.
What the resource returns
The endpoint is /services/data/vXX.X/limits, relative to your instance URL. A GET with no parameters returns a JSON object. Each key is a limit name, and each value is an object with two numbers:
Maxis the allocation for the limit.Remainingis how much is left right now.
Usage is Max - Remaining. The resource does not return a "used" field, so you always compute it yourself.
Here is the request from the Topic Spine:
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/limits"
# The response is a JSON object keyed by limit name. For example:
# { "DailyApiRequests": { "Max": 15000, "Remaining": 14980 }, ... }The numbers above are illustrative. Your org's Max depends on its edition, license count, and purchased add-ons.
Common keys
The exact set of keys varies by API version and org. The table lists a few you will meet often.
| Key | What it measures |
|---|---|
| `DailyApiRequests` | API calls in the rolling 24-hour window |
| `DailyBulkApiBatches` | Bulk API batches in the rolling 24-hour window |
| `DailyAsyncApexExecutions` | Asynchronous Apex executions in 24 hours |
| `ConcurrentAsyncGetReportInstances` | Concurrent requests for asynchronous report results |
| `DataStorageMB` | Data storage, in megabytes |
| `FileStorageMB` | File storage, in megabytes |
| `SingleEmail` | Single emails sent through the API and Apex |
Do not hard-code an assumption that a key exists. Newer API versions add keys, and some features (such as Streaming API limits) appear only when the org has access to them. Read the keys you need with a default, and log a warning when one is missing.
Rolling windows
DailyApiRequests is a rolling 24-hour limit. It is not a counter that resets at midnight. Calls made 23 hours ago still count against you, and they stop counting only when they age out of the window. A burst at 09:00 therefore keeps Remaining low until about 09:00 the next day, even if nothing else runs in between.
This changes how you read the numbers. A drop in Remaining that looks sudden usually reflects a recent burst, not a slow leak. A recovery that looks slow reflects the window, not a fault.
Authentication and permissions
The request needs a valid access token in the Authorization header. The user behind the token also needs the API Enabled permission. Without it, the call fails even though the endpoint itself is read-only.
Two failures are common:
- 401 with
INVALID_SESSION_ID. The token is expired or was revoked. Refresh it and retry once. - 403. The user lacks API access, or the connected app's policies block the token.
Choose the identity for monitoring on purpose. A monitoring job that runs as a named employee breaks when that person leaves. Prefer a dedicated integration user with the narrowest permissions that still allow API access.
Calculating percentage used in Python
The next script gets the resource, computes the percentage of the daily limit used, and prints it. It is a more defensive version of the Topic Spine example. It reads the usage header with a regular expression, which avoids a parsing bug explained in the next section.
import os
import re
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
# Matches "api-usage=25/15000" but not "per-app-api-usage=17/250".
ORG_USAGE = re.compile(r"(?<![\w-])api-usage=(\d+)/(\d+)")
def get_limits():
resp = requests.get(
f"{instance_url}/services/data/v60.0/limits",
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
resp.raise_for_status()
return resp
def percent_used(limits, name):
entry = limits.get(name)
if entry is None or not entry.get("Max"):
return None
used = entry["Max"] - entry["Remaining"]
return used, entry["Max"], 100 * used / entry["Max"]
resp = get_limits()
result = percent_used(resp.json(), "DailyApiRequests")
if result is None:
print("DailyApiRequests not present in the response")
else:
used, maximum, percent = result
print(f"Daily API requests used: {used}/{maximum} ({percent:.1f}%)")
header = resp.headers.get("Sforce-Limit-Info", "")
match = ORG_USAGE.search(header)
if match:
print(f"From header: {match.group(1)} of {match.group(2)}")Several details are worth noting:
raise_for_status()turns a 4xx or 5xx response into an exception, so a failed call cannot be mistaken for "zero usage".percent_usedreturnsNonewhen the key is missing orMaxis zero. This prevents a divide-by-zero on limits that an org does not have.- The
timeoutis required in practice. Without it, a stalled connection can hang a scheduled monitor forever.
The usage header on the same response
Every REST API response carries a Sforce-Limit-Info header, including the response from the Limits resource. Its format is:
Sforce-Limit-Info: api-usage=25/15000The first number is the calls used and the second is the daily maximum. The next chapter covers this header in depth. For now, you need one gotcha that affects code in this chapter.
When a request comes from a connected app that has its own per-app limit, the header can carry a second section:
Sforce-Limit-Info: api-usage=25/15000; per-app-api-usage=17/250(appName=MyConnectedApp)Naive parsing breaks here. Two things go wrong:
"per-app-api-usage="contains the text"api-usage=", so a plain substring search can match the wrong section.- Splitting the text after the first
api-usage=on/produces a second piece such as15000; per-app-api-usage=17, which is not a number.
The regular expression in the script uses a lookbehind, (?<![\w-]), so that api-usage= matches only when no letter, digit, underscore, or hyphen precedes it. It captures the digits explicitly, so trailing text is ignored.
The header and the resource are two views of the same counter, but they are not identical in cost. The header arrives free with whatever call you were already making. The resource costs an extra request but returns every limit, not only the daily API count. A good design uses both: read the header on every call for near-real-time tracking, and call the resource on a schedule for the full picture.
Sequence of a monitoring poll
Edge cases and pitfalls
Values are a snapshot. Remaining reflects the moment of the call. Other integrations may consume calls in the seconds after. Do not use a reading as a guarantee that a batch of 5,000 calls will succeed. Use a margin.
Counts can lag. Usage figures may trail real activity slightly. Alert on trends and thresholds with headroom, not on exact equality.
The limit is shared across the org. One noisy integration can drain DailyApiRequests for every other integration in the org. The Limits resource tells you the org total, not who consumed it. To find the consumer, use the Setup pages and the ApiTotalUsage event logs covered in later chapters.
Missing or zero Max. Some limits report Max of 0 when a feature is not provisioned. Guard your division, as the script does.
API version drift. The path includes a version such as v60.0. Pin a version in your config and upgrade it deliberately. A new version can add keys, and an old one can omit them.
Do not poll from many places. If five services each poll the resource every minute, you spend 7,200 calls a day on monitoring alone, which is half of a 15,000 call allocation. Run one monitor and share its results.
Estimating time to exhaustion
With two readings, you can estimate how long the current rate can continue. The shell sketch below uses jq to read Remaining and shows the arithmetic. It assumes jq is installed.
remaining=$(curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/limits" \
| jq '.DailyApiRequests.Remaining')
echo "Remaining daily API requests: $remaining"Run it twice, an hour apart. If Remaining fell from 12,000 to 11,000, the burn rate is 1,000 per hour, and 11,000 remaining calls last about 11 hours at that rate. Because the window is rolling, older calls will also age out, so this estimate is conservative. It is still a useful early warning.
Summary of what to remember
- One GET returns
MaxandRemainingfor each limit. You compute usage yourself. DailyApiRequestsis a rolling 24-hour window, so recovery is gradual.- The call needs API Enabled permission and a valid token, and it uses API capacity itself.
- Parse the header with a pattern that does not confuse
api-usagewithper-app-api-usage. - The resource shows totals for the org, not which user or app caused them.
Exercise
Your monitor reads the Limits resource and gets "DailyApiRequests": { "Max": 15000, "Remaining": 3000 }. What percentage of the daily limit has been used, and why might Remaining still be low at 09:00 even though your integrations were idle all morning?
Show answer
Used is 15000 - 3000 = 12000, which is 100 * 12000 / 15000 = 80%. The limit is a rolling 24-hour window, not a midnight reset, so calls made the previous afternoon or evening still count until they are 24 hours old. Idle hours in the morning do not restore capacity until those earlier calls age out of the window.
Exercise
A colleague parses Sforce-Limit-Info with header.split("api-usage=")[1].split("/")[:2]. The header is api-usage=25/15000; per-app-api-usage=17/250(appName=MyConnectedApp). What does the code return for the maximum, and how would you fix it?
Show answer
Splitting on "api-usage=" gives the text after the first occurrence, 25/15000; per-app-api-usage=17/250(appName=MyConnectedApp). Splitting that on "/" and taking the first two pieces gives 25 and 15000; per-app-api-usage=17, so the "maximum" is not a number and converting it to an integer fails. Fix it with a regular expression such as (?<![\w-])api-usage=(\d+)/(\d+), which matches only the org-wide section and captures just the digits.