0
0
Node.jsframework~8 mins

MySQL connection with mysql2 in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: MySQL connection with mysql2
MEDIUM IMPACT
This affects the initial page or API response load time by how quickly the database connection is established and queries are executed.
Connecting to MySQL and running queries in a Node.js app
Node.js
import mysql from 'mysql2/promise';
const pool = mysql.createPool({host: 'localhost', user: 'root', database: 'test', waitForConnections: true, connectionLimit: 10});
async function getUsers() {
  const [rows] = await pool.query('SELECT * FROM users');
  return rows;
}
Reuses connections from a pool asynchronously, reducing connection overhead and avoiding blocking.
📈 Performance GainReduces connection overhead by up to 90%, non-blocking queries improve throughput and lower latency
Connecting to MySQL and running queries in a Node.js app
Node.js
const mysql = require('mysql2');
const connection = mysql.createConnection({host: 'localhost', user: 'root', database: 'test'});
connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});
connection.end();
Creates a new connection for every query, blocking the event loop and causing delays under load.
📉 Performance CostBlocks event loop during connection setup, triggers multiple TCP handshakes, increases response time by 100-200ms per query
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Single connection per queryN/AN/AN/A[X] Bad
Connection pool with async queriesN/AN/AN/A[OK] Good
Rendering Pipeline
Database connection and query execution happen before the server sends the response, affecting how fast the browser receives content.
Server Processing
Network Request
First Byte Time
⚠️ BottleneckConnection setup and synchronous query execution block server event loop
Core Web Vital Affected
LCP
This affects the initial page or API response load time by how quickly the database connection is established and queries are executed.
Optimization Tips
1Always use connection pooling to reuse MySQL connections.
2Use async/await queries to avoid blocking the Node.js event loop.
3Avoid creating a new connection for every query to reduce latency.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using a connection pool with mysql2 in Node.js?
AIt compresses the database responses to save bandwidth
BIt automatically caches query results in the browser
CReusing existing connections reduces connection overhead and latency
DIt prevents SQL injection attacks
DevTools: Network
How to check: Open DevTools Network panel, observe Time to First Byte (TTFB) for API calls that query MySQL
What to look for: High TTFB indicates slow database response; lower TTFB with pooling means better performance