cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Databricks Free Edition Help
Engage in discussions about the Databricks Free Edition within the Databricks Community. Share insights, tips, and best practices for getting started, troubleshooting issues, and maximizing the value of your trial experience to explore Databricks' capabilities effectively.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Issues making requests to Databricks from AWS Lambda

Sunioj
New Contributor

Hello,
I am getting acquainted with Databricks, of which I have signed up for a free account. 
I have a Lambda function using Python 3.14 and the databricks-sql-connector library that runs on a schedule, to take data from a file in S3 and put the differential data into a workspace in Databricks. There are two errors that I am having:

1.  RequestError: Error during request to server: BAD_REQUEST: Cannot create the resource, please try again later.

Here is a snippet:

from databricks import sql

conn = sql.connect(server_hostname=databricks_host,
                    http_path="/sql/1.0/warehouses/%s" % warehouse,
                    access_token=databricks_token,
            ) 

This code works fine locally, but in AWS lambda seems to fail randomly without much explanation. I tried to consult with Genie, other LLMs, Google, etc. to figure out the issue. Genie recommended that I implement a retry loop, but I am not sure if that makes sense since subsequent invocations of the code also had the same error. 

Instead, I implemented that Lambda makes a REST API call to Databricks before the "connection" takes place. It seemed to work for a bit, then I started getting the next error:

2. requests.exceptions.HTTPError: 400 Client Error: Bad Request for url:
Snippet: 

response = requests.post(
            "%s/api/2.0/sql/warehouses/%s/start" % (databricks_host,warehouse),
            headers={
                "Authorization": "Bearer %s" % databricks_token
            }
        )
        
response.raise_for_status()

AWS logs shows the URL which the request failed with, and that URL when consulting with Genie also seems fine. This code also works just fine locally as well.

I tried to search within this forum to see similar issues, but did not find any. If anyone could help it would be appreciated.


3 REPLIES 3

Yougasundar
Contributor

Hi @Sunioj ,

Both errors most likely mean that the SQL warehouse could not start at that moment, so the first step is to read the real error text. requests.raise_for_status() hides the response body, so log response.status_code and response.text before you raise; the JSON body has an error_code and a message that say why the start was refused. Free Edition has fixed limits that matter here: one SQL warehouse, limited to 2X-Small, and a fair usage quota. The Free Edition limitations page says that if you exceed your quota, "your workspace's compute resources will be shut down and unavailable for the rest of the day". A scheduled Lambda that wakes the warehouse many times a day can reach that limit, and then both the connect and the start call fail until the quota resets. That can look random, and it can also explain why a test from your laptop at another time works. To check, open SQL Warehouses in the workspace when the Lambda fails, look at the warehouse state, and note the time of day of the failures. A retry with a growing wait (for example 30 seconds, 2 minutes, 5 minutes) is fine for a short start-up problem, but it will not help when the quota is used up, so run the Lambda less often or load more data per run. Also note that Free Edition has no SLA or support, so a paid workspace is the safer place for a production schedule.

 

Docs: https://docs.databricks.com/aws/en/getting-started/free-edition-limitations

ShamenParis
Honored Contributor

Hi @Sunioj ,

Both of your errors are caused by Databricks Free Edition compute limits and how databricks-sql-connector handles warehouse startups:

  • Error 1 (BAD_REQUEST: Cannot create the resource): Free Edition accounts only get one 2X-Small Serverless SQL Warehouse with a strict daily compute quota (and no capacity SLA). Because your AWS Lambda runs on a schedule, repeatedly waking or running the warehouse exhausts your daily free compute limit. Once that quota is reached (or when the shared free-tier pool is busy), Databricks blocks the warehouse from starting for the rest of the dayโ€”which is why retries also fail.

  • Why it works locally: When you test locally, you are usually running while you still have daily quota left or while the warehouse is already RUNNING in your browser.

  • Error 2 (400 Bad Request on /start): First, you don't need this API callโ€”sql.connect() automatically wakes up a stopped SQL Warehouse. Second, response.raise_for_status() hides the real Databricks error message. Calling /start returns a 400 either because your daily Free Edition quota is exhausted (you can verify this by printing response.text), or because databricks_host is missing https:// (sql.connect expects a bare hostname, while requests.post requires https://).

How to fix it:

  • Remove the /start API call: Let sql.connect() start the warehouse automatically, set your Lambda timeout to at least 60โ€“120 seconds for cold starts, and use a with sql.connect(...) as conn: block so connections close properly.

  • Reduce your schedule frequency: Set your SQL Warehouse Auto Stop to the minimum (5โ€“10 minutes) in the UI and run your Lambda less frequently (e.g., hourly or once a day) so you don't burn through your daily Free Edition quota.

  • Pull from S3 instead of pushing from Lambda: Instead of waking up the warehouse from Lambda for small inserts, consider using a scheduled Databricks Job with Auto Loader or COPY INTO to pull new files directly from S3 in batchesโ€”it uses a fraction of the compute time.

 

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