1. Use a Connection Pool
Instead of opening and closing database connections for each operation, use a connection pool. A pool maintains a set of open connections and reuses them, which improves performance and resource management.
Examples of pooling libraries:
Node.js: pg-pool for PostgreSQL, mysql2 for MySQL
Java: HikariCP, Apache DBCP
Python: SQLAlchemy with pooling, or psycopg2 with pool management
PHP: Use persistent connections or libraries like Doctrine
Example in Node.js using PostgreSQL:
javascript
Copy
Edit
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'mydb',
password: 'pass',
port: 5432,
max: 20
});
async function fetchData() {
const client = await pool.connect();
try {
const res = await client.query('SELECT * FROM users');
return res.rows;
} finally {
client.release();
}
}
2. Close Connections Properly
Always ensure database connections are closed or released back to the pool after use. Use try-finally blocks to guarantee cleanup even if errors occur.
3. Configure Timeouts and Limits
Set connection timeouts to avoid hanging requests. Configure the pool with a maximum number of connections and idle timeout to prevent resource exhaustion.
4. Monitor Connection Usage
Regularly monitor your database to check how many connections are in use, query performance, and idle connections. Use built-in tools like pg_stat_activity in PostgreSQL or SHOW PROCESSLIST in MySQL.
5. Avoid Connection Leaks
Connection leaks occur when a connection is opened but not released or closed. This can eventually exhaust all available connections.
To avoid leaks:
Always release or close connections in all execution paths
Use logging or monitoring tools to detect unusual patterns
Review error handling logic to ensure connections are cleaned up
6. Use Environment-Specific Configurations
Use different settings for development, testing, and production. Configuration options include host, database name, credentials, max pool size, and timeout durations.
7. Understand Your ORM Behavior
If you're using an ORM like Sequelize, SQLAlchemy, Hibernate, or Doctrine, understand how it manages connections and pooling. Tune its settings according to your application's load and usage patterns.