也许多连接
错误信息
也许多连接
快速摘要
数据库服务器's max_connections 限制有 是 reached — 否新 连接能 是打开.
为什么发生
application 是打开也 许多连接不使用关闭它们
连接 pool 大小是 也大 跨越多个 app 实例
连接 leaks — 连接是 不是 returned 到 pool
max_connections 是设置也 低 for workload
最小示例
✗ 错误代码
// Each request opens a new connection
app.get('/users', async (req, res) => {
const client = new Client({ connectionString });
await client.connect(); // never closed!
const result = await client.query('SELECT * FROM users');
res.json(result.rows);
});✓ 修复代码
// Use a shared connection pool
const pool = new Pool({ connectionString, max: 10 });
app.get('/users', async (req, res) => {
const result = await pool.query('SELECT * FROM users');
res.json(result.rows);
});Using 连接 pool reuses 连接相反的 打开新 one 每请求, preventing 连接 exhaustion.
如何诊断
检查 current 连接数量:
SELECT 数量(*) FROM pg_stat_activity检查 max_connections 设置:
SHOW max_connectionsLook for idle 连接那个是 不是 used
检查 for 连接 leaks in application
如何修复
关闭 idle 连接 and fix 连接 leaks
Reduce 连接 pool 大小
Increase max_connections on 服务器
Use 连接 pooler 如 PgBouncer 到 multiplex 连接
如何预防
Use 连接 pooling 使用 appropriate pool 大小
总是发布连接后面到 pool
Use 外部 pooler (PgBouncer, ProxySQL) for 许多 app 实例
Monitor 连接数量 and alert 之前限制是 reached
相关资源
相关课程
- 连接 Pooling
学习关于 managing 连接.