0
0
Node.jsframework~8 mins

PostgreSQL connection with pg in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: PostgreSQL connection with pg
MEDIUM IMPACT
This affects the initial page load speed and responsiveness by controlling how database queries impact server response time.
Connecting to PostgreSQL in a Node.js app
Node.js
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function fetchData() {
  const res = await pool.query('SELECT * FROM users');
  return res.rows;
}
Using a connection pool reuses existing connections, reducing connection overhead and improving query speed.
📈 Performance GainReduces query latency and server blocking by reusing connections instead of reconnecting each time.
Connecting to PostgreSQL in a Node.js app
Node.js
import { Client } from 'pg';

async function fetchData() {
  const client = new Client({ connectionString: process.env.DATABASE_URL });
  await client.connect();
  const res = await client.query('SELECT * FROM users');
  await client.end();
  return res.rows;
}
Creating and closing a new client connection for every query causes high overhead and delays.
📉 Performance CostBlocks server response for each query due to repeated connection setup and teardown.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
New client per queryN/AN/AN/A[X] Bad
Connection pool reuseN/AN/AN/A[OK] Good
Rendering Pipeline
Database connection patterns affect server response time, which impacts how fast the browser receives data to render the page.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing due to connection overhead and query execution time
Core Web Vital Affected
INP
This affects the initial page load speed and responsiveness by controlling how database queries impact server response time.
Optimization Tips
1Avoid creating a new PostgreSQL client for every query to reduce connection overhead.
2Use a connection pool to reuse database connections efficiently.
3Monitor server response times to catch slow database interactions affecting user experience.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with creating a new PostgreSQL client for every query in Node.js?
AIt causes repeated connection overhead, slowing server response.
BIt increases browser rendering time directly.
CIt reduces network bandwidth usage.
DIt improves query execution speed.
DevTools: Network
How to check: Open DevTools, go to Network tab, observe server response times for API calls that query the database.
What to look for: Look for long waiting times (TTFB) indicating slow server responses due to inefficient DB connections.