Files
nexus/wiki/concepts/ConnectionPooling.md
2026-05-03 05:42:12 +08:00

47 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Connection Pooling"
type: concept
tags: [database, connection-pool, postgresql, supabase, performance, infrastructure]
last_updated: 2026-05-01
---
# Connection Pooling
## Definition
数据库连接池是一种在应用程序和数据库服务器之间维护一组持久连接的技术,避免每次请求都创建新连接,从而防止连接耗尽、提升响应速度。
## Why It Matters
- 数据库连接是稀缺资源PostgreSQL 默认 max_connections = 100
- 无连接池时:高并发下连接数爆炸 → OOM → 服务崩溃
- 无连接池时:每次请求建立 TCP + 认证开销(~20-50ms 延迟)
## Key Tools
| 工具 | 说明 |
|------|------|
| **PgBouncer** | 轻量级 PostgreSQL 连接池,支持事务模式和会话模式 |
| **Supabase Pooler** | Supabase 内置连接池,自动管理事务模式连接 |
| **PlanetScale** | 内置连接池,无服务器架构 |
| **PgBouncer 事务模式** | 连接归还池复用,适合 serverless |
| **PgBouncer 会话模式** | 保持长连接,适合需要 SET session.* 的场景 |
## Supabase 连接池示例
```typescript
// Supabase 事务模式Serverless 推荐)
const pooledUrl = process.env.DATABASE_URL?.replace(
'5432', // 标准端口
'6543' // 事务模式端口
);
```
## Source
- [[engineering-database-optimizer]]
## Connections
- [[engineering-backend-architect]] — 架构设计时必须考虑连接池
- [[engineering-sre]] — 连接池配置是 SRE 容量规划的关键
- [[engineering-database-optimizer]] — 核心关注点之一