
# Your app's Postgres

Each app has its own managed Postgres 18 database, and production, every mirror and every rehearsal are branches of it. Your code gets the connection string in one environment variable, `DATABASE_URL` unless `[data.db] env` names another. `agc doctor` passes its "data wiring" check when your source reads that name.

```toml
[data.db]
env        = "DATABASE_URL"
migrations = "migrations/"
```

## Ask your agent

```text
Wire the app to Agent Cloud's Postgres through DATABASE_URL, with a small pool that closes idle connections, and check it with agc doctor.
```

```text
Before we add bookings and payments, check our schema against Agent Cloud's data
conventions and fix anything in a new migration.
```

## Steps

```bash runnable
agc doctor
agc up --detach
agc db query "SELECT version()"
```

## How it works

**One project per app.** When an app is created, Agent Cloud makes its managed Postgres project (names and region under Reference). A mirror is a masked branch of production. A rehearsal is a fresh unmasked branch, dropped afterwards. Production's credentials never leave Agent Cloud: each new mirror branch gets a new owner password, so a mirror's URL can't open production.

**What the app receives.**

| Where | `DATABASE_URL` (or your `env`) points at | TLS |
|---|---|---|
| Production | The production branch, direct (not pooled) | `sslmode=verify-full` |
| Rehearsal | Its own branch of production, with a fresh owner password | `sslmode=verify-full` |
| Mirror, inside the OS sandbox | `127.0.0.1:<port>`, a relay agc runs outside the sandbox | `sslmode=disable` on the loopback leg; the relay verifies the database provider's certificate and host name |
| Mirror, unsandboxed process | The mirror branch | `sslmode=verify-full` |

So the same code must work with and without TLS parameters in the URL. Pass it to your driver as is. Don't add `ssl: { rejectUnauthorized: false }` or a fixed `sslmode`. The default Python image sets `PGSSLROOTCERT` to the system CA file so psycopg can verify. The mirror's database is also on `localhost` for your own tools: `agc up` prints `database.host` and `database.port`.

**Suspend and wake.** Production, mirror and rehearsal compute autoscales and suspends when idle (numbers under Reference). The next connection wakes it. An open connection, a `LISTEN`, or a pool that keeps sockets alive keeps it awake.

**Connection hygiene.**

- Use a small pool that closes idle connections after about a second (`idleTimeoutMillis: 1000` in node-postgres).
- Don't `LISTEN` for work. A worker polls, every 10 seconds while it finds jobs, doubling after each empty poll up to 10 minutes ([Background work](/docs/build/background-work-and-workers.md)).
- The first query after a quiet spell wakes the database, so keep request timeouts generous.
- The URL is a direct connection, not the database provider's pooler. Don't rewrite it to a pooled host.

**Private targets.** On a customer's own target, the app reaches Postgres through the target's relay. Production answers only Agent Cloud's own addresses (the relay and the control plane), so a leaked URL works nowhere else ([Data on private targets](/docs/data/reading-production-safely.md#data-on-private-targets)).

## Data modelling conventions

Five conventions keep the data correct and mirrors useful. None blocks a ship; each is a warning or review finding (table below). Each is cheap in the first migration and expensive once production has rows. Success is no money warning from `agc check` and no `no-primary-key` or `unindexed-fk` finding from `agc review`.

```sql
-- migrations/20261020100000_bookings.sql
CREATE TABLE users (
  id    uuid PRIMARY KEY,          -- agent.cloud's user.id
  email text
);

CREATE TABLE bookings (
  id          bigserial PRIMARY KEY,
  user_id     uuid   NOT NULL REFERENCES users (id),
  camp_id     bigint NOT NULL REFERENCES camps (id),
  price_cents bigint NOT NULL CHECK (price_cents >= 0),
  currency    text   NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),   -- ISO 4217, like 'USD'
  status      text   NOT NULL DEFAULT 'pending',
  created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX bookings_user_id ON bookings (user_id);
CREATE INDEX bookings_camp_id ON bookings (camp_id);
```

```bash
agc migrate
agc check
agc review
```

**Money as integer minor units.** Binary floats can't hold 0.10 exactly, so sums drift by fractions of a cent. Store `bigint` cents (or the currency's minor unit) next to a `currency` column, and format at the edge. `numeric` is also exact, but cents are simpler to sum and compare. `agc check` scans every migration for a float column with a money word in its name and warns ([the warning and word list](/docs/checks/checks-overview.md#lint-warnings)).

Moving an existing float column is a [safe schema change](/docs/data/safe-schema-changes.md): add `amount_cents`, backfill, switch reads, then drop `amount` with a `drops` header in a later ship.

**Users keyed on `user.id`, a uuid.** Agent Cloud sign-in returns a stable `user.id` per app. Mirrors mask emails and names but keep uuids. So a mirror's `users` rows still join to its other data, and its test sign-in can sign you in as any of them by id. Keying on email breaks both, and emails change. Behind the edge gate there's only the email header: key on the email there.

**A primary key on every table.** Without one, duplicate rows appear and a single row can't be updated or deleted reliably. Rehearsals check by primary key that no existing row disappeared, so a table without one gets no such check. Changing a primary key later needs a `-- agentcloud: rekeys <table>` header.

**An index on every foreign key.** Postgres doesn't index the referencing side. Lookups by that column, and deletes on the referenced table, scan the whole table, which gets slow as it grows. An index whose leading columns are the foreign key's columns counts.

**Keep labels low-cardinality.** Default masking keeps a label only with at most 20 distinct values and five filled rows per distinct value, and free text is masked. An owner can make a column visible, but an inferred manifest `keep` cannot override policy. A `status` with a small, fixed set of values is more useful on a mirror than a free-text description.

| Convention | Checked by | Name | Severity |
|---|---|---|---|
| Money not in a binary float (`real`, `double precision`, `float`, `float4`, `float8`) | `agc check` | money lint warning | warning |
| Primary key on every table | `agc review` | `no-primary-key` | medium |
| Index on every foreign key | `agc review` | `unindexed-fk` | low; medium above about 10,000 estimated rows |
| Uploaded files kept out of the database | `agc review` | `blob-in-postgres` | info |
| Users keyed on `user.id` | Not checked | | |
| Masking keeps a text column visible | Platform policy ([Masking](/docs/concepts/masking.md)) | | |

## Reference

| Setting | Value |
|---|---|
| Postgres version | 18 |
| Project | `agc-<app>`, region `aws-us-west-2` |
| Branch, database, owner role | `production`, `app`, `app_owner` |
| Compute | 0.25 to 1 CU, suspends after 60 s idle (production) |

The `[data.db]` keys (`env`, `migrations`, `mask`, `seed`) are in the [manifest reference](/docs/reference/agentcloud-toml-reference.md).

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md).

| Check | Exit | Cause | Fix |
|---|---|---|---|
| `agc doctor` "data wiring" warn | 0 | No source file mentions the `env` name | Read the URL from that variable, or set `[data.db] env` to the one the code uses |

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "up",
  "data": { "mirror": "main", "host": "ep-example-123456.us-west-2.aws.neon.tech", "port": 5432 },
  "error": {
    "code": "mirror.db_unreachable",
    "message": "This machine can’t open a connection to the mirror’s database at ep-example-123456.us-west-2.aws.neon.tech:5432 (ETIMEDOUT).",
    "fix": "Run agc up where outbound connections to port 5432 are allowed, or test against a local Postgres and let `agc ship` rehearse the release on agent.cloud.",
    "retryable": false
  },
  "next": [{ "cmd": "agc ship", "why": "agent.cloud rehearses the release on a branch of production, without a mirror" }]
}
```

## Agent notes

- Don't ask the person for a database URL or put one in a file; Agent Cloud injects it. To look at production, people use the console's one-hour read-only logins ([Console database access](/docs/data/reading-production-safely.md#console-database-access)) and agents use masked reads ([Reading production safely](/docs/data/reading-production-safely.md)).
- Name money columns for what they hold (`price_cents`): the money lint reads column names.
- An ORM's own migrator must not run at start-up or anywhere else ([Migrations](/docs/data/migrations.md)).
- Put foreign-key indexes in the table's own migration. Don't use `float` for amounts even in a prototype; changing the type later is a multi-ship migration.
- Use opaque ids (numbers or uuids) for workflow event entities too, never names or emails.

## Related

- [Migrations](/docs/data/migrations.md)
- [Safe schema changes](/docs/data/safe-schema-changes.md)
- [Reading production safely](/docs/data/reading-production-safely.md)
- [Background work and workers](/docs/build/background-work-and-workers.md)
- [Well-Architected review](/docs/ship/well-architected-review.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "data/your-apps-postgres: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
