0

I have a 3rd party API service that I am interacting with, via my Rails app, and they have quite low daily limits. Wondering what the best way to track API calls is?

  • Database
  • Redis
  • In memory
  • Other

I have a service object that makes all the calls. Just need a good way to track each call made and not go over the daily limit.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
michaelosmith
  • 15
  • 1
  • 7

1 Answers1

0

This is for anyone who stumbles across this at a later date.

so I managed to find something that works for this.

basically I use Rails Cache and set a key with a raw: true set.

Rails.cache.fetch("unique_key", raw: true, expires_at: expiry_time)

This allows me to then increment the value whenever a request to the external service is sent.

Rails.cache.increment("unique_key")

I also set the max daily calls as a constant

MAX_DAILY_API_CALLS = 2000

then used a custom error class to raise an error if the limit is reached

class TooManyApiCallsToday < StandardError
      def message
        Rails.logger.info "MINDBODY: There is a daily limit of #{MAX_DAILY_API_CALLS} and it has been reached. It will reset at midnight."
      end
    end

raise TooManyApiCallsToday if @api_calls >= MAX_DAILY_API_CALLS

Hope that helps.

michaelosmith
  • 15
  • 1
  • 7