Sub topic 8
Tracking usage with the Sforce-Limit-Info header
This chapter assumes you can make authenticated HTTP requests to the Salesforce REST API and that you know what the daily API request limit is. It covers how to read usage from the Sforce-Limit-Info response header, so you can track consumption without making extra calls.
What the header is
Salesforce adds a Sforce-Limit-Info header to API responses. It reports how many daily API requests your org has used and the daily maximum. A typical value looks like this:
Sforce-Limit-Info: api-usage=25/15000The first number is the requests used in the current 24-hour rolling window. The second is the org's maximum. The numbers here are illustrative.
Why use it instead of the Limits resource
The REST Limits resource returns the same figures, but every call to it is itself an API request. The header comes back on responses you are already making, so it costs nothing extra.
| Approach | Extra API call | Detail returned | Best for |
|---|---|---|---|
| Limits resource | Yes | All org limits | Periodic checks, dashboards |
| Sforce-Limit-Info header | No | Daily API usage only | Tracking on every call |
Use the header for continuous tracking. Use the Limits resource when you need other limits as well.
Parsing the header
The format is api-usage=used/max. Some responses can include extra parts, such as per-app-api-usage, separated by a semicolon and a space. Parse defensively and look for the api-usage= part.
import os
import re
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
def parse_limit_info(header_value):
"""Return (used, maximum) from a Sforce-Limit-Info value, or None."""
match = re.search(r"(?<![\w-])api-usage=(\d+)/(\d+)", header_value or "")
if not match:
return None
return int(match.group(1)), int(match.group(2))
resp = requests.get(
f"{instance_url}/services/data/v60.0/query",
params={"q": "SELECT Id FROM Account LIMIT 1"},
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
resp.raise_for_status()
usage = parse_limit_info(resp.headers.get("Sforce-Limit-Info"))
if usage:
used, maximum = usage
print(f"Daily API requests: {used}/{maximum} ({100 * used / maximum:.1f}%)")
else:
print("No api-usage value in this response")The regular expression uses a lookbehind so that it matches api-usage= but not per-app-api-usage=.
Common errors
- Assuming the header is always present. Not every response carries it. Treat a missing header as "no new information" and keep your last known value.
- Splitting on the wrong character. If you split the whole value on
/, extra parts break the result. Matchapi-usage=first. - Treating the value as exact. Other clients in the same org use the same limit. Your last reading can be out of date by the time you act on it.
- Checking only at the start. A job that reads usage once at startup will not notice that it is consuming the limit as it runs. Update the counter on every response.
Using the value in an integration
A simple pattern is to wrap your HTTP calls so that each response updates a shared value, then compare it to thresholds before sending more work.
class UsageTracker:
def __init__(self, warn_at=0.8, stop_at=0.95):
self.used = None
self.maximum = None
self.warn_at = warn_at
self.stop_at = stop_at
def update(self, response):
usage = parse_limit_info(response.headers.get("Sforce-Limit-Info"))
if usage:
self.used, self.maximum = usage
def status(self):
if self.used is None:
return "unknown"
ratio = self.used / self.maximum
if ratio >= self.stop_at:
return "stop"
if ratio >= self.warn_at:
return "warn"
return "ok"Call tracker.update(resp) after each request and check tracker.status() before the next batch. The thresholds are examples. Choose values that match how much headroom your org needs. Designing alerts around them is covered in a later chapter.
Exercise
A response contains the header value api-usage=12000/15000. What percentage of the daily limit has been used, and which status would the UsageTracker above report with its default thresholds?
Show answer
12000 / 15000 is 80%. The ratio equals the default warn_at of 0.8 and is below stop_at of 0.95, so status() returns "warn".
Exercise
Why is reading the header preferable to calling the Limits resource before every request in a high-volume integration?
Show answer
Each Limits resource call counts as an API request, so polling it before every request would add to the consumption you are trying to measure. The header arrives on responses you already make and costs no extra requests.