← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · ✎ updated 7d
← Back to glossary

Memory Exhaustion

PHP PHP 4.0+ Intermediate
debt(d9/e5/b5/t7)
d9 Detectability Operational debt — how invisible misuse is to your safety net

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.

e5 Effort Remediation debt — work required to fix once spotted

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.

b5 Burden Structural debt — long-term weight of choosing wrong

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.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

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.

About DEBT scoring →

Also Known As

memory limit out of memory Allowed memory size exhausted memory leak PHP PHP OOM

TL;DR

PHP's Allowed Memory Size Exhausted fatal error — caused by loading too much data into memory at once, unbounded loops accumulating objects, or memory leaks in long-running processes.

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

⚠ Increasing memory_limit to fix exhaustion masks the real leak rather than solving it—queue workers and CLI daemons that process jobs in loops will still leak across iterations because PHP's garbage collector doesn't run automatically; you must call gc_collect_cycles() explicitly or restart the worker process after each batch.

Common Misconception

✗ Increasing memory_limit fixes memory exhaustion. Increasing the limit defers the problem — it does not solve it. A script loading 1 million database rows into an array will exhaust even a 2GB limit at scale. The correct fix is to change the data access pattern: stream the data instead of loading it all at once, use SQL cursors or keyset pagination, or process in batches. Raising the limit is only appropriate when the task genuinely requires more memory and the consumption is bounded.

Why It Matters

Memory exhaustion is the most common fatal error in PHP batch processing, data imports, and report generation. A script that works fine on 1,000 rows crashes on 100,000 because the developer loaded the entire result set into a PHP array. The generator pattern and PDO cursor fetching allow processing arbitrarily large datasets with constant memory usage regardless of dataset size. In queue workers, undetected memory leaks cause workers to consume increasing memory until the process is killed, which drops queued jobs unless handled carefully.

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

💡 Note
Bad: loading a 50k-row database result into a single array ($rows = $pdo->query('SELECT * FROM users')->fetchAll()) exhausts memory; Good: processing rows in chunks with LIMIT/OFFSET or using a generator (yield from a cursor) keeps memory constant.
✗ Vulnerable
// 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
}
✓ Fixed
// 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
}

Added 23 Mar 2026
Edited 4 Jul 2026
Views 201
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 19 Google 16 PetalBot 14 SEMrush 10 Ahrefs 10 ChatGPT 7 Scrapy 7 Perplexity 6 Bing 5 Majestic 3 Meta AI 2 Applebot 2 Sogou 1 Twitter/X 1 Baidu 1
crawler 99 crawler_json 5
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
PHP php A server-side scripting language that generates web pages and APIs — the code runs on the server, and only its output (usually HTML or JSON) reaches the browser.

PHP is often the first server-side language people meet, and understanding its execution model — script starts fresh on every request, no memory between requests — explains most of how the web backend works: sessions, databases, and caching all exist to bridge that per-request amnesia.

💡 Start with PHP 8.x, declare(strict_types=1), and PDO — skip any tutorial that mentions mysql_query().

Ask Codex about PHP →
⚡ DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Medium
⚡ Quick Fix
Replace fetchAll() with a PDO cursor fetch() loop, use yield to create generators for large collections, process in SQL-paginated batches of 500–1000 rows
📦 Applies To
PHP 4.0+ web cli
🔗 Prerequisites
⚠ Related Problems


✓ schema.org compliant