Always cache rate limited API call results

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the caching category.

Last Updated: 2021-05-16

I was debugging some nasty accounting code on the server. Between my own attempts to re-run the code, and and the background job retrying things again and again, I soon hit the API limit for a HTTP service I used in this code.

def get_exchange_rates
  formatted_date = date.strftime('%Y-%m-%d')

  response = HTTP.get(endpoint(formatted_date))
  status = response.status
  raise ApiError, "Got status: #{status}" unless status == 200

  json = JSON.parse(response.to_s)
  json['rates']
end

# nth time
=> ApiError

The fix was to write it in a way that cached the results. This meant that I could retry the code again and again without hitting the API limits and potentially incurring charges.

def get_exchange_rates
  formatted_date = date.strftime('%Y-%m-%d')

  Rails.cache.fetch("fixer-rates-#{formatted_date}") do
    response = HTTP.get(endpoint(formatted_date))
    status = response.status
    raise ApiError, "Got status: #{status}" unless status == 200

    json = JSON.parse(response.to_s)
    json['rates']
  end
end