MeWrite Docs

PostgreSQL: Connection pool exhausted

PostgreSQL接続プール枯渇エラーの解決方法

概要

PostgreSQLへの接続プールが枯渇し、新しい接続を確立できない状態です。

エラーメッセージ

Error: timeout expired while waiting for connection

または

too many connections for role "myuser"

原因

  1. 接続リーク: 接続が解放されない
  2. プールサイズ不足: 同時接続数が多い
  3. 長時間トランザクション: 接続が長時間占有
  4. max_connections超過: PostgreSQLの上限

解決策

1. 接続を確実に解放

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const pool = new Pool({
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000
});

async function query(sql, params) {
  const client = await pool.connect();
  try {
    return await client.query(sql, params);
  } finally {
    client.release();  // 必ず解放
  }
}

2. プールサイズ調整

1
2
3
4
5
const pool = new Pool({
  max: 20,          // 最大接続数
  min: 5,           // 最小接続数
  idleTimeoutMillis: 30000
});

3. PostgreSQL設定

1
2
3
4
5
6
7
8
-- 現在の接続数確認
SELECT count(*) FROM pg_stat_activity;

-- max_connections確認
SHOW max_connections;

-- 設定変更(postgresql.conf)
-- max_connections = 200

4. PgBouncer使用

1
2
3
4
5
6
7
[databases]
mydb = host=localhost dbname=mydb

[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

よくある間違い

  • try-finallyで接続解放を保証しない
  • サーバーレス環境でのプール設定

PostgreSQL の他のエラー

最終更新: 2025-12-09