Search code examples
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.

    • It allows me to narrow down my thinking to one small problem when I am in that child actor and I don't have think about the bigger picture while doing that.
    • Breaking down in this way also help test item logic in isolation in addition to any larger tests
    • Child actor can be killed and re-spawned without affecting the entire state of all other items
    • Actors are cheap and millions can be created on typical hardware
    • Distributed Data: In a more advanced used case, it can help you scale over different nodes. For example, you can have an akka cluster where each cluster node is responsible for a subset of entities (aka sharding)

    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.