Connection pooling và query optimization là hai yếu tố quan trọng nhất để NestJS app chịu tải tốt ở production.
Connection Pooling với TypeORM:
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => ({
type: 'postgres',
url: config.get('DATABASE_URL'),
// Connection pool settings
extra: {
max: 20, // Max connections (CPU cores * 2-4 là rule of thumb)
min: 2, // Min connections luôn mở
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
},
logging: config.get('NODE_ENV') === 'development',
}),
})Query optimization:
1. Dùng select để chỉ lấy columns cần thiết
2. Tạo indexes trên foreign keys và frequently queried columns
3. Dùng QueryBuilder với addSelect thay vì relations cho large datasets
4. Paginate tất cả list queries — không bao giờ findAll() không có limit
5. Slow query logging: enable logging: ['query', 'slow'] với maxQueryExecutionTime: 1000
DataSource injection (TypeORM 0.3+):
constructor(private readonly dataSource: DataSource) {}
// Dùng this.dataSource.createQueryRunner() cho transactionsConnection pooling and query optimization are the two most critical factors for a NestJS app to handle production load well.
Connection Pooling with TypeORM:
TypeOrmModule.forRootAsync({
useFactory: (config) => ({
type: 'postgres',
url: config.get('DATABASE_URL'),
extra: { max: 20, min: 2, idleTimeoutMillis: 30000 },
logging: config.get('NODE_ENV') === 'development',
}),
})Query optimization:
1. Use select to fetch only needed columns
2. Index foreign keys and frequently queried columns
3. Paginate all list queries — never findAll() without limit
4. Enable slow query logging: maxQueryExecutionTime: 1000