0

I have the following setup:

Sinatra app proxied through nginx, with a redirect defined in the nginx-configuration:

http://www.example.com/api to http://api.example.com

I initialize the use of sessions with:

use Rack::Session::Pool

Now I can store and retrieve session-data with:

  get '/make_it_so' do
    session[:data] = 'yes indeed.'
  end

  get '/what_gives' do
    session[:data]
  end

For 3 to 5 reloads of http://www.example.com/what_gives I can see the session data, then suddenly it disappears to nil.

Can anybody help?

Similar questions are:

Rack Sessions getting lost in Chrome

Sinatra not persisting session with redirect on Chrome

Community
  • 1
  • 1
Tobias Gassmann
  • 11,399
  • 15
  • 58
  • 92
  • How are you running your Sinatra app? – matt Oct 19 '15 at 18:18
  • do you mean this: "rerun -- unicorn -c unicorn.rb -E test" ? by the way, when I use the answer http://stackoverflow.com/a/19251746/2767626 (based on Rack::Session:Cookie) everything works ok! – Tobias Gassmann Oct 19 '15 at 18:38
  • Using `rerun` could explain it. If `rerun` is relaunching your app for some reason then the memory based sessions (in `Rack::Session::Pool`) would be lost. Cookie based sessions would still work. Is anything changing in the directory that would cause `rerun` to restart the app? – matt Oct 19 '15 at 21:35

1 Answers1

0

I think your problem might be Unicorn workers. As far as I know Unicorn creates an application instance per worker. Each of these instances will have a separate session pool unfortunately, so this would only work with 1 worker.

I had this same problem, and it's not that sessions are being lost with time, it's that requests are being handled by different workers. Suppose your first request hits worker 1 and it sets a session key 'sessionkey1', you get a cookie with that same value. Then you make a second request and it hits worker 2, it will not find your key, so you will be assigned a new session and cookie, making it seem like your session was lost.

I don't know if there is a way to connect these pools, but I think it would be easier to move to an external session store, like Redis. Redis integrates easily with Rack through the redis-rack gem, so you should give that a try.

Hope this helps.