Trung BìnhNestJS iconNestJS

Connection pooling và database performance optimization trong NestJS?

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:

typescript
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+):

typescript
constructor(private readonly dataSource: DataSource) {}
// Dùng this.dataSource.createQueryRunner() cho transactions

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS