1. guides
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. guides

Connection Pooling & Performance

Prorm manages database connections through a configurable pool so that repeated queries reuse warm connections instead of paying the cost of a fresh handshake every time. This guide covers how to size and tune the pool, retry transient failures, apply connection and query timeouts, watch pool health through events and metrics, and squeeze more performance out of individual queries. Every option shown here maps directly to the PoolOptions, RetryOptions, and QueryOptions types exposed by the library.

Two pools: the driver's and prorm.pool#

[!IMPORTANT]
The connections your queries run on are pooled by the driver (pg.Pool
for PostgreSQL, mysql2's pool for MySQL, mssql's for SQL Server). The
top-level pool option sizes that driver pool, and a size in
dialectOptions wins over it. The same pool option also builds a separate
DatabaseConnectionPool, exposed as prorm.pool, which tracks placeholder
connections for events and stats; queries do not check connections out of
it. Before 4.9.2 the top-level pool did not reach the driver at all, so
pool.max alone changed nothing.
This was checked by constructing each dialect and reading back the driver
config it was given:
OptionsDriver poolprorm.pool.max
postgres, pool: { max: 50 }, dialectOptions: { max: 25 }max: 2550
postgres, pool: { max: 50 } onlymax: 5050
mysql, pool: { max: 50 }, dialectOptions: { pool: { max: 15 } }connectionLimit: 1550
mysql, pool: { max: 50 } onlyconnectionLimit: 5050
On SQLite three concurrent prorm.query() calls left prorm.getPoolStats()
at acquired: 0: there is one connection and nothing is borrowed from the
tracking pool.
Size the driver's pool per dialect:
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'postgres',
  host: process.env.DB_HOST,
  database: 'app',
  username: 'app',
  password: process.env.DB_PASSWORD,
  dialectOptions: {
    max: 20,                        // pg.Pool size (dialect default 20)
    idleTimeoutMillis: 10_000,      // close a connection idle this long (default 30000)
    connectionTimeoutMillis: 5_000, // wait this long for a connection (default 2000)
    statementTimeout: 30_000,       // server-side statement_timeout per connection
  },
});
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'mysql',
  host: process.env.DB_HOST,
  database: 'app',
  username: 'app',
  password: process.env.DB_PASSWORD,
  dialectOptions: {
    pool: { max: 20 },      // becomes mysql2's connectionLimit (default 10)
    connectTimeout: 5_000,  // TCP + handshake
    idleTimeout: 60_000,    // close an idle connection after this long
  },
});
import { Prorm } from 'ts-prorm-orm';

// One file, one connection: there is no pool to size. Concurrent root
// transactions are queued so each runs BEGIN … COMMIT on its own.
const prorm = new Prorm({ dialect: 'sqlite', storage: './app.sqlite' });

Enabling the pool#

Pass a pool object to the Prorm constructor. Once configured, Prorm creates a DatabaseConnectionPool, initializes it, and exposes it as prorm.pool, with the events and stats described below. Size the driver's pool alongside it, as above.
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'app',
  username: 'app',
  password: 'secret',
  pool: {
    max: 20,   // never open more than 20 connections
    min: 5,    // keep at least 5 idle connections warm
    acquire: 30000, // wait up to 30s for a free connection
    idle: 10000,    // evict connections idle for 10s (down to `min`)
  },
});
If you omit pool, prorm.pool is null and connections are handled directly by the dialect driver.

The lifecycle of one query#

This is the shape of every pool here: the driver's, and the one createPool()
builds. The path to watch is queue → timeout. Those errors say the pool is
exhausted, not that the database is slow — and they look identical from the
outside unless you check whether the database is actually busy.

Pool configuration#

The pool key accepts PoolOptions. All fields are optional and fall back to the defaults below.
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'mysql',
  pool: {
    max: 20,                // Maximum connections in the pool (default 10)
    min: 2,                 // Minimum idle connections to maintain (default 0)
    acquire: 60000,         // Max ms to wait for a connection (default 60000)
    idle: 30000,            // Max ms a connection may sit idle (default 30000)
    evict: 1000,            // How often (ms) to sweep for idle connections (default 1000)
    handleDisconnects: true,   // Automatically handle dropped connections
    enableEvents: true,        // Emit pool:* events (default true)
    logPoolOperations: false,  // Log every acquire/release/destroy to console
    onConnect: (conn) => {     // Called when a connection is acquired
      // e.g. set a session variable
    },
    onDisconnect: (conn) => {  // Called when a connection is released
      // e.g. reset session state
    },
  },
});

What min/max/idle/acquire actually do#

max caps concurrency. When every connection is busy, further requests queue.
min keeps a floor of warm, idle connections so the first requests after a lull don't pay connection setup cost. The evictor never drops the pool below min.
idle is how long a connection may sit unused before the background evictor closes it (respecting min).
acquire is the ceiling on how long a caller waits in the queue for a free connection. If it expires, the acquire rejects with a ConnectionAcquireTimeoutError ("Acquisition timeout …") — a signal that max is too low or queries are holding connections too long.
evict controls how frequently the evictor timer runs its idle sweep.

Sizing the pool#

Pick max based on your database server's connection limit and your app's concurrency, not arbitrarily high — every open connection consumes server resources. Keep the tracking pool's numbers in step with the driver's so its stats and events describe the same limits:
import { Prorm } from 'ts-prorm-orm';

// Low traffic
const low = new Prorm({
  dialect: 'postgres',
  pool: { max: 10, min: 2, acquire: 30000, idle: 30000 },
  dialectOptions: { max: 10, idleTimeoutMillis: 30000 },
});

// Medium traffic
const medium = new Prorm({
  dialect: 'postgres',
  pool: { max: 20, min: 5, acquire: 30000, idle: 10000 },
  dialectOptions: { max: 20, idleTimeoutMillis: 10000 },
});

// High traffic
const high = new Prorm({
  dialect: 'postgres',
  pool: { max: 50, min: 10, acquire: 20000, idle: 10000 },
  dialectOptions: { max: 50, idleTimeoutMillis: 10000 },
});
The number that matters is the total across processes. Every instance of
your app opens its own pool, so the database sees instances × max:
Value
PostgreSQL max_connections200
reserved for admin, migrations, replication20
app instances at peak (autoscaled)8
per-instance max(200 − 20) / 8 = 22
[!WARNING]
Raising max when you add instances is how a deploy ends with too many connections on every request. Recompute the budget whenever the instance
count can grow, or put PgBouncer or a managed proxy between the app and the
database.

Connection retry#

Transient failures — a database restart, a momentary network blip, "too many connections" — are worth retrying. Retry is applied by the dialect around each statement, from RetryOptions. A default for every statement goes in the top-level retry option, which PostgreSQL, MySQL and SQL Server read, or in dialectOptions.retry, which wins over it. Before 4.9.2 the top-level retry was not forwarded, and PostgreSQL ignored it:
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'mysql',
  dialectOptions: {
    retry: {
      max: 3,               // Retry up to 3 times (default 3)
      timeout: 1000,        // Base delay between attempts in ms (default 1000)
      backoff: true,        // Use exponential backoff (default false)
      backoffMultiplier: 2, // Delay grows by this factor each attempt (default 2)
      backoffMax: 10000,    // Cap the backoff delay at 10s (default 10000)
      match: [              // Only retry when the error message matches one of these
        'ECONNREFUSED',
        'ETIMEDOUT',
        'too many connections',
        'Connection terminated',
      ],
    },
  },
});
When match is omitted, the dialect falls back to a built-in list of common transient connection errors (for example ECONNREFUSED, ENOTFOUND, ETIMEDOUT, connection timeout, too many connections). With backoff: true, the wait between attempts is timeout * backoffMultiplier^attempt, capped at backoffMax.

Per-query retry#

Every pooled SQL dialect with retry support (PostgreSQL, MySQL, MariaDB,
SQLite, DuckDB, CockroachDB, Redshift) honours retry in the query options.
This is the portable way to opt a statement in:
// Retry this read up to 3 times with default error matching
const rows = await prorm.query('SELECT * FROM users', {
  retry: { max: 3 },
});

// Retry only on specific, known-transient error patterns
await prorm.query('SELECT * FROM reports', {
  retry: { max: 5, match: ['Lock not available', 'too many connections'] },
});
The defaults for match are per dialect: SQLite retries SQLITE_BUSY,
SQLITE_LOCKED and database is locked; MySQL adds Lock wait timeout and
Deadlock to the connection errors.
[!NOTE]
Retry is skipped for a statement that runs inside a transaction. After an
error the transaction is aborted and every later statement on it fails until
ROLLBACK, so re-sending one statement can only produce a second, misleading
error. Retry the whole transaction with
transaction(fn, { retry }).

Timeouts#

There are three timeouts worth tuning, at three different layers: getting a
connection, keeping one, and running a statement. Each dialect names them
differently, and all of them go in dialectOptions:
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'postgres',
  dialectOptions: {
    connectionTimeoutMillis: 5_000, // connect, or wait for a free pooled connection
    idleTimeoutMillis: 60_000,      // close a connection idle this long
    statementTimeout: 15_000,       // server cancels a statement after this
    queryTimeout: 20_000,           // client gives up waiting for a result
  },
});
A statement that runs past statementTimeout fails with canceling statement due to statement timeout.
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'mysql',
  dialectOptions: {
    connectTimeout: 5_000, // TCP + handshake
    idleTimeout: 60_000,   // close a pooled connection idle this long
  },
});

// A per-statement ceiling is an optimizer hint in the SQL itself:
await prorm.query('SELECT /*+ MAX_EXECUTION_TIME(15000) */ * FROM big_table');
The connect timeout governs the initial TCP/auth handshake.
The idle timeout is the driver-level lifetime of an unused physical connection.
The statement timeout is the only one that stops a slow query; the others only bound waiting.
The top-level connectTimeout / idleTimeout options reach the driver in
its own spelling (connectionTimeoutMillis / idleTimeoutMillis for pg,
connectTimeout / idleTimeout for mysql2, connectionTimeout for
mssql); a value in dialectOptions wins. The per-query timeout option is
sent as node-postgres query_timeout and as the mysql2 timeout, and a
statement that runs past it fails with a TimeoutError carrying .sql:
await prorm.query('SELECT pg_sleep(5)', { timeout: 50 }); // TimeoutError
Before 4.9.2 these options were declared in the types but not read.

Inspecting the pool#

Prorm exposes the live pool and a lightweight stats snapshot.
// The pool instance (or null if pooling isn't configured)
const pool = prorm.getPool();

// A quick stats snapshot
const stats = prorm.getPoolStats();
// => { size, available, inUse, pending } | null

if (stats) {
  console.log(`${stats.available}/${stats.size} idle, ${stats.inUse} busy, ${stats.pending} waiting`);
}
The pool object surfaces the same numbers as properties, plus configured limits:
console.log('Pool size:', prorm.pool?.size);
console.log('Available:', prorm.pool?.available);
console.log('In use:', prorm.pool?.used);      // alias for inUse
console.log('Pending:', prorm.pool?.pending);
console.log('Max / Min:', prorm.pool?.max, prorm.pool?.min);
console.log('Destroyed?', prorm.pool?.isDestroyed);
These numbers describe prorm.pool. For the connections your queries actually
use on PostgreSQL, read the driver's pool, which the dialect returns from
getConnection():
import type { Pool } from 'pg';

const driverPool = prorm.getDialectInstance()?.getConnection() as Pool | null;
if (driverPool) {
  console.log({
    total: driverPool.totalCount,     // open connections
    idle: driverPool.idleCount,       // open and free
    waiting: driverPool.waitingCount, // callers queued for one
  });
}
A pending (or waitingCount) that stays above zero means requests are queuing for connections — a strong hint to raise max or to find the queries that hold connections too long.

Pool events#

When enableEvents is on (the default), Prorm forwards prorm.pool's lifecycle events on its own emitter under the pool: prefix. They fire when that pool's connections are acquired and released (by your own prorm.pool.acquire() calls, for instance), not for each query, which runs on the driver's pool; for per-query monitoring use the query event in the next section.
prorm.on('pool:acquire', (conn) => {
  // a connection left the pool for a caller
});

prorm.on('pool:release', (conn) => {
  // a connection returned to the pool
});

prorm.on('pool:create', (conn) => { /* new physical connection opened */ });
prorm.on('pool:remove', (conn) => { /* connection removed from the pool */ });
prorm.on('pool:enqueue', () => { /* a request had to wait for a connection */ });
prorm.on('pool:dequeue', () => { /* a waiting request was served */ });

prorm.on('pool:timeout', () => {
  console.warn('A connection acquisition timed out — pool may be undersized');
});

prorm.on('pool:error', (err) => {
  console.error('Pool error:', err);
});
Repeated pool:enqueue and pool:timeout events are the clearest signal that the pool is saturated.

Logging and slow-query detection#

Prorm emits a query event after every statement and a slowQuery event whenever a query exceeds slowQueryThreshold. Combined with the pool metrics, these are your main performance hooks.
const prorm = new Prorm({
  dialect: 'postgres',
  logging: (sql, timing) => console.log(`(${timing}ms) ${sql}`),
  logSlowQueries: true,     // enabled by default
  slowQueryThreshold: 200,  // ms; queries over this fire `slowQuery` (default 1000)
});

prorm.on('query', (event) => {
  // { sql, duration, timestamp, type, model?, error? }
  metrics.observe('query_duration_ms', event.duration);
});

prorm.on('slowQuery', (event) => {
  // { sql, duration, threshold, ... }
  console.warn(`Slow query (${event.duration}ms > ${event.threshold}ms): ${event.sql}`);
});
You can override logging per query — for example to silence a noisy statement or to route it to a custom sink:
await prorm.query('SELECT 1', { logging: false });

await prorm.query('SELECT * FROM audit_log', {
  logging: (sql, time) => auditLogger.info({ sql, time }),
});

Per-query performance tips#

Reuse the pool, don't rebuild it. Construct one Prorm instance per process. Creating a new instance per request defeats pooling entirely.
Keep connections checked out briefly. The pool serializes access once max is hit; long-running work while holding a connection starves everyone else. Do heavy in-memory processing after releasing.
Use raw when you don't need mapping. Skipping model hydration avoids per-row object construction:
const rows = await prorm.query('SELECT id, name FROM users', { raw: true });
Set a slowQueryThreshold low enough to catch regressions, then let the slowQuery event surface the offenders so you can add indexes or narrow selections.
Match pool.max to real concurrency. An oversized pool can overwhelm the database server; an undersized one queues requests. Watch the driver pool's waitingCount (see Inspecting the pool) under real load to find the right value.

Graceful shutdown#

Close the instance on shutdown. prorm.close() disconnects the dialect (ending the driver's pool) and destroys prorm.pool, whose evictor timer would otherwise keep the process alive.
async function shutdown() {
  await prorm.close(); // driver pool ended, prorm.pool destroyed
  process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
To tear down only the tracking pool, call prorm.pool.destroy(); with no argument it tears down the whole pool, and passing a single connection destroys just that one.

Advanced: the standalone pool#

The pool that Prorm builds internally is also usable on its own via createPool. This is useful when you manage raw driver connections yourself but still want pooling, health checks, and validation. It accepts everything in PoolOptions plus factory, healthCheck, validateOnBorrow, and reconnection settings.
import { createPool } from 'ts-prorm-orm';

const pool = createPool({
  max: 10,
  min: 2,
  acquire: 30000,
  idle: 10000,
  factory: async () => driver.connect(), // opens a real connection
  validateOnBorrow: true,
  validationQuery: 'SELECT 1',
  healthCheck: {
    enabled: true,
    interval: 30000,
    timeout: 5000,
    query: 'SELECT 1',
    maxFailures: 3,
  },
});

async function withConnection<T>(fn: (conn: any) => Promise<T>): Promise<T> {
  const conn = await pool.acquire();
  try {
    return await fn(conn);
  } finally {
    pool.release(conn); // always release, even on error
  }
}
Always release connections in a finally block. A connection that is never released stays "in use" forever, and once every connection leaks the pool exhausts and subsequent acquire() calls time out.
Here is that exhaustion, run for real against a pool of two placeholder
connections with a 200 ms acquire:
import { createPool } from 'ts-prorm-orm';

let opened = 0;
const pool = createPool({ max: 2, acquire: 200, factory: async () => ({ id: ++opened }) });
pool.on('release', (c) => console.log('release', c.id));
pool.on('timeout', () => console.log('timeout event'));

const a = await pool.acquire();
const b = await pool.acquire();          // pool is now full
const waiter = pool.acquire();           // queued
pool.release(a);                         // hands connection 1 to the waiter
console.log('waiter got', (await waiter).id);

try {
  await pool.acquire();                  // nothing frees within 200 ms
} catch (err) {
  console.log((err as Error).message);
}
pool.release(b);
await pool.destroy();
release 1
waiter got 1
timeout event
Acquisition timeout after 200ms. Pool size: 2, max: 2
release 2
The timeout rejects with a ConnectionAcquireTimeoutError, a ConnectionError
with code CONNECTION_TIMED_OUT, so isRetryableError() answers true for
it and its timeout property says how long the caller waited. pool.pending
and pool.stats.pending both count the callers waiting in the queue. Before
4.9.2 the timeout was a plain Error, and pool.pending stayed at 0.

Related reading#

Replication — splitting reads and writes across hosts
SQL constants — why session state and pools interact badly
Modified at 2026-10-04 00:40:16
Previous
Compliance & data protection
Next
Security in the console
Built with