A simple way to implement Retry Support For Akka Future in Scala

Table of contents
Reading Time: < 1 minute

[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.

Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.

9 thoughts on “A simple way to implement Retry Support For Akka Future in Scala1 min read

  1. May be I am missing something obvious, but what is the parameter value ‘true’ being used for?

    1. 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.

  2. 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.

  3. 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!

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading