Connection pooling helps manage database connections efficiently by reusing them instead of opening a new one every time.
0
0
Connection pooling in GraphQL
Introduction
When your app needs to talk to the database many times quickly.
When you want to make your app faster by avoiding delays opening connections.
When you want to reduce the load on the database server.
When multiple users access the database at the same time.
When you want to save resources on your server.
Syntax
GraphQL
const pool = new Pool({ connectionString: 'your-database-url', max: 10, // max number of connections idleTimeoutMillis: 30000 // close idle connections after 30 seconds });
This example shows how to create a pool with a max of 10 connections.
Idle connections close after 30 seconds to save resources.
Examples
Creates a pool with up to 5 connections to a PostgreSQL database.
GraphQL
const pool = new Pool({ connectionString: 'postgresql://user:pass@localhost/db', max: 5 });
Creates a pool for PostgreSQL with connections closing after 10 seconds of inactivity.
GraphQL
const pool = new Pool({ connectionString: 'postgresql://user:pass@localhost/db', idleTimeoutMillis: 10000 });
Sample Program
This code creates a connection pool with 3 max connections. It fetches user ids and names from the users table, then releases the connection back to the pool.
GraphQL
const { Pool } = require('pg'); const pool = new Pool({ connectionString: 'postgresql://user:pass@localhost/mydb', max: 3, idleTimeoutMillis: 20000 }); async function fetchUsers() { const client = await pool.connect(); try { const res = await client.query('SELECT id, name FROM users'); console.log(res.rows); } finally { client.release(); } } fetchUsers();
OutputSuccess
Important Notes
Always release connections back to the pool to avoid running out of connections.
Adjust max connections based on your app's needs and database limits.
Summary
Connection pooling reuses database connections to improve speed and resource use.
It is useful when many database requests happen quickly or at the same time.
Remember to release connections after use to keep the pool healthy.