How to track the number of API requests when using Rack Cache

I will use Rack Cache (with Memcache) to cache responses from the API that I create using Rails. Also, I need to implement hit counting for the API. Any suggestions for withdrawals? I assume that it will need to be processed using Rack, but I'm not sure where to start. Thanks!

+4
source share
2 answers

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

For example, to do this using 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 every request /path would increment the Redis key request_counter:/path

+5
source

Depending on your production setup, you can do this in one of the following ways.

  • analyze nginx logs using either native scripts or splunk ( example )
  • write your own nginx module to do the counting
  • attach your own Rack middleware to Rack :: Cache to do the counting ( guides )
+1
source

Source: https://habr.com/ru/post/1502322/


All Articles