CQRS Design Pattern

  • CQRS stands for command query responsibility segregation.
  • The service to view data is separate and it doesn’t handles create, update and delete operations. This service has its own database.
  • For example we have a service to publish and subscribe requests events then we have a service for creating and updating and deleting request. For generating a report of these requests we will have a separate report service of this request.
  • When we segregate create, update and delete from view CQRS comes into picture.
  • Command stands for Create, update, delete database and query stands for viewing database only.
  • Data in report service is handled by events for example we may have a event to publish and subscribe requests from pubsub service and we may have a create/update event from request service.
  • Data in Report service can also be handled by database triggers and procedures.
  • We can replicate data in our report service using DB triggers and procedures or by events.
  • This has some limitations as follows
    • There may be replication delay in the system.
    • There may be extra complexity.
    • There is code duplication.
  • Benefits of this are as follows
    • Responsibility segregation which is the core principle of micro services distributed systems.
    • Simpler command and Query models
    • Flexibility to choose database and view.
    • Easy to scale.
  • In CQRS we have a command API and Query API. 
    • In command API we have
      • Command
      • Command Handler
      • Events Handler
      • We use a Write DB and Event Store
      • A basic flow of Command API can be
        • API interacts with Controller
        • Controller sends commands to Command Gateway
        • Command Gateway handles the command using a Command Handler/Aggregate and creates an event.
        • The event is published in the Event Store.
        • Then an Events handler listens to the events in the Event Store.
        • The Events is processed using a Repository by Events Handler and DB is updated to the next stable state. 
    • In Query API we have
      • Query
      • Query Handler
      • Events Handler
      • We use a Read DB
      • A basic flow of Query API can be
        • API interacts with Controller
        • Controller sends commands to Query Gateway
        • Query Gateway handles the command using a Query Handler/Projection and creates an event.
        • We will have an event handler to handler events or we can directly send data from Projections as well.
    • We use events to communicate or transfer data between Command API and Query API
    • Events are stored in Events Store

No comments:

Post a Comment

Recursion

Q What do you understand by a Recursive  Programme? Recursion Is the process of repeating items in a self similar way. In programming langua...