Watch the Routees

I answered a question in the Akka mailinglist with example code that might be interesting if you need to do something similar. The use case is to perform a job consisting of a bunch of tasks. Delegate the tasks to worker actors, behind a router. Aggregate the results of workers and reply with one answer. Additionally, a worker should retry failed messages a few times, and then stop. If one worker terminates due to failure the whole job should be aborted. 

Here is the example code:

The retry is implemented by forwarding the failing message to itself in preRestart. This places the message last in the mailbox, so ordering of messages is assumed to be unimportant for the processing of the tasks. Note that forward is necessary to retain the master as sender.

Workers are restarted in case of failure, and stopped after 2 restarts. This is handled by the supervisor of the worker routees, i.e. the router. A supervisorStrategy is specified when creating the router.

To be able to abort the whole job when one worker is stopped the master subscribe to termination, death watch, of the workers. References to the workers is obtained by sending a CurrentRoutees message to the router, which replies with RouterRoutees. context.watch(actorRef) initiates the death watch subscription. Terminated is delivered when a worker has been stopped.

When the master stops itself the children are also stopped, i.e. the router and its worker routees are stopped together with the master.

Aggregation is implemented by correlating the replies from the workers with a message id.