Search code examples
ruby-on-railsredisunicorn

What happens if I don't $redis = Redis.new in after_fork?


What's the negative impact of not putting $redis = Redis.new in Unicorn's after_fork, since redis-rb is thread safe? Assuming I have more than one worker.

As opposed to just putting that line of code in the environment.rb or an intializer?


Solution

  • after_fork has little to do with thread safety. It it used when a parent process forks a child process, not when spawning a thread.

    Why you should care

    If you never fork, you probably don't.

    When you fork, the parent and child processes share file and socket descriptors (db connections, redis connections). If you don't re-open the connection to Redis in the child, data from the parent can be interleaved on the socket with data from the child.

    Read A Unix Shell in Ruby Pipes for a much more detailed description of what's going on.