qwen_agent/.features/memory/decisions/2026-06-connection-pool.md
2026-06-01 11:51:21 +08:00

26 lines
1.1 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.

---
date: "2026-06-01"
status: adopted
topic: "connection-pool"
impact: [memory, performance, stability]
---
# 连接池主动释放 + Mem0 实例 LRU 缓存
## 背景
Mem0 的 PGVector 后端在实例 `__init__` 时从连接池取一个连接,理论上在 `__del__` 时归还。
但 Python GC 时机不确定,高并发下连接迟迟不归还会迅速打满 `MEM0_POOL_SIZE`(默认 50导致后续请求阻塞。
同时若为每个 `(user_id, agent_id)` 都新建 Mem0 实例且不回收,也会无限占用连接。
## 决策
1. `Mem0Manager``OrderedDict` 维护最多 50 个 Mem0 实例的 LRU 缓存,超出淘汰最旧的。
2. 每次记忆操作recall/add后调用 `_release_connection()` 立即把连接归还连接池,不等 GC。
## 影响
- 连接池不再被慢 GC 拖垮,高并发稳定。
- 实例数量有上界,内存可控。
## Gotchas
- 不要在操作链路里持有 Mem0 实例的连接跨多个 await会绕过释放逻辑。
- LRU 上限50`MEM0_POOL_SIZE`50相关联调整其一时需一并评估。