Event-sourcing with akka-persistance: growing state as list?
Asked Answered
W

1

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.

Willtrude answered 30/10, 2015 at 8:36 Comment(3)
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?Arrant
Thanks for your comment @Arrant - 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?Willtrude
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..Arrant
W
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.

Willtrude answered 4/12, 2015 at 10:24 Comment(4)
+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.Farny
Indeed, that's what I'm doing: modify behavior according to state.Willtrude
Solution seems reasonable, but how do you obtain i.e. all User actors?Farny
@BranislavLazic - see this questionArcturus

© 2022 - 2024 — McMap. All rights reserved.