Allowed memory size of 134217728 bytes exhausted (tried to allocate 42 bytes)

Allowed memory size of 134217728 bytes exhausted (tried to allocate 42 bytes)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Allowed memory size of 134217728 bytes exhausted (tried to allocate 42 bytes)

You are hitting a classic PHP limitation, but the solution isn't about changing your architecture to use threading or spawning child processes. The error message Allowed memory size of 134217728 bytes exhausted tells you exactly what happened: your script tried to build a data structure in RAM that was too large for the limit set by the PHP runtime.

The specific detail (tried to allocate 42 bytes) is often misleading. While the immediate request failed because of those 42 bytes, the actual issue is likely that the cumulative memory usage of your variables has grown beyond the 128 MB ceiling (134,217,728 bytes). In your scenario, retrieving more than 0.2 million rows from a MySQL table and loading them directly into an array in PHP is an anti-pattern for high-volume data.

Why Loading Millions of Rows Fails

When you execute a query that returns hundreds of thousands of rows, PHP creates an associative or indexed array to hold every single record. Each row contains multiple columns. If you have ten columns and 200,000 rows, you are essentially instantiating 2 million distinct objects (or strings) in memory.

Even with a modest 8 GB system, the PHP process is constrained by two factors:

  1. The memory_limit directive: By default, many shared hosting environments or XAMPP installations cap this at 128 MB to prevent runaway scripts from crashing the web server. Your error confirms you are hitting this specific wall.
  2. Garbage Collection Overhead: PHP's garbage collector runs periodically, but it cannot reclaim memory that is currently referenced by active variables. If your script holds the entire result set in $rows = $conn->fetchAll(), that memory remains allocated until the script ends.

The Correct Approach: Pagination and Generators

Instead of asking for threading, which introduces significant complexity regarding context switching and data serialization overhead, you should change how you retrieve and process the data.

1. Fetch in Batches (Pagination)
The most effective immediate fix is to paginate your query. Instead of fetching all rows at once, modify your SQL to use LIMIT and OFFSET, or better yet, fetch a small batch per loop iteration using LIMIT 100.

// Bad: Loads everything into memory
$rows = $pdo->query("SELECT * FROM table_name")->fetchAll(PDO::FETCH_ASSOC);

// Good: Process in chunks of 100
$batchSize = 100;
$page = 1;

while (true) {
    $sql = "SELECT * FROM table_name LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $batchSize, PDO::PARAM_INT);
    $stmt->bindValue(':offset', ($page - 1) * $batchSize, PDO::PARAM_INT);
    
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($rows)) {
        break;
    }

    // Process each row here
    foreach ($rows as $row) {
        processRow($row); 
    }

    $page++;
}

2. Use Lazy Loading with Generators
If you are iterating through a massive dataset, consider using a generator function. This ensures that rows are processed one by one without storing the intermediate array in memory.

function chunkedQuery($pdo, $sql, $params) {
    $stmt = $pdo->prepare($sql);
    return new Generator(function() use ($stmt, $params) {
        while (true) {
            $stmt->execute($params);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (empty($rows)) {
                break;
            }

            foreach ($rows as $row) {
                yield $row;
            }
        }
    });
}

// Usage
$generator = chunkedQuery($pdo, "SELECT * FROM table_name", []);
foreach ($generator as $row) {
    // Handle single row immediately
    handleRow($row); 
}

Adjusting the memory_limit (Not Recommended for Large Datasets)

Some developers might suggest increasing the memory_limit in php.ini or via .htaccess. While this resolves the immediate crash, it is not a sustainable architectural fix. If you increase the limit to 2 GB just to hold 0.2 million rows, you risk exhausting the physical RAM on your server, causing the OS to swap heavily and slowing down other processes.

Furthermore, if you are running PHP in a shared hosting environment or within an application pool (like IIS), increasing the memory limit might hit the maximum allowed by the host provider or cause the worker process to restart unexpectedly.

When Threading Is Not The Answer

Your question regarding threading suggests a desire to parallelize the work. In PHP, this usually implies pcntl_fork on Linux or spawning multiple CLI processes. However, for a web request handling a database query:

  • Concurrency Overhead: Spawning threads to fetch data from a single relational database adds little benefit because the bottleneck is almost certainly I/O (waiting for MySQL to send rows), not CPU.
  • Database Locking: Parallel queries against the same table can lead to lock contention or deadlocks if not carefully managed with transactions and isolation levels.
  • Complexity: Managing data distribution between threads is significantly harder than simply fetching a smaller chunk of data.

Summary of Recommendations

  1. Stop loading the full result set. Use LIMIT clauses to fetch data in manageable chunks (e.g., 50–200 rows).
  2. Process immediately. Do not store fetched batches in a temporary array if you can avoid it; yield them or iterate directly.
  3. Check your SQL. Ensure the query is optimized with proper indexes so that fetching even small chunks doesn't trigger unnecessary index scans on massive tables.

By shifting from a bulk-load strategy to a stream-processing approach, you respect the memory constraints of PHP without needing to refactor your entire application architecture or rely on complex threading models.

Our network