Concurrent Ruby is a concurrency toolkit that builds on a lot of interesting ideas from many functional languages and classic concurrency patterns. When it comes to writing threaded code in Rails applications, look no further since concurrent ruby is already included in Rails via Active Support.
In one of our applications, to improve performance we added threaded code using Concurrent::Future. It worked really well for us until one day it stopped working.
“Why threads?” one might ask. The code in question was a textbook threading use case. It had a few API calls, some DB requests and finally an action that was performed on all the data that was aggregated.
Let us look at what this code looks like.
Non threaded code
Converting the above code to use Concurrent::Future is trivial.
A bit more about Concurrent::Future
It is often intimidating to work with threads. They can bring in complexity and can have unpredictable behaviors due to lack of thread-safety. Ruby, being a language of mutable references, we often find it difficult to write 100% thread-safe code.
Inspired by Clojure’s Future function, Concurrent::Future is a primitive that guarantees thead safety. It takes a block of work and performs the work asynchronously using Concurrent Ruby’s global thread-pool. Once a block of work is scheduled, Concurrent Ruby gives us a handle to this future work, on which when #value (or #deref) is called block’s value is returned.
when an exception occurs in the main thread,
the interpreter stops
gathers the exception data.
In the case of Ruby Threads,
any unhandled exceptions are reported
is an better alternative
which will cause all threads to exit
exception is raised
in any running thread.
published a blog
recently which talks about this in great detail.
Exception handling in Concurrent Ruby
Where did the exception go? This code fails silently and swallows the exceptions. How can we find out if the code executed successfully?
How we fixed our issue
We found places in our application where Concurrent::Future was used in a way that would swallow exceptions. It is also a possibility that people might overlook the explicit need to manually report exception. We addressed these concerns with the following wrapper class.
Please note that using Concurrent Ruby Futures caused segmentation fault while running specs in Circle CI. As of this writing, we are using normal looping instead of Futures in Circle CI until the reason for the segfault is isolated and fixed.
Concurrent::Future also gives us another API which not only returns the value of the block but also posts/raises any exceptions that occur into the main thread.