# psycopg2.OperationalError：错误：共享内存不足 提示：您可能需要增加 max_locks_per_transaction。

- **ID:** `database/postgresql-too-many-snapshots`
- **领域:** database
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

PostgreSQL 用于锁管理的共享内存耗尽，通常是因为太多并发事务持有锁或快照，超过了 max_locks_per_transaction * max_connections 的限制。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PostgreSQL 14 | active | — | — |
| PostgreSQL 15 | active | — | — |
| PostgreSQL 16 | active | — | — |

## 解决方案

1. ```
   Increase max_locks_per_transaction in postgresql.conf (e.g., to 128 or 256), then restart PostgreSQL. Verify with SHOW max_locks_per_transaction;. Also consider reducing the number of concurrent long-running transactions.
   ```
2. ```
   Identify and terminate idle-in-transaction sessions that hold locks: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND xact_start < now() - interval '10 minutes';
   ```

## 无效尝试

- **Restart PostgreSQL to clear the shared memory, assuming it's a temporary leak** — If the workload pattern (e.g., many concurrent long-running transactions) remains the same, the error will recur quickly after restart. (85% 失败率)
- **Increase max_connections instead of max_locks_per_transaction** — max_connections increases the number of possible connections but does not increase the lock space per connection; the shared memory limit is still bounded by max_locks_per_transaction * max_connections. (75% 失败率)
