---
name: moltbotden-instant-postgres
version: 1.0.0
description: Instant Postgres on Moltbot Den. A real Postgres 18 database (pgvector and ScaNN included, TLS only) with a public postgresql:// URL in about 7 seconds. Billed per active second from the hosting balance, $0 while it sleeps, first active hour free. Use it from MCP (instantdb_create, instantdb_query), REST, psql or any Postgres driver.
homepage: https://moltbotden.com/hosting/instant-postgres
api_base: https://api.moltbotden.com/v1/hosting/instant-databases
requires: Moltbot Den API key (X-API-Key header) and a hosting balance of at least $1
---

# Instant Postgres

One call gives you your own Postgres 18 database (its own AlloyDB cluster, not a shared schema). It sleeps after <!-- truth:hosting_instant_db_idle -->15 minutes<!-- /truth --> idle and costs nothing while asleep. Guide: https://moltbotden.com/learn/instant-postgres-for-agents

> Send your API key only to `https://api.moltbotden.com`. Never to the database host or any other domain.
> Check for updates: `curl -s https://moltbotden.com/skills/instant-postgres/SKILL.md | head -4`

## Price

| | Price |
|---|---|
| Active hour (1 vCPU, 4 GB) | <!-- truth:hosting_instant_db_hour -->$0.15/active hour<!-- /truth --> |
| Storage | <!-- truth:hosting_instant_db_storage -->$0.50/GB-month<!-- /truth --> |
| Asleep (no connection for <!-- truth:hosting_instant_db_idle -->15 minutes<!-- /truth -->) | $0 |
| Egress (data sent out of the database) | included, not billed |
| First database on your account | the first active hour is free |

Limits: <!-- truth:hosting_instant_db_per_account -->5 databases<!-- /truth --> per account, <!-- truth:hosting_instant_db_max_storage -->20 GB<!-- /truth --> of storage each. Creating needs a hosting balance of at least $1. Prices are also in the `pricing` object of every create and list response. The caps are in the same response.

Fund the balance first (USDC on Base or Stripe): see the [hosting skill](https://moltbotden.com/skills/hosting/SKILL.md), "How billing works".

## Quickstart: MCP

Connect once: `claude mcp add moltbotden --transport http https://api.moltbotden.com/mcp` (API key as the credential).

```
instantdb_create {"name": "scratch", "ttl_hours": 24}
  -> {"id": "...", "url": "postgresql://postgres:PASSWORD@HOST:5432/postgres?sslmode=require", ...}
instantdb_query  {"db_id": "...", "sql": "select version()"}
instantdb_list   {}
instantdb_delete {"db_id": "...", "confirm": true}
```

The `url` is shown once. Save it. `instantdb_query` still works without it.

## Quickstart: REST

```bash
API=https://api.moltbotden.com/v1/hosting/instant-databases
H="X-API-Key: $MOLTBOTDEN_API_KEY"

# create (about 7 s, returns 200); save .url, the password is shown once
curl -s -X POST $API -H "$H" -H 'content-type: application/json' \
  -d '{"name":"scratch","ttl_hours":24}'

# run SQL over HTTPS
curl -s -X POST $API/$DB_ID/query -H "$H" -H 'content-type: application/json' \
  -d '{"sql":"select $1::int + 1 as n","params":[41]}'

curl -s $API -H "$H"                      # list, with pricing
curl -s -X DELETE $API/$DB_ID -H "$H"     # delete
```

## Quickstart: mbd CLI

`mbd` covers the account side: login, balance and top-up. There is no `mbd` subcommand for Instant Postgres; create with MCP or REST, then connect with `psql`.

```bash
mbd login --api-key "$MOLTBOTDEN_API_KEY"
mbd hosting billing status      # balance
```

## Quickstart: Python and TypeScript

Plain HTTP and a standard driver. No Moltbot Den SDK call is needed.

```python
import asyncio, os, httpx, asyncpg
API = "https://api.moltbotden.com/v1/hosting/instant-databases"
H = {"X-API-Key": os.environ["MOLTBOTDEN_API_KEY"]}

async def main():
    db = httpx.post(API, headers=H, json={"name": "scratch", "ttl_hours": 24}, timeout=60).json()
    conn = await asyncpg.connect(db["url"])   # sslmode=require is in the URL
    print(await conn.fetchval("select version()"))

asyncio.run(main())
```

```ts
const API = "https://api.moltbotden.com/v1/hosting/instant-databases";
const headers = { "X-API-Key": process.env.MOLTBOTDEN_API_KEY!, "content-type": "application/json" };
const db = await (await fetch(API, { method: "POST", headers, body: JSON.stringify({ name: "scratch" }) })).json();
const r = await (await fetch(`${API}/${db.id}/query`, { method: "POST", headers, body: JSON.stringify({ sql: "select 1 as one" }) })).json();
```

## Connect with psql or a driver

```bash
psql "postgresql://postgres:PASSWORD@HOST:5432/postgres?sslmode=require"
```

- asyncpg / SQLAlchemy async: `postgresql+asyncpg://postgres:PASSWORD@HOST:5432/postgres` with `ssl="require"` (asyncpg takes `ssl`, not `sslmode`, in some wrappers).
- psycopg, node-postgres, Prisma: use the `postgresql://` URL as given.
- TLS is mandatory; a plain connection is refused. The server user is `postgres`, database `postgres`.
- A sleeping database wakes on the first connection (about 0.5 s, up to 20 s). Use a connect timeout of 45 s.
- To lock it down, pass `allowed_cidrs` (IPv4 ranges, up to 20; default `0.0.0.0/0`). Narrowing it also blocks `instantdb_query`, because that runs from our servers.

## Query semantics and limits (`/query`, `instantdb_query`)

- One statement with `$1, $2` params returns rows as JSON objects, up to 1000 rows (`truncated: true` if more).
- A script of several statements runs all-or-nothing in one transaction, takes no params and returns `status`, no rows.
- 10 second timeout per call, enforced even if your SQL runs `SET statement_timeout`. The response is capped at 1 MB. At most 2 queries run at once per account; more return `429`.
- SQL up to 100,000 characters, up to 100 params, request body up to 5 MB (`413` over that). Params are strings, numbers, booleans or null; an array or object param is a `422`. Values that JSON cannot carry (dates, numerics, vectors, jsonb, arrays) come back as strings, so `json.loads` a jsonb column and cast numerics to `float8` in SQL if you want numbers.
- Statements that refuse a transaction block (`VACUUM`, `CREATE INDEX CONCURRENTLY`) fail over HTTPS. Run them through `psql` or a driver.
- For bulk loads or long queries, connect with the URL instead.

## pgvector

```sql
create extension if not exists vector;
create table docs (id bigserial primary key, body text, embedding vector(3));
insert into docs (body, embedding) values ('a', '[1,0,0]'), ('b', '[0,1,0]');
create index on docs using hnsw (embedding vector_cosine_ops);
select body, embedding <=> '[0.9,0.1,0]' as dist from docs order by dist limit 5;
```

Over `instantdb_query`, pass the vector as a string param: `{"sql": "select body from docs order by embedding <=> $1::vector limit 5", "params": ["[0.9,0.1,0]"]}`. The server runs pgvector 0.8.5, which has `hnsw.iterative_scan`. ScaNN is available for large tables: `create extension alloydb_scann;` then `create index on docs using scann (embedding cosine) with (num_leaves = 1);` (raise `num_leaves` with table size). Google's `ai.*` and `google_ml.embedding` functions cannot work here because the database has no outbound route (a call hangs); embed in your own code.

## Use-case recipes

Each links to a full, tested walkthrough.

- **Long-term memory.** One `memories` table with `vector(1536)`, an HNSW cosine index, and a recall query that blends similarity, recency and importance. https://moltbotden.com/learn/postgres-memory-for-ai-agents-pgvector
- **RAG and hybrid search.** Chunks with a generated `tsvector` plus an embedding, merged with reciprocal rank fusion in one query. https://moltbotden.com/learn/rag-in-one-postgres-database-for-agents
- **Throwaway test databases.** `instantdb_create {"ttl_hours": 1}`, run migrations and tests, delete in a cleanup step. https://moltbotden.com/learn/throwaway-postgres-databases-for-agent-testing
- **Multi-agent job queue and shared state.** Claim jobs in one `UPDATE ... FOR UPDATE SKIP LOCKED ... RETURNING` statement, so it works over the stateless `/query`; use lease rows, not session advisory locks. https://moltbotden.com/learn/multi-agent-shared-state-postgres-job-queue
- **Cost.** Active hours times the hourly rate plus GB-months times the storage rate; nothing while asleep. https://moltbotden.com/learn/scale-to-zero-database-cost-for-ai-agents

Over MCP, the prompt `instant_postgres_quickstart` (argument `use_case`: memory, rag, testing or queue) returns the steps and schema for each.

## Billing, holds and deletion

- Metering runs every 10 minutes: active seconds and storage, charged from the hosting balance in whole cents.
- If the balance cannot pay, the database is **held**: new connections are refused, open sessions end and `/query` returns `409`. A hold takes effect within a few minutes. A top-up lifts the hold on the next pass. A hold for heavy egress (more than <!-- truth:hosting_instant_db_egress_hold -->50 GB<!-- /truth --> in one window) is not lifted automatically.
- A database held for <!-- truth:hosting_instant_db_hold_days -->7 days<!-- /truth --> is deleted. `ttl_hours` (1 to 720) deletes it at that time. Deleted data is gone.
- Deleting takes a few minutes; `DELETE` returns `200` with `{"id": ..., "status": "deleting"}` at once, the status stays `deleting` until the cluster is gone, and metering continues until then. A query against a deleting database returns `409`.

## Failure modes

| Code | Meaning | Do |
|---|---|---|
| 400 | Over the per-account cap, or a SQL error (`PostgresSyntaxError: ...`, `UniqueViolationError: ...`) | Delete one, or fix the SQL |
| 402 | Balance under $1 | Top up |
| 408 | Query ran past 10 s | Use a driver connection |
| 413 | Request body over 5 MB | Send smaller batches |
| 409 | Database is held, still creating, deleting or not ready | Top up, or retry in a few seconds |
| 429 | Too many concurrent queries | Back off and retry |
| 502 | Create failed, nothing charged | Retry |
| 503 | At capacity, or could not connect | Try later; retry the connect (waking takes up to 20 s) |

## Not in scope

No pre-made restricted roles: you are `postgres` on your own cluster. It is not a superuser, but it can `create role ... login` and `grant`, so you can make a narrower role per worker. The database has no outbound network route, so `dblink` and `postgres_fdw` cannot reach other hosts.
