Typeorm - Connection Pool configuration MySQL and Postgres

This tutorial explains how to define a connection pool in the TypeOrm NodeJS application.

Connection pools are pre-created pools of connections used in NestJS or javascript applications to Connect to a Database.

Connection is an HTTP Connection used to connect to the Database to do DB operations.

Connection is required for each operation, examples of operations are Create, Update, Delete Read.

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

MySQL Datasource contains the below configurations

pool.max : Maximum number of connections, default is 10 poo.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 It contains 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
  }
}