Chapter 12 · Patterns · CQRS

CQRS

CQRS in Symfony 8: a separate model for writing and for reading, a command bus and a query bus in Messenger, read models, and eventual consistency. Plus the cases where CQRS does not pay off.

Author M. Katuščák
Reading time ≈ 40 min
Difficulty advanced
Published · Updated ·
In this chapter

12.01 What is CQRS?#

CQRS starts from a plain observation: the model that serves for writing data does not have to be the same model that serves for reading it. CQRS (Command Query Responsibility Segregation) carries the separation of reads and writes from a single method over to the whole model. Greg Young described it [1]. Its roots go back to Bertrand Meyer's Command-Query Separation (CQS) [2]. In CQRS Documents, Young adds that in the first years people talked about the pattern as an extension of CQS at a higher level, and he himself calls that formulation inaccurate. After years of the two terms being confused, CQRS settled as a pattern in its own right, not as a variant of the older rule.

A traditional application uses one entity for both (typically a Doctrine ORM entity): it creates an order and also shows it in a list through the same Order object. CQRS splits this responsibility into two models, each with its own job and its own optimization profile.

CQRS is often combined with Event Sourcing, which stores the history of changes as a sequence of events instead of the current state. The two patterns are independent, though. A full CQRS implementation can stand on classic Doctrine ORM persistence on the write side and denormalized tables on the read side, without Event Sourcing.

12.02 CQS vs. CQRS – where is the line?#

Bertrand Meyer formulated Command-Query Separation (CQS) as a rule at the method level: every method either changes state (a command) or returns a value (a query), never both. CQS is a design rule for class interfaces.

Greg Young moved the same idea from the method to the model: CQRS splits one domain model into two, each with its own set of classes and its own optimization profile. A separate store is optional (see Three myths about CQRS). Young stresses that CQRS is not an architecture but an architectural pattern. It describes something inside a single system or component, not the arrangement of the whole application [5].

CQS is the natural starting point for CQRS. Teams that follow CQS at the method level soon find that the methods changing state need markedly different data than the methods reading it. CQRS draws the conclusion: two separate models.

12.03 Benefits of CQRS#

The benefits show mainly in applications with non-trivial domain logic and different requirements for reading and writing.

The first is separation of responsibilities. The write model carries the domain logic, invariants, and data consistency; the read side is left with a single job – to deliver data in the shape the screen needs. Each model contains only what it needs for its work and is optimized independently. The write side has a normalized relational schema and Doctrine ORM entities with domain logic; the read side has a denormalized table, an Elasticsearch index, or a Redis cache – whatever suits the specific queries best. The same separation gives freedom to evolve. A read model can be rebuilt at any time (a projection rebuild), another one can be added for a new use case, or the query structure can change, all without touching the write model.

Two more benefits:

  • Scalability – Young notes that in systems, and especially on the web, the query side routinely serves two or more orders of magnitude more operations than the write side [1]. CQRS lets you scale the read side independently (replicas, caches, CDN) with no impact on the write side.
  • Testability – Command handlers are tested as domain logic (given state → when command → then events/state); query handlers only need the returned data checked for correctness. The two responsibilities do not get tangled in one test suite. See the chapter Testing DDD.

12.04 Challenges and limitations of CQRS#

Instead of one model there are two or more. Every command and every query needs its own class, a handler, and often its own data structure: where CRUD would get by with one class, several appear. Separate stores add synchronization: the read model has to be updated after every change to the write model. A failure in propagation (a queue outage, a projector bug) lets the models drift apart.

Eventual consistency belongs here too. Between the write and the read model update there is a window in which the user who has just submitted a form sees the “old” version of the data. UI patterns for it are described in the Eventual consistency in practice section.

The last cost is onboarding the team. Developers used to one model for all operations have to think differently and understand concepts such as the message bus, eventual consistency, handler idempotence, and read model projection.

Technical criteria are not the only axis of the decision. Udi Dahan, who helped popularize the pattern, builds on how collaborative the domain is: CQRS pays off where several actors change the same data according to rules that depend on context [6]. A shopping cart is not one of those domains, because nobody edits someone else's cart, so according to Dahan it is not a candidate for CQRS. Martin Fowler urges the same caution: the pattern is decided per Bounded Context, not for the whole system [7].

12.05 Symfony Messenger as the foundation of CQRS#

A message bus is not a prerequisite for CQRS. Separate command and query classes called directly from the controller are a full level 1, and a small application needs nothing more. A bus pays off once shared infrastructure starts to accumulate around processing: transactions, validation, logging, deferred execution. In Symfony, Messenger fills this role. The specialized PHP libraries from 2014–2018 have meanwhile ended (broadway/broadway is archived) or have not had a commit in years (prooph/service-bus, SimpleBus). The choice has narrowed to Messenger or your own thin layer over the container.

What matters about Messenger for CQRS is the ability to define several message buses: for commands, for queries, and for domain events. Each bus has its own middleware set and its own processing strategy. The Symfony documentation adds a condition worth taking seriously: one bus is a good default, and another one is added when it needs a different middleware stack, not because some pattern recommends it [8]. The configuration below meets the condition – the command bus wraps the handler in a transaction, the query bus does not.

FIG. 12.5-A Symfony Messenger as a CQRS bus

The configuration defines three transports: async_commands and async_events for processing through a queue, and sync for immediate execution in the same process. There are also three buses. command.bus for commands has the doctrine_transaction middleware, an automatic transaction around the handler. query.bus has only validation. The doctrine:// transport (for example MESSENGER_TRANSPORT_DSN=doctrine://default) comes from the symfony/doctrine-messenger package; without it, Messenger reports “No transport supports Messenger DSN”. For AMQP, the equivalent is symfony/amqp-messenger.

event.bus serves domain events and differs in one essential point: a command without a handler is an error, an event without a listener is a normal state. Hence allow_no_handlers: true; without it, Messenger throws NoHandlerForMessageException for every event nobody subscribes to yet.

Once you have more than one bus, a plain type hint on MessageBusInterface and a bare #[AsMessageHandler] are no longer enough. The type hint gets the default_bus, and the handler is registered on all buses. Both are solved explicitly:

php snippet.php
1final readonly class OrderPlacedProjectorRegistration2{3    // Injecting a specific bus4    public function __construct(5        #[Target('event.bus')]6        private MessageBusInterface $eventBus,7    ) {}8}9 10// A handler that belongs to one bus11#[AsMessageHandler(bus: 'event.bus')]12final readonly class OrderPlacedProjector { /* … */ }

The Outbox shows why this matters. A relay that sends a domain event to command.bus runs into a missing handler and exhausts its retries. The event never reaches the listeners: without a failure_transport, Messenger discards it; with one, it ends up in the dead letter queue from 12.14 and waits for manual intervention. That is exactly what the Outbox is meant to prevent. debug:autowiring MessageBus lists the available aliases.

12.06 Implementing commands#

In Symfony 8, a command is a plain PHP class: an immutable data object (DTO) that carries all the data needed to perform an operation. It contains no domain logic; it only transports data.

A well-designed command:

  • is immutable (readonly properties) and does not change after it is created;
  • carries validation attributes, so the validation middleware on the command bus checks it before it reaches the handler;
  • expresses intent through its name – RegisterUser, PlaceOrder, CancelSubscription, not SaveUser or UpdateOrder;
  • works with primitive types (string, int, float) or serializable value objects (OrderId, Money), because it has to pass safely through an asynchronous channel.

The intent does not come from nowhere. In Young's work, CQRS is preceded by a task-based UI, an interface made up of tasks (“Change delivery address,” “Cancel order”), not a form over an entity with a Save button. A form mapped to an entity produces a single UpdateOrder command, and the information about what the user actually wanted is lost before it ever enters the domain. The tasks in the UI usually correspond to the domain events the team found during Event Storming.

Validation attributes on the command and domain rules in the handler deal with two different things. Dahan separates validation, which does not depend on context (is the email an email, does the password have enough characters), from business rules, which do (someone already used this email, the customer has used up the daily limit). A formally valid command can therefore fail in the domain, because the conditions changed in the meantime. The validation middleware does not replace the domain check; it only filters out messages that are already formally wrong.

12.07 Implementing queries#

A query differs from a command in the direction of the data flow: it does not change the state of the system, it only reads. The implementation is similar, an immutable DTO. The difference is that a query always returns a value, which the handler passes through HandledStamp.

The query carries a single field: the ID of the user whose profile should be loaded. An invalid UUID is rejected by the validation middleware before processing.

12.08 Implementing handlers#

The handler is where the message meets the logic. In Symfony 8 it is a class with the AsMessageHandler attribute and an __invoke() method; Messenger pairs it with the message by the parameter's type hint.

A command handler and a query handler have different responsibilities:

  • Command handler – Loads the aggregate from the repository, calls a domain method on it (which guards the invariants), and saves the changes. It can emit domain events. It works with the domain model (entities, value objects, repositories).
  • Query handler – Reads data from an optimized source (a denormalized table, Elasticsearch, a cache) and returns it as a ViewModel. It deliberately bypasses the domain model, because that model is not optimized for reading.

The difference shows directly in the dependencies. The command handler works with the domain model (UserRepository, the User entity, value objects). The query handler reaches into a read repository (UserProfileReadRepository), which returns a ViewModel directly – a simple data structure for presentation – and never passes through the domain model.

The read repository interface belongs to the read side, not to the domain, and it is deliberately narrow:

php src/UserManagement/Profile/ReadModel/UserProfileReadRepository.php
1<?php2 3declare(strict_types=1);4 5namespace App\UserManagement\Profile\ReadModel;6 7use App\UserManagement\Profile\ViewModel\UserProfileViewModel;8 9interface UserProfileReadRepository10{11    public function findById(string $userId): ?UserProfileViewModel;12}

12.09 ViewModels and read models#

A ViewModel (or read model) is a data structure designed for a specific query or screen. It contains no domain logic; it is purely presentational. The User domain entity protects invariants and encapsulates behavior; UserProfileViewModel carries exactly the data that the template or API endpoint needs.

A ViewModel often contains data from several aggregates – the example above combines user details with the number of orders and the membership tier. Through the domain model, the same view would mean loading the user and their orders and calculating the tier, which is slow and breaks the boundaries of aggregates. The read model has this data ready in denormalized form.

12.10 Implementing the command and query buses#

What remains is getting commands and queries to the right handler. Besides the #[Target] attribute from 12.05, Symfony 8 also supports named autowiring: a constructor parameter named after a bus from messenger.yaml ($commandBus for command.bus) receives exactly that bus:

The profile renders a ViewModel, not the aggregate, so the template computes nothing:

twig src/UserManagement/Profile/View/profile.html.twig
1{% extends 'base.html.twig' %}2 3{% block body %}4    <h1>{{ profile.name }}</h1>5    <dl>6        <dt>Email</dt>        <dd>{{ profile.email }}</dd>7        <dt>Registered</dt>   <dd>{{ profile.registeredAt|date('j. n. Y') }}</dd>8        <dt>Orders</dt>       <dd>{{ profile.totalOrders }}</dd>9        <dt>Tier</dt>         <dd>{{ profile.membershipTier }}</dd>10    </dl>11{% endblock %}

The registration template is an ordinary Twig form; form_row also renders the errors that the controller put into the fields from the command validation:

twig src/UserManagement/Registration/View/registration.html.twig
1{% extends 'base.html.twig' %}2 3{% block body %}4    {# Without this block, the user never learns about the email collision: the controller5       reports it as a flash, not as a field error. #}6    {% for message in app.flashes('error') %}7        <p class="error">{{ message }}</p>8    {% endfor %}9 10    {{ form_start(form) }}11        {# form_errors prints the errors on the form root, typically CSRF. #}12        {{ form_errors(form) }}13        {{ form_row(form.name) }}14        {{ form_row(form.email) }}15        {{ form_row(form.password) }}16        <button type="submit">Register</button>17    {{ form_end(form) }}18{% endblock %}

A vertical slice needs two more things next to the controller. The templates live with the feature, not in the central templates/, so Twig has to know their directory under a name. And the form is an ordinary FormType next to them:

yaml config/packages/twig.yaml (addition to the recipe)
1# Only the `paths` key is added to the file from the symfony/twig-bundle recipe.2# The rest (default_path, file_name_pattern…) stays as the recipe created it.3twig:4    paths:5        # Without this line, Twig reports “There are no registered paths6        # for namespace UserManagement” and the template next to the feature is not found.7        '%kernel.project_dir%/src/UserManagement': UserManagement
php src/UserManagement/Registration/Form/RegistrationFormType.php
1<?php2 3declare(strict_types=1);4 5namespace App\UserManagement\Registration\Form;6 7use Symfony\Component\Form\AbstractType;8use Symfony\Component\Form\Extension\Core\Type\EmailType;9use Symfony\Component\Form\Extension\Core\Type\PasswordType;10use Symfony\Component\Form\Extension\Core\Type\TextType;11use Symfony\Component\Form\FormBuilderInterface;12use Symfony\Component\OptionsResolver\OptionsResolver;13use Symfony\Component\Validator\Constraints\NotBlank;14 15final class RegistrationFormType extends AbstractType16{17    public function buildForm(FormBuilderInterface $builder, array $options): void18    {19        // NotBlank here does not duplicate the command's rule. Without data_class,20        // the form does not take over the command's constraints, and an empty field arrives21        // in the constructor as null – a 500 before validation even runs.22        $builder23            ->add('name', TextType::class, [24                'label' => 'Name',25                'constraints' => [new NotBlank()],26            ])27            ->add('email', EmailType::class, [28                'label' => 'Email',29                'constraints' => [new NotBlank()],30            ])31            ->add('password', PasswordType::class, [32                'label' => 'Password',33                'constraints' => [new NotBlank()],34            ]);35    }36 37    public function configureOptions(OptionsResolver $resolver): void38    {39        // Without data_class the form returns an array, and that is intended here: the command40        // has promoted readonly properties that PropertyAccess41        // cannot write to (“is a promoted readonly property”). The controller42        // builds the command from the array itself.43        $resolver->setDefaults(['data_class' => null]);44    }45}

So both controllers get their bus by the parameter name: $commandBus points to command.bus, $queryBus to query.bus.

12.11 Optimizing read models#

The read side has a free hand in choosing its structure. The write model keeps normalization for data consistency; the read model can go the opposite way and denormalize data into exactly the shape the screen or API endpoint expects.

Before any strategy is chosen, one operational detail decides things: denormalized tables are not ORM entities. Doctrine does not know about them, so doctrine:schema:update proposes dropping them, and doctrine:schema:validate reports a schema mismatch. They are created by a migration, and a filter excludes them from schema comparison:

yaml config/packages/doctrine.yaml (excerpt: read model)
1doctrine:2    dbal:3        # Read model tables are managed by migrations, not by the ORM. Every new4        # projection has to be added to the list, otherwise Doctrine5        # proposes dropping it on the next diff.6        schema_filter: '~^(?!order_dashboard|reporting_orders)~'

The block belongs in the same doctrine.yaml that already holds mappings, naming_strategy, and the custom types from the chapter on aggregates; the url from the recipe stays. The book assembles the Doctrine configuration step by step, but in a project it is one file.

Read model optimization strategies

Denormalized tables as a read model

The most widespread strategy in practice is a denormalized table with data precomputed for a single screen or endpoint. It is updated through domain events, either synchronously in the same transaction as the aggregate or asynchronously through a queue. It is created by a migration, not through schema:update – Doctrine does not know about it, and without the schema_filter above it would propose dropping it:

php migrations/Version20260906090000.php
1<?php2 3declare(strict_types=1);4 5namespace DoctrineMigrations;6 7use Doctrine\DBAL\Schema\Schema;8use Doctrine\Migrations\AbstractMigration;9 10final class Version20260906090000 extends AbstractMigration11{12    public function getDescription(): string13    {14        return 'Read model: order_dashboard';15    }16 17    public function up(Schema $schema): void18    {19        // DDL for PostgreSQL. The read model is not an entity, so20        // `migrations:diff` does not generate it – this migration is written by hand,21        // and for another platform it is rewritten by hand too: MySQL wants22        // CHAR(36) instead of UUID, DATETIME(6) instead of TIMESTAMP(6), and the upsert23        // in the projector below writes through ON DUPLICATE KEY UPDATE.24        $this->addSql(<<<'SQL'25            CREATE TABLE order_dashboard (26                order_id        UUID          NOT NULL,27                customer_id     UUID          NOT NULL,28                total_amount    INT           NOT NULL,29                status          VARCHAR(32)   NOT NULL,30                shipment_id     UUID          DEFAULT NULL,31                placed_at       TIMESTAMP(0)  NOT NULL,32                -- Microseconds are not cosmetic: the protection against a late event33                -- rests on comparing updated_at, and two events34                -- of one aggregate routinely fall into the same second.35                updated_at      TIMESTAMP(6)  NOT NULL,36                -- ON CONFLICT (order_id) in the projector relies on exactly this key.37                PRIMARY KEY (order_id)38            )39        SQL);40 41        // The dashboard sorts by date and filters by status.42        $this->addSql('CREATE INDEX idx_dashboard_status_placed43            ON order_dashboard (status, placed_at)');44    }45 46    public function down(Schema $schema): void47    {48        $this->addSql('DROP TABLE order_dashboard');49    }50}

The status column carries the screen's vocabulary, not the values of the OrderStatus enum. An order that the aggregate holds in the Confirmed state is shown on the dashboard as placed. A read model may have its own labels, because nobody uses it to decide on state transitions.

Who dispatches the domain events

The projector above assumes that someone delivers the OrderShipped or OrderCancelled events to it. In the simplest form, the application layer pulls them from the aggregate after flush() with releaseEvents() and sends them to the event bus; the mechanism is described in the section Aggregates and domain events: the lifecycle. A synchronous projection under the doctrine_transaction middleware is a fully valid choice. The projector runs inside the same transaction, and when the commit fails, its write is rolled back too.

The weak spot appears only with asynchronous routing, because sending to a queue is not atomic with the write. Under the doctrine_transaction middleware, the message leaves before the commit. When the commit fails, the projection receives an event that never happened. Without the middleware, with dispatch after the commit, the opposite risk appears: a process crash between the commit and the dispatch loses the event. In both cases the projection silently drifts apart from the write model. For asynchronous projections, the production solution therefore stores events in an outbox table in the same transaction as the aggregate, and a separate relay process publishes them to the queue – in detail in the chapter Outbox Pattern.

Rebuilding projections

Projections allow a complete rebuild of the read model. When the structure of a denormalized table changes (a new column, a different data format), the steps are:

  1. Create a new version of the projection table.
  2. Replay all relevant events through the projector.
  3. Switch the read queries to the new table.
  4. Delete the old table.

A rebuild works only while the source events are still available (in an Event Store or in a message log). Without Event Sourcing a rebuild is possible, but it needs another data source (for example, change data capture from the write database).

12.12 Eventual consistency in practice#

Eventual consistency is the most common source of uncertainty when adopting CQRS. With asynchronous propagation of changes from the write side to the read side, there is a time window (typically milliseconds to a few seconds) in which the read model does not yet reflect the latest write. The user submits a form and gets a success confirmation, but the list on the next page does not show the new record yet.

This window is a property of asynchronous propagation, not a bug. The diagram captures the data flow from the write, through asynchronous propagation, to the read, and highlights the window in which eventual consistency shows:

FIG. 12.12-A Eventual consistency in the CQRS flow

The sequence below shows over time when the user gets a 404 even though the command succeeded:

FIG. 12.12-B The staleness window – when a GET returns 404 after a successful POST

UI strategies

Read-your-writes at the HTTP level

The strategies in the table deal with what the user sees in the browser. API clients need a harder guarantee: “read what you just wrote” (read-your-writes). It is achieved by passing the write position: the response to the command carries the aggregate version number or the offset the projection has to reach, and the client sends the value with the next query, typically in a header.

The read endpoint compares the projection's current position with the requested one. When the projection lags behind, it waits briefly (tens to hundreds of milliseconds) and repeats the comparison. After the limit expires, it returns a retry signal to the client – 202 Accepted with a Retry-After header – and the client loads the data again after the stated pause. Status code 304 does not fit here: it means “your cache is valid,” not “the data is not there yet.”

The pattern pays off only on paths where the client reads the same data right after the write. Applied across the board, it would burden the read side with waiting that most queries do not need.

12.13 Asynchronous processing#

Asynchronous processing follows naturally from a separate command side. In Symfony 8 it is configured through Messenger transports. A message routed to an asynchronous transport is serialized on dispatch and placed in a queue, from which a worker later picks it up and passes it to the handler.

The configuration gives the async_events transport a retry strategy: three retries with exponential backoff. The jitter key adds a random spread to the computed delay and distributes retries over time; without it, all messages come back at once after an outage. The whole strategy can be replaced with your own implementation of RetryStrategyInterface through the service key. For critical events, a separate async_priority_high transport with its own queue is added – its worker can run with a higher priority or on a separate server.

Reliable handoff of domain events to the queue, atomic with the aggregate write, is provided by the Outbox Pattern.

A message can also carry its transport itself: the #[AsMessage(transport: 'async_events')] attribute on a command or event class replaces the corresponding line in the routing: section. It is a matter of habit: YAML keeps routing in one place, the attribute keeps it with the message.

12.14 Error handling and the dead letter queue#

In an asynchronous environment, errors are handled differently than in a synchronous one. With a synchronous dispatch, the exception bubbles straight up to the controller, and the user sees an error message. With an asynchronous one, the message waits in a queue; when the handler fails, the user does not know, and the message has to be processed again.

Retry strategy

Messenger can retry failed messages automatically. The retry_strategy configuration on the transport determines how many times and with what delay the handler is called again (values from the configuration in 12.13):

  • max_retries: 3 – The maximum number of retries.
  • delay: 1000 – The delay of the first retry (in ms).
  • multiplier: 2 – Exponential backoff: 1s → 2s → 4s.
  • max_delay: 60000 – The maximum delay (60 seconds).
  • jitter: 0.2 – Random spread of the delay, a value from 0 to 1 (default 0.1).

Failed transport (dead letter queue)

When all attempts fail, Messenger moves the message to the failed transport (the dead letter queue). There it waits for manual intervention: a developer examines it, fixes the cause of the error, and sends it again.

The failure_transport key works globally as well as on an individual transport. Projections can therefore have their own dead letter queue, separate from emails and reports, which makes both monitoring and bulk replay after a projector fix easier.

12.15 Middleware in CQRS#

Middleware in Symfony Messenger forms a chain around the handler and intercepts the message before and after processing. This is how validation, logging, transactions, or authorization enter the dispatch cycle without the handler changing.

You already know the built-in validation and doctrine_transaction middleware from the configuration in 12.05. For other needs, you can write your own:

The order of middleware matters. Logging goes first, so it also captures validation errors. Validation follows, rejecting an invalid command before a transaction starts, and finally doctrine_transaction wraps the handler in a database transaction.

12.16 Testing CQRS#

Command handlers, query handlers, and projectors are isolated components with clearly defined inputs and outputs, so they test well. The strategy differs by component.

Testing command handlers

A command handler is often tested as a unit test with an in-memory fake repository (Testing DDD). RegisterUserHandler is an exception: email uniqueness is enforced by a database index, not by a condition in code. Neither a fake nor a mock repository has an index, so the test would pass even over a handler that lets duplicates through. That is why it runs against a real database:

Testing query handlers

For a query handler, the test checks the mapping of data from the read repository onto the ViewModel. An integration test with a real database also exercises the SQL queries themselves:

Testing projectors

Projectors are best tested as integration tests with a real database. The test checks that after a sequence of events has been processed, the read model contains the expected data:

Testing aggregates, value objects, and domain services is covered in the chapter Testing DDD.

12.17 Sagas and the Process Manager#

CQRS across several Bounded Contexts sooner or later needs to coordinate long-running processes across contexts. A saga listens to domain events and sends commands based on them. In this way it connects the command side and the event side of CQRS into coherent domain processes. In its orchestrated form it is driven by a Process Manager, a component with its own state that decides on the next step.

Sagas, including their implementation in Symfony Messenger, compensation strategies, and testing, are covered in the chapter Sagas and Process Managers.

Frequently asked questions

What is CQRS?

CQRS (Command Query Responsibility Segregation) is an architectural pattern that splits the model of a system or Bounded Context into two separate models: a write model for state changes and a read model for queries. The write model focuses on domain logic and validating invariants; the read model serves fast presentation of data to the user. Each model can be optimized and scaled independently. Greg Young described it; its roots go back to the older CQS rule of Bertrand Meyer, but Young himself calls the formulation “CQRS is an extension of CQS” inaccurate and speaks of a pattern in its own right. See the introductory section.

What is the difference between CQS and CQRS?

CQS (Command Query Separation) is a design rule at the method level: every method should either change state or return a value, not both. CQRS (Command Query Responsibility Segregation) moves the same idea from the method to the model: instead of one domain model, there are two separate ones, each with its own classes and optimization profile, and optionally its own store. So CQS is a principle inside a class, while CQRS is a decision about the shape of the model inside a system. More in the CQS vs. CQRS – where is the line? section.

When is CQRS worth adopting?

CQRS pays off in applications where the requirements for writing and reading differ markedly – for example, a domain-rich write model with many invariants against heavily dominant queries that need denormalized data. It also helps where reading has an independent scaling profile (replicas, caches, full-text search) or where a separate audit of changes matters. For simple CRUD operations, it increases the number of classes without a matching benefit. A detailed analysis is in Benefits of CQRS and Challenges and limitations of CQRS.

Do I have to use Event Sourcing when I use CQRS?

No. CQRS and Event Sourcing are independent patterns that are often combined, but each can be introduced on its own. CQRS can be fully implemented with classic Doctrine ORM persistence on the write side and denormalized SQL tables on the read side. Conversely, Event Sourcing can be introduced without CQRS – although combining the two is common in practice, because they benefit each other. The relationship between the two patterns is discussed in the What is CQRS? section.

Does CQRS need a queue or a second database?

No. A message bus, an asynchronous transport, and a separate store are choices, not part of the pattern. Greg Young describes the read side as a thin layer over the same database that projects rows straight into DTOs; the Azure Architecture Center states that messaging is not a prerequisite for CQRS. Most applications therefore do fine with the simplest form: separate command and query handlers over one database. See Three myths about CQRS.

How is CQRS implemented in Symfony?

The basic building block is the Symfony Messenger component, which works as a bus for commands and queries. For CQRS, two to three separate buses are usually defined (command.bus, query.bus, and event.bus for domain events), each with its own set of handler classes and middleware. The Symfony documentation recommends adding another bus only when it needs a different middleware stack. Commands change state and return no data, at most the identifier of a new record; queries return ViewModels (read models) and do not change state. Asynchronous processing is turned on through a transport and takes long operations out of the request-response cycle. More in the Symfony Messenger as the foundation of CQRS section.