Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rkron86's avatar

Laravel Batch consumes lot of memory when dispatched in chunk

The users list have 160000 Records and its chunked to created 1000 per batch. The userjob Class has no processing logic and returns just 0. When I remove the batch in the below code and check consumption, the memory is just 4mb., but on adding the batches the memory keeps crawling up to 4gb,looks like all the batches are loaded into memory. How do I fix this?

    User::chunk(1000, function ($ids) {
                $calculationJob = [];
                foreach ($ids as $id) {
                    $calculationJob[] = new UserJob();
                }

                $batch = Bus::batch([])
                    ->onQueue('process-1')
                    ->dispatch();

                $batch->add($calculationJob);
            });
0 likes
9 replies
Tray2's avatar

Of course it does, you add to the $batch variable every time you itterate orver the next chunk

$batch->add($calculationJob);
rkron86's avatar

@Tray2 Without the variable its the same, nothing changes.

Bus::batch($calculationJob)
                    ->onQueue('process-1')
                    ->dispatch();
Snapey's avatar

in a similar situation, I passed an offset and chunk size (only) into each job and each was responsible for retrieving its own chunk of records using the offset when it eventually ran.

1 like
rkron86's avatar

@ahmedragab There is no issue with chunk, problem is with batch->add no matter wat on same script it does not clear memory

Snapey's avatar

So, let me get this straight. You want to add 160,000 jobs to a batch so that it can track that they all run, and you are surprised its a heavy process?

We have an expression "off your trolley" perhaps you know what this means?

Please or to participate in this conversation.