Database and schedules
MarkdownEach application can have its own database, SQLite unless it needs PostgreSQL, and its actions can also run on a schedule, with nobody calling them.
The examples use $TOKEN, $API_KEY and $APP_ID as Build an
application defines them.
Its database
Section titled “Its database”A page’s server knows the person only by
x-apigami-user-ref, which Apigami’s session sets on every route of your app’s own address: a visitor and the side panel get none, and anyone can load a page, so it renders nothing personal without it. In the page, apigami.js calls an action for the person, andapigami.call()fetches their data through it. An action learns who it serves only from its run token:GET /v1/meanswersuser_ref, the person, the same in every browser of theirs. Key every per-person row onuser_ref. Never pick the person from the input, from the most recent row, frominstall_reforbrowser_pseudonym, which name a browser, or from a person a URL names. An OAuth callback reads the person inx-apigami-user-ref, and checks itsstateagainst a__Host-cookie its/oauth/startset.
Take the SQLite database by default:
"x-apigami": { "database": "sqlite" }true means the same. Take the PostgreSQL database, "database": "postgres", only for a real need: a schema
or a library already written for PostgreSQL, queries past 30 seconds, many concurrent writes, a PostgreSQL add-on.
A PostgreSQL database is billed markedly more: a flat fee, then its operations and its storage. A SQLite
database costs almost nothing while the application serves little.
The database is created the first time a version declaring it runs or deploys, and every version of the application shares it. Once it exists, it stays, even for a version that stops declaring it, and the application keeps its kind: a version declaring another one is refused. To change kind, create a new application, except from a database of your own, which deleting its address unlinks (A PostgreSQL database of your own). An application that declares none has none.
| SQLite (default) | PostgreSQL | |
|---|---|---|
| In your code | env.DB |
env.DATABASE_URL, one connection per request |
| Size | 10 GB at most | no fixed cap, storage billed |
| One query | 30 seconds | 60 seconds by default (Timeouts) |
| Concurrency | one query at a time per database, about 1,000 a second at 1 ms each | 45 direct connections |
| One statement | 100 KB, 100 parameters, 2 MB per row | PostgreSQL’s own limits |
| Queries per request your code receives | 1,000 | no cap of its own |
| Backup | back to any minute of the last 30 days, reversible | one copy a day the database changed, kept 7 days, no return to the minute |
| Schema | files of migrations/, applied by Apigami (Migrations) |
the same |
On PostgreSQL, env.DATABASE_URL is the URL to use. env.DIRECT_URL serves only what a pooled connection cannot
hold, listen/notify or a session-level lock, and each such connection takes one of the database role’s
connections.
To restore either, write to contact@apigami.com: a restore applies to every version, since they share the database. Deleting the application deletes a PostgreSQL database at once; a SQLite database is kept 30 days, during which it can still be restored, then deleted.
env.DB: querying the SQLite database
Section titled “env.DB: querying the SQLite database”| Call | Answers |
|---|---|
env.DB.prepare(sql) |
a statement, its values written ?1, ?2, never assembled into the SQL |
.bind(...values) |
the statement with its values: strings, numbers, booleans, null, bytes |
.all() |
{ results, meta }: results the rows, as objects |
.first() |
the first row, or null; .first('id') that column’s value |
.run() |
the same as .all(), for a write: meta.changes rows written, meta.last_row_id the last row inserted |
env.DB.batch([statements]) |
one answer per statement, all in one transaction: every one or none |
import { Hono } from 'hono'
type Statement = { bind(...values: unknown[]): Statement all<Row = Record<string, unknown>>(): Promise<{ results: Row[]; meta: { changes: number; last_row_id: number } }> first<Row = Record<string, unknown>>(): Promise<Row | null> run(): Promise<{ results: unknown[]; meta: { changes: number; last_row_id: number } }>}type Database = { prepare(sql: string): Statement; batch(statements: Statement[]): Promise<{ results: unknown[] }[]> }const app = new Hono<{ Bindings: { DB: Database; APIGAMI_API_URL: string } }>()
app.post('/api/notes', async (c) => { const me = await fetch(`${c.env.APIGAMI_API_URL}/v1/me`, { headers: { Authorization: `Bearer ${c.req.header('X-Apigami-Run')}` } }) if (!me.ok) return c.json({ error: 'unauthorised' }, 401) const { user_ref: userRef } = await me.json() const { body } = await c.req.json<{ body: string }>() const note = await c.env.DB.prepare('insert into notes (user_ref, body) values (?1, ?2) returning id, created_at') .bind(userRef, body).first<{ id: number; created_at: string }>() const { results: notes } = await c.env.DB.prepare('select id, body from notes where user_ref = ?1 order by id desc limit 50') .bind(userRef).all<{ id: number; body: string }>() return c.json({ note, notes })})The tables come from migrations/, never from an action.
A PostgreSQL database of your own
Section titled “A PostgreSQL database of your own”An application that already pays for a PostgreSQL server elsewhere, or sends it more queries than a database billed by the query is worth, declares it instead:
"x-apigami": { "database": "postgres-external", "subprocessors": [{ "name": "Scaleway", "category": "database", "role": "Hosts the application's PostgreSQL database.", "location": "FR", "hosts": ["51-15-1-2.rdb.fr-par.scw.cloud"] }]}Your code reads it exactly as the PostgreSQL database above: env.DATABASE_URL, through a pool of connections kept
near the database, and env.DIRECT_URL, the address itself, for listen/notify and session-level locks. The pool
caches no query: a row your code has just written is the row it reads back. migrations/, app_query and
app_schema work on it with the same limits; app_schema lists the tables its role owns, not those its host keeps
beside them.
Its host receives the data of the people who use your application, so it is one of the services the application
declares in subprocessors: a version declaring "postgres-external" without a subprocessor whose category is
"database" is refused when it is written (The manifest).
A human types its address, never an AI. app_environment_write with DATABASE_URL in names answers a link; the person
opens it and types the address, as postgres://user:password@host:5432/database; your code reads it as
DATABASE_URL. Until it is typed, a try and a deployment are refused as for any missing variable. Saving it checks it first, and stores nothing when a check fails:
postgres://orpostgresql://, a host name rather than an IP address, a user, a password of 8 characters or more, and a database;- TLS, its certificate checked against the host name (
sslmode=verify-full): a certificate no public authority issued is refused unless you give it (below), and so is an address withsslmode=disable,alloworprefer. The address is kept withsslmode=verify-full, soenv.DIRECT_URLchecks the certificate too, against the public authorities; the pool behindenv.DATABASE_URLrequires TLS, and checks the certificate when you give its authority’s; - the database’s direct address, never a pooler in transaction mode (a host with
-pooler.in it, or port 6543), where the lock Apigami holds while it migrates would outlive its connection; a pooler’s session mode will do; - a host that resolves to public addresses only, never to a private network nor to Apigami’s own services. The name is resolved again before each connection Apigami opens;
- a database that answers: Apigami connects, reads
version()andcurrent_user, and creates a table inpublic, whereapigami_migrationsgoes, then rolls it back. A refusal comes back in PostgreSQL’s own words; - a database your deployed code can reach too: the check says which of the two connections failed;
- a database no other Apigami application is linked to: two applications on one database would share Apigami’s record of its migrations. Another database on the same server will do.
A database whose provider signs its own certificate. Some providers sign each database’s TLS certificate
themselves rather than through a public authority, and give it in their console. Paste that certificate on the same
page, under the address: one save sends both. The PEM file whole, from
-----BEGIN CERTIFICATE----- to -----END CERTIFICATE-----, one certificate or the few of a chain. Apigami then
trusts it alone for this database, still against the host name, so give the address with a host name the
certificate names, never its IP address. Saving it checks that it is an X.509 certificate valid today, 5 KB at
most, with no private key beside it; once DATABASE_URL is saved too, each save connects to check that the
certificate verifies the database, and stores nothing when it does not. Apigami’s own connections, for the migrations,
app_query and app_schema, verify the database with it. The pool behind env.DATABASE_URL of a deployed version
does too when it is a certificate authority’s; a certificate the provider signs itself for the server is checked by
Apigami on its own connections only, and the connection your deployed code uses stays encrypted but does not check it
(pool_verifies_certificate in app_status). Nothing hands it to your code’s own connections yet: env.DIRECT_URL, and both addresses an app_run gives the
code, which are the address itself, check the certificate against the public authorities only, and cannot reach such
a database. Replace the certificate when your provider renews the database’s: past its expiry, no connection opens. Removing it is refused while the database still needs it. A certificate authority is public, unlike the address.
Typing the address of another database first applies to it the migrations/ of the versions your application
serves, production and --staging; if they fail, nothing changes and the refusal says why. When another authority
signs the new database’s certificate, change both in one save, since each half alone is checked against the other
and refused: type the new address, then either paste the new certificate, or, for a database a public authority
certifies, empty the certificate field, and save. Either sends the address with it; removing the certificate alone
waits until the address is saved. Through the API, the
address’s PUT takes the certificate as ca_certificate, null to remove it. Production then reads the
new database at once, with the rows it holds: Apigami copies none. While a deployment of the application runs, the
address is refused, since that deployment migrates the database it reads now: save it again once it ends.
Apigami connects from addresses that are not fixed, so the database opens to the Internet behind TLS and a strong password, with a role of its own for the application.
It stays yours. Apigami never backs it up, never restores it and never deletes it: its backups are those its host
keeps. Deleting DATABASE_URL (app_environment_write, at once), or deleting the application, makes Apigami forget the address
and the pool, and leaves the database and its data where they are. Apigami never shows the address back, not even
to you: keep it where you keep your other secrets. An application whose database Apigami created
cannot switch to one of its own: Apigami copies no data, so start a new application, or move the data yourself with
pg_dump and pg_restore into a new one.
A row that belongs to one person carries their user_ref, and every query that reads or writes it
filters on the user_ref the token names. GET /v1/me answers it, once per invocation: each call of
an action gets a token of its own, even when a page calls it again with the same token, so there is
nothing to keep from one call to the next:
// The person this invocation serves, from its own token: X-Apigami-Run is new on every call.export const personOf = async (env, token: string) => { const me = await fetch(`${env.APIGAMI_API_URL}/v1/me`, { headers: { Authorization: `Bearer ${token}` } }) if (!me.ok) return null const run = await me.json() return run.user_ref}
export const readBasket = async (request: Request, env) => { const token = request.headers.get('X-Apigami-Run') const userRef = token ? await personOf(env, token) : null // A run that serves nobody, a key without X-Apigami-User-Ref for one, has no basket to read. if (!userRef) return Response.json({ error: 'this action serves one person, and its token names none' }, { status: 401 }) const { results: items } = await env.DB.prepare('select item, quantity from basket_items where user_ref = ?1 order by item') .bind(userRef).all() return Response.json({ items })}What each call of env.DB answers: env.DB.
user_ref is the same in every browser of the person and for every application of your group.
install_ref and browser_pseudonym change with the browser, and the input is whatever the caller
sent: none of them says who the person is.
Migrations: migrations/
Section titled “Migrations: migrations/”The schema of the database, of either kind, lives in the version, one file per change:
create table basket_items ( user_ref text not null, item text not null, quantity integer not null, primary key (user_ref, item));A file is named migrations/NNNN.sql or migrations/NNNN_name.sql, four digits giving its order. Apigami
applies the new ones one at a time, in that order, before each try and each deployment, on the database
production reads, and records them in apigami_migrations: read that table, never write it, neither with
app_query nor from your code. A file once applied is never changed: add a new one.
That table has one row per applied file: number (the four digits, as an integer), name (what follows
the underscore, null without one), sha256 (of the file, which is how a changed file is refused) and
applied_at (UTC; ISO 8601 text on SQLite, a timestamptz on PostgreSQL, in the public schema). app_schema
does not list it:
select number, name, applied_at from apigami_migrations order by number;A file is one transaction, which Apigami opens and commits, so it holds neither BEGIN nor COMMIT
(migration_transaction). A file that fails leaves nothing behind: it is not applied, the try or the deployment
stops on it, and it is fixed or removed in the next version. The files before it are applied, and stay as they are.
app_version lists each file of a version with its state, applied, skipped, pending or running, how long
it took, who skipped it, and why its last attempt failed. A file applied but missing from the version, or changed
since, is shown as such.
On SQLite, foreign keys stay on: PRAGMA foreign_keys is refused; rebuild a table under
PRAGMA defer_foreign_keys = on. A file has about 30 seconds, all its statements together, during which the
database answers nobody else, production included. A large UPDATE is split over several files, each one well under
that; a single statement that takes longer on its own cannot be a migration.
On PostgreSQL, each statement waits 5 seconds at most for a lock, and runs 5 minutes at most. The 5 seconds protect production: a migration waiting behind a long query would otherwise hold up every query that comes after it. When the lock is not obtained, the file is not applied and nothing in it is wrong: run or deploy the same version again. A file that needs more sets its own limits on its first lines:
set local statement_timeout = '12min';update basket_items set quantity = 1 where quantity is null;A file runs 15 minutes at most, all its statements together. A statement that cannot run in a transaction,
create index concurrently above all, goes alone in a file whose first line is the directive
-- apigami:no-transaction. It then runs outside any transaction, with 14 minutes for that one statement:
-- apigami:no-transactioncreate index concurrently if not exists basket_items_by_item on basket_items (item);concurrently without the directive is refused (migration_transaction), and so is a second statement under it.
A concurrently statement waits, within those 14 minutes, for the transactions already open on its table to end,
rather than giving up after 5 seconds; any other statement under the directive keeps the 5 seconds.
A create index without concurrently blocks every write to its table while it builds, production’s included:
it is warned of (migration_locking_index), except on a table the same file creates. When a build under the
directive fails, it leaves an invalid index behind, and the failure names it: drop it with app_query
(drop index concurrently if exists …) before the next try, and never skip the file or make it if not exists
over it: that records the file while the index stays unused, its uniqueness unenforced. The directive does not exist on SQLite, where it is
refused.
A PostgreSQL database that already holds tables and no apigami_migrations, built by hand before its first
migration, stops the first try: mark with app_migrations_write the files that describe what it already holds
(Skipping a file), then run again. When none does, first add a migrations/0001_init.sql that
describes what app_schema shows, skip that one, and number the new files after it. A SQLite database has no such rule: a create table if not exists from your code, as the watch example does, works for a table no migration
creates.
Read or change the rows without going through your own code, with app_query or over HTTP:
curl -s -X POST "https://api.eu.apigami.com/v1/apps/$APP_ID/database/queries" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d '{"sql":"select item, quantity from basket_items where user_ref = ?1","params":["usr_…"]}'
curl -s "https://api.eu.apigami.com/v1/apps/$APP_ID/database" -H "Authorization: Bearer $TOKEN"One database for every version means a migration applied while trying a version changes what production reads. That is deliberate — there is one truth — and it is worth knowing before the migration, not after: add first, remove later. A new column or table comes in one version; the column the version in production still reads is dropped or renamed only in a version after it is published.
Skipping a file
Section titled “Skipping a file”app_migrations_write with action: "skip_execution", a version_id and a number records that one file of
the version in apigami_migrations without running it. It never runs afterwards, in that version or any
other. A skip is a decision about the database, never written in the version. It fits three cases:
- the database was built by hand or by your code, and
0001_init.sqldescribes it after the fact; - a fix was run by hand during an incident, and the file repeats it;
- everything the file does is already in the database.
Compare the file with app_schema first. In any other case, a file that fails on already exists is fixed
instead, with if not exists, in a new version: skipping a file of five statements because its second fails
loses the other four. One number per call; a number already recorded is refused, and so is a skip while the
application is being deployed. Nothing undoes a skip: a wrong one is corrected by a new file. Once it is
done, deploy the same version again, not a new one. Another version holding a different file under that number
is then refused, migration_changed, a deployed one outside production included: the answer names them.
Timeouts
Section titled “Timeouts”A SQLite query stops at about 30 s, all the statements of one call together, and nothing lifts it: split the work, or index what the query searches. Whether a write stopped there was kept is unknown: read before sending it again. A migration file stops the same way, all its statements together. The timeouts of a PostgreSQL migration are its own.
Every connection to a PostgreSQL database starts with statement_timeout at 60 s: a query that runs longer is
cancelled, so one stuck query cannot hold the database for everyone.
It is a default, not a ceiling. app_query sets it to its timeout_ms, 10 s by default and 60 s at most, and
stops waiting for the answer a second after that; the SQL it runs can still change statement_timeout. Through
DATABASE_URL, set it for one transaction with set local statement_timeout = '5min' inside
begin … commit, up to 10 minutes. alter role current_user set statement_timeout = … changes the default
for every later connection; keep it finite rather than 0.
Never hold a transaction open around a call to the browser: POST /call may wait up to 35 s for a
browser coming back online, and the transaction keeps its locks for all of that wait.
Space your requests to a site
Section titled “Space your requests to a site”Apigami puts no rate limit on the requests your code sends to a site. When a site wants them spaced, keep one row per person in your database and take the next slot in one statement: a SQLite database runs one statement at a time, so two runs of the same person never get the same slot.
create table site_pace (user_ref text primary key, next_at integer not null);// One request every two seconds per person, whichever run sends it. Times in milliseconds.const waitForTurn = async (env, userRef: string) => { const now = Date.now() const { next_at } = await env.DB.prepare(`insert into site_pace (user_ref, next_at) values (?1, ?2 + 2000) on conflict (user_ref) do update set next_at = max(site_pace.next_at, ?2) + 2000 returning next_at`).bind(userRef, now).first() await new Promise((resolve) => setTimeout(resolve, next_at - 2000 - now))}Call waitForTurn(env, run.user_ref) before each request.fetch to that site. Wait for a turn only
while the whole action, every wait included, still answers in under 30 seconds; otherwise answer 429 with
Retry-After instead (Answer quickly, queue long work).
Triggers: x-apigami.crons
Section titled “Triggers: x-apigami.crons”x-apigami.crons declares global recurring actions in the version. Apigami owns their schedule.
Each declaration has an id,
action, interval_minutes, audience: "application" and input. One minute is the shortest
interval. The action receives input as its JSON body and must use a method other than GET or HEAD.
There is no per-person cron audience: a global action can add queued tasks with a user_ref for each
person it serves. Work that needs that person’s Chrome goes to their own queue, held while it is offline, under an
id that stays the same from one pass to the next (A queue per person, held while their
Chrome is offline). It lists them with GET /v1/users and calls with env.APIGAMI_KEY, the key of the
version in production, refused on any other (The server).
A trigger runs in production on its own schedule as soon as its version is published. On the version being tried, at the staging address, it starts paused: that version reads and writes the same database as production, so a running copy would make every call of the trigger twice. To watch it run there, resume it, then pause it again:
curl -s -X PATCH "https://api.eu.apigami.com/v1/apps/$APP_ID/crons/refresh" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{"paused":false,"environment":"staging"}'$TOKEN is your author access token. A pause survives version changes. Production and staging keep separate
queues and pause states, production by default. From your code, the key picks: under the env.APIGAMI_KEY of the
version at your staging address, the queue routes read and write the staging queues, whose tasks name only your
team’s members.
app_queues_write with action: "pause" or "resume" and cron_id: "refresh" offers the same controls.
A pause may include an ISO until date to resume automatically, even across version changes.
app_run with trigger: "refresh" tries its declared input with no person, even if you are connected. GET /v1/me under the trigger’s token returns
user_ref: null; browser work belongs to the tasks that name a person.
When it runs. One pending occurrence is kept per trigger. Finishing it and recording its successor
commit together. Missed intervals are skipped, and the next occurrence is always in the future. A
minute sweep repairs a missing successor. A failed attempt follows the queue retry policy before
its occurrence ends; Retry-After on a 429 or 503 postpones it without spending a failure attempt.
An attempt fails when the code throws or uses more than its 300 seconds of computing time
(Limits).
GET /v1/apps/{app}/crons lists each trigger with its pause and last start. app_status shows the same
summary; app_runs includes the trigger id and environment in the run’s output. Queue task logs retain
attempt outcomes for seven days.
Managing queues through MCP
Section titled “Managing queues through MCP”Use app_queues for reads and app_queues_write for changes. Both take app_id and
environment: "production" | "staging", defaulting to production. The read tool defaults to
view: "queues"; "tasks" reads pending work and "logs" reads seven days of history.
All views accept queue, cursor and limit. Tasks also accept tag, user_ref and task_id;
logs accept task_id. Reuse the returned next with the same view and filters.
For writes, choose an action:
configure:queueand completesettings, with exactly oneinternal_app_pathorexternal_url; omitted setting fields take their defaults. A queue whose work needs one person’s Chrome is theirs,{user_ref}:<name>withhold_while_user_offlineset to them (A queue per person, held while their Chrome is offline).pauseorresume: exactly onequeue,tagorcron_id;pauseoptionally takesuntil.add_tasks: atasksarray of at most 1000 entries, in already configured queues; an existing id replaces that task’s pending version.remove_tasks: eithertask_idsortag, plusconfirm: true;purge:queueandconfirm: true. Reserved work may still run; purging keeps the queue settings.update_tasks:where(user_ref, and optionallyinstall_ref,queue,tag,actionortask_ids) andset.install_ref, a browser of that person ornull; each waiting task keeps everything else, the application it is done for included. Running tasks are skipped and counted, andremainingcounts them with what is left: a try at a browser that is gone comes back waiting, still naming it. Call again with the same fields whileremainingis not 0, a few seconds later when nothing moved.requeue: thecursorof an abandoned or expired entry fromapp_queues view: "logs". Current access is checked again. An existing task with that id causes 409 and remains unchanged.
Write responses point back to the relevant app_queues view. Trigger declarations still belong in
the version manifest; these tools cannot create or edit them.