Correct Ruby Threads and ActiveRecord Connections

14-May-2020 1599
Recently, we had an opportunity to trivially parallelize some ActiveRecord queries in our Ruby server. In a common response structure, we needed to both query for the actual data requested along with some meta-information about pagination, etc.Instead of querying for both parts of this response in sequence, we could query for both concurrently, using Ruby’s thread implementation. By default, Ruby threads will execute until they are waiting on an I/O event (like a database query), at which point they hand off Ruby’s GIL execution lock to another thread. Once the I/O response is ready, the kernel will pre-emptively pause another thread to pick it back up. This allows you to wait for multiple I/O responses at the same time, rather than in sequence.
Use coupon code:

RUBYONRAILS

to get 30% discount on our bundle!
Prepare for your next tech interview with our comprehensive collection of programming interview guides. Covering JavaScript, Ruby on Rails, React, and Python, these highly-rated books offer thousands of essential questions and answers to boost your interview success. Buy our 'Ultimate Job Interview Preparation eBook Bundle' featuring 2200+ questions across multiple languages. Ultimate Job Interview Preparation eBook Bundle