Skip to content

redis rb on Phusion Passenger

imwilsonxu edited this page Sep 18, 2012 · 12 revisions

Problem:

Because of the fork() nature of Passenger, you might accidentally share the exact-same Redis connection between Passenger workers. A few harmful things can happen in this situation:

  • User X on worker A might accidentally do unexpected things on User Y's stuff on worker B. For more details, visit: 12.3.1. Example 1: Memcached connection sharing (harmful)

  • If you set your Redis to never disconnect clients(timeout 0), your workers will hold on to that open connection forever. And that may not be desirable.

Solution:

You need to re-establish Redis connection when a new Passenger worker is created. See code example below (add to e.g. environment.rb):

if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    # We're in smart spawning mode.
    if forked
      # Re-establish redis connection
      require 'redis'
      redis_config = YAML.load_file("#{Rails.root.to_s}/config/redis.yml")[Rails.env]

      # The important two lines
      $redis.client.disconnect
      $redis = Redis.new(:host => redis_config["host"], :port => redis_config["port"])
    end
  end
end

About this issue: it should no longer happen when you use redis-rb 3.0. Starting with that version, redis-rb will complain when you try to reuse a connection across processes, and it has primitive protection against multi-threading issues with a lock around every call.

Clone this wiki locally