Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle asynchronous calls inside receive method of Akka actor

I am trying to persist data into database. My persist method is asynchronous.

class MyActor(persistenceFactory:PersistenceFactory) extends Actor {
  def receive: Receive = {
    case record: Record =>
      // this method is asynchronous, immediate return Future[Int]
      persistenceFactory.persist(record) 
  }
}

The bottleneck is here either we get out of memory or no thread available when the application runs under increased load.

So what is the best way to handle asynchronous calls inside receive method of Akka actor ?

like image 625
Sky Avatar asked Aug 14 '16 19:08

Sky


1 Answers

This is a great example of when you should have an actor create another actor to handle an interaction. Basically the flow is like this and you can use FSM (finite state machine) too if it makes it easier for you.

  1. Parent actor receives message
  2. Parent actor creates child transaction actor
  3. Parent sends the child the original message
  4. Child calls async method and stores the Future
  5. Child uses become() to change its behavior to wait for completion of the future. There are a number of ways to do this, including FSM.
  6. Child schedules periodic messages to itself to check the Future
  7. The Child's new behavior checks the Future if it is complete on each receive
  8. When the Future is complete, child can reply with the result to the parent or to the original sender (if the parent fwded the message with the original sender).
like image 56
dres Avatar answered Nov 02 '22 01:11

dres