You are making redis connection for each controller request. This will be a disaster on scale. Ideally, you should open one connection for one rails instnace. To do that, create config/initializers/redis.rb
redis_host = Rails.application.secrets.redis && Rails.application.secrets.redis['host'] || 'localhost'
redis_port = Rails.application.secrets.redis && Rails.application.secrets.redis['port'] || 6379
# The constant below will represent ONE connection, present globally in models, controllers, views etc for the instance. No need to do Redis.new everytime
REDIS = Redis.new(host: redis_host, port: redis_port.to_i)
See the application secrets part, there I'm specifying the configuration to be used, and exposing the host
and port
for production and other environments in their own secrets. This enables me to have dynamic control of redis host and port based on environment, and fallback to localhost:6379 (Default) on local.
def online?
!Redis.new.get("#{self.auth_token}").nil?
end
should become
def online?
REDIS.get("#{self.auth_token}").present?
end
How to debug and know if this problem is being caused by redis or not?
See the Rails server exception's log to see what breaks and why. Use gem like exception_notification
to send you mails when exception is triggered on different envs.
What is the proper way to use Redis in Rails?
See the initial part of this answer. Make one connection, use Rails secrets or environment variables to expose host, port. Totally depends on how and where you setup Redis instance.
Does redis need extra confguration for server (nginx) to work properly
in production?
Doesn't need anything special for nginx. You just have to configure it in your application and make sure you are able to connect.