Doctrine UnitOfWork and Memory in Long-Running CLI Workers

Why Doctrine's identity map keeps growing in long CLI commands and queue workers, and how clearing the EntityManager in batches kept memory flat on one import.

· 3 min read · Erik Kubica

On the Symfony projects I've worked on, one of the more common "why did it stop?" questions is a background CLI worker that dies without a useful stack trace.

In a standard PHP web request, memory management is forgiving. An HTTP request hits your Symfony controller, Doctrine queries twenty database entities, Twig renders the HTML template, and PHP terminates the process, freeing every allocated byte.

Because of that lifecycle, it's easy to never think about how Doctrine's UnitOfWork manages entity state. I didn't for a long time either.

Then you write your first long-running CLI command or background queue worker.

When an Import Hit 512 MB

I once helped troubleshoot an import command that processed 60,000 customer invoice records from a legacy CSV file or external accounting API.

The code looked clean and idiomatic Doctrine:

// The silent memory leak in long-running CLI scripts
public function execute(InputInterface $input, OutputInterface $output): int {
    $invoices = $this->invoiceRepository->findAllUnprocessed();

    foreach ($invoices as $invoice) {
        $invoice->markAsProcessed();
        $this->entityManager->persist($invoice);
        $this->entityManager->flush();
    }

    return Command::SUCCESS;
}

The script starts executing. It processes the first 1,000 invoices without trouble. The process memory sits at 28 MB.

By row 5,000, memory usage climbs to 180 MB. By row 12,000, the process crawls as PHP's garbage collector scans circular object graphs. At row 14,210, the command crashes:

Fatal error: Allowed memory size of 536870912 bytes exhausted 
(tried to allocate 20480 bytes) in .../Doctrine/ORM/UnitOfWork.php

The first instinct is usually to increase PHP's memory limit: ini_set('memory_limit', '2G'). That can buy time, but it doesn't address the cause; it just moves the crash to a later row.

Why UnitOfWork Keeps Everything

Doctrine is an implementation of the Data Mapper pattern. To calculate which fields changed during $em->flush(), Doctrine relies on an internal Identity Map managed by UnitOfWork.

For every managed entity: 1. UnitOfWork keeps an object reference in memory. 2. It stores a snapshot of the entity's original property values for dirty checking. 3. It retains references to lazy-loaded relationship proxies (User, Address, LineItems).

Even after you call $em->flush(), Doctrine does not detach the entity. It assumes you might want to modify it again later. As your loop iterates, every entity object stays in RAM.

A second thing worth checking: $repository->findAll() loads every record into a PHP array up front. Using query iteration ($query->toIterable()) instead of $query->getResult() streams rows one at a time instead of buffering 60,000 of them.

The identity map is useful in a single web request, but it's worth remembering it keeps growing inside a long CLI loop.

Batching and Clearing

For long-running queue workers or large batch migrations, what worked for me was explicitly detaching entities and clearing the identity map:

public function importInvoices(iterable $records): void {
    $batchSize = 100;
    $i = 0;

    foreach ($records as $record) {
        $invoice = new Invoice($record['amount'], $record['currency']);
        $this->entityManager->persist($invoice);

        if ((++$i % $batchSize) === 0) {
            $this->entityManager->flush();
            $this->entityManager->clear(); // Detaches all entities and frees RAM
        }
    }

    $this->entityManager->flush();
    $this->entityManager->clear();
}

After adding that $this->entityManager->clear() call every 100 records, on that import:

  • RAM footprint: memory stayed flat at around 32 MB across all 60,000 rows.
  • Garbage collection overhead: dropped by roughly 80%, and the run went from about 48 minutes to about 4 minutes.
  • Reliability: the queue workers ran for weeks without a memory exhaustion alert.

Your numbers will differ depending on entity size and relations. One caveat: after clear(), entities you loaded earlier are detached, so you have to re-fetch anything you still need rather than keep using old references.

If you run Doctrine in long-running processes, it helps to treat memory as something you manage yourself: the EntityManager keeps what it has loaded until you tell it to let go.

Tell me what you need built

Usually a reply within a day, by email or WhatsApp.