Olivier Liechti
Olivier Liechti

Reputation: 3188

Design pattern: how to implement a chain of actors processing a single logical message

I am starting to look at Akka and I am wondering about the proper way to implement a pipeline of actors, collaborating to process a message. Let me take a use case to illustrate my question:

  1. I have a message that represents a "decision" that has to be made by the collaborating actors.

  2. I want to be able to create several "voters"; every voter will express his opinion on the decision to be made (based on its own strategy and rules).

  3. I could implement different strategies to aggregate the opinions of the different agents, but let's imagine that I want to take a POSITIVE decision if and only if ALL of the agents in the chain make a positive decision.

How would I implement that in akka? Would I implement a first actor that represents the entire chain and that receives the DECISION message? Would this actor have a many children as there are voters in the chain? How would the father interact with the children and who would control the flow of events? Would it be the same DECISION message flowing from one voter to the next? Or would there be a series of interaction between the parent and one child?

What are the recommended patterns for this type of use cases?

Many thanks for your feedback!

Olivier

Upvotes: 4

Views: 921

Answers (1)

Diego Martinoia
Diego Martinoia

Reputation: 4652

You have probably already answered yourself, but this is what I'd do:

trait DecisionActor extends Actor

class AbsoluteAgreementActor extends DecisionActor {
  val numberOfVoters = 100
  def receive = {
    case d:Decision = {
      computeDecision(d) pipeTo sender
    }
  }

  def computeDecision(d) = {
    val votes = for {
      i <- 0 until numberOfVoters
      //Naming it for re-usual in case you don't delete it
      voter = context.actorOf(Props[VoterActor], s"Voter $i")           
    } yield {
      voter ? d
    }
    Future.sequence(votes).foldLeft(True)(&&)
  }
}

Then in your main you just ask the decision to the desired strategy actor. I voluntarily omitted cancellation of voter/strategy actors because you may not want to delete them in case you re-need them. Or you could avoid creating them and fetching them from a pool common to all the strategies. It depends on our scenario. You can then create various decision actors with different strategies, extending the DecisionActor trait.

Upvotes: 2

Related Questions