Sub topic 10
Pagination, error responses, and rate limits
This chapter assumes you can call a Databricks REST endpoint with a bearer token, as covered in the REST API basics and Jobs API chapters. It also assumes basic Python with the requests library. You will learn how to read a full list that spans several pages, how to interpret error responses, and how to retry safely when the server asks you to slow down.
Why single calls are not enough
A script that calls an endpoint once and trusts the result works in a demo and fails in production. Three things go wrong.
- A list endpoint returns only one page. If you have more jobs than the page size, you silently process a partial list.
- A request can fail for reasons you can fix (a typo in a parameter) or reasons that will pass (a brief service outage). The two need different handling.
- Many scripts sharing one workspace can exceed the request limits. The server then rejects calls until you back off.
Pagination
Most list endpoints return results in pages. The response contains the items for the current page plus information for fetching the next one. The Jobs API 2.1 jobs/list endpoint uses a token:
limitsets the page size. The maximum is 100 for jobs, and the default is smaller.page_tokenis the value you send to get the next page.- The response includes
has_moreandnext_page_token.
You keep requesting until next_page_token is absent or has_more is false. Treat the token as an opaque string. Do not parse it or build one yourself.
curl -sS -G "$DATABRICKS_HOST/api/2.1/jobs/list" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
--data-urlencode "limit=25" | jq '{count: (.jobs | length), has_more, next_page_token}'If next_page_token comes back non-empty, pass it as page_token in the next call. The -G flag makes curl send the data as query parameters on a GET request.
Some points to know:
- Endpoints differ. Older ones accept
offsetinstead of a token. Check the API reference for each endpoint, because the field names and maximum page sizes are not the same everywhere. - When there are no results, the list key (for example
jobs) can be missing from the response entirely. Read it with a default, such as.get("jobs", [])in Python. - The CLI commands such as
databricks jobs listfetch all pages for you. Thedatabricks apicommand sends exactly one request, so you handle the tokens yourself. - The SDK for Python returns an iterator that fetches pages as you loop, which is why
w.jobs.list()needs no loop logic.
Error responses
When a call fails, Databricks returns a non-2xx HTTP status and a JSON body with two fields:
{
"error_code": "RESOURCE_DOES_NOT_EXIST",
"message": "Job 999 does not exist."
}The status code tells you the category. The error_code tells you the specific cause. The message is for humans, so log it but do not match on its wording.
| Status | Typical `error_code` | Meaning | Retry? |
|---|---|---|---|
| 400 | `INVALID_PARAMETER_VALUE` | The request is malformed or a value is wrong | No, fix the request |
| 401 | `UNAUTHENTICATED` | Token missing, expired, or invalid | No, refresh credentials |
| 403 | `PERMISSION_DENIED` | The identity lacks the needed permission | No, change permissions |
| 404 | `RESOURCE_DOES_NOT_EXIST` | The job, run, or path is not there | No, check the ID |
| 429 | `TOO_MANY_REQUESTS` or `REQUEST_LIMIT_EXCEEDED` | Rate limit hit | Yes, after waiting |
| 500, 502, 503, 504 | `INTERNAL_ERROR`, `TEMPORARILY_UNAVAILABLE` | Server-side or transient failure | Yes, with backoff |
The exact error_code strings vary by endpoint, so branch on the status code first and use error_code for finer detail.
Two habits prevent most debugging pain:
- Call
raise_for_status()or checkresp.okon every response. Arequestscall that gets a 404 does not raise by itself, andresp.json()then returns the error body as if it were data. - Print the response body when you fail.
raise_for_status()shows only the status line, and themessagefield usually explains the problem.
200 does not mean the work succeeded
The Jobs API reports the outcome of a run separately from the success of the HTTP call. A runs/get call that returns 200 only means the API answered. Whether the run worked is in state.result_state, such as SUCCESS or FAILED. The polling example in the previous chapter reads that field for this reason.
Rate limits
Databricks limits how many requests an identity or workspace can send in a given time. The limits differ by endpoint and can change, so do not hard-code a number from a document. Treat a 429 response as the signal.
When you receive a 429:
- Stop sending requests on that path.
- Look for a
Retry-Afterheader. If present, wait that many seconds. - If the header is missing, wait using exponential backoff, which doubles the delay on each attempt (1, 2, 4, 8 seconds).
- Add random jitter, a small random amount on top of the delay. Without it, many clients that failed together retry together and fail again.
- Give up after a fixed number of attempts and raise the error.
Slow down on the happy path too. A polling loop that calls runs/get every second for hours wastes quota. The 15-second sleep in the earlier example is a reasonable default. Raise it for long jobs.
A reusable client
This script wraps retries and pagination in two small functions. It reads DATABRICKS_HOST and DATABRICKS_TOKEN from the environment.
import os
import random
import time
import requests
HOST = os.environ["DATABRICKS_HOST"].rstrip("/")
HEADERS = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
RETRYABLE = {429, 500, 502, 503, 504}
def call(method, path, max_attempts=5, **kwargs):
"""Send one request, retrying transient failures with backoff and jitter."""
for attempt in range(1, max_attempts + 1):
try:
resp = requests.request(
method, f"{HOST}{path}", headers=HEADERS, timeout=60, **kwargs
)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
time.sleep(2 ** (attempt - 1) + random.random())
continue
if resp.ok:
return resp.json()
if resp.status_code in RETRYABLE and attempt < max_attempts:
try:
delay = float(resp.headers["Retry-After"])
except (KeyError, ValueError):
delay = 2 ** (attempt - 1)
time.sleep(delay + random.random())
continue
# Not retryable, or out of attempts: show the API's own explanation.
raise RuntimeError(f"{resp.status_code} {resp.text}")
def list_jobs(page_size=25):
"""Yield every job, following next_page_token until it runs out."""
params = {"limit": page_size}
while True:
page = call("GET", "/api/2.1/jobs/list", params=params)
yield from page.get("jobs", [])
token = page.get("next_page_token")
if not token:
break
params["page_token"] = token
if __name__ == "__main__":
for job in list_jobs():
print(job["job_id"], job["settings"]["name"])Retrying is safe for GET requests because reading twice changes nothing. Retrying a POST such as jobs/run-now is riskier. If the first request reached the server but the response was lost, a retry could start a second run. The run-now endpoint accepts an idempotency_token, a string you choose. If you send the same token twice, Databricks returns the existing run instead of starting another. Generate the token once, before the retry loop, and reuse it on every attempt.
Edge cases
- A page can be shorter than
limitand still have anext_page_token. Always rely on the token, not on the item count. - Data can change between page requests. A job created while you page through the list may be missed or appear twice, so deduplicate by ID if exact counts matter.
- A token from one query is only valid with the same filters. Keep every other parameter the same across pages.
- A 401 in the middle of a long loop usually means an OAuth token expired. Fetch a new one and resume with the same
page_token, instead of starting over.
Exercise
A script calls GET /api/2.1/jobs/list with limit=100 and reports "87 jobs". The workspace has 140 jobs. The response had "has_more": true. What are two possible mistakes in the script, and how do you fix them?
Show answer
The script read only the first page and did not follow nextpagetoken, and it may have judged completeness by item count. Fix it by looping: pass the returned nextpagetoken as page_token on the next request, and stop only when no token is returned. A page can hold fewer items than limit while more pages remain, so the token is the reliable signal.
Exercise
Your script receives HTTP 429 with the header "Retry-After: 30" from jobs/run-now. Describe what it should do, and how it avoids starting two runs if the first request had actually succeeded.
Show answer
Wait at least 30 seconds, plus a little random jitter, then retry, giving up after a fixed number of attempts. To avoid duplicate runs, generate an idempotency_token once before the first attempt and send the same value on every retry. Databricks then returns the existing run for a repeated token instead of starting a new one.