Read Models, Projections, and Performance
Read models, projections, and performance of a DDD application on Symfony and Doctrine ORM: N+1 queries, the impact of aggregate boundaries, building projections, snapshots, and read model caching.
In this chapter
16.01 Performance in the context of DDD#
The reputation of DDD as slow rests on anecdotes rather than measurements. Performance problems come from poor implementation: aggregates that are too large, ill-suited lazy loading, a missing read model. A domain model does not rule out a fast application.
Performance becomes critical in three scenarios: in applications with dozens of interconnected aggregates, in large aggregates with collections of thousands of items, and in systems with a high read frequency. The last group also needs response times in the tens of milliseconds.
The chapter has two halves that must not be confused. Sections 16.02 (except keyset paging), 16.03, 16.06, and 16.08 deal with the write side: the aggregate, the Unit of Work, and batch writes. The limit there is consistency, so no optimization may break an invariant. Sections 16.04, 16.07, and part of 16.09 belong to the read side: the query, the projection, the cache, and the replica. Nobody holds an invariant there, so the data may be denormalized, duplicated, and even returned stale. Sections 16.05 and 16.10 concern both sides. Advice that holds on one side often does harm on the other.
16.02 The N+1 problem and lazy loading in Doctrine#
N+1 is the typical anti-pattern of any ORM without an explicitly chosen fetch strategy. The application runs one query for a list of entities and then loads the associated data for each of them separately – N+1 SQL statements in total instead of one or two.
For collections (OneToMany, ManyToMany), Doctrine uses lazy loading by default: the collection stays uninitialized until code accesses it for the first time. When the code never uses the collection, that is an advantage. When iterating over many aggregates, however, it produces the N+1 problem described above.
Solution 1: EXTRA_LAZY collections
Doctrine offers the EXTRA_LAZY strategy for collections. Standard lazy loading loads the whole
collection on first access. EXTRA_LAZY instead handles count(), contains(),
or slice() with direct SQL queries and never loads the collection into memory.
Solution 2: Fetch join in DQL for eager loading
When it is clear up front that the code will iterate over collections, a fetch join in DQL is more efficient:
the alias of the joined association is added to the SELECT clause (SELECT o, i). Doctrine then loads
the aggregate including the associated objects in a single SQL query with a LEFT JOIN or INNER JOIN.
When a fetch join is combined with pagination (setMaxResults(), setFirstResult()),
Doctrine prints no warning. LIMIT applies to the rows of the SQL result, in which
the root entity repeats because of the join. Hydration then silently returns fewer entities or truncated collections.
The solution is Doctrine\ORM\Tools\Pagination\Paginator, which first selects the identifiers
of the root entities for the given page and only then loads the data for them, or native SQL
with custom result mapping.
Paginator has its price, though. By default it issues three queries: a COUNT with DISTINCT,
a subquery with the root entity identifiers for the given page, and a final WHERE IN.
The constructor parameter $fetchJoinCollection: false cuts that to two and is appropriate where
the query joins only to-one associations. The DISTINCT in the count query can be suppressed with the
Paginator::HINT_ENABLE_DISTINCT hint. The constant belongs to the Paginator class, not to Query.
Aggregate functions in SELECT behave unpredictably with fetchJoinCollection: true;
for a query with SUM() or COUNT(), writing a custom count query is the better option.
Solution 3: batched eager fetch
For a collection mapped as fetch: 'EAGER', Doctrine does not issue a JOIN. It loads a OneToMany collection
with a second query that serves several root entities at once. The batch size defaults to 100
and is set by Configuration::setEagerFetchBatchSize(int $batchSize = 100). N+1 queries
thus become N/100 + 1, and the mechanism works even without explicit configuration.
Batching does not apply to ManyToMany: an eager ManyToMany collection costs one query per parent,
so N+1 remains. The same holds for OneToMany with indexBy or with a composite foreign key.
The catch: EAGER in the mapping applies globally, even to queries that do not
need the association at all. The ORM documentation therefore recommends solving N+1 primarily with a fetch join in DQL.
Eager mapping remains the last resort for associations that are loaded practically always.
Deep pagination and keyset paging
The database does not skip the rows before OFFSET; it has to walk through them and discard them. On the first
page this is unmeasurable; on page five thousand the same query is an order of magnitude slower. The second
problem is drift: a record is added between two requests, the list shifts, and the reader sees
an item on the next page that they have already read.
Keyset paging (the seek method) uses the values of the last item of the previous page as a predicate
instead of an offset. The condition must contain the entire ORDER BY including a unique column; otherwise
records with an identical timestamp get lost at the page boundary.
The read model has its own table, so the index is designed directly for the query that reads it, not for the domain schema. On the write side, by contrast, indexes mainly serve to look up an aggregate by identity. The price of keyset paging is losing the jump to an arbitrary page: the seek method can do “next” and “previous,” not “page 137.”
16.03 Aggregates and performance: getting the boundaries right#
An aggregate holds a consistency boundary: invariants apply within a single aggregate. A boundary drawn too wide means the aggregate pulls an extensive object graph from the database, even when the operation needs only a small part of the data.
Solution: splitting the aggregate and specialized repository methods
The first step is to review whether OrderItem really has to be part of
the Order aggregate, or whether it is a separate aggregate with a reference to OrderId.
The invariant decides. If the order holds no rule across the whole collection
(a limit on the number of items, a minimum cart value), the collection has no business being in the aggregate.
Moving it out is then a design fix, not a performance trick.
Performance can enter the decision in two ways. As a signal of a badly drawn boundary, it is a legitimate prompt: slow loading points to a collection that was never part of an invariant. As a reason to break an invariant, however, it does not hold up. The answer there remains a read model, not moving the rule outside the aggregate. Aggregate size is analyzed in detail in the Aggregate size and its consequences section.
The aggregate boundary follows domain invariants; performance requirements are handled elsewhere. Evans and Vernon both draw it the same way, through the rule that must hold in one transaction. When performance pushes against the domain model, the answer is a read model (see the next section), not a violation of domain integrity.
16.04 Read model optimization (CQRS)#
Separating the write side (operations through aggregates) from the read side (queries for presentation) is the strongest lever against performance problems in DDD. The read side needs no domain objects and returns the data structure for the UI or API client directly.
It is also the lever with the highest cost. Martin Fowler writes about CQRS that “for most systems CQRS adds risky complexity.” He describes the cases he has seen as a source of trouble rather than a rescue. He recommends applying it to an individual Bounded Context, never across the board [2]. The complete list of trade-offs is in the Challenges and limitations of CQRS section. Before a query ends up in a separate read model, it pays to go through the cheaper steps.
The query stays within one aggregate and carries the customer only as customerId. The customer's name lives
in a different aggregate, and DQL would need a mapped Order → Customer association for it, which
the book forbids on the write side (see References by identity, not by object).
On the read side, joining the two tables is fine. It happens one level lower, though, in SQL over
the tables, not through a mapped object graph, as the following example shows.
Doctrine NativeQuery for complex reporting queries
DQL covers most queries, but it is not enough for complex reporting queries (aggregations, window functions, CTEs).
For those, Doctrine runs native SQL with custom result
mapping via ResultSetMapping.
16.05 UUID vs. integer primary keys#
An aggregate must know its identity before it is saved to the database. The identifier is generated in domain code without a database sequence or auto-increment value. For distributed systems, event sourcing, and parallel creation of aggregates, this is not an option but a requirement.
Time-ordered identifiers: UUID v7 and ULID
ULID (Universally Unique Lexicographically Sortable Identifier) and UUID versions 6/7 (ordered UUID) solve index fragmentation by being time-ordered. Apart from minor deviations between generators, new values are greater than previous ones and are inserted at the end of the B-tree index. The behavior comes close to an auto-increment integer, but global uniqueness remains and no central generator is needed. This book uses UUID v7; ULID is an alternative with a shorter Crockford base32 representation (26 characters vs. 36).
16.06 Doctrine Identity Map and Unit of Work#
Doctrine ORM implements the Identity Map pattern (Martin Fowler, Patterns of Enterprise Application
Architecture, Addison-Wesley, 2003).
Each managed entity is stored in memory under its identifier within one EntityManager.
If you load the same aggregate twice via find() by ID, Doctrine returns
the object from memory the second time without an SQL query. A repeated DQL query does run SQL, but during hydration
it returns the existing instance from the Identity Map, not a new copy.
The problem with batch processing
The Identity Map assumes a typical web request: a handful to a few dozen aggregates. Bulk processing (imports, migrations, reports) pours thousands of objects into the Identity Map, and they stay there for the entire run. Memory consumption grows as if the application had a memory leak, and dirty checking slows down because Doctrine has to walk an ever larger set of managed objects.
The batch size is an empirical value, not a constant from the documentation. The Doctrine documentation advises
experimenting with it: a larger batch saves overhead but makes a single flush() longer. Its own
examples work with a batch of 20. The optimum depends on the row width, the number of indexes,
and the database settings. The hundred rows in the example are a starting point, not a target.
Read-only entities and the scope of dirty checking
On every flush(), dirty checking compares the current state of managed objects with their
snapshot from the moment they were loaded. For reference data this is pure waste: lookup tables, the catalog, and
the price list do not change during a single run. The first lever is read-only entities.
#[ORM\Entity(readOnly: true)] marks a whole class, UnitOfWork::markReadOnly() a single
instance for the given run. flush() does not write changes to such an object to the database.
The second lever is the change tracking policy. The default DEFERRED_IMPLICIT walks through
all managed objects on flush(). The alternative DEFERRED_EXPLICIT checks only objects that the code
explicitly passes to persist(); it saves work, but a forgotten persist() means a silently unsaved
change. For a regular web request the default setting is fine; in a batch run it is worth considering.
16.07 Caching in a DDD architecture#
A cache belongs on results that are expensive in computation or I/O and do not change over time (or change predictably). It serves the infrastructure, not domain decisions.
Query cache and result cache in Doctrine
Doctrine offers two levels of caching for SQL queries:
- Query cache: caches the DQL → SQL translation. Parsing DQL is relatively expensive, and the query cache saves it for repeated queries. The translation of DQL to SQL does not change over time, so this cache does not need to be invalidated.
- Result cache: caches the results of an SQL query. It is enabled on a specific query with the
enableResultCache(?int $lifetime, ?string $resultCacheId)method. Suitable for read-heavy queries with a controlled lifetime.
The result cache is not invalidated by a domain event but by its key. Either you pass the query your own
$resultCacheId and delete it after the data changes via $em->getConfiguration()->getResultCache(),
or you derive the key from the data (for example, from the time of the last change) and let the old entry expire.
Without a named key, Doctrine generates a hash from the SQL and the parameters, which you have no way
of reproducing in application code. Such a query can be invalidated only by the TTL expiring.
Besides that there is the Second Level Cache, which caches the entities and collections themselves in the
READ_ONLY, NONSTRICT_READ_WRITE, and READ_WRITE modes. The documentation still labels it
experimental, and this book does not use it: a cache at the read model level solves the same thing
more clearly and without ties to the entity lifecycle.
The cache holds a finished ViewModel, not a domain aggregate. Serializing an aggregate is fragile: after deserialization you get an object detached from the Unit of Work, lazy association proxies stop working, and the Identity Map is bypassed. A ViewModel made of plain values has none of these problems. This matches the principle from the callout above: the cache holds read model results, not aggregate state.
The example uses Cache Contracts (Symfony\Contracts\Cache\CacheInterface), not bare PSR-6.
Besides shorter code, Contracts hold a lock for the duration of the computation, so when an entry expires,
only one process recomputes the value and the others on the same server wait. On top of that, by default
($beta = 1.0) Contracts use probabilistic early expiration: the closer an entry is to the end of its lifetime, the greater the chance
that one randomly chosen request recomputes it before it expires. Both prevent a cache stampede,
when hundreds of concurrent requests run the same query at once after a hot key expires.
Bare PSR-6 via CacheItemPoolInterface remains for interoperability with third-party libraries.
Cache invalidation on domain events
In DDD, the cache is best invalidated by listening to domain events. When an aggregate changes state and records a domain event, a listener invalidates the corresponding entries. Invalidation then follows the domain flow instead of ad hoc calls scattered through the code.
The example assumes a UserEmailChanged event. The canonical User from the
Implementation in Symfony 8 chapter does not have it;
its changeEmail() records no event. This is an extension: after changing the
address, the method would call $this->record(new UserEmailChanged($this->id, $newEmail)).
One domain event typically invalidates several derived views, not one key. That is exactly why
the listener deletes a tag rather than an item: the list, the detail page, and the dashboard tile carry the same tag
and disappear with one call. Tags require a pool with tagging support: in the framework.cache configuration,
either tags: true or the cache.adapter.redis_tag_aware adapter. A group can then also be
invalidated manually from the console with the cache:pool:invalidate-tags command.
16.08 Bulk operations and batch processing#
The standard DDD procedure works with individual aggregates: load the aggregate, apply the domain
logic, call flush(). For bulk operations (importing thousands of records,
bulk status updates, data migrations), it is inefficient. Each cycle adds
an aggregate to the Identity Map, and dirty checking on flush() walks all managed objects.
Without a periodic clear(), memory consumption and the duration of a single flush() therefore both grow: each further
write compares a larger set of objects than the one before.
DQL bulk UPDATE and DELETE – bypassing the Identity Map
Bulk updates that do not have to go through domain logic can be handled by Doctrine
directly as a DQL UPDATE or DELETE. These bypass the Identity Map and the Unit of Work,
because they are direct SQL statements translated from DQL. The drawback:
after a DQL bulk operation, the managed entities in the Identity Map are inconsistent with the state in the database.
A DQL UPDATE also changes only the listed columns, so it does not increment the version from #[ORM\Version].
A concurrent write through an aggregate that loaded the row earlier then does not detect the conflict and overwrites
the bulk change. For a versioned entity, o.version = o.version + 1 therefore belongs in the SET as well.
The usual advice is to call clear(). In ORM 3, however, clear() accepts no argument, so it detaches
everything, including the caller's work in progress. A safer order is to run the bulk operation
before anything is loaded into the entity manager, or to run it on a separate entity manager
reserved for maintenance tasks. A clear() at the end of the handler is then a safeguard, not a fix.
Batch writing via persist()/flush()/clear() is shown by the handler in the
Doctrine Identity Map and Unit of Work section; the same procedure applies to imports.
One more note on debugging: setSQLLogger() has been deprecated since DBAL 3.2,
and DBAL 4 removed it. Logging is turned off through configuration (doctrine.dbal.logging: false)
or by removing the logging middleware, not programmatically in the middle of a batch.
Reading large results one row at a time
Writing is only half of a batch job. The other half is reading: getResult() materializes the whole result
into an array, so a million rows end up in PHP memory at once. AbstractQuery::toIterable() returns
a Traversable and hydrates one row at a time; the iterate() method that ORM 2 users know
is gone in ORM 3. Two limitations apply to it:
toIterable()cannot be combined with a fetch join of a collection. One aggregate spreads across several rows in the SQL result, and row-by-row hydration cannot put them back together. This runs against the recommendation from the section on N+1: in a batch, collection fetch joins are not used.- Objects yielded by the iteration remain managed. Without a periodic
clear(), you save only the memory for the result array, not for the Identity Map.
When data is enough and aggregates are not needed, DBAL is more straightforward: Connection::iterateAssociative()
(and its siblings iterateNumeric(), iterateKeyValue(), iterateAssociativeIndexed(),
iterateColumn()) returns a Traversable of arrays, and the ORM stays out of the way entirely. The database client
library may buffer the result outside PHP memory, so memory_get_usage() may not show
the savings; monitoring the memory of the whole process is more reliable.
Symfony Messenger for asynchronous batch processing
A large import does not have to run in a single synchronous process where one error ends the whole batch. The work can be split into smaller tasks sent through Symfony Messenger to an asynchronous transport (RabbitMQ, Redis Streams, Amazon SQS). Each message processes one aggregate or a small batch, and the memory requirements and processing time of a single message become predictable.
Sending the messages does not end the work; it only moves it to the workers. A PHP process that runs for hours
gradually accumulates memory, so the worker is started with limits and allowed to restart:
messenger:consume async_commands --memory-limit=128M --time-limit=3600 --limit=1000.
The async_commands transport is the same one as in the Messenger configuration,
and ImportProductChunk has to be routed to it under routing:. Without that, Messenger handles it
synchronously and splitting into chunks brings nothing. Restarts are managed by
supervisor or systemd, not by the application. The number of concurrent workers has a ceiling in the database.
Each one holds its own connection, so ten workers on the primary mean ten more
connections. How this ties into pooling is covered in the Read replicas and connection pooling section.
16.09 Operational performance patterns#
The previous sections deal with performance at the level of a single query or a single aggregate. An application running around the clock under real load runs into problems that local profiling does not reveal: concurrency of many clients, the database as a shared resource, and the operational limits of Doctrine across multiple processes.
Hot aggregates and optimistic lock thrash
A hot aggregate is an aggregate that many clients modify at the same time. Classic
examples: the global Inventory of one product when a campaign launches, a Tournament
aggregate with 1000 participants who all confirm their attendance in parallel, or a company's BankAccount
with thousands of transactions a day.
With #[ORM\Version] (optimistic locking), concurrent modification leads to
OptimisticLockException exceptions. As long as conflicts are rare, a retry is cheap: the second attempt
goes through. Once conflicts multiply, the share of work that ends up discarded grows. The system
degrades to serial operation, and the load → modify → save → conflict → retry loop consumes
more capacity than the processing itself. Throughput drops, latency rises.
No universal number says when the tipping point comes. It depends on the length of the transaction, the number of clients,
and how often they target the same aggregate. It can be measured, though: the share of OptimisticLockException
among write attempts on a given aggregate is a metric worth tracking permanently.
Solution strategies are discussed in the Hot aggregate section; from an operational point of view, three matter, in this order:
- Redesigning the aggregate boundaries. A hot
Inventoryis often not really one aggregate but N separate aggregates, for example one per warehouse, region, or SKU. Conflicts then arise not among all clients but only among clients of the same location. - Eventual consistency instead of strong consistency. Instead of “deduct 1 unit from
Inventorysynchronously,” anItemReserved(productId, qty)event is published, and the aggregate processes it asynchronously through a saga. The saga resolves conflicts through compensation, not the optimistic lock. - CRDTs / pure counter aggregates. When the domain operation is a pure increment
(
view_count,like_count), the whole aggregate is not needed; a PostgresUPDATE counters SET n = n + 1 WHERE id = ?is enough. This is not typical DDD, but for truly commutative operations it is a legitimate solution.
Partitioning large tables
PostgreSQL declarative partitioning is the standard solution for tables that have outgrown
the server's memory and where only the most recent part actively changes (typically by created_at):
orderspartitioned by month – the active partition holds only the last month, so it fits into the cache together with its indexes. Old partitions (read-only) can live on a slower disk or in an archive.audit_logpartitioned by day – once the retention period passes, the old partition is detached (DETACH PARTITION, since PostgreSQL 14 alsoCONCURRENTLY) and dropped. A longDELETEover active data is no longer needed.projection_*tables with a high write rate.
For DDD, partitioning has one more consequence. When the table is partitioned by
created_at and the domain knows only OrderId, a query by ID has to go through all
partitions. There are two solutions. The repository gets the partition key: created_at
(or the derived month) is added to the OrderId value object and used for
partition pruning. The other route is to partition the table by ID directly: UUID v7 carries
a time component in its most significant bits, so ID ranges correspond to time periods.
Read replicas and connection pooling
In a CQRS architecture, read models are a good candidate for read replicas: a separate database (or a Postgres streaming replica) that receives all queries. The write model stays on the primary. Consequences for DDD code:
- The write-side repository holds an
EntityManagerInterfacemapped to the primary. - The read-side query handler holds a separate
ConnectionorEntityManagermapped to the replica (doctrine.orm.read_entity_manager). - Replication lag means that a query to the replica may not see a change right after
save()on the primary. It is the same “read your writes” problem as with eventual consistency. For the solution pattern, see CQRS – Eventual consistency in practice. The size of the lag is a property of the specific deployment, not a constant. On a Postgres replica it is given by the differencenow() - pg_last_xact_replay_timestamp(), and it belongs in monitoring next to query latency.
The cheapest defense against “read your writes” is routing, not domain code: after a write, the session sticks to the primary for a short time and reads from there. Sticky routing handles exactly the moment when the user submits a form and immediately afterward sees a listing. An alternative using the write position in an HTTP header is described in the Read-your-writes at the HTTP level section.
The identifier doctrine.orm.read_entity_manager is valid only when an entity manager
of that name is configured. Symfony generates a
doctrine.orm.<name>_entity_manager service for each manager, and autowiring follows the parameter name:
Doctrine does not support associations between entities of different managers. For a read model this is more of an advantage: it forces you to write queries over tables, not over an object graph across aggregate boundaries.
Connection pooling is a separate problem. The PHP-FPM model “1 worker = 1 PHP process
= 1 DB connection” adds up: 4 application pods × 100 PHP-FPM workers
= 400 connections to the primary, four times the default max_connections = 100
in Postgres.
The standard solution is PgBouncer / RDS Proxy between the application and the DB in transaction
pooling mode. Caution: transaction pooling by itself does not support prepared statements,
and Doctrine uses them. The solution is either session pooling (less efficient) or PgBouncer
1.21 or later with max_prepared_statements > 0. PgBouncer then intercepts the client's prepare,
assigns it an internal name, and prepares it again on the backend when needed. The option
was introduced precisely in version 1.21 with a default of 0, that is, disabled; it is enabled by default
(200) only from 1.24, so on an older version it has to be set explicitly. The condition: these must be
prepared statements at the database protocol level, that is, PQprepare/PQexecPrepared
in libpq. PgBouncer does not track the SQL statements PREPARE/EXECUTE. A
prepared_statements = true configuration option does not exist.
Projections in production: lag and rebuild
How to write a projection is shown in the CQRS and
Event Sourcing chapters. The operational half begins where they end:
with an asynchronous projection, there is always some lag between a write and its display. A synchronous
projection under doctrine_transaction has no lag; it pays for that with a longer write transaction.
It can be measured directly. The projector keeps a checkpoint, that is, the position of the last processed event. Against it stands the head of the stream. The difference between the two values is the projection lag, and it can be expressed in two ways: by the number of unprocessed events and by the age of the oldest of them. The first number says how much work remains, the second what the user will see. Both belong in monitoring, because a projection stuck on one faulty event has a small lag in events and a growing one in seconds.
A rebuild is the second operational situation, and it is better planned in advance. Replaying the whole stream into an empty table takes longer the longer the stream is, and the projection is unusable for the entire time. A proven procedure:
- A new table or schema next to the existing projection, filled from the beginning of the stream (blue/green).
- Meanwhile, the old table serves reads until the new one catches up with the head of the stream.
- The switch is a table rename or a change in the read-side configuration, an operation on the order of milliseconds.
- The old table stays for one more operational day as a fallback.
A rebuild reads and writes at full speed, so without limits it can swamp the same database that users read from. There are two solutions: run the rebuild against a replica and write to a separate instance, or throttle the batches. A fixed batch size and a short pause between batches keep the load under control at the cost of a longer run.
The last question is usually when to drop a projection instead. If a query over the write model completes in single-digit milliseconds and the data is read once a day, the projection adds operational cost without benefit. A table that nobody reads but that a projector maintains is pure waste.
Snapshotting in Event Sourcing (overview)
With Event Sourcing (the Event Sourcing chapter), the time to reconstruct
an aggregate's state grows linearly with the number of events. For an aggregate with 100 events it is instant; at
1000 events it starts to show, and at 100k+ events (a long-lived aggregate such as
UserAccount after years in production) hydration is unusable.
A snapshot is a condensed state of the aggregate stored periodically:
- After every N events, a
Snapshot{aggregateId, version, state}is saved. Snapshots are introduced only once replay measurably slows down; that tends to happen at hundreds to thousands of events. The interval (50 in the example in the Event Sourcing chapter) is a tunable parameter, not a recommendation. It depends on the size of the state and the ratio of reads to writes. - During hydration, the latest snapshot is loaded, plus only the events newer than its version.
- The cost: faster reads, but the snapshot table grows and its structure is tied to a specific version of the aggregate (the schema evolution problem, see Event Sourcing – event versioning).
The detailed implementation including Symfony code is in the Event Sourcing – Snapshotting section. From a performance point of view, a snapshot is not the default choice but an escape hatch for long-lived aggregates. Most DDD aggregates have dozens of events over their entire lifecycle and do not need snapshotting.
16.10 Profiling DDD applications#
You cannot find a bottleneck without measuring. For PHP/Symfony there are three layers of tools at hand: a development profiler, production profiling, and a middleware that counts SQL queries. The Stopwatch component complements them and is the cheapest of all: it runs without an extension even in production and measures things the Profiler does not see – such as the duration of one projector run or of processing one Messenger message.
Symfony Profiler (Web Debug Toolbar)
In the development environment, the Symfony Profiler is the first to reveal N+1 and slow queries
(active with APP_ENV=dev). The Doctrine panel shows:
- The total number of SQL queries per request. An excessive number signals the N+1 problem.
- The duration of each query; slow queries need an index or a rewrite.
- The complete SQL with parameters, so the query can be tried directly in a database client.
- A stack trace for each query, showing which part of the code issued it. It is collected only
after the
profiling_collect_backtraceoption is enabled on the DBAL connection.
Doctrine query logging
In the dev environment, counting queries is covered by the Doctrine panel in the Profiler. It is enabled by the
doctrine.dbal.profiling option, active by default in debug mode; logging controls
only writing queries to the logger. A custom middleware makes sense elsewhere: in an integration test
where an assertion targets the number of queries (“loading the order list must not issue more than two
queries”), or when debugging a batch that never ends up in the Profiler at all.
The middleware is registered as a service with the doctrine.middleware tag. In a test, all it takes is
calling reset() before the scenario and getQueryCount() after it. An assertion on the number of queries catches
a regression of the “someone removed the fetch join” kind before production monitoring does.
Blackfire.io for production profiling
For profiling PHP in a production or staging environment, Blackfire.io is the common choice. It captures the complete call graph of the profiled request or CLI command, including the duration, number of calls, and memory footprint of each function. On top of the profiles you can write performance tests (Blackfire Builds) that catch performance regressions in the CI/CD pipeline.
Symfony runtime optimization
One group of interventions does not touch the domain model at all and still speeds up every request:
the runtime environment settings. For production, Symfony recommends OPcache with preloading
(opcache.preload pointing to config/preload.php), disabled timestamp validation
(opcache.validate_timestamps=0), sufficient opcache.memory_consumption,
and opcache.max_accelerated_files above the number of files in the project. Add to that an enlarged realpath
cache (realpath_cache_size, realpath_cache_ttl), an autoloader generated via
composer dump-autoload --no-dev --classmap-authoritative, and, in the container configuration,
.container.dumper.inline_factories: true.
None of these options changes a single line of domain code. Before deciding to split an aggregate for performance reasons, it pays to verify that the application runs in production with preloaded OPcache at all. Otherwise the measurement reflects anything but the domain model.
The three levers of performance in DDD are aggregate boundaries, the read model, and profiling. The work always starts with measurement. Cheap interventions follow (N+1, indexes, a query outside the ORM), and only then a read model according to the escalation ladder. The aggregate boundary moves only when measurement reveals a collection that does not belong to the invariant. The next chapter is Testing DDD.
Frequently asked questions
Does DDD slow an application down compared to CRUD?
DDD by itself does not reduce performance. Domain classes are plain PHP without runtime overhead. Slowdowns occur when an aggregate is poorly designed (it loads more data than necessary). Other causes are a missing read model in CQRS or incorrect use of Doctrine lazy loading, which leads to N+1 queries. Explicit boundaries actually make optimization easier: it is clear what is loaded because of an invariant and what only for display. See the Performance in the context of DDD section.
How do you solve the N+1 problem with aggregates in DDD?
N+1 arises when the application fetches the inner elements of each loaded object with a separate query. The first choice is a fetch join in DQL (SELECT o, i FROM Order o LEFT JOIN o.items i) in a repository method. For reading data into the UI, a denormalized read model that skips ORM lazy loading entirely is often even more straightforward. Only the last choice is fetch: 'EAGER' in the mapping: for OneToMany collections it issues not a JOIN but a second, batched query (default size 100; ManyToMany has no batching), and it applies globally, even to queries that do not need the association. The solutions are analyzed in The N+1 problem and lazy loading in Doctrine.
Does aggregate size affect performance?
Yes. An aggregate that is too large pulls more data from the database than the operation needs. If every change bumps the root's version, it also leads to frequent optimistic locking conflicts. Doctrine, however, does not bump the version on its own when a child changes, so without bumping it manually, the invariant is silently broken instead of a conflict being raised (see Anti-Patterns and Common Mistakes). A well-chosen aggregate holds only what must be consistent in one transaction. When two parts of an aggregate do not share an invariant, they are usually two separate aggregates. Splitting them increases both parallelism and the speed of operations. A detailed analysis is in the Aggregates and performance: getting the boundaries right section.
How do you optimize a read model in CQRS?
A read model is designed directly for the given query. Denormalized tables match the shape of the UI, not the domain model. Typical optimizations are indexes designed for specific filters, materialized projections instead of JOIN queries over the write model, or replicating the read model to a different data store (Elasticsearch, Redis). When the events are stored, the read model can be rebuilt from them, and a change to its schema does not require a classic migration. A detailed analysis is in the Read model optimization (CQRS) section.
Which is better for performance, a UUID or an integer primary key?
An integer key is faster in indexes and takes up less space, but it requires an auto-increment generated by the database. A UUID lets the domain generate the identity without a round trip to the DB, and that is exactly what DDD requires: the aggregate gets its ID before persistence. The performance difference depends on the database engine, index width, and the ratio of writes to reads, so there is no general number. With UUID v7, however, the main drawback of random UUIDs, B-tree index fragmentation, goes away. For DDD, UUIDs are the recommendation. Both variants are compared in the UUID vs. integer primary keys section.