Tomas Jablonskis
Tomas Jablonskis

Reputation: 4376

CQS: Who is responsible for data caching and when?

When and who should be responsible for caching data into local data store from API GET requests in DDD architecture with CQS based use cases?


First thing that comes to mind:

Initiate a Query to get some data from local data store and if it is empty, fetch required data from API -> cache it into local data store -> return it

This solution does not seem to follow CQS correctly because Queries should not alter data store (or can they?).


Second thing that comes to mind:

Execute a Command to fetch fresh data from API -> update data store -> raise a data updated event -> event handler listens for data updated events and executes new Query to get fresh data


Second solution seems to follow CQS pattern better, tho I am not sure if any of these solutions are by any means correct way of handling data caching in CQS based architecture.

Upvotes: 0

Views: 602

Answers (1)

Levi Ramsey
Levi Ramsey

Reputation: 20541

The first option isn't, to my mind, any "bigger" of a violation of CQS/CQRS as the second. The query isn't altering authoritative state (e.g. a DDD aggregate), it's just copying it into a cache. It does require cache invalidation.

The second is questionable because a query results in a command (it's sometimes reasonable to treat a query as a read-only command (provided the query limits itself to a single aggregate) in order to have a stronger consistency guarantee).

A better approach to my mind is to have a hybrid of the two:

  • Queries are served from the cache if possible
  • When commands result in updates to aggregates, events are published (ideally listing the aggregates which changed)
  • Event handler listens for update events and invalidates cache based on which aggregates have changed.

A further evolution of this would be event sourcing, where the updates are the events and the queries only get served by a read model fed by the events.

Upvotes: 2

Related Questions