10

I am designing a backend using CQRS + Event sourcing, using Akka + Scala. I am not sure about how to handle a growing state. For instance, I will have a growing list of users. To my understanding, each user will be created following a UserCreated event, such events will be replayed by the PersistentActor, and the users will be stored in a collection. Something like:

class UsersActor extends PersistentActor {

    override def persistenceId = ....

    private case class UsersState(users: List[User])

    private var state = UsersState()

    ....
}

Obviously such state would eventually grow too big to be held in memory by this actor, so I guess I'm doing something wrong.

I found this example project: the idea seems that each user should be held by a different actor, and loaded (from the event history) as needed.

What is the right way to do this? Thanks a lot.

ticofab
  • 7,551
  • 13
  • 49
  • 90
  • Event sourcing isn't appropriate for all parts of the application.. do you need the list of all users in order to query it to let users log in or out? – jazmit Oct 30 '15 at 16:12
  • Thanks for your comment @jazmit - no, I don't need to have all users "present" at once. I am studying the project I linked, it seems to only "inflate" the item it needs in order to serve or update it. Do you have further hints? – ticofab Oct 30 '15 at 16:15
  • Yes, but the seed project uses one persistent actor per user.. still not sure what exactly you're after, the only thing I can think to say is not to design domain actors with ever-growing state.. – jazmit Oct 30 '15 at 16:23

1 Answers1

2

The answer is: each aggregate/entity (in my example, each User) gets its own actor, which embeds the state for that particular entity and that one only.

ticofab
  • 7,551
  • 13
  • 49
  • 90
  • +1. Not the place for discussion, but do you modify behavior depending on state of `PersistentActor`? I.e. if event called `UserCreated` gets persisted, do you modify behavior so that only i.e. `UserRemoved` and `UserUpdated` events can be persisted? Or i.e. if `UserRemoved` event gets persisted that none of other events cannot be persisted anymore for an actor with that specific persistence id. – Branislav Lazic Feb 12 '16 at 21:35
  • 1
    Indeed, that's what I'm doing: modify behavior according to state. – ticofab Feb 12 '16 at 21:40
  • Candy for you. Thanks for a quick answer. :) – Branislav Lazic Feb 12 '16 at 21:41
  • 1
    Solution seems reasonable, but how do you obtain i.e. all `User` actors? – Branislav Lazic Feb 17 '16 at 07:34
  • @BranislavLazic - see [this question](https://stackoverflow.com/questions/43375781/how-to-fetch-all-persisted-entities) – vaan Jul 17 '20 at 11:43