[Note: This blog has been updated on 22nd August 2013, after the valuable feedback of readers.]
In this blog, I have explained a simple way to implement retry support for Akka future in Scala.
When Akka actor dies for any reason and we try to receive response from Akka future, this implementation would work.
Here is the logic:
When Akka future fails to respond, this retry logic would start automatically and would work until result is obtained or until number of retry limit is finished.
If we would not provide any limit, this would work indefinitely until result is obtained.
A sample call to this method :-
Here number of retry limit is 10. So above call would hit retry method 10 times. If limit is over and actor is not reachable, retry
method would return None as future response.
You can return default result according to your requirement.
After getting Future, you can use the mapTo
method to safely cast a Future to an expected type. This will return the result, if the cast is successful. Otherwise it will return ClassCastException
.
If you have implemented any better approach, please suggest.
Any suggestion would be appreciated.
May be I am missing something obvious, but what is the parameter value ‘true’ being used for?
Good catch Nirmalya, I think Ayush would need to correct that
Hi Nirmalya,
Thanks for pointing out. I have corrected this. Please check.
You can avoid the blocking/Await by using Pattern.after + recoverWith.
√
Hi Viktor,
Thanks for your valuable feedback. I completely agree with your point. We should always avoid Await.result unless there is a very specific reason to use this.
I used this because I had a very specific reason to use this. It was my bad that I have not mentioned this anywhere in my blog. I would mention the reason to use Await in my another Blog.
“Await” is a sign of bad thing. “Everything is an object” is not always good. I wish every processing unit is an actor, just like in Erlang.
Hello Guys,
Thanks for your valuable comments. I have updated the blog. Please check and let me know if still you find any issue.
Your comments would be appreciated.
Suppose you want to try about 10 times, for up to 1 second total. In your code above, you’ll have to set the “ask” timeout to 100ms. This means your code will never succeed in the case that the remote system takes 150ms to respond correctly. But you would have been fine if you didn’t retry!
I’m following Dzhaughn answer: you never exactly know computing or networking time: better use intermediate actor behaving as a supervisor and correctly define your retry strategy given the exception thrown by actual underlying actor.
Have a look at : http://doc.akka.io/docs/akka/snapshot/general/supervision.html#Delayed_restarts_with_the_BackoffSupervisor_pattern
Cheers