Ruby Multithreading - Concurrent API Requests

This article contains boilerplate code demonstrating how multithreaded requests can be made in ruby; ruby makes it easy to make multiple API requests at the same time!

Today, while putting finishing touches on a fin-tech MVP I'm building, I realized I needed to hit an external API twice before loading one of the pages... ew. Totally not cool, and definitely wouldn't give a programmer like myself a big-O (please look up big-O notation if you didn't get that. I'm funny, I swear).

Anyway, since I'm ABSOLUTELY NOT willing to increase my server response time by 50 ms, today was the day that I learned how to make concurrent API (HTTPS) requests in ruby.

Please find below boilerplate code demonstrating how multithreaded requests can be made in ruby:

require 'httparty'
require 'nokogiri'
require 'thread'

def return_parsed_response(url)
  HTTParty.get(url).parsed_response 
end

threads = []

parsed_response_a = nil
parsed_response_b = nil

url_a = 'https://snapagram.com'
url_b = 'https://twitterface.com'

threads << Thread.new { 
  parsed_response_a = return_parsed_response(url_a)
}

threads << Thread.new { 
  parsed_response_b = return_parsed_response(url_b)
}

# wait for threads to finish execution before continuing
threads.each(&:join)

Note: There is no need to start a thread after creating it, it begins running automatically when CPU resources become available.


I hope you found this quick tutorial on multithreading in ruby helpful!