Files
PaperClipAI/docs/deploy/database.md
T
627e1be76d fix(db): give each database address time for a retransmitted SYN (#23784)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server reads and writes all state through one postgres.js pool
in `packages/db`.
> - Sentry recorded a production query failure. Every address of the
database host failed to connect: `connect ETIMEDOUT` on three IPv4
addresses and `ENETUNREACH` on three IPv6 addresses.
> - Node tries the addresses of a host name in turn ("happy eyeballs").
It gives each address except the last only 250 ms. The last address was
IPv6 and this host has no IPv6 route, so it failed at once.
> - Thus the connection failed after about 750 ms. One dropped SYN was
sufficient, because Linux sends the first SYN again only after 1 s. The
30 s `connect_timeout` of postgres.js did not apply.
> - This pull request gives each address 2 s by default, so a
retransmitted SYN can get an answer.
> - The benefit is that a short network stall to the database no longer
fails queries.

## Linked Issues or Issue Description

No public GitHub issue exists. This is a bug report.

**What happened?**

A server query failed with `Failed query: select ... from "companies"
...`. The cause was an `AggregateError` with code `ETIMEDOUT`. Its
errors were `ETIMEDOUT`, `ENETUNREACH`, `ETIMEDOUT`, `ENETUNREACH`,
`ETIMEDOUT`, `ENETUNREACH`. Each `ETIMEDOUT` came from Node's
per-address attempt timer (`internalConnectMultipleTimeout`), not from
postgres.js.

**Steps to reproduce**

1. Use a database host name that resolves to IPv4 addresses and IPv6
addresses, on a machine without an IPv6 route.
2. Make the IPv4 addresses drop SYN packets for less than one second.
3. Run a query that opens a new pooled connection.

**Expected behavior**

The connection waits for a retransmitted SYN. It fails only after
`connect_timeout`.

**Actual behavior**

The connection fails after about 750 ms with `AggregateError`
`ETIMEDOUT`.

## What Changed

- `patches/postgres@3.4.9.patch`: postgres.js now calls
`socket.connect({ port, host, autoSelectFamilyAttemptTimeout })` when
the new `auto_select_family_attempt_timeout` option is set. Without the
option, the call is the same as before. The change is in both the ESM
and CJS builds.
- `packages/db/src/client.ts`: new `connectAttemptTimeoutMs` client
option and `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` variable.
`resolveDatabaseClientOptions` sets a default of 2000 ms, so all pools
from `createDb` use it. `client.ts` was already longer than 1,000 lines.
This change adds the option next to the other driver options in that
file, because they share one parser and one mapping.
- `packages/db/src/postgres-connect-attempt-timeout.test.ts`: new
regression test. It examines the arguments that the patched driver gives
to `net.Socket.prototype.connect`.
- `packages/db/src/client-options.test.ts`: tests for the new variable,
its validation, the mapping and the default.
- `docs/deploy/database.md` and `doc/DATABASE.md`: document the new
variable.
- I did not commit `pnpm-lock.yaml`. The patch hash changes, and the
lockfile policy in `doc/ci-workflows.md` lets CI and the refresh
workflow update it.

## Verification

- Red, then green: `cd packages/db && npx vitest run
src/postgres-connect-attempt-timeout.test.ts`. Before the fix, both
tests failed. The driver called `connect(1, "127.0.0.1")` with no
options. After the fix, both tests pass.
- Focused: `npx vitest run src/postgres-connect-attempt-timeout.test.ts
src/client-options.test.ts src/postgres-connection-recovery.test.ts
src/client-disconnect-replay.test.ts src/client.test.ts
src/postgres-receive-buffer.test.ts`. Result: 6 files, 48 tests pass.
Some of these tests open real connections through the patched driver.
- `pnpm exec tsc --noEmit -p packages/db` passes.
- `pnpm verify` exits 2, because the postgres patch is a global CI
input. Required CI supplies the broad coverage.
- Manual reproduction on Node v24.23.0. A script overrides `dns.lookup`
to give the production address shape: three loopback IPv4 listeners with
full accept queues, which drop SYNs, and three unroutable IPv6
addresses. The listeners start to accept after 600 ms.
- Before: `AggregateError code=ETIMEDOUT after 764ms
inner=ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH`.
This is the same as the production error.
- After, with the 2000 ms default: the listener accepted the client's
retransmitted SYN at 1.035 s, and the TCP connection opened. The stub
was not a Postgres server, so the query then stopped at the test's 3 s
`connect_timeout`.

## Risks

- Low risk. The option changes only how long Node waits for one address
before it tries the next one. `connect_timeout` still bounds the whole
attempt.
- If an IPv6 address comes first and drops packets without an error,
each new connection can wait up to 2 s before it tries IPv4, not 250 ms.
Operators can set `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` lower.
- Unix-socket connections (`path`) and custom `socket` factories do not
change.
- The patch hash of `postgres@3.4.9` changes. CI resolves the lockfile
for this run, and the refresh workflow commits the new lockfile after
merge.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit and test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:08:46 -08:00

6.0 KiB
Raw Blame History

title, summary
title summary
Database Embedded PGlite vs Docker Postgres vs hosted

Paperclip uses PostgreSQL via Drizzle ORM. There are three ways to run the database.

1. Embedded PostgreSQL (Default)

Zero config. If you don't set DATABASE_URL, the server starts an embedded PostgreSQL instance automatically.

pnpm dev

On first start, the server:

  1. Creates ~/.paperclip/instances/default/db/ for storage
  2. Ensures the paperclip database exists
  3. Runs migrations automatically
  4. Starts serving requests

Data persists across restarts. To reset: rm -rf ~/.paperclip/instances/default/db.

The Docker quickstart also uses embedded PostgreSQL by default.

2. Local PostgreSQL (Docker)

For a full PostgreSQL server locally:

docker compose up -d

This starts PostgreSQL 17 on localhost:5432. Set the connection string:

cp .env.example .env
# DATABASE_URL=postgres://paperclip:paperclip@localhost:5432/paperclip

Push the schema:

DATABASE_URL=postgres://paperclip:paperclip@localhost:5432/paperclip \
  npx drizzle-kit push

3. Hosted PostgreSQL (Supabase)

For production, use a hosted provider like Supabase.

  1. Create a project at database.new
  2. Copy the connection string from Project Settings > Database
  3. Set DATABASE_URL in your .env

Use the direct connection (port 5432) for migrations and the pooled connection (port 6543) for the application.

If your transaction-mode pooler does not support protocol-level named prepared statements, disable them via the environment:

DATABASE_PREPARED_STATEMENTS=false

For a direct connection or a pooler that supports named prepared statements, DATABASE_PREPARED_STATEMENTS=true also prepares parameterized ORM queries and queries inside transactions and reserved or dedicated connections. Check the provider's configuration before you enable it. Preparation caches statement metadata, not query results. Unset preserves the existing ORM behavior and the driver default for tagged SQL. Explicit per-query options still apply. Each database client prepares at most 1,000 distinct statements and skips statements longer than 8 KB. If a prepared statement fails because the pooler's copy is stale after a schema change or was lost, Paperclip stops preparing that statement and retries it once unprepared.

Related optional client tuning: DATABASE_POOL_MAX, DATABASE_IDLE_TIMEOUT_SECONDS, DATABASE_CONNECT_TIMEOUT_SECONDS, DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, DATABASE_MAX_LIFETIME_SECONDS, DATABASE_APPLICATION_NAME. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (DATABASE_IDLE_TIMEOUT_SECONDS=0 keeps them open), each address of the database host gets 2 seconds to answer a connection attempt, and the server's main pool reports application_name=paperclip:<boot id> (other pools use names that start with paperclip). See Connection pool settings.

Connection Pool Settings

The server opens one postgres.js pool for its own queries (and a second one when DATABASE_MIGRATION_URL points at a different connection). Every setting is optional:

Variable Default Effect
DATABASE_POOL_MAX 10 (driver) Maximum pooled connections.
DATABASE_IDLE_TIMEOUT_SECONDS 60 Close a pooled connection after this much idle time. 0 keeps idle connections open forever (the driver default).
DATABASE_CONNECT_TIMEOUT_SECONDS 30 (driver) Give up on a connection attempt after this long.
DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS 2000 When the database host name resolves to several addresses, wait this long for one address before trying the next. Node's own default (250 ms) is shorter than one TCP retransmission, so a single dropped packet could fail the connection. DATABASE_CONNECT_TIMEOUT_SECONDS still bounds the whole attempt.
DATABASE_MAX_LIFETIME_SECONDS 30–60 min, randomized (driver) Recycle a pooled connection once it is this old.
DATABASE_APPLICATION_NAME paperclip:<boot id> (server main pool) Value of application_name in pg_stat_activity. The boot id tells the sessions of each server process apart after a restart. Find Paperclip's backends with SELECT * FROM pg_stat_activity WHERE application_name LIKE 'paperclip%';
DATABASE_DEDICATED_CONNECTION_MAX 24 Dedicated lock connections in use at once per process before new callers wait. Nested callers do not wait.
DATABASE_DEDICATED_CONNECTION_WAIT_MS 30000 After this wait, a queued caller gets a dedicated connection over the limit.
DATABASE_PREPARED_STATEMENTS Unset true opts parameterized ORM queries into preparation. false disables preparation. Use false when the pooler does not support named statements. Unset preserves existing behavior.

The server ends its pools during shutdown (SIGINT/SIGTERM) and when startup fails after the pool was opened, so a restarting server does not leave idle backends behind. Size max_connections on the PostgreSQL side for at least DATABASE_POOL_MAX per server process plus your other clients. Each server process also opens private pools and dedicated lock connections. With the defaults, one process can open up to 73 connections: DATABASE_POOL_MAX (10), 9 in private pools (lease renewal, checkpoints, file storage), 2 notification listeners, and up to 52 dedicated lock connections (application_name=paperclip-workspace-finalization-lock). DATABASE_DEDICATED_CONNECTION_MAX (default 24) bounds the dedicated connections in use; the worst case is twice that value plus 4 idle. Count all of these per process when you size max_connections, or lower DATABASE_DEDICATED_CONNECTION_MAX to fit.

Switching Between Modes

DATABASE_URL Mode
Not set Embedded PostgreSQL
postgres://...localhost... Local Docker PostgreSQL
postgres://...supabase.com... Hosted Supabase

The Drizzle schema (packages/db/src/schema/) is the same regardless of mode.