Matt Fordham
Matt Fordham

Reputation: 3187

How to track number of API requests when using Rack Cache

I will be using Rack Cache (with Memcache) to cache responses from an API I am building with Rails. In addition, I need to implement hit counting for the API. Any suggestions on to pull this off? I am guessing it would need to be handled with Rack, but am not sure where to start. Thanks!

Upvotes: 4

Views: 986

Answers (2)

lmars
lmars

Reputation: 2532

I would suggest adding a piece of Rack middleware to the top of your middleware stack which increments a counter for the request path.

For example, to do this with Redis:

# lib/request_counter.rb
class RequestCounter
  def self.redis
    @redis ||= Redis.new(host: ENV["REDIS_HOST"], port: ENV["REDIS_PORT"])
  end

  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    self.class.redis.incr "request_counter:#{request.fullpath}"
    @app.call(env)
  end
end

# config/application.rb (in the Rails::Application subclass)
require "request_counter"
config.middleware.insert(0, RequestCounter)

This would mean that each request to /path would increment the Redis key request_counter:/path

Upvotes: 5

James Lim
James Lim

Reputation: 13054

Depending on your production setup, you might be able to do this in one of the following ways

  • parse nginx logs, either with your own scripts or using splunk (example)
  • write your own nginx module to do the counting
  • attach your own Rack middleware before Rack::Cache to do the counting (guides)

Upvotes: 1

Related Questions