atomic) and no prefix. When a prefix is configured, every table name starts with it (for example, prefix: "team_" maps atomic.session_sessions to atomic.team_session_sessions).
Where the time goes
Three bottlenecks typically limit multi-agent throughput on PostgreSQL:- Round trips: Every save waits for the server to acknowledge it; higher network latency adds directly to every save and lock hold time.
- Connections: Exceeding
max_connectionsrejects new work with errors. - Locks: Agents writing to the same session wait in line for each other.
atomic with your database name):
Connections by state (active = executing a query; idle = open and waiting):
Lock indicates contention; Client / ClientRead typically reflects network round-trip latency):
max_connections:
uptime: if load average sits well below CPU core count while agents feel slow, the workload is waiting on network latency or locks rather than CPU.
Put the database close to the agents
Every save waits for at least one network round trip, and transactions hold their locks across those round trips:
Run PostgreSQL in the same region—and ideally the same availability zone—as your agents. No server parameter compensates for network distance. Also run
atomic storage migrate after upgrades so session appends use the single-round-trip path instead of two round trips (see After you upgrade Atomic).
Connections
Each Atomic process opens up tomaxConnections + readerMaxConnections connections (10 by default), plus 1 wake-up connection per Intercom broker. See Count the connections Atomic needs and Tuning for many concurrent agents for sizing.
On the server:
max_connections(requires restart): set high enough for Atomic’s connections (or PgBouncer’s server pool), one wake-up connection per broker, and admin/monitoring overhead.- Per-role cap: cap
atomic_runtimeto PgBouncer’s pool plus broker wake-ups plus a safety margin so a fleet surge cannot starve administrators (see Connection limits). - Connection pooler: deploy PgBouncer when fleet demand exceeds
max_connections.
Memory
Shared buffers
shared_buffers controls PostgreSQL’s shared page cache (requires restart). A good starting point is 25% of host RAM (for example shared_buffers = 8GB on a 32 GB host). Atomic’s working set usually fits comfortably inside this cache, so allocating much more rarely helps.
Huge pages
Linux normally tracks memory in 4 KB pages, and every PostgreSQL backend keeps its own page-table entries for shared memory. With largeshared_buffers and hundreds of connections, page tables alone can consume gigabytes. Linux 2 MB huge pages shrink those page tables by 512×.
PostgreSQL uses huge pages automatically when huge_pages is try (default) or on and enough huge pages are reserved at the OS level. Managed services configure huge pages for you; on self-hosted Linux:
1
Ask PostgreSQL how many huge pages it needs
Stop PostgreSQL first (Elsewhere,
-C reads this only while stopped), then run postgres as the postgres user (on Debian/Ubuntu, adjust 18 for your PostgreSQL version):postgres -D <data-dir> -C shared_memory_size_in_huge_pages is usually enough. Note the printed count (for example 4259).2
Reserve slightly more pages persistently
Round up with headroom (for example
4350 for 4259 needed):3
Start PostgreSQL and verify
on (PostgreSQL 17+; on PostgreSQL 16, verify HugePages_Rsvd in /proc/meminfo matches the expected count).Reserved huge pages remain unavailable to other host processes even when PostgreSQL is stopped. To release them, stop PostgreSQL and set
vm.nr_hugepages = 0.See what is slow
Usepg_stat_statements to measure total and per-call execution time across all agent queries:
1
Preload pg_stat_statements and restart PostgreSQL
Add to
postgresql.conf (or append to an existing comma-separated list):2
Create the extension as a superuser or managed-service admin
3
Grant stats visibility to your monitoring role
Without
pg_read_all_stats, a role can inspect only its own query text:atomic database:
Top queries by total execution time (start here):
pg_advisory_xact_lock—a high percentage means agents are contending on the same data rather than waiting on PostgreSQL):
Busy small tables
Three small tables receive frequent updates:Clean them up sooner
Because PostgreSQL uses MVCC, every update leaves a dead tuple until autovacuum reclaims it. PostgreSQL’s default 20% dead-tuple ratio can let thousands of dead versions accumulate on small, hot tables.atomic storage migrate (run as the owner role) automatically configures fixed dead-tuple autovacuum thresholds: 500 for session_sessions and intercom_leases, and 1000 for snapshot_session_links. No restart is needed, and migrate preserves any custom threshold you have set manually:
session_entries keep PostgreSQL’s default autovacuum settings.
Updates that stay on their page
When an updated row version fits on the same 8 KB page and modifies no indexed column, PostgreSQL performs a HOT (Heap-Only Tuple) update—skipping index writes and reducing bloat.atomic storage migrate configures this automatically:
- Sets
fillfactor = 80onsession_sessionsandintercom_leases, andfillfactor = 85onintercom_outbox, leaving free space on new pages for in-place HOT updates. (Rewriting pre-existing pages viaVACUUM FULL—which locks the table—orpg_repackis optional.) - Replaces the legacy
snapshot_session_links_leavespartial index (which filtered onchildren = 0) withsnapshot_session_links_anchored(WHERE anchor_seq IS NOT NULL), built concurrently without blocking writes. Because no index referenceschildrenanymore, parent-linkchildrenincrements on session appends stay HOT updates whenever the page has free space. Combined with the autovacuum threshold (1000), this keepssnapshot_session_linkscompact and fast.
The search index
Atomic indexes session history text with a GIN trigram index (atomic.session_search_trgm on atomic.session_search_entries). New writes land in the GIN pending list (immediately searchable) and merge in bulk.
atomic storage migrate sets gin_pending_list_limit to 64 MB (replacing PostgreSQL’s 4 MB default or any previous 1 MB limit) so foreground writes rarely trigger an inline merge, and configures autovacuum on atomic.session_search_entries to run after every 1,000 inserted rows so pending entries flush regularly. Agents connecting as the index owner also clean the pending list asynchronously in the background; agents connecting as the least-privilege atomic_runtime role rely on autovacuum to perform those merges—so keep autovacuum enabled. Search indexing does not hold session write locks.
Verify the index and table storage parameters:
pgstattuple requires a superuser or managed-service admin):
Intercom’s wake-up notices
When a broker sends a cross-host message, it writes a short wake-up hint toatomic.intercom_wakeups alongside the durable message in atomic.intercom_outbox. Atomic marks intercom_wakeups as UNLOGGED (either on creation or during atomic storage migrate) to eliminate WAL writes and disk flushes for ephemeral hints.
Normally, brokers receive LISTEN/NOTIFY notifications immediately and poll intercom_wakeups every 5 seconds (or every 0.5 seconds if LISTEN/NOTIFY is unavailable; see Wake-ups). If PostgreSQL crashes or fails over to a standby, the unlogged intercom_wakeups table empties—losing only hints while messages remain safely in intercom_outbox. Independently of wake-up hints, every broker scans intercom_outbox directly every 30 seconds as a backup safety net, so every message still arrives within at most 30 seconds.
Compression of large values
atomic storage migrate automatically switches large text, JSON, and binary columns (session_entries, chunk tables, snapshot blobs, chat records, and intercom_outbox) from PostgreSQL’s default pglz compression to lz4 whenever the server supports it (standard in most PostgreSQL 14+ builds).
lz4 compresses and decompresses roughly 2–4× faster than pglz—especially on already-compressed content like images and archives—for only a few percent more disk space on plain text, while avoiding the ~2× storage overhead of disabling compression (SET STORAGE EXTERNAL). Existing rows remain readable as-is; new writes use lz4. If your server was compiled without lz4, migrate reports this and leaves columns unchanged.
Check active compression methods on session_entries (NULL means a value was small enough to store inline uncompressed):
Settings you can usually leave alone
synchronous_commit: Keeponserver-wide so crashes cannot drop committed session entries or messages. Atomic already setssynchronous_commit = offper transaction for repeatable broker lease heartbeats (every 10 seconds), where losing one write is harmless.wal_compression: Keep your server default.deadlock_timeout: Leave at default; Atomic’s expected lock waits use its own timeouts. Keepinglog_lock_waits = onis helpful for diagnosing long waits.
After you upgrade Atomic
Runatomic storage migrate once as the owner role after every Atomic upgrade, before launching your agent fleet:
migrate as the owner role ensures:
- Fast startup: Agents open an up-to-date database in a couple of round trips with no schema-init contention.
- Owner-only optimizations and lazy objects: Applies
fillfactor, autovacuum thresholds,lz4compression, search index tuning, unloggedintercom_wakeups, the concurrentsnapshot_session_links_anchoredindex rebuild (up to a 6-hour statement timeout for large tables without blocking writes), the single-round-trip session append function, and lazily initialized tables (fork staging, chat records, Intercom ended-child queue). Each table tuningALTER TABLEuses a 2-secondlock_timeoutand gracefully skips busy tables without failing the migration—re-run later if any table was skipped. - Faster resume with worktree snapshots: Atomic keeps the small snapshot fields it compares during resume in a dedicated
session_capture_headingstable maintained by triggers and populated lazily per session on first read—so CLI startup never alters or scanssession_entries. Runningatomic storage migrateas the owner creates the table and triggers for runtime roles and backfills existing snapshots in bounded, crash-resumable batches without blocking writes. Sessions can still resume using the unindexed path until the table is created. If interrupted, rerun the same command.
Checklist
On managed services (Amazon RDS, Azure Database for PostgreSQL, Google Cloud SQL), adjust server settings through parameter groups or console controls; SQL statements work identically (creating extensions requires the managed admin role).
Related pages
- PostgreSQL setup: database roles, TLS, proxies, and troubleshooting.
- Tuning for many concurrent agents: client pool arithmetic and
maxConnections. - Use PgBouncer with PostgreSQL: transaction pooling configuration and health checks.