- PostgreSQL 16 or newer. While the standalone
@bastani/atomic-storage-postgresadapter connects to PostgreSQL 14+, Atomic’s session store requires PostgreSQL 16 or newer (forIS JSONandpg_input_is_valid). @bastani/atomic-storage-postgresinstalled on every machine that connects (see Join a machine).
PostgreSQL with PgBouncer
Put PgBouncer in front when agent processes exceed PostgreSQL’s connection limit.
Tune PostgreSQL for many agents
Server-side memory, huge pages,
pg_stat_statements, busy tables, and lz4 compression.A default PostgreSQL server allows 100 connections, and each Atomic process opens up to 10 (11 for an Intercom broker). If you plan to run more than ~8 processes, read Tuning for many concurrent agents before scaling out.
Set up the database
Atomic stores its tables in a dedicated schema namedatomic rather than public. Production deployments use two roles:
- Owner role (
atomic_owner): owns the database andatomicschema; runsatomic storage migrateto create and upgrade tables. - Runtime role (
atomic_runtime): used by agent machines; reads and writes rows only and cannot alter or drop schema objects.
1
Create the roles and database
Connect as a superuser (or your managed service’s administrator role) and run:On managed services where the admin role is not a superuser, uncomment the
GRANT line so the admin can create a database owned by atomic_owner.2
Allow TLS connections
On self-hosted servers, enable TLS first (see TLS)—Atomic verifies the server’s certificate and hostname by default. Allow agent machines as Managed services enable TLS by default and use firewall or private-network rules instead of
atomic_runtime and your migration host as atomic_owner in pg_hba.conf, then reload with SELECT pg_reload_conf();:pg_hba.conf.3
Create Atomic's tables with atomic storage migrate
On a machine with Atomic installed, install the PostgreSQL adapter, save the owner password in an owner-only file, and run
atomic storage migrate directly against PostgreSQL (not through a connection pooler):--password-file, --token-file, --auth, and --prefix work only alongside --db. Without --db, atomic storage migrate targets the database configured in this machine’s storage setting.4
Grant runtime privileges
Connect to the
atomic database as atomic_owner and run:ALTER DEFAULT PRIVILEGES covers objects added by future Atomic upgrades, so you only need to run this step once. Intercom LISTEN/NOTIFY and advisory locks require no extra grants.5
Join agent machines as the runtime role
Follow Join a machine on each host. If you are deploying PgBouncer in front of PostgreSQL, configure PgBouncer first and join with its endpoint (see Configure Atomic).
StorageConfigError (reason: "missing-privilege"), naming the exact GRANT or atomic storage migrate command to run.
After each Atomic upgrade
Runatomic storage migrate once as the owner role after upgrading Atomic and before scaling up agents. Because the runtime role cannot run DDL, running migrate handles everything that requires table ownership:
- Schema and lazy objects: creates new tables, lazily initialized tables/functions (fork staging, chat records, the single-round-trip session append function, and Intercom’s ended-child queue tables), and shared-history fork upgrades.
- Non-blocking index rebuilds: rebuilds the
snapshot_session_linksindex concurrently without blocking writes (with a 6-hour statement timeout for large tables). - Table tuning: applies
fillfactor, autovacuum thresholds, search index parameters, unlogged wake-up notices, andlz4compression where supported (see Server tuning). Each table tuning statement uses a 2-secondlock_timeoutand gracefully skips busy tables rather than failing the migration—re-run later if any table was reported busy. - Search trigram index: installs
pg_trgmonce allowed on managed providers (see Managed PostgreSQL services).
atomic storage migrate on an already up-to-date database is a no-op.
Share one database between teams
Isolate teams or projects either in separate databases or with a tableprefix (no prefix by default). Pass the same --prefix to atomic storage migrate and to every atomic storage join in that group; hosts with a different prefix cannot see those sessions.
On PostgreSQL, a prefix may contain at most 24 lowercase ASCII characters. Longer prefixes fail with StoragePrefixError (too-long), and uppercase letters fail with uppercase.
Upgrading from tables in public
Older Atomic releases placed tables in the public schema. Atomic continues using them until you migrate them to atomic:
- Upgrade Atomic on every machine sharing the database.
- Run
atomic storage migrateonce as the owner of the tables inpublic(moves all Atomic tables—and any legacywf_*tables—toatomicin one transaction). - Grant runtime privileges on
atomicas in step 4 of Set up the database. - Restart every Atomic process that opened the database before the move.
public after the move are refused so data never splits across schemas. If an older process creates a stray table in public afterward, the next atomic storage migrate names it and stops rather than discarding it.
Join a machine
Run these steps on each machine as the user who runs Atomic:1
Install the PostgreSQL adapter
2
Save the runtime password to a private file
Reading from stdin keeps the password out of shell history:
3
Join the database
SELECT 1 probe (15-second timeout) before writing anything, copies the password to an owner-only ~/.atomic/agent/storage-token.<id> file (mode 600), and updates only the top-level storage key in ~/.atomic/agent/settings.json.4
Restart Intercom and verify status
Restart the local Intercom broker so it adopts the shared database (safe if no broker is running; already-open sessions keep their old store until restarted):
atomic storage status exits 0 when both sessions and Intercom connect, reporting multi-node: on and wake-ups: LISTEN/NOTIFY. The broker starts on demand with the first session that uses Intercom, so brokers: 0 live right after a restart is expected.5
Delete your temporary password file
atomic storage join already saved its own private copy inside ~/.atomic/agent/.atomic storage join accepts a postgres:// or postgresql:// URL with the username and never a password. Supply exactly one credential flag:
atomic storage join overwrites any existing top-level storage setting without keeping a backup. Save your previous storage value first if you need it.~/.atomic/agent/settings.json entry looks like this (keep the exact storage-token.<id> filename that atomic storage join generated on your machine; storage-token.example is a placeholder in the examples below):
secrets.password.file paths resolve against the storage home (~/.atomic). You can also author this object directly in settings.json, ATOMIC_STORAGE, or --storage using { "file": "<path>" } or { "env": "<VAR>" }. Atomic re-reads secrets.password on every new connection, so rotated passwords take effect without restarts. A password placed in options is ignored, and missing secrets.password fails with StorageConfigError (secret-missing).
Connection options
Configure these underoptions (defaults suit small deployments; see Tuning for many concurrent agents for larger fleets):
For SDK apps using
openPostgresDatabase(), see @bastani/atomic-storage-postgres and SDK session storage.
TLS
Atomic encrypts every remote connection and verifies both the server’s certificate and hostname (sslmode=verify-full) by default. Connections to localhost, loopback addresses, and Unix sockets skip TLS unless sslmode is specified in the URL. When the URL omits a host, Atomic reads PGHOST.
Override TLS behavior with a lowercase sslmode query parameter in url:
Note that
require without sslrootcert verifies more strictly than psql. Unknown sslmode values or uppercase TLS parameter names fail with StorageConfigError.
Certificate authorities (sslrootcert):
- Self-hosted PostgreSQL: Enable
ssl = on,ssl_cert_file, andssl_key_fileinpostgresql.confwith a certificate matching the hostname inurl. For a private CA, append?sslrootcert=/path/to/root.crt. Default distro self-signed certificates (like Debian’ssnakeoil) fail default verification. - Azure Flexible Server, Azure HorizonDB, and Neon: Trusted by Node.js’s built-in CA store; no
sslrootcertneeded. - Supabase: Download the project CA from Project Settings → Database → SSL Configuration and pass
?sslrootcert=/path/to/supabase-ca.pem. - Amazon RDS / Aurora: Download
https://truststore.pki.rds.amazonaws.com/<region>/<region>-bundle.pemand pass?sslrootcert=/path/to/bundle.pem. - Google Cloud SQL: Export the server CA with
gcloud sql instances describe <instance> --format='value(serverCaCert.cert)'. Over private IP, pass?sslmode=verify-ca&sslrootcert=/path/to/server-ca.pem(the certificate does not list private IPs).
Through an HTTP proxy
When outbound network traffic must traverse an HTTP proxy, Atomic tunnels PostgreSQL connections using HTTPCONNECT. Allow <database-host>:5432 (or your server port) on the proxy.
- Proxy selection: Reads
HTTPS_PROXY/https_proxy, thenALL_PROXY(forhttp://orhttps://), thenHTTP_PROXY. Embedded proxy credentials are sent to the proxy and redacted from logs and errors. - Bypass rules:
NO_PROXY/no_proxyaccepts hostnames,.example.com,*.example.com,host:port, or*.localhost, loopback addresses, and Unix sockets always connect directly. - Per-store override: Set
options.proxyto a proxy URL for one store, or"none"to ignore environment proxy variables. - End-to-end TLS: TLS runs inside the tunnel so the proxy sees encrypted bytes only. With
verify-full, the certificate must match the database hostname;verify-cadefends against proxy interception only whensslrootcerttrusts solely your database CA.
403 or 407 proxy rejection fails immediately with StorageUnavailableError. Connection drops or 502/503 responses retry like an unreachable server and log a warning naming the proxy.
Connection budget
Connections are pooled per Atomic process. Each of the following counts as one process:- every interactive
atomicoratomic -pinvocation; - every
atomic --mode rpcsubprocess; - each Intercom broker (one per agent directory, typically one per host or container).
At defaults, one agent process opens at most 10 connections, and an Intercom broker opens at most 11.
Connections open lazily and scale back down automatically: burst connections close after 10 seconds idle, while the final connection in each pool stays warm for
idleTimeoutMs (5 minutes by default). Open connections never prevent a process from exiting.
- Small team / interactive use: keep the defaults.
- Large fleet with idle periods: size
maxConnectionsvia Tuning for many concurrent agents and loweridleTimeoutMs(for example10000–30000) so idle processes release connections faster. - More processes than
max_connectionsallows: deploy PgBouncer in transaction mode and pointlistenUrldirectly at PostgreSQL.
Connection poolers
Atomic supports connection poolers in transaction mode or session mode (never statement mode), including self-hosted PgBouncer, Azure Flexible Server’s built-in PgBouncer (port 6432), Supabase Supavisor (port 6543), and Neon’s-pooler endpoint.
Transaction poolers cannot forward PostgreSQL LISTEN/NOTIFY notifications, so set listenUrl to PostgreSQL’s direct endpoint (for example port 5432 on Azure, or Neon’s non--pooler host). Without listenUrl, Intercom still delivers messages by polling every 0.5 seconds (see Wake-ups).
For a complete TLS + SCRAM PgBouncer setup, see PostgreSQL with PgBouncer.
Wake-ups
When a machine sends a cross-host Intercom message, the receiving broker learns about it immediately through PostgreSQLLISTEN/NOTIFY. Each listening process (such as an Intercom broker) holds one dedicated atomic-listen connection per database.
Atomic backs up real-time notifications with two independent polling safety nets:
- Wake-up hint poll (
intercom_wakeups): WhileLISTEN/NOTIFYis live, each broker polls wake-up hints every 5 seconds to catch any missed notification. If theLISTENconnection drops—orurlpoints at a transaction pooler withoutlistenUrl—brokers poll wake-up hints every 0.5 seconds (500 ms) instead. Atomic retries reconnecting a droppedLISTENconnection every 30 seconds (behind a transaction pooler withoutlistenUrl, it stays in polling mode until restart). - Backup outbox scan (
intercom_outbox): Independently of wake-up hints, every broker scans the durable outbox table directly every 30 seconds. Even if a server crash or failover empties the unloggedintercom_wakeupstable, every message still arrives within 30 seconds (see Intercom’s wake-up notices).
atomic storage status:
Managed PostgreSQL services
All major managed PostgreSQL services work with the roles in Set up the database. Provider-specific notes:Azure
- Azure Database for PostgreSQL Flexible Server: Connect to
<server>.postgres.database.azure.com:5432(TLS trusted automatically). Run role setup as a member ofazure_pg_admin(if usingschema: "public", also runGRANT CREATE ON SCHEMA public TO atomic_owner;). On General Purpose / Memory Optimized tiers, enable built-in PgBouncer (pgbouncer.enabled, port 6432) and pointlistenUrlat port 5432. AllowPG_TRGMinazure.extensionsand runatomic storage migratefor indexed history search. Note smaller tiers like Burstable B1ms allow only 50 connections (with 15 reserved for admins). - Azure HorizonDB (preview, PostgreSQL 17): Connect to the read/write endpoint (
<cluster>.rw.<id>.<region>.horizondb.azure.com:5432); read-only endpoints are unsupported because Atomic writes on open. Wake-ups work on the read/write endpoint. Allowpg_trgmin the compute pool’s parameter group, then runatomic storage migrate. - Both support Microsoft Entra ID via
--auth azure.
Amazon RDS and Aurora
- Connect to the writer endpoint (never a read-only replica) and pass the regional CA bundle via
?sslrootcert=/path/to/<region>-bundle.pem(see TLS). - If using Amazon RDS Proxy, point
listenUrlat the DB instance endpoint and setmaxPreparedStatements: 0(RDS Proxy listens on port 5432 and does not preserve prepared statements orLISTEN). - Supports IAM authentication via
--auth aws.
Google Cloud SQL
- Run initial role creation as
postgresor a member ofcloudsqlsuperuser, and pass the exported server CA viasslrootcert(usesslmode=verify-caover private IP; see TLS). - Supports IAM authentication via
--auth gcp.
Neon and Supabase
- Neon: Built-in TLS CA is trusted automatically. For pooled connections, point
urlat the-poolerhost andlistenUrlat the direct host without-pooler. - Supabase: Download the project CA certificate for
sslrootcert(see TLS). For Supavisor transaction pooling, pointurlat port 6543 andlistenUrlat port 5432; leavemaxPreparedStatementsunset so Atomic keeps prepared statements off behind Supavisor.
Cloud identities
Machines on Azure, AWS, or Google Cloud can authenticate using short-lived cloud IAM tokens instead of static passwords. Tokens are requested per new connection and kept in memory only. Install the provider’s library once per machine:atomic install places these libraries in ~/.atomic/agent/npm, where @bastani/atomic-storage-postgres discovers them. Missing libraries or unavailable credentials fail immediately with StorageConfigError (auth-unavailable). Cloud IAM tokens require TLS, so keep the default sslmode.
Map the cloud identity to a PostgreSQL role and grant it the runtime privileges from Set up the database:
- Azure: Enable Microsoft Entra authentication, connect to
postgresas the Entra admin, runSELECT * FROM pgaadauth_create_principal('<identity name>', false, false);, grantCONNECTon theatomicdatabase, and use<identity name>as the URL user. - AWS: Enable IAM database authentication, run
CREATE USER atomic; GRANT rds_iam TO atomic;, and grant the IAM identityrds-db:connectonarn:aws:rds-db:<region>:<account>:dbuser:<DbiResourceId>/atomic. - Google Cloud: Enable
cloudsql.iam_authentication=on, add the service account as an IAM database user withroles/cloudsql.instanceUser, and use the service account email without.gserviceaccount.comas the URL user (Compute Engine VMs need thecloud-platformscope).
@bastani/atomic-storage-postgres for full SDK options.
Tuning for many concurrent agents
Write parallelism scales with each process’s connection pool: writes to different sessions run concurrently on separate connections, while writes to the same session serialize. This section covers client-side Atomic settings; for server memory, autovacuum, and monitoring, see Server tuning. Every Atomic process across all hosts shares PostgreSQL’smax_connections. Give each process as many connections as the server can safely spare, and no more.
Count the connections Atomic needs
Plan for each process’s peak connection count (from Connection budget):- Agent process (including each
atomic --mode rpcchild):maxConnections + readerMaxConnections - Intercom broker:
maxConnections + readerMaxConnections + 1(for wake-ups)
maxConnections:
- Compute available =
max_connections− reserved slots − non-Atomic client connections. - Count P (total Atomic processes across all hosts) and B (Intercom brokers—usually one per host or container).
- Each process gets
floor((available − B) / P)connections. - Set
maxConnections= that budget minusreaderMaxConnections.
maxConnections below 2, put PgBouncer in front of the server (see the second example below).
A default server (max_connections = 100, 3 superuser slots) fits about 8 processes at default settings (10 per agent, 11 per broker). For example, 20 agents across 4 machines (4 brokers) can open up to 20 × 10 + 4 × 11 = 244 connections—requiring higher max_connections, lower maxConnections, or PgBouncer.
Example: 24 processes on a large server
Four machines each run 5 agent processes and 1 Intercom broker (P = 24, B = 4). The server hasmax_connections = 500, 3 superuser slots, 0 other reserved slots, and 20 non-Atomic connections:
- available = 500 − 3 − 0 − 20 = 477
- Per-process budget =
floor((477 − 4) / 24)= 19 - With default
readerMaxConnections: 2, setmaxConnections: 17.
~/.atomic/agent/settings.json on each machine:
Example: 150 machines on a smaller server
Here, 150 CI runners each run 1 agent process and 1 Intercom broker (P = 300, B = 150) against a server withmax_connections = 300, 3 superuser slots, and 10 other clients (available = 287).
Even with maxConnections: 1 and readerMaxConnections: 0, 300 processes need 300 + 150 = 450 connections—more than 287. Route traffic through PgBouncer in transaction mode on port 6432:
- Point
urlat PgBouncer and keepmaxConnections: 8. Set PgBouncer’smax_client_connaboveP × (maxConnections + readerMaxConnections)(300 × 10 = 3000). - Point
listenUrldirectly at PostgreSQL (optional). WithlistenUrl, each broker holds 1 direct connection for instant wake-ups and polls hints every 5 seconds; without it, brokers poll every 0.5 seconds. - Cap PgBouncer’s server pool within remaining capacity (
287 − 150 = 137withlistenUrl, or287without). A smaller pool (such as 80 + 5 reserve in the PgBouncer guide) often outperforms a larger one.
Other settings
Tune these underoptions (all timeouts are integers in milliseconds):
- Colocate database and agents. Every save waits for at least one network round trip—run PostgreSQL in the same region as your agents, and run
atomic storage migrateafter upgrades so saves use the single-round-trip append path. idleTimeoutMs(default300000): lower (for example30000) when idle processes hold connections on a busy server.statementTimeoutMs(default30000): raise only if legitimate queries hitStorageTransientError(transaction-timeout).connectTimeoutMs(default10000): raise for high-latency or slow-accepting servers.keepAliveIdleMs(default60000): lower if connections fail withconnection-lostafter idle periods (NAT, firewall, or load balancer dropping idle TCP sockets).maxPreparedStatements(default256, or0behind unsupported poolers): lower if server per-connection memory is tight. Atomic auto-detects poolers on ports6432and6543; behind a pooler on another port, setlistenUrlormaxPreparedStatements: 0. See Prepared statements.
Check the effect
Run these queries as an administrator (replaceatomic with your database name):
Connections by Atomic pool and state:
max_connections:
The first two rows surface as
StorageTransientError (connection-refused) with the quoted message as cause; the third surfaces as StorageUnavailableError.