Skip to Content
Runlane
Run in production

Run behind PgBouncer

Pool storage queries while keeping migrations and listeners on a direct Postgres connection.

PgBouncer lets many app connections share a smaller set of Postgres connections. Runlane's storage queries support transaction pooling. Migrations and LISTEN need a connection that stays on one Postgres session.

Configure PgBouncer

Runlane reuses named protocol-level prepared statements by default. To keep that behavior, use PgBouncer 1.21 or later, in transaction mode, with prepared-statement tracking enabled:

pgbouncer.ini
[pgbouncer]
pool_mode = transaction
max_prepared_statements = 200

Set max_prepared_statements above 0. Its default is 200 since PgBouncer 1.24; older supported versions default to 0. Runlane never uses SQL-level PREPARE.

max_prepared_statements caps a cache on each server connection. Runlane shares that cache with every other client of the same pool, including your app. Cache use grows with the named query shapes your workload uses. Start with 200 and size it for your workload. Check yours with PgBouncer's SHOW SERVERS admin command: its prepared_statements column shows the count for each server connection. Statement pooling is unsupported because Runlane uses transactions with multiple statements. See PgBouncer's configuration reference.

Use a dedicated schema, such as runlane, behind a pooler. Outside public, Runlane names its schema in every query, so a client's session search_path can't change which tables it uses. In public, the default, table names are unqualified. In transaction mode, PgBouncer doesn't reset a server connection between clients, so a SET search_path left by another client can redirect those queries.

Watch for a ?schema= parameter in your URLs. Runlane reads it when you don't pass schema, and Prisma-style URLs often carry ?schema=public. Pass schema: 'runlane' explicitly.

Keep prepared-statement tracking disabled

If your transaction pool uses max_prepared_statements = 0, set preparedStatements: false on Runlane's Postgres options. You can keep the pooler's setting unchanged:

import { postgresPollingLane } from '@runlane/lane-postgres-polling'

const lane = postgresPollingLane({
  connectionString: 'postgresql://user:password@pooler:6432/app',
  directConnectionString: 'postgresql://user:password@postgres:5432/app',
  schema: 'runlane',
  preparedStatements: false,
})

The option defaults to contractDefaults.postgres.preparedStatements (true). Setting it to false removes statement names from query execution, including transaction clocks, retry locks, stream appends, and notification publishing. SQL values remain parameterized. Runlane gives up named statement reuse; it keeps the same SQL, transactions, locks, and retry rules. The performance cost depends on your queries and polling rate; measure your workload if it matters. See node-postgres query options.

For postgresSqsLane(), set postgres.preparedStatements: false. Standalone storage drivers accept preparedStatements: false in createPostgresStorageDriver().

This option does not make LISTEN or session advisory locks work through transaction pooling. Keep directConnectionString for listeners and migrations. If runtime listeners cannot use a direct or session-mode connection, set workHints: false and runHints: false on a polling lane to use local wakes and polling. On a Postgres/SQS lane, set the top-level runHints: false; SQS already replaces the work listener. Migrations still need a direct or session-mode connection. PgBouncer's feature map lists these session requirements.

Use another pooler

The same setup works with any pooler that meets two requirements:

  • Storage queries (connectionString) need protocol-level prepared-statement support when preparedStatements is true. Set it to false for a transaction pooler without statement tracking, or use session mode.
  • Listeners and migrations (directConnectionString) need one Postgres session for the whole connection. Use a direct Postgres URL or a session-mode pool.

Check your pooler's documentation for how it handles prepared statements and LISTEN in transaction mode. Then run the deployment check below. It catches both problems under load.

Configure both URLs on the lane

Use connectionString for the transaction pool and directConnectionString for Postgres directly, or a session-mode pool. Both must reach the same database. The direct URL defaults to connectionString when omitted.

src/runlane.ts
import { createRunlane, RunRetention, queue } from '@runlane/core'
import { postgresPollingLane } from '@runlane/lane-postgres-polling'
import * as z from 'zod'

import { sendEmail } from './tasks/send-email.js'

const { DATABASE_URL, DIRECT_DATABASE_URL } = z
  .object({ DATABASE_URL: z.string().min(1), DIRECT_DATABASE_URL: z.string().min(1) })
  .parse(process.env)

export const emailQueue = queue({ name: 'email', default: true })

export const runlane = createRunlane({
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    cancelled: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    expired: RunRetention.deleteAfter('7d'),
  },
  lane: postgresPollingLane({
    connectionString: DATABASE_URL,
    directConnectionString: DIRECT_DATABASE_URL,
    schema: 'runlane',
  }),
  queues: [emailQueue],
  tasks: { sendEmail },
})

The query pool uses DATABASE_URL. Both the worker wake-up listener and the run-progress listener use DIRECT_DATABASE_URL. Producers, workers, maintenance, and scheduled drains can share this configuration. Only long-running polling workers open a worker listener; scheduled drains do not.

For postgresSqsLane, put both URLs in its postgres options. SQS carries worker wake-ups, so that lane opens no worker listener. Its run-progress listener still uses the direct URL. Set runHints: false on serverless consumers to skip that connection. Run subscribers then fall back to streams.pollInterval.

Run migrations before deployment

The CLI obtains its Postgres adapter from the runtime in your Runlane config. When that runtime uses the lane above, both migrate and status automatically use directConnectionString:

runlane adapter postgres migrate
runlane adapter postgres status

Use --config <path> to select another CLI config. --connection-string overrides either configured URL:

runlane adapter postgres migrate --connection-string "$DIRECT_DATABASE_URL"

A standalone migration script can pass the same connectionString and directConnectionString to applyPostgresStorageMigrations(). It connects through the direct URL.

Migrations hold a session advisory lock and set the session's search_path. Through a transaction pool, both can go wrong. The lock and unlock can land on different server connections, leaving a lock behind. The search_path setting stays on its server connection and reaches the next client of that connection, including your app. Always use a direct or session-mode URL, even if a quiet pooled test appears to work. Use the direct URL for application migration tools that depend on session state too.

Budget connections

Each lane has its own query pool, with node-postgres's default maximum of 10 connections. When pooled, these are connections to PgBouncer. Keep max_client_conn above their total across processes. PgBouncer's default_pool_size bounds server connections for each user and database pair. A Runlane client holds a server connection only while a storage transaction is open or a single statement runs.

Budget direct connections separately: one run listener per started lane with runHints: true, plus one worker listener per polling lane with a long-running worker and workHints: true. These count against Postgres's limit even when queries go through PgBouncer. Allow room for migrations, application pools, and operations. See polling connection budgets.

When all server connections are busy, PgBouncer queues transactions. A connection dropped after query_wait_timeout is reported as retryable storage_unavailable.

Troubleshoot

A storage call reports configuration_invalid about a prepared statement. SQLSTATE 42P05 or 26000 can mean the pooler did not handle Runlane's named prepared statements. These failures can appear only under concurrent load, while a quiet test passes, because PgBouncer reuses the most recently used server connection first. Set preparedStatements: false and restart the Runlane processes, or use PgBouncer 1.21 or later with max_prepared_statements above 0. With another pooler, enable its statement tracking, disable Runlane's named statements, or use a session-mode pool or direct connection. Runlane does not switch modes or retry these configuration errors automatically. The original error remains available as the cause for local diagnostics.

A storage_background_failure log or metric shows operation work_listener or run_listener with code configuration_invalid. Notifications aren't reaching that LISTEN connection. Configure observability.telemetry.logger to see these logs; the runtime logs the operation and error code, not the error message. After each listener connects, Runlane checks delivery using a private channel and a notification sent through the query pool. If it receives nothing within about five seconds after sending, it reports non-retryable configuration_invalid once for that connection. The operation is work_listener or run_listener. If the check's own notify query fails, that storage error is reported under the same operation instead. Set directConnectionString to a direct Postgres or session-mode URL and restart the process.

If polling workers cannot keep a direct or session-mode connection, set workHints: false on postgresPollingLane(). This removes the work listener, its delivery check, and work publications. Same-runtime commits still wake local workers; other work waits for polling. Disable runHints too when run readers cannot keep a listener.

This check runs in the background and does not delay startup or stop listening. Reports use the storage driver's observeBackgroundFailures path, which the runtime routes to its telemetry logger and metrics. Standalone drivers without an observer emit a structured process warning. Work and readers continue through polling. A passed check proves delivery at that moment; polling still covers later lost hints.

A migration waits on a lock. A previous migration may have used the transaction pool and left its session lock behind. Stop the waiting job, reconnect PgBouncer's server connections with its RECONNECT admin command, then rerun migrations through the direct URL.

Check the deployment

  1. Run migrations through the configured direct URL.
  2. In PgBouncer's admin console, run SHOW VERSION and SHOW CONFIG. Confirm pool_mode is transaction. With Runlane's default preparedStatements: true, require version 1.21 or later and max_prepared_statements above 0. If tracking stays at 0, confirm preparedStatements: false on every Runlane producer and worker.
  3. Trigger a concurrent burst of tasks, such as 200 at once, through the pooled URL. Confirm none fails and workers finish them. A single quiet trigger can pass even when named statements and the pooler's settings disagree.
  4. Confirm neither listener reports a failed check after startup.
  5. Inspect PgBouncer's SHOW POOLS during load. If cl_waiting grows, raise server capacity within the Postgres budget or lower worker concurrency.

On this page