Typeorm - Connection Pool configuration MySQL and Postgres

This tutorial will guide you through defining a connection pool in a TypeORM Node.js application.

Connection pools are pre-created pools of connections used in NestJS or JavaScript applications to connect to a database.

A connection is an HTTP connection used to establish a connection to the database for performing DB operations. Each operation, such as Create, Update, Delete, and Read, requires a connection.

To configure the database with TypeORM, the following configuration is required for the MySQL database:

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "",
  "database": "test",
  "entities": ["**/*.entity{.ts,.js}"],
  "synchronize": true
}

TypeORM Connection Pool MySQL Configuration

The MySQL Datasource contains the following configurations.

  • pool.max: Maximum number of connections (default is 10)
  • pool.min: Minimum connections (default is zero)
  • pool.idle: Connection idle timeout
  • pool.acquire: Connection acquire timeout
{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "",
  "database": "test",
  "entities": ["**/*.entity{.ts,.js}"],
  "synchronize": true,
  "pool": {
    "max": 5,
    "min": 0,
    "acquire": 30000,
    "idle": 10000
  }
}

How to set poolSize for Postgres in TypeORM database connection

For Postgres configuration, an extra option is configured in ormconfig.js containing the following parameters:

  • poolSize: Maximum number of database connections
  • connectionTimeoutMillis: Connection timeout
  • query_timeout
  • statement_timeout
{
  "type": "postgres",
  "host": "localhost",
  "port": 5126,
  "username": "pgadmin",
  "password": "pgadmin",
  "database": "test",
  "entities": ["**/*.entity{.ts,.js}"],
  "synchronize": true,
  "extra": {
    "poolSize": 20,
    "connectionTimeoutMillis": 2000,
    "query_timeout": 1000,
    "statement_timeout": 1000
  }
}