New version!

A new version of this website is available at architectural-patterns.net.

This architecture is only useful if your application process huge amounts of data. Further, the views that present the data to the user are complex and cannot be generated real-time.

In this architecture reading and writing information is separated into two separate models.

Examples

  • Banking. Bank account transactions are stored in one store. Bank account views are stored in a different model and updated infrequently (once a day).

Where does it come from?

CQRS was created by Greg Young.

When should you use it?

  • When your data needs to be available real-time to a user and it cannot be constructed real-time by a conventional database.
  • When your system needs multiple views on the same data, in such a way that a single data model is ineffective.

    How does it work?

    A CQRS system separates a Command Model from a Query Model. Whenever the system executes an action, an Action object is created and this is stored in the command model. A signal is then sent to the Query Model and all models that depend on this command are updated, asynchronously.

    Data entering the system is written only to the Command Model. When an application needs to show data, it is read from the Query model.

    The Query Models are "throw away" and may be recreated from the Command Model. However, it may take (considerable) time to recreate the Query Models.

    Problems

  • Since the Query Model is updated asynchronously, it may not represent the current state of the data. When this data is used errors occur that need to be solved later (perhaps manually).

    Common implementation techniques

    • CQRS is normally used in conjection with Event sourcing to store its Commands.
    • In theory it is possible to use CQRS with just a plain database that only stores the current state as a Command Model, but this is not much different from plain caching.

    Links

  •