Sobes.tech
Junior — Middle

Do you have experience solving performance optimization problems in databases?

sobes.tech AI

Answer from AI

Database performance optimization in Node.js often involves several approaches:

  • Using indexes to speed up queries.
  • Caching frequently requested data (e.g., with Redis).
  • Optimizing SQL queries themselves, avoiding excessive JOINs and subqueries.
  • Using connection pools for efficient management of database connections.
  • Asynchronous request processing to improve application responsiveness.

Example of using a connection pool with MySQL in Node.js:

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'testdb',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

async function getUsers() {
  const [rows] = await pool.query('SELECT * FROM users WHERE active = ?', [1]);
  return rows;
}

This approach allows efficient resource utilization and reduces database response time.