Resource limits
jed meters the execution cost of every query deterministically — the same query against the same database always costs the same, on every core. Cost ceilings bound metered work; a separate scalar allocation budget rejects large repeat/padding results and decimal scratch allocations before construction; an opt-in query-memory budget bounds retained rows, operator state, and pending writes; and an opt-in storage limit bounds committed in-memory pages or live file pages. These are independent limits, with the coverage described below.
Two ceilings
max_cost— per statement (54P01). A ceiling on a single statement: the instant a query’s accrued cost reaches it, execution aborts with54P01. This stops one runaway query — a cross join, a giantgenerate_series, an expensive expression over a huge input.lifetime_max_cost— per session (54P02). A budget on the whole session’s cumulative cost. The session holds a running total into which every statement accrues; the instant that total reaches the budget, the in-flight statement aborts with54P02. This stops a flood of cheap statements that each slip undermax_costbut together burn unbounded CPU.
Both default to 0 (unlimited). A statement aborts at whichever ceiling it reaches first.
use jed::{CreateOptions, Database, SessionOptions};
fn main() -> jed::Result<()> {
let db = Database::create(CreateOptions { path: Some("app.jed".into()), ..Default::default() })?;
// Serve untrusted queries through a session with independent work and memory limits:
// max_cost — a per-STATEMENT ceiling: one runaway query aborts 54P01.
// lifetime_max_cost — a per-SESSION budget: the session's cumulative cost is capped, so a
// flood of cheap queries can't burn unbounded CPU. It aborts 54P02.
let mut untrusted = db.session(SessionOptions {
max_scalar_bytes: 8 * 1024 * 1024, // covered scalar allocations; not total heap
max_query_memory_bytes: 64 * 1024 * 1024, // rows held at once (54P05); not total heap
max_cost: 10_000,
lifetime_max_cost: 3, // tiny, for illustration
..SessionOptions::default()
});
// Each statement accrues into the session's running total; read it with lifetime_cost().
untrusted.execute("SELECT 1", &[])?; // cost 1 — cumulative 1
untrusted.execute("SELECT 1", &[])?; // cost 1 — cumulative 2
// The third drives the cumulative to the budget — the in-flight statement aborts 54P02, and the
// partial cost still counts, so the session is now spent.
let denied = untrusted.execute("SELECT 1", &[]);
assert_eq!(denied.unwrap_err().code(), "54P02");
assert_eq!(untrusted.lifetime_cost(), 3);
// Once spent, every further statement is rejected at admission — the session is done.
let after = untrusted.execute("SELECT 1", &[]);
assert_eq!(after.unwrap_err().code(), "54P02");
untrusted.close();
Ok(())
}
package main
import (
"context"
"fmt"
"log"
jed "github.com/jackc/jed/impl/go"
)
func main() {
db, err := jed.CreateDatabase(jed.CreateOptions{Path: "app.jed"})
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
// Serve untrusted queries through a session with independent work and memory limits:
// MaxCost — a per-STATEMENT ceiling: one runaway query aborts 54P01.
// LifetimeMaxCost — a per-SESSION budget: the session's cumulative cost is capped, so a flood
// of cheap queries can't burn unbounded CPU. It aborts 54P02.
untrusted, err := db.Session(jed.SessionOptions{
MaxCost: 10000,
LifetimeMaxCost: 3,
MaxScalarBytes: 8 * 1024 * 1024, // covered scalar allocations; not total heap
MaxQueryMemoryBytes: 64 * 1024 * 1024, // rows held at once (54P05); not total heap
})
if err != nil {
log.Fatal(err)
}
defer untrusted.Close()
// Each statement accrues into the session's running total; read it with LifetimeCost().
untrusted.Exec(ctx, "SELECT 1") // cost 1 — cumulative 1
untrusted.Exec(ctx, "SELECT 1") // cost 1 — cumulative 2
// The third drives the cumulative to the budget — the in-flight statement aborts 54P02, and the
// partial cost still counts, so the session is now spent.
if _, err := untrusted.Exec(ctx, "SELECT 1"); err != nil {
fmt.Println("denied:", err.(*jed.EngineError).Code()) // 54P02
}
fmt.Println("spent:", untrusted.LifetimeCost()) // 3 — the budget
// Once spent, every further statement is rejected at admission — the session is done.
if _, err := untrusted.Exec(ctx, "SELECT 1"); err != nil {
fmt.Println("admission:", err.(*jed.EngineError).Code()) // 54P02
}
}
import { createDatabase, EngineError } from 'jed-ts';
const db = await createDatabase({ path: 'app.jed' });
try {
// Serve untrusted queries through a session with independent work and memory limits:
// maxCost — a per-STATEMENT ceiling: one runaway query aborts 54P01.
// lifetimeMaxCost — a per-SESSION budget: the session's cumulative cost is capped, so a flood of
// cheap queries can't burn unbounded CPU. It aborts 54P02.
const untrusted = await db.session({
maxCost: 10000n,
lifetimeMaxCost: 3n,
maxScalarBytes: 8n * 1024n * 1024n, // covered scalar allocations; not total heap
maxQueryMemoryBytes: 64n * 1024n * 1024n // rows and operator state (54P05); not total heap
});
try {
// Each statement accrues into the session's running total; read it with lifetimeCost().
await untrusted.execute('SELECT 1'); // cost 1 — cumulative 1
await untrusted.execute('SELECT 1'); // cost 1 — cumulative 2
// The third drives the cumulative to the budget — the in-flight statement aborts 54P02, and the
// partial cost still counts, so the session is now spent.
try {
await untrusted.execute('SELECT 1');
} catch (e) {
if (!(e instanceof EngineError) || e.code() !== '54P02') throw e;
console.log('denied:', e.code()); // 54P02
}
console.log('spent:', await untrusted.lifetimeCost()); // 3n — the budget
// Once spent, every further statement is rejected at admission — the session is done.
try {
await untrusted.execute('SELECT 1');
} catch (e) {
if (!(e instanceof EngineError) || e.code() !== '54P02') throw e;
console.log('admission:', e.code()); // 54P02
}
} finally {
await untrusted.close();
}
} finally {
await db.close();
}
How the budget behaves
- The partial cost of an aborted statement still counts. The work happened, so it is charged — reaching the budget genuinely spends it.
- Once spent, the session is done. Every further statement is rejected
54P02at admission, before it can run (so a missing-table query under an exhausted budget is54P02, not42P01). - The cumulative is session state, not data. It does not roll back when a transaction rolls back — the compute was spent regardless. Read it any time with the cumulative-cost gauge.
This is the clean “this session has a total compute allowance” model for a multi-tenant or untrusted-query host: a session granted only the privileges it needs, capped per statement, and budgeted over its lifetime.
Scalar allocation budget
max_scalar_bytes defaults to 64 MiB per statement. Set it through session options or set_max_scalar_bytes(bytes) (Rust), SetMaxScalarBytes(bytes) (Go), or await session.configure({ maxScalarBytes: bytes }) (TypeScript).
Non-positive values restore the finite default. A reservation above it fails with 54P04;
exact equality is allowed. The budget resets for each statement and accumulates across nested
calls, rows, subqueries and CTEs. A cursor keeps its original budget until it closes.
This budget covers the functions where one call can multiply its input by an amount an argument
controls: the exact output bytes of repeat, lpad, rpad, replace, regexp_replace, jsonb_pretty (UTF-8), array_replace, and the capture arrays of regexp_match and regexp_matches (a pattern of nested groups repeats the matched text once per group), the text of concat_ws and format (a separator repeats per argument; a format width or a reused %1$s multiplies its argument), and logical
scratch reservations in decimal sqrt, exp, ln, log, log10, power, pow. These functions also charge their input and output bytes
as cost before they build anything; decimals charge inside their algorithms. A cost ceiling can
reject the work before its allocation budget is used.
Functions whose output is at most a small multiple of their inputs do not use this budget, so
large bulk statements are not capped by it. These are the array builders (ARRAY[…], array_append, array_cat, array ||), the JSON builders (jsonb_build_object, to_jsonb, jsonb_set, jsonb ||, and the like), and the functions and casts that render text with escapes
or hex (concat, encode, quote_literal, quote_ident, quote_nullable, casts from an array, bytea, or jsonb to text, and ->>, #>>, jsonb_each_text, and jsonb_array_elements_text when the member they return is an object or array). Instead they charge one cost unit per byte they build (32 per array element or JSON node
plus its contents), which lets max_cost stop a query that doubles a value over and over. A value
built only from constants, such as ARRAY[1, 2, 3] in a WHERE clause, costs nothing extra.
jsonpath queries (jsonb_path_query, @?, JSON_QUERY, JSON_TABLE, and the rest) are metered
by the work the path does: each byte of the path compiled, each step applied, each item produced,
each object member searched, and each comparison a filter makes. A filter that compares every
array element against every other element therefore costs in proportion to the pairs it tests.
Sorts, GROUP BY, DISTINCT, set operations other than UNION ALL, and window partitions charge
each row’s key values by size, once per row: one cost unit per byte of a text, bytea, decimal,
array, or JSON key, and for a key sorted under a linguistic collation one unit per character. Integer,
date, timestamp, uuid, and other fixed-width keys charge nothing. So a query that repeats one large
value across many rows and sorts or deduplicates them pays for the value in every row, and max_cost stops it. A sort that an index or the primary key makes unnecessary charges nothing.
Query memory budget
max_query_memory_bytes bounds the rows and operator state a statement holds at once:
materialized relations, join results, grouped and DISTINCT rows, set-operation and CTE buffers, RETURNING results, and the rows the engine’s own collect-everything helpers (such as Rust query_rows) gather — plus the working state of the operators that produce them:
hash-join tables, group and dedup tables, aggregate inputs such as json_agg’s, window
partitions and the operand values a window caches, sort buffers, the sort keys a collated sort
builds, and the rows a spilled sort reads back to merge. It also holds the writes an open transaction has staged but not yet
committed (see below). It is unlimited by default — like max_cost, a host serving untrusted
SQL opts in. Set it through session options or set_max_query_memory_bytes(bytes) / SetMaxQueryMemoryBytes(bytes) / await session.configure({ maxQueryMemoryBytes: bytes });
non-positive values restore unlimited. A statement that would exceed it fails with 54P05;
exact equality is allowed.
The budget counts logical bytes from a fixed schedule — 32 bytes per row, per value, and per
hash-table entry, plus the UTF-8 length of text, the length of bytea, and similar payloads — not
the runtime’s actual allocations. That makes the limit deterministic: the same query aborts at the same row on every
core. Rows released along the way (filtered out, consumed by the next stage, handed to your cursor)
give their bytes back, and a streaming query that hands each row to you as it is produced holds
almost nothing. A single-table query streams when nothing needs all its rows at once: no join,
aggregate, window, or DISTINCT, an ORDER BY its index or primary key already provides (or none),
and, without ORDER BY or LIMIT, a select list that computes a value and calls no host function.
A cursor keeps its statement’s budget until it closes.
TypeScript’s public async all() gathers its result objects on the application thread. That
collection has a separate runtime.maxResultBytes limit (default 2 MiB) and rejects oversized
results with TransportError code RESULT_TOO_LARGE. The session’s maxQueryMemoryBytes still
bounds query execution inside the worker. Use query() with async iteration to consume bounded
batches instead of collecting the whole result; values your application keeps after iteration
remain its responsibility.
Uncommitted writes count against the same budget. Every row version and index entry a transaction
writes reserves its stored size — its on-disk record plus any value stored out of line — until the
transaction commits or rolls back. Each statement starts with those bytes already counted, a write
adds its own as soon as it has written its rows (beside whatever the statement still holds, such as
an INSERT … SELECT’s source rows or a RETURNING result), and after every statement they must
still fit, so a long transaction of many small INSERTs fails with 54P05 instead of growing
without bound. While a budget is set, the count is what the transaction ends up holding: rewriting a
row it already wrote replaces that row’s bytes rather than adding to them, and deleting a row it
inserted gives them back. Writes made with no budget set still count, but are not tracked row by
row, so rewriting them later counts again. The same holds for rows written before a SAVEPOINT, which
the savepoint keeps for a possible ROLLBACK TO. Temporary tables are bounded by max_temp_storage_bytes instead.
Storage limit
max_storage_bytes bounds how much a database keeps once its transactions commit — the one
thing the per-statement and per-transaction budgets cannot see, since many small committed
transactions each fit them. Without it, a session that can insert can grow an in-memory database
until RAM runs out, or a file until the disk fills. It belongs to the database rather than to a
session, so every session shares it. Set it in the create options (max_storage_bytes / MaxStorageBytes / maxStorageBytes) or in the open options of a file. Rust and Go also accept it
on an attachment’s source. Change it later with set_max_storage_bytes(name, bytes) (Rust), SetMaxStorageBytes(name, bytes) (Go), or await db.setMaxStorageBytes(name, bytes) (TypeScript),
where name is main or an attachment. It is unlimited by default;
non-positive values restore unlimited. It is a handle setting, not stored in the file.
A commit that would grow the database past the limit fails with 54P06 and commits nothing. A
commit that only deletes rows or drops objects always succeeds, so a full database can always be
cleaned up. The Rust storage_bytes(name), Go StorageBytes(name), and TypeScript await db.storageBytes(name) gauges report the committed bytes the limit checks, excluding pending
writes. TypeScript accepts and returns bigint bytes. The measure depends on where the database lives.
In-memory databases count their pages: the page high-water times the page size. A commit that would raise it past the limit first reclaims any dead pages. jed keeps freed pages for reuse and reclaims them in batches, so a database under a limit of B bytes reliably holds about B/2 bytes of live pages and may hold up to B. A commit that fits in freed pages always succeeds, even when a lowered limit is already below the current size. A read session that predates the last commit can keep dead pages from being reclaimed; closing it frees them for the next commit.
File-backed databases count their live pages: the pages reachable from the current schema and data, times the page size. Pages freed by deletes and updates do not count, and neither does the file’s length, so a delete lowers the count at once and a limit of B bytes holds B bytes of live data. A commit that does not add live pages always succeeds, even under a lowered limit. jed stores the exact count in the file and updates it on every commit, so opening a file never scans it, and the count is the same whether one process writes the file or several share it. Each process enforces the limit its own handle was given.
The file itself can be longer than the live count: freed pages wait for safe reuse. Old read
snapshots, including page-client snapshots, can keep pages pinned; the owner reclaims pages once
the reader watermark allows it.
That extra space is bounded by how much writing produced it, which max_cost and lifetime_max_cost limit, and compact returns it.
Page cache
A file-backed database holds its table data in a page cache of leaf pages read from the file,
bounded by the cache_bytes / CacheBytes / cacheBytes open option (default 256 MiB). Each
cached page is counted at the memory it actually takes (its used bytes plus a little bookkeeping), and
a budget smaller than one page still keeps one page cached. When the cache is full, jed evicts a
page; it can always read that page back from the file. Because of that, the cache never fails a query, and its size never changes a
query’s results or cost. It is a memory and speed setting, not a limit an untrusted query can hit.
The budget bounds the cached pages, with two qualifications:
- Pages in use stay alive. An evicted page is not freed while a query or open cursor is still reading it: at most one root-to-leaf path per running query, plus each open cursor’s current page. So the cache can briefly hold a few pages over its budget with many concurrent readers.
- Some structures are not in the cache. The interior pages of every table and index tree stay in
memory. They are a small fraction of a tree’s pages, since each one routes to many leaves. The
index tree of a GiST index also stays in memory, and grows with the number of indexed rows.
cache_bytesdoes not bound these. They are part of the pagesmax_storage_bytescounts, so it bounds them indirectly on both kinds of database.
An in-memory database ignores cache_bytes: all of its pages stay in memory, and max_storage_bytes is the limit for them.
Memory coverage
These budgets are guardrails, not a process-memory cap. The query-memory budget covers row
buffers and operator state: hash-join tables, group, DISTINCT, and set-operation tables, json_agg-style and ordered-set accumulators, window partitions and operand caches, sort buffers,
top-k heaps, and collation sort keys, the resident part of spilling operators and the rows they
merge back, and the writes pending in an open transaction. The
storage limit covers an in-memory database’s committed pages and a file database’s live pages. A file-backed database’s page cache
is bounded by its cache_bytes open option, which evicts pages and never fails a query (see the
page cache section above). On native file hosts,
sort, hash JOIN, aggregation, and DISTINCT spill when they exceed work_mem — and also when the
query-memory budget would otherwise reject them, so a large sort or aggregate spills rather than
fails and releases its charge as it spills. Row buffers that cannot spill, such as a derived
table’s result, still fail at the budget; work_mem = 0 disables spilling entirely. Spill scratch storage preserves results and deterministic costs;
in-memory and OPFS databases remain resident. max_temp_storage_bytes limits retained temporary
storage (54P03); temp_buffers bounds how much of it stays in memory before a file-backed
database spills temp tables to a scratch file.
Hosts exposing arbitrary untrusted SQL should combine these settings with process-level memory
limits and account for host-retained results.