Search code examples
scalaakkaakka-persistence

how can I verify that the persistence process is completed in order to gracefully shutdown the system?


using akka actor - I am sending heavy rate of messages to the actor that updates it's state

for (i <-0 to 100000){
  persistentActor ! Cmd("foo"+i)
}

and using the persistAsync like this

 val receiveCommand: Receive = {
    case Cmd(data) =>
      persistAsync(Evt(s"${data}-${numEvents}"))(updateState)
    case "snap"  => saveSnapshot(state)
    case "print" => println(state)
  }

how can I verify that the persistence process is completed in order to gracefully shutdown the system ?


Solution

  • Your actor will receive acknowledge after snapshot's persistence:

     var count = 0
     var shutdown = false
     def checkShutDown() = if (shutdown && count == 0) context stop self
    
     def receive = {
         case "snap"  => count++; saveSnapshot(state)
         case SaveSnapshotSuccess(metadata)         =>
             count --; checkShutDown()
         case SaveSnapshotFailure(metadata, reason)  =>
             count --; checkShutDown()
         case ShutDown => 
             shutdown = true; checkShutDown()
     }
    

    And finally you could use The Reaper pattern to shutdown your system after actors shutdown.