Search code examples
cqrsakka-persistence

How to send response to a Command in CQRS?


I'm implementing a CQRS system with Akka persistence and I'm trying to understand the request response bit of CQRS.

There are few answers on SO on how to send response back to client and this article also mentions a few good patterns. But instead of generalising using big words can someone please explain how should I send response back to the client in CQRS for the following simple use case.

Use case

Suppose the user is on a page which displays users profile which displays the following information

  1. Username
  2. Address
  3. Phone number

And In my system I have one Actor per User which stores that user's profile information.

On the UI user wants to update the address and the following things happen:

  1. User makes an AJAX REST call to update address of user
  2. UpdateUserAddressCommand(address:String) generated
  3. UpdateUserAddressEvent(address:String) generated
  4. UserAddressUpdatedEvent(updatedAddress:String) generated (state of the UserActor updated)

Now how do I send back the full state of UserProfile in the system ? Since CQRS discourages sending response for a Command ?


Solution

  • With respect to the CQRS pattern, the REST layer can be considered a client of the system using CQRS, and therefore you may send a response (from the REST server to the web browser) without violating a "principle".

    In your case, it's quite simple:

    1. REST call to /api/endpoint/1234 -> REST server generates the command as above.
    2. Server returns code "202 Accepted" and sets the Location: header to something like /api/user/profile/1234
    3. Client queries /api/user/profile/1234 to query the full state of the UserProfile.

    You can combine 3. with HTTP long polling if you are using asynchronous query side updates/eventual consistency.