akkaakka-persistenceakka-actor

Keep an Entity as State or Child Actor in Akka


Consider the use case of an online shopping, where I have an inventory and items. I see couple options to model this using Akka actors.

  1. Create a persistent actor called Inventory, keeping the items in its state inside a list, for example.

  2. Create a actor called Inventory and then a child persistent actor for each item. Each item keeping its own state.

The question is - Does the second option make sense? When should I keep an entity as state of an actor or model it as an child actor? What should we take in consideration in this case?


Solution

  • This might be subjective, I would prefer option two.

    When should I keep an entity as state of an actor or model it as a child actor?

    In my personal experience, when you have hierarchical state and 2nd level state requires individual operations, it makes sense to create child actor for each 2nd level entity. For example:

    case class Employee(Id, Name, Address)
    

    In this case if there is only top level actor for all employees, it will have to have a state probably like:

    Map[Id, Employee]
    

    And if the messages are as follows: AddEmployee(Employee), DeleteEmployee(Id) then it's not a big deal. But if they are like: UpdateName(Id, Name) or UpdateAddress(Id, Address) then it becomes cumbersome to manage these operation on that Map.