# psycopg2.OperationalError: ERROR: out of memory
DETAIL: Failed on request of size 123456.

- **ID:** `database/postgresql-too-many-pins`
- **Domain:** database
- **Category:** resource_error
- **Verification:** ai_generated
- **Fix Rate:** 82%

## Root Cause

PostgreSQL server ran out of memory, typically due to excessive work_mem usage from multiple concurrent queries, or a single query with very large memory needs (e.g., sorting, hashing).

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| PostgreSQL 14 | active | — | — |
| PostgreSQL 15 | active | — | — |
| PostgreSQL 16 | active | — | — |

## Workarounds

1. **Reduce work_mem for the session or globally to limit per-operation memory usage:
SET work_mem = '32MB';
Or in postgresql.conf:
work_mem = 32MB
Then restart or reload.** (85% success)
   ```
   Reduce work_mem for the session or globally to limit per-operation memory usage:
SET work_mem = '32MB';
Or in postgresql.conf:
work_mem = 32MB
Then restart or reload.
   ```
2. **Identify and optimize the problematic query using EXPLAIN ANALYZE, then rewrite it to use less memory (e.g., add indexes, reduce sort operations).** (80% success)
   ```
   Identify and optimize the problematic query using EXPLAIN ANALYZE, then rewrite it to use less memory (e.g., add indexes, reduce sort operations).
   ```

## Dead Ends

- **Increasing shared_buffers without adjusting work_mem** — shared_buffers is for caching, not for per-query memory; it does not prevent out-of-memory errors from work_mem. (85% fail)
- **Restarting PostgreSQL without changing memory settings** — The memory is freed temporarily but the same query pattern will exhaust it again. (90% fail)
