← Back to Node.js Course | Chapter 9: Database Integration | Lesson 4 of 7

Connection pooling

A pool keeps a set of open database connections ready to reuse instead of opening a new one per request.

In this page:

  1. Connection pooling
Syntax
javascript
const pool = mysql.createPool({ host: 'host', user: 'user', database: 'database', connectionLimit: n });
const [rows] = await pool.query('SQL', [values]);

Connection pooling

Opening connections is slow, so pools hand out idle ones and take them back when released. You set a maximum size. Requests wait when all connections are busy. Always release connections you check out.

Note: Size the pool for your database's connection limit.

Example: Connection pooling

javascript
class Pool {
  constructor(max) { this.max = max; this.inUse = 0; this.waiting = []; }
  async acquire() {
    if (this.inUse < this.max) { this.inUse++; return; }
    await new Promise((r) => this.waiting.push(r));
  }
  release() {
    const next = this.waiting.shift();
    if (next) next(); else this.inUse--;
  }
}
const pool = new Pool(2);
(async () => {
  const job = async (n) => { await pool.acquire(); console.log("job", n, "running, inUse:", pool.inUse); await new Promise((r) => setTimeout(r, 5)); pool.release(); };
  await Promise.all([job(1), job(2), job(3)]);
  console.log("all done, inUse:", pool.inUse);
})();

// Output:
// job 1 running, inUse: 2
// job 2 running, inUse: 2
// job 3 running, inUse: 2
// all done, inUse: 0

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Not releasing connections
  2. Making the pool too large
  3. Creating a new pool per request
Chapter Summary
  • Pools reuse connections
  • Set a maximum size
  • Always release
  • One pool per app
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.