Question

In config/boot.rb, if set some environment variable:

ENV['some'] = 1

Will that stay in memory across requests (for both development and production environments)? The only time it is deleted is when the application shuts down, correct?

Was it helpful?

Solution

It will stay on memory for the lifetime of the process.

Will that stay in memory across requests

It will, but beware of the following gotcha: If you are using a multi-process server (such as unicorn, rainbows, passenger, puma in cluster mode etc) AND you modify the environment variable after the application boot, the change won't be shared between the different application instances.

Run (and play with) this example to get a better idea: (fork is what multi-process servers do to spawn multiple instances).

ENV["some"] = "1"
puts "Value on master process: #{ENV['some']}"

fork do
  puts "Initial value on process 1: #{ENV['some']}"

  sleep 1
  ENV["some"] = "2"
  puts "Final value on process 1: #{ENV['some']}"
end

fork do
  puts "Initial value on process 2: #{ENV['some']}"

  # Wait for the process 1 to finish
  sleep 2
  puts "Final value on process 2: #{ENV['some']}"
end

Process.waitall

Output:

Value on master process: 1
Initial value on process 1: 1
Initial value on process 2: 1
Final   value on process 1: 2
Final   value on process 2: 1

The change of ENV['some'] on "process 1" isn't seen from "process 2", even though they are initially the same (and both inherit it from the "master" process).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top