A Symfony application that responds in 200ms with ten rows in the database and takes three seconds with ten thousand almost never has a database problem - it has a Doctrine usage problem. The ORM deliberately hides the complexity of the underlying SQL, which is exactly what lets functionally correct code silently turn catastrophic as data volume grows. The causes are almost always the same: N+1 queries, oversized hydration, and flush() called carelessly inside a loop.

The N+1 problem: the evergreen classic

The symptom is always the same: a list of 50 items triggers 51 SQL queries instead of one or two.

// Triggers 1 query to fetch the orders,
// then 1 EXTRA query per order to load its customer
$orders = $em->getRepository(Order::class)->findAll();

foreach ($orders as $order) {
    echo $order->getCustomer()->getName(); // lazy query on every iteration
}

The underlying mechanism is proxies and lazy loading. By default, a ManyToOne or OneToMany relation is not loaded with the owning entity: Doctrine generates a proxy that only fires the actual SQL query on the first access to a property of the related entity. That's a reasonable default (don't load what you don't use), but disastrous the moment a loop systematically touches the relation.

// Fix: explicit join with addSelect to load everything in one query
$orders = $em->createQueryBuilder()
    ->select('o', 'c')
    ->from(Order::class, 'o')
    ->leftJoin('o.customer', 'c')
    ->getQuery()
    ->getResult();

The underlying mechanism: Unit of Work and the identity map

Doctrine keeps a Unit of Work in memory that tracks every managed entity and computes, at flush() time, the full set of changes to persist by comparing each entity's current state against the state known when it was loaded. Every loaded entity stays referenced in the identity map for the entire lifetime of the EntityManager. This mechanism is what lets Doctrine guarantee that the same database row never produces two different PHP objects within the same HTTP request - but it carries a memory and CPU cost that grows with the number of loaded entities, invisible unless you specifically look at the query count or the hydration time.

Diagnosing before optimizing blindly

The Symfony Profiler's Doctrine panel immediately shows the number of queries executed per page - a count that grows with data volume instead of staying constant is the textbook N+1 signal. To go further:

// Temporarily enable the SQL logger to inspect generated queries
$em->getConnection()->getConfiguration()->setSQLLogger(
    new \Doctrine\DBAL\Logging\DebugStack()
);
-- Check that an index actually exists on the foreign key used in joins
EXPLAIN ANALYZE
SELECT o.*, c.* FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending';

An EXPLAIN ANALYZE revealing a Seq Scan on a table with hundreds of thousands of rows, where an Index Scan was expected, usually points to a missing index on the join or filter column - a problem that exists independently of Doctrine, but one the ORM tends to mask since it generates the query for you.

The fix, and its tradeoffs

The fetch join (leftJoin + addSelect) solves the N+1, but introduces a symmetric trap: joining several OneToMany collections in the same query triggers a cartesian explosion of duplicated rows before hydration, which can be worse than the original N+1 for large collections. The right practice is to limit the fetch join to one collection at a time, and use a second call (or application-level pagination) for the following relations.

// Correct pagination with a join: use Doctrine's Paginator,
// not a plain setMaxResults on a query with a one-to-many join
use Doctrine\ORM\Tools\Pagination\Paginator;

$query = $em->createQueryBuilder()
    ->select('o', 'items')
    ->from(Order::class, 'o')
    ->leftJoin('o.items', 'items')
    ->getQuery();

$paginator = new Paginator($query);
$paginator->setUseOutputWalkers(false); // adjust depending on the query, see Doctrine docs
$total = count($paginator);

For pure read lists (reporting APIs, exports, read-only screens), array hydration (->getQuery()->getArrayResult()) or partial objects avoid building full entities with their entire graph of proxies, which meaningfully cuts CPU and memory cost when no mutation of that data is planned.

When flush() in a loop becomes the real bottleneck

// Anti-pattern: flush() inside the loop recomputes the changeset
// of EVERY managed entity on each iteration
foreach ($rows as $row) {
    $product = new Product();
    $product->setName($row['name']);
    $em->persist($product);
    $em->flush(); // growing cost: O(n) per call, O(n^2) across the whole loop
}

Every flush() call triggers a changeset computation across every entity currently managed by the EntityManager, not just the one that was just modified. For an import of ten thousand rows, the cumulative cost becomes quadratic rather than linear, because the identity map keeps growing on every iteration and is never cleared.

// Fix: batched flush, with periodic clear() to release the identity map
foreach ($rows as $i => $row) {
    $product = new Product();
    $product->setName($row['name']);
    $em->persist($product);

    if (($i + 1) % 200 === 0) {
        $em->flush();
        $em->clear(); // detaches every managed entity, frees memory
    }
}
$em->flush();

The tradeoff of clear() is that it detaches every entity, including ones still needed later in the processing - which means any reused entity has to be explicitly reloaded after a clear(), or risk an EntityNotFoundException or a silently inconsistent detached entity.

When the easy fix isn't enough

For a massive import (several hundred thousand rows), even batched flush() stays too costly: Doctrine builds full PHP objects with their entire lifecycle (events, listeners, validation) for every row. At that scale, a bulk insert straight through DBAL ($connection->executeStatement() with multi-row INSERT statements) or a COPY load (PostgreSQL) deliberately bypasses the ORM, trading away lifecycle hooks for a one- or two-order-of-magnitude gain in execution time.

A more insidious edge case concerns long-running processes (a Symfony Messenger worker, a batch-processing CLI command): the identity map never clears itself, so a worker processing thousands of messages without periodically calling $em->clear() accumulates entities in memory until available RAM runs out - a behavior that only shows up after several hours of continuous execution, and therefore rarely in tests.

Finally, cascade: ["remove"] combined with orphanRemoval: true on a OneToMany relation can trigger unanticipated cascading deletes - each individual deletion of a child entity generates its own DELETE query, turning what looked like a trivial deletion into hundreds of sequential queries against a large collection.

Second-level cache: a tool, not a silver bullet

Doctrine's second-level cache stores hydrated entity data outside the identity map, shared across requests, which can remove the query entirely for data that changes rarely (a product catalog, a list of countries, configuration values). It's tempting to reach for it as a blanket fix once query counts stop improving through fetch joins and partial hydration alone.

// config/packages/doctrine.yaml
doctrine:
    orm:
        metadata_cache_driver:
            type: pool
            pool: doctrine.system_cache_pool
        query_cache_driver:
            type: pool
            pool: doctrine.system_cache_pool
        result_cache_driver:
            type: pool
            pool: doctrine.result_cache_pool
#[ORM\Entity]
#[ORM\Cache(usage: 'NONSTRICT_READ_WRITE')]
class Country
{
    // ...
}

The tradeoff is invalidation correctness, not raw performance. NONSTRICT_READ_WRITE accepts a short window of staleness after a write, which is fine for a country list and unacceptable for an account balance. Caching an entity that's actually updated frequently just moves the bug from "slow" to "occasionally wrong," which is a strictly worse failure mode in production. The second-level cache earns its place only on data that's genuinely read-heavy and tolerant of brief staleness, never as a reflex fix for a query that's merely unoptimized.

Takeaway

Performance with Doctrine is managed by watching three precise signals - query count per page, in-memory identity map size, and the cumulative cost of flush() calls - rather than by optimizing individual queries at random. Fetch joins, partial hydration and periodic clear() cover the vast majority of cases; beyond a certain volume, stepping outside the ORM for bulk operations is a legitimate architectural choice, not an admission of failure.