anuj_lathi
Databricks Employee
Databricks Employee

Short version: both errors look like the same problem, the SQL warehouse being in a state where it can't accept the request (starting, stopping, or unavailable), and raise_for_status() is hiding the real message. A retry alone won't fix it. You need to check the warehouse state and wait for it to be RUNNING before you connect.

What's likely happening

  • BAD_REQUEST: Cannot create the resource, please try again later is typically what the connector surfaces when it opens a session against a warehouse that is stopped, mid-start, or mid-stop. It works locally mostly because of timing: your local runs probably hit an already-running warehouse. Free Edition warehouses auto-stop quickly, so a scheduled Lambda will often hit a cold one.
  • The 400 on /start is most likely the same race. Calling start on a warehouse that is already STARTING or RUNNING, or one that is STOPPING, can be rejected. Because raise_for_status() throws away the response body, you only see "Bad Request". The JSON body has the actual reason.
  • Free Edition limits can cause persistent failures. It has a small compute allotment, a single small warehouse, and daily usage quotas. If the quota is exhausted, or the warehouse is being shut down or recycled, every invocation fails for a while. That would explain why subsequent invocations had the same error and why a retry loop with a 1–2 second delay didn't help. Check the warehouse and usage state in the workspace UI when it fails.

Step 1: Stop swallowing the error

r = requests.post(url, headers=headers, timeout=30)
if not r.ok:
    print(r.status_code, r.text)   # this is the real error message
    r.raise_for_status()

Post that body here if it still doesn't make sense. It will say whether it's a state conflict, a quota issue, or a permissions issue.

Step 2: Check state, start only if stopped, then wait

Don't blindly POST /start. Read the state first and poll until it's RUNNING:

import time, requests

def ensure_warehouse_running(host, warehouse_id, token, timeout_s=300):
    base = f"https://{host}/api/2.0/sql/warehouses/{warehouse_id}"
    h = {"Authorization": f"Bearer {token}"}
    deadline = time.time() + timeout_s

    while time.time() < deadline:
        r = requests.get(base, headers=h, timeout=30)
        if not r.ok:
            raise RuntimeError(f"GET warehouse failed: {r.status_code} {r.text}")
        state = r.json()["state"]   # STARTING, RUNNING, STOPPING, STOPPED, ...

        if state == "RUNNING":
            return
        if state == "STOPPED":
            s = requests.post(f"{base}/start", headers=h, timeout=30)
            if not s.ok:
                print("start failed:", s.status_code, s.text)
        # STARTING / STOPPING: just wait
        time.sleep(5)

    raise TimeoutError("Warehouse did not reach RUNNING in time")

Then call sql.connect(...). A retry with backoff does make sense here, but only around a state-aware check like this, not around a blind reconnect.

Step 3: Lambda-specific things to check

  • Lambda timeout: a cold warehouse can take a minute or more to start. Set the function timeout well above that. The default 3 seconds will fail in confusing ways.
  • Hostname format: sql.connect(server_hostname=...) wants the bare hostname with no https://. The REST calls need the full https:// URL. If you're reusing one variable for both, one of them is wrong.
  • Python 3.14: the connector pulls in compiled dependencies such as pyarrow, so make sure they're packaged for Lambda's architecture (x86_64 vs arm64) and your Python version. If the import works but behavior is odd, try a 3.12 or 3.13 runtime to rule it out.
  • Overlapping invocations: if the schedule fires while the previous run is still waiting on the warehouse, you can get concurrent start and connect attempts against a tiny warehouse. Set reserved concurrency to 1.

Step 4: Credentials

A bad or expired PAT would normally give you a 401/403, not a 400, so I don't think that's your issue. Still, for an unattended job the better long-term pattern is OAuth machine-to-machine with a service principal instead of a long-lived personal token [1]. Store the credentials in AWS Secrets Manager, not in plain Lambda environment variables.

If the response body from Step 1 mentions quota, limits, or "resource" availability, that's a Free Edition capacity issue. In that case, schedule the job less frequently or at a different time of day, and batch the work into fewer connections.

References

[1] Authorize access to Databricks resources | Databricks on AWS — https://docs.databricks.com/aws/en/dev-tools/auth

Anuj Lathi
Solutions Engineer @ Databricks