---
title: "Stream large SQL results from a Retool backend function"
description: "Why does a 19 MB query result exceed a 192 MiB memory limit? Each MiB returned cost about 3 MiB of budget. Return the SQL stream instead"
canonical: "https://stackdrop.co/blog/stream-large-sql-results-backend-function"
published: "2026-11-24T18:12:28.377Z"
updated: "2026-11-24T18:48:25.401Z"
authors: ["Arsany Milad"]
topics: ["Retool", "Data foundations"]
readers: ["builders"]
---

# Stream large SQL results from a Retool backend function

_A Databricks result that ran out of memory in a backend function, what we measured, and the one-line change._

A Databricks query returning about 19 MB of rows failed twice in a React app on Retool: first on the timeout, then on memory. The query itself was sound. What failed was returning the full result from the backend function, and returning the SQL stream instead let the same query complete. Here is what broke, what we measured, and the lines you can copy.

One note before the numbers. Everything below comes from our own tests in one environment, and none of it is a platform specification. Thresholds moved by a few MiB between identical runs, so read every figure as approximate.

## **The timeout came first**

The page did not load because the function timed out. A backend function raises its own timeout by exporting a config from the file that defines it:

```
export const retoolConfig = { timeoutSeconds: 300 }
```

With 300 seconds available, the query ran long enough to reach the second failure: `Code exceeded the 192MiB memory limit`.

## **A lighter query did not fix it**

We added partition filters and filtered joins, which reduced what Databricks scanned and returned. The memory error stayed.

So we ran the same query and returned only the row count. It completed in 11.9 seconds. The query could execute inside the function. Handing back a large result was the step that failed.

## **How 19 MB outgrows 192 MiB**

Each backend function call ran as its own Node.js process, capped at 192 MiB of heap. Our out-of-memory stack traces ended in Node's own startup frames, so nothing carried over between calls. The return value cannot leave that process by reference: it is serialized out while the original is still alive.

Three measurements explain the gap:

- **Headroom is about 140 MiB, not 192.** An otherwise empty function could retain about 140 MiB of strings before it stopped. The runtime uses part of the budget before application code starts.
- **Returning costs memory.** Each MiB of string returned cost about 3 MiB of budget, plus a fixed 11 MiB, on top of whatever else is still held.
- **Mapping makes the return bigger.** The mapped rows came to 19.2 MB of JSON, against 16.7 MB for the raw rows.

That gives a rough rule for when a call stops (a heuristic, not an accounting formula):

```
held memory + 3 × returned size + 11 MiB > available headroom
```

We checked this with the real 19 MB query and the original row mapping, 11 runs per variant:

- **Hold the raw and mapped rows, return only a count:** passed 11 of 11.
- **Return the raw rows without mapping (16.7 MB):** passed 10 of 11.
- **Return the mapped rows (19.2 MB of JSON):** failed 11 of 11.

The mapped rows reuse the raw rows' strings, so holding both is cheap. Returning the bigger mapped set is what goes past 140 MiB.

Our return cost comes from plain strings. Row objects may cost more, and we did not measure them directly.

One aside on units: the documentation we read says 200 MB and the error says 192 MiB. They are the same budget. 192 MiB is about 201 MB in decimal units.

## **The fix: return the stream**

The Retool CLI generates TypeScript types for each connection at backend/resources/sql/\_types.d.ts. On every SQL resource we inspected, Databricks included, those types list a method called `queryStreamRaw`.

Instead of loading the rows into the function and returning them, return the stream:

```
return databricks.queryStreamRaw(sql)
```

Retool consumed the stream into rows on the page, and the memory failure went away. The backend code never holds the full result.

Databricks also streamed in a compact column format. The same result went from 16.7 MB of JSON to 6.26 MB on the wire.

What we saw after the change:

- **The 19 MB result:** streamed in 12.75 to 23.5 seconds across runs. The same query had run out of memory before.
- **A 50 MB result:** 40,218 rows (49.5 MB of JSON) in about 61 seconds, with no memory error.
- **Stress test:** 120,000 synthetic rows completed in 186 seconds. At 250,000 rows the run stopped at 475 seconds, likely a time limit rather than memory.

## **What the stream asks of you**

- **Transform elsewhere.** The function passes the stream through, so it cannot map the full row set. Move that work into SQL or the frontend.
- **Return it untouched.** When we wrapped the stream in a custom loop, the page received raw bytes instead of parsed rows.
- **Check your own types first.** `queryStreamRaw` was in the generated types and not in the public documentation when we tested. Confirm it exists in your app, test it, and expect that its behavior may change.
- **SQL only.** We tested the SQL streaming path. REST calls and file reads are outside this finding.

We also wrapped stream startup in a small helper that retries temporary Databricks errors and logs every attempt. For a read-only query, a failure before any data is sent can be retried safely. Once delivery has started, the helper can log a broken stream but cannot restart a response that is already partly delivered.

## **How we measured**

The test environment exposed no memory reading: no usable `process.memoryUsage()` and no profiler. A function either ran or stopped at the limit. What made measurement possible is that Retool still returned the function's `console.log` lines after an out-of-memory stop, along with V8's last garbage collection lines.

The headroom probe retains strings in 1 MiB steps and logs after each one:

```
const keep = []
```

`for (let i = 1; ; i++) {`

`  keep.push(new TextDecoder().decode(new Uint8Array(1024 * 1024).fill(120)))`

`  console.log('hr ' + i)`

`}`

The last `hr N` before the stop is how much retained string data fit. Across 34 runs in an empty function it averaged 139.94 MiB, and no run went below 139. That is an allocation threshold, not a reading of free memory.

Holding a fixed amount and returning at once agreed: 140 MiB passed 32 of 32 runs and 142 MiB passed 0 of 25.

Two details change what the probe reports:

- **Lazy strings.** V8 can build `'x'.repeat(n)` lazily, so three nominal 100 MiB strings "fit" under a 192 MiB limit. `TextDecoder` produces flat strings.
- **Chunk size.** With 64 KiB chunks the probe reached only about 106 MiB. We kept 1 MiB chunks so the ruler stayed the same, and did not isolate the cause.

After a real query the probe got noisy: identical runs read anywhere from 30 to 107 MiB free. So we do not quote a memory size for the real rows.

For the return overhead, the function held a fixed amount of memory and returned a string. At each held amount we binary-searched the return size, then ran 30 or more trials around the edge. About 600 runs gave a fitted cost of 2.88 MiB per MiB returned (95% confidence interval 2.80 to 3.00).

For planning we use the size that passed 95% of the time: `held + 3 × returned ≤ 115 MiB`. Rate-limited runs were dropped, not counted as failures.

Two observations from those runs are worth keeping:

- **Delivery can fail after the function finishes.** A nominal 40 MiB return failed after about 34 MB had already reached the browser.
- **Releasing data first can help.** Holding 90 MiB and returning 20 MiB passed 2 of 30 runs. Setting the held data to `null` first passed 25 of 30. On the real query it did not help, because the mapped rows shared the raw rows' strings.

We then checked the behavior in the app itself. A test page with 41 presets called the same function, and its boundaries matched the Resource Explore runs within the noise.

Three simultaneous calls, each holding 100 MiB, all passed. That is consistent with a separate budget for each invocation. Helper functions inside one call shared that call's budget.

These probes stop the function on purpose. Do not run them in production.

## **The lines to copy**

For a long query, raise the function timeout:

```
export const retoolConfig = { timeoutSeconds: 300 }
```

For a large SQL result, return the stream if your generated types expose it:

```
return databricks.queryStreamRaw(sql)
```

For anything you still return in full, keep `held + 3 × returned` under 115 MiB. Row objects may cost more than strings, so leave extra room. Measure in your own environment before you rely on it.
