Memory Exhaustion
debt(d9/e5/b5/t7)
Closest to 'silent in production until users hit it' (d9). The detection_hints.tools list is not specified, and memory exhaustion in PHP batch jobs or queue workers typically surfaces only when a real-scale dataset is processed — often in production. Local testing with small datasets passes fine; the fatal error only appears when the volume scales up, making it invisible until users or monitors report it.
Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix requires replacing fetchAll() with cursor-based fetching, converting data pipelines to use generators with yield, and restructuring batch loops to paginate — this goes beyond a single-line swap and typically touches data-access layers, loop logic, and result-handling code across one or more components.
Closest to 'persistent productivity tax' (b5). Memory exhaustion applies to both web and CLI contexts (broad applies_to scope) and imposes an ongoing design constraint on every batch job, import script, and queue worker. Developers must consistently choose streaming/pagination patterns over convenience methods like fetchAll(), and must monitor peak memory in production — a persistent productivity tax across multiple work streams.
Closest to 'serious trap' (t7). The misconception field directly states the canonical wrong belief: developers increase memory_limit thinking it fixes the problem, when in fact it only defers it. This contradicts intuition — raising a limit appears to resolve an 'out of memory' error, but the root cause (loading entire result sets into arrays) remains. This mirrors how a similar concept (stack size limits) behaves differently, making the PHP memory_limit a genuine behavioral trap that contradicts developer expectations.
Also Known As
TL;DR
Explanation
PHP enforces a memory limit (memory_limit in php.ini, default 128M) and throws a fatal error when exceeded. Common causes: loading entire database result sets into arrays (SELECT * with 100k rows); storing large files or images in strings; recursive functions with deep call stacks; accumulating objects in loops without unsetting them; memory leaks in long-running CLI scripts or queue workers. Diagnosis: memory_get_peak_usage() shows maximum memory consumed; Xdebug's memory profiler shows allocations by function. Solutions: process data in chunks (SQL LIMIT/OFFSET or cursor); use generators (yield) for lazy iteration; stream files instead of reading into strings; unset large variables when done; increase memory_limit as a last resort only after ruling out the actual cause. In queue workers and CLI scripts running indefinitely, PHP's garbage collector (gc_collect_cycles()) must be called periodically or objects accumulate across jobs.
Watch Out
Common Misconception
Why It Matters
Common Mistakes
- Using fetchAll() on large result sets — use PDO cursor (fetch() in a loop) or SQL LIMIT with pagination instead.
- Not unsetting large arrays after use inside loops — PHP's reference-counted garbage collection needs unset() or variable reassignment to free memory.
- Accumulating results in a global array during batch processing — write results to a file or database as you go instead of collecting them in memory.
- Not monitoring peak memory usage in production — add memory_get_peak_usage() to application logs for batch jobs.
Avoid When
- Describing out-of-memory errors in compiled languages (C, Go, Rust) or JVM-based applications—use language-specific terms like 'heap exhaustion' or 'OutOfMemoryError' instead.
- Referring to slow performance or high CPU usage that happens to correlate with memory consumption—Memory Exhaustion specifically means hitting PHP's memory_limit, not general inefficiency.
- Documenting stack overflow errors from infinitely recursive functions—these are distinct fatal errors ('Maximum function nesting level' or segfaults) not caused by data accumulation in heap memory.
- Diagnosing swap thrashing or OS-level memory pressure on the host system—Memory Exhaustion is a PHP-level limit, not a system resource exhaustion issue.
When To Use
- A PHP script crashes with 'Allowed memory size exhausted' error, and you need to diagnose whether it's a code issue (unbounded loops, large dataset loads) or legitimate peak usage requiring a memory_limit increase.
- You're optimizing a long-running queue worker or CLI script that processes jobs sequentially and you suspect memory isn't being freed between iterations due to accumulated objects or leaked references.
- A database-driven page or API endpoint suddenly becomes slow or crashes when query result sets grow large (e.g., exporting 50k+ rows), and you need to refactor from loading all data at once to streaming or pagination.
- You're debugging a recursive function or deeply nested loop that accumulates data structures in memory and need to understand peak memory consumption patterns to redesign for lazy evaluation or chunked processing.
Code Examples
// Loads entire table into memory — crashes on large datasets
function exportUsers(PDO $pdo): array {
return $pdo->query('SELECT * FROM users')->fetchAll();
// 500k users × ~1KB each = ~500MB — memory_limit exceeded
}
// Generator — constant memory regardless of dataset size
function exportUsers(PDO $pdo): Generator {
$stmt = $pdo->query('SELECT * FROM users');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
yield $row; // one row in memory at a time
}
}
// Usage — writes CSV without loading all users
$fh = fopen('export.csv', 'w');
foreach (exportUsers($pdo) as $user) {
fputcsv($fh, $user);
// $user goes out of scope — garbage collected
}